1696bd635SAlexander Shaposhnikov //===-- CommandObjectCommands.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"
203eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
217594f14fSEnrico Granata #include "lldb/Interpreter/CommandHistory.h"
22ebc09c36SJim Ingham #include "lldb/Interpreter/CommandInterpreter.h"
23de164aaaSGreg Clayton #include "lldb/Interpreter/CommandObjectRegexCommand.h"
24ebc09c36SJim Ingham #include "lldb/Interpreter/CommandReturnObject.h"
2547cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.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"
31145d95c9SPavel Labath #include "lldb/Utility/Args.h"
32573ab909SZachary Turner #include "lldb/Utility/StringList.h"
33ebc09c36SJim Ingham 
34ebc09c36SJim Ingham using namespace lldb;
35ebc09c36SJim Ingham using namespace lldb_private;
36ebc09c36SJim Ingham 
37ebc09c36SJim Ingham //-------------------------------------------------------------------------
38ebc09c36SJim Ingham // CommandObjectCommandsSource
39ebc09c36SJim Ingham //-------------------------------------------------------------------------
40ebc09c36SJim Ingham 
411f0f5b5bSZachary Turner static OptionDefinition g_history_options[] = {
421f0f5b5bSZachary Turner     // clang-format off
431f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "count",       'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "How many history commands to print." },
441f0f5b5bSZachary 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)." },
451f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "end-index",   'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to stop printing history commands." },
461f0f5b5bSZachary Turner   { LLDB_OPT_SET_2, false, "clear",       'C', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeBoolean,         "Clears the current command history." },
471f0f5b5bSZachary Turner     // clang-format on
481f0f5b5bSZachary Turner };
491f0f5b5bSZachary Turner 
50b9c1b51eSKate Stone class CommandObjectCommandsHistory : public CommandObjectParsed {
515a988416SJim Ingham public:
52b9c1b51eSKate Stone   CommandObjectCommandsHistory(CommandInterpreter &interpreter)
53b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command history",
54aab5be05SJim Ingham                             "Dump the history of commands in this session.\n"
55aab5be05SJim Ingham                             "Commands in the history list can be run again "
56aab5be05SJim Ingham                             "using \"!<INDEX>\".   \"!-<OFFSET>\" will re-run "
57aab5be05SJim Ingham                             "the command that is <OFFSET> commands from the end"
58aab5be05SJim Ingham                             " of the list (counting the current command).",
596e3d8e7fSEugene Zelenko                             nullptr),
60b9c1b51eSKate Stone         m_options() {}
615a988416SJim Ingham 
626e3d8e7fSEugene Zelenko   ~CommandObjectCommandsHistory() override = default;
635a988416SJim Ingham 
64b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
655a988416SJim Ingham 
665a988416SJim Ingham protected:
67b9c1b51eSKate Stone   class CommandOptions : public Options {
68a5a97ebeSJim Ingham   public:
69b9c1b51eSKate Stone     CommandOptions()
70b9c1b51eSKate Stone         : Options(), m_start_idx(0), m_stop_idx(0), m_count(0), m_clear(false) {
71a5a97ebeSJim Ingham     }
72a5a97ebeSJim Ingham 
736e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
74a5a97ebeSJim Ingham 
7597206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
76b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
7797206d57SZachary Turner       Status error;
783bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
79a5a97ebeSJim Ingham 
80b9c1b51eSKate Stone       switch (short_option) {
81a5a97ebeSJim Ingham       case 'c':
82fe11483bSZachary Turner         error = m_count.SetValueFromString(option_arg, eVarSetOperationAssign);
83a5a97ebeSJim Ingham         break;
84a5a97ebeSJim Ingham       case 's':
85fe11483bSZachary Turner         if (option_arg == "end") {
867594f14fSEnrico Granata           m_start_idx.SetCurrentValue(UINT64_MAX);
877594f14fSEnrico Granata           m_start_idx.SetOptionWasSet();
88b9c1b51eSKate Stone         } else
89fe11483bSZachary Turner           error = m_start_idx.SetValueFromString(option_arg,
90b9c1b51eSKate Stone                                                  eVarSetOperationAssign);
917594f14fSEnrico Granata         break;
927594f14fSEnrico Granata       case 'e':
93fe11483bSZachary Turner         error =
94fe11483bSZachary Turner             m_stop_idx.SetValueFromString(option_arg, eVarSetOperationAssign);
957594f14fSEnrico Granata         break;
9663123b64SEnrico Granata       case 'C':
9763123b64SEnrico Granata         m_clear.SetCurrentValue(true);
9863123b64SEnrico Granata         m_clear.SetOptionWasSet();
99a5a97ebeSJim Ingham         break;
100a5a97ebeSJim Ingham       default:
101b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
102b9c1b51eSKate Stone                                        short_option);
103a5a97ebeSJim Ingham         break;
104a5a97ebeSJim Ingham       }
105a5a97ebeSJim Ingham 
106a5a97ebeSJim Ingham       return error;
107a5a97ebeSJim Ingham     }
108a5a97ebeSJim Ingham 
109b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1107594f14fSEnrico Granata       m_start_idx.Clear();
1117594f14fSEnrico Granata       m_stop_idx.Clear();
1127594f14fSEnrico Granata       m_count.Clear();
11363123b64SEnrico Granata       m_clear.Clear();
114a5a97ebeSJim Ingham     }
115a5a97ebeSJim Ingham 
1161f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
11770602439SZachary Turner       return llvm::makeArrayRef(g_history_options);
1181f0f5b5bSZachary Turner     }
119a5a97ebeSJim Ingham 
120a5a97ebeSJim Ingham     // Instance variables to hold the values for command options.
121a5a97ebeSJim Ingham 
1227594f14fSEnrico Granata     OptionValueUInt64 m_start_idx;
1237594f14fSEnrico Granata     OptionValueUInt64 m_stop_idx;
1247594f14fSEnrico Granata     OptionValueUInt64 m_count;
12563123b64SEnrico Granata     OptionValueBoolean m_clear;
126a5a97ebeSJim Ingham   };
127a5a97ebeSJim Ingham 
128b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
129b9c1b51eSKate Stone     if (m_options.m_clear.GetCurrentValue() &&
130b9c1b51eSKate Stone         m_options.m_clear.OptionWasSet()) {
1317594f14fSEnrico Granata       m_interpreter.GetCommandHistory().Clear();
1327594f14fSEnrico Granata       result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
133b9c1b51eSKate Stone     } else {
134b9c1b51eSKate Stone       if (m_options.m_start_idx.OptionWasSet() &&
135b9c1b51eSKate Stone           m_options.m_stop_idx.OptionWasSet() &&
136b9c1b51eSKate Stone           m_options.m_count.OptionWasSet()) {
137b9c1b51eSKate Stone         result.AppendError("--count, --start-index and --end-index cannot be "
138b9c1b51eSKate Stone                            "all specified in the same invocation");
1397594f14fSEnrico Granata         result.SetStatus(lldb::eReturnStatusFailed);
140b9c1b51eSKate Stone       } else {
141b9c1b51eSKate Stone         std::pair<bool, uint64_t> start_idx(
142b9c1b51eSKate Stone             m_options.m_start_idx.OptionWasSet(),
143b9c1b51eSKate Stone             m_options.m_start_idx.GetCurrentValue());
144b9c1b51eSKate Stone         std::pair<bool, uint64_t> stop_idx(
145b9c1b51eSKate Stone             m_options.m_stop_idx.OptionWasSet(),
146b9c1b51eSKate Stone             m_options.m_stop_idx.GetCurrentValue());
147b9c1b51eSKate Stone         std::pair<bool, uint64_t> count(m_options.m_count.OptionWasSet(),
148b9c1b51eSKate Stone                                         m_options.m_count.GetCurrentValue());
149a5a97ebeSJim Ingham 
1507594f14fSEnrico Granata         const CommandHistory &history(m_interpreter.GetCommandHistory());
1517594f14fSEnrico Granata 
152b9c1b51eSKate Stone         if (start_idx.first && start_idx.second == UINT64_MAX) {
153b9c1b51eSKate Stone           if (count.first) {
1547594f14fSEnrico Granata             start_idx.second = history.GetSize() - count.second;
1557594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
156b9c1b51eSKate Stone           } else if (stop_idx.first) {
1577594f14fSEnrico Granata             start_idx.second = stop_idx.second;
1587594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
159b9c1b51eSKate Stone           } else {
1607594f14fSEnrico Granata             start_idx.second = 0;
1617594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
1627594f14fSEnrico Granata           }
163b9c1b51eSKate Stone         } else {
164b9c1b51eSKate Stone           if (!start_idx.first && !stop_idx.first && !count.first) {
1657594f14fSEnrico Granata             start_idx.second = 0;
1667594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
167b9c1b51eSKate Stone           } else if (start_idx.first) {
168b9c1b51eSKate Stone             if (count.first) {
1697594f14fSEnrico Granata               stop_idx.second = start_idx.second + count.second - 1;
170b9c1b51eSKate Stone             } else if (!stop_idx.first) {
1717594f14fSEnrico Granata               stop_idx.second = history.GetSize() - 1;
1727594f14fSEnrico Granata             }
173b9c1b51eSKate Stone           } else if (stop_idx.first) {
174b9c1b51eSKate Stone             if (count.first) {
1757594f14fSEnrico Granata               if (stop_idx.second >= count.second)
1767594f14fSEnrico Granata                 start_idx.second = stop_idx.second - count.second + 1;
1777594f14fSEnrico Granata               else
1787594f14fSEnrico Granata                 start_idx.second = 0;
1797594f14fSEnrico Granata             }
180b9c1b51eSKate Stone           } else /* if (count.first) */
1817594f14fSEnrico Granata           {
1827594f14fSEnrico Granata             start_idx.second = 0;
1837594f14fSEnrico Granata             stop_idx.second = count.second - 1;
1847594f14fSEnrico Granata           }
1857594f14fSEnrico Granata         }
186b9c1b51eSKate Stone         history.Dump(result.GetOutputStream(), start_idx.second,
187b9c1b51eSKate Stone                      stop_idx.second);
1887594f14fSEnrico Granata       }
1897594f14fSEnrico Granata     }
190a5a97ebeSJim Ingham     return result.Succeeded();
191a5a97ebeSJim Ingham   }
1925a988416SJim Ingham 
1935a988416SJim Ingham   CommandOptions m_options;
194a5a97ebeSJim Ingham };
195a5a97ebeSJim Ingham 
196a5a97ebeSJim Ingham //-------------------------------------------------------------------------
197a5a97ebeSJim Ingham // CommandObjectCommandsSource
198a5a97ebeSJim Ingham //-------------------------------------------------------------------------
199a5a97ebeSJim Ingham 
2001f0f5b5bSZachary Turner static OptionDefinition g_source_options[] = {
2011f0f5b5bSZachary Turner     // clang-format off
2021f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-error",    'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on error." },
2031f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on continue." },
2041f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "silent-run",       's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true don't echo commands while executing." },
2051f0f5b5bSZachary Turner     // clang-format on
2061f0f5b5bSZachary Turner };
2071f0f5b5bSZachary Turner 
208b9c1b51eSKate Stone class CommandObjectCommandsSource : public CommandObjectParsed {
2095a988416SJim Ingham public:
2107428a18cSKate Stone   CommandObjectCommandsSource(CommandInterpreter &interpreter)
211b9c1b51eSKate Stone       : CommandObjectParsed(
212b9c1b51eSKate Stone             interpreter, "command source",
213b9c1b51eSKate Stone             "Read and execute LLDB commands from the file <filename>.",
2146e3d8e7fSEugene Zelenko             nullptr),
215b9c1b51eSKate Stone         m_options() {
2165a988416SJim Ingham     CommandArgumentEntry arg;
2175a988416SJim Ingham     CommandArgumentData file_arg;
2185a988416SJim Ingham 
2195a988416SJim Ingham     // Define the first (and only) variant of this arg.
2205a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
2215a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
2225a988416SJim Ingham 
223b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
224b9c1b51eSKate Stone     // argument entry.
2255a988416SJim Ingham     arg.push_back(file_arg);
2265a988416SJim Ingham 
2275a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
2285a988416SJim Ingham     m_arguments.push_back(arg);
2295a988416SJim Ingham   }
2305a988416SJim Ingham 
2316e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
2325a988416SJim Ingham 
233b9c1b51eSKate Stone   const char *GetRepeatCommand(Args &current_command_args,
234b9c1b51eSKate Stone                                uint32_t index) override {
2355a988416SJim Ingham     return "";
2365a988416SJim Ingham   }
2375a988416SJim Ingham 
2382443bbd4SRaphael Isemann   int HandleArgumentCompletion(
2392443bbd4SRaphael Isemann       CompletionRequest &request,
2402443bbd4SRaphael Isemann       OptionElementVector &opt_element_vector) override {
2412443bbd4SRaphael Isemann     auto completion_str = request.GetParsedLine()[request.GetCursorIndex()].ref;
2422443bbd4SRaphael Isemann     completion_str = completion_str.take_front(request.GetCursorCharPosition());
2435a988416SJim Ingham 
2442443bbd4SRaphael Isemann     bool word_complete = request.GetWordComplete();
245b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
246b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
2472443bbd4SRaphael Isemann         completion_str, request.GetMatchStartPoint(),
2482443bbd4SRaphael Isemann         request.GetMaxReturnElements(), nullptr, word_complete,
2492443bbd4SRaphael Isemann         request.GetMatches());
2502443bbd4SRaphael Isemann     request.SetWordComplete(word_complete);
2512443bbd4SRaphael Isemann     return request.GetMatches().GetSize();
2525a988416SJim Ingham   }
2535a988416SJim Ingham 
254b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
2555a988416SJim Ingham 
2565a988416SJim Ingham protected:
257b9c1b51eSKate Stone   class CommandOptions : public Options {
258e16c50a1SJim Ingham   public:
259b9c1b51eSKate Stone     CommandOptions()
260b9c1b51eSKate Stone         : Options(), m_stop_on_error(true), m_silent_run(false),
261b9c1b51eSKate Stone           m_stop_on_continue(true) {}
262e16c50a1SJim Ingham 
2636e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
264e16c50a1SJim Ingham 
26597206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
266b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
26797206d57SZachary Turner       Status error;
2683bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
269e16c50a1SJim Ingham 
270b9c1b51eSKate Stone       switch (short_option) {
271e16c50a1SJim Ingham       case 'e':
272fe11483bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_arg);
273e16c50a1SJim Ingham         break;
274340b0309SGreg Clayton 
275e16c50a1SJim Ingham       case 'c':
276fe11483bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_arg);
277e16c50a1SJim Ingham         break;
278340b0309SGreg Clayton 
27960986174SMichael Sartain       case 's':
280fe11483bSZachary Turner         error = m_silent_run.SetValueFromString(option_arg);
28160986174SMichael Sartain         break;
282340b0309SGreg Clayton 
283e16c50a1SJim Ingham       default:
284b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
285b9c1b51eSKate Stone                                        short_option);
286e16c50a1SJim Ingham         break;
287e16c50a1SJim Ingham       }
288e16c50a1SJim Ingham 
289e16c50a1SJim Ingham       return error;
290e16c50a1SJim Ingham     }
291e16c50a1SJim Ingham 
292b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
293012d4fcaSEnrico Granata       m_stop_on_error.Clear();
294340b0309SGreg Clayton       m_silent_run.Clear();
295340b0309SGreg Clayton       m_stop_on_continue.Clear();
296e16c50a1SJim Ingham     }
297e16c50a1SJim Ingham 
2981f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
29970602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
3001f0f5b5bSZachary Turner     }
301e16c50a1SJim Ingham 
302e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
303e16c50a1SJim Ingham 
304012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
305340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
306340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
307e16c50a1SJim Ingham   };
308e16c50a1SJim Ingham 
309b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
3104574a890SZachary Turner     if (command.GetArgumentCount() != 1) {
3114574a890SZachary Turner       result.AppendErrorWithFormat(
3124574a890SZachary Turner           "'%s' takes exactly one executable filename argument.\n",
3134574a890SZachary Turner           GetCommandName().str().c_str());
3144574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
3154574a890SZachary Turner       return false;
3164574a890SZachary Turner     }
317ebc09c36SJim Ingham 
3184574a890SZachary Turner     FileSpec cmd_file(command[0].ref, true);
3196e3d8e7fSEugene Zelenko     ExecutionContext *exe_ctx = nullptr; // Just use the default context.
320ebc09c36SJim Ingham 
321340b0309SGreg Clayton     // If any options were set, then use them
322340b0309SGreg Clayton     if (m_options.m_stop_on_error.OptionWasSet() ||
323340b0309SGreg Clayton         m_options.m_silent_run.OptionWasSet() ||
324b9c1b51eSKate Stone         m_options.m_stop_on_continue.OptionWasSet()) {
325340b0309SGreg Clayton       // Use user set settings
32626c7bf93SJim Ingham       CommandInterpreterRunOptions options;
3274574a890SZachary Turner       options.SetStopOnContinue(m_options.m_stop_on_continue.GetCurrentValue());
32826c7bf93SJim Ingham       options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
3297d8555c4SJim Ingham       options.SetEchoCommands(!m_options.m_silent_run.GetCurrentValue());
3307d8555c4SJim Ingham       options.SetPrintResults(!m_options.m_silent_run.GetCurrentValue());
33126c7bf93SJim Ingham 
3324574a890SZachary Turner       m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, result);
333b9c1b51eSKate Stone     } else {
33405097246SAdrian Prantl       // No options were set, inherit any settings from nested "command source"
33505097246SAdrian Prantl       // commands, or set to sane default settings...
33626c7bf93SJim Ingham       CommandInterpreterRunOptions options;
3374574a890SZachary Turner       m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, result);
338ebc09c36SJim Ingham     }
339ebc09c36SJim Ingham     return result.Succeeded();
340ebc09c36SJim Ingham   }
3416e3d8e7fSEugene Zelenko 
3425a988416SJim Ingham   CommandOptions m_options;
343ebc09c36SJim Ingham };
344ebc09c36SJim Ingham 
345ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
346ebc09c36SJim Ingham //-------------------------------------------------------------------------
347ebc09c36SJim Ingham // CommandObjectCommandsAlias
348ebc09c36SJim Ingham //-------------------------------------------------------------------------
349ebc09c36SJim Ingham 
3501f0f5b5bSZachary Turner static OptionDefinition g_alias_options[] = {
3511f0f5b5bSZachary Turner     // clang-format off
3521f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "help",      'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Help text for this command" },
3531f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Long help text for this command" },
3541f0f5b5bSZachary Turner     // clang-format on
3551f0f5b5bSZachary Turner };
3561f0f5b5bSZachary Turner 
357b9c1b51eSKate Stone static const char *g_python_command_instructions =
358b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
359be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
36044d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
361be93a35aSEnrico Granata 
362b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
36345d0e238SEnrico Granata protected:
364b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
365ebc09c36SJim Ingham   public:
366b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
36745d0e238SEnrico Granata 
36845d0e238SEnrico Granata     ~CommandOptions() override = default;
36945d0e238SEnrico Granata 
3701f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
37170602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
3721f0f5b5bSZachary Turner     }
37345d0e238SEnrico Granata 
37497206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
375b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
37697206d57SZachary Turner       Status error;
37745d0e238SEnrico Granata 
3781f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
3798cef4b0bSZachary Turner       std::string option_str(option_value);
38045d0e238SEnrico Granata 
381b9c1b51eSKate Stone       switch (short_option) {
38245d0e238SEnrico Granata       case 'h':
3838cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
38445d0e238SEnrico Granata         m_help.SetOptionWasSet();
38545d0e238SEnrico Granata         break;
38645d0e238SEnrico Granata 
38745d0e238SEnrico Granata       case 'H':
3888cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
38945d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
39045d0e238SEnrico Granata         break;
39145d0e238SEnrico Granata 
39245d0e238SEnrico Granata       default:
393b9c1b51eSKate Stone         error.SetErrorStringWithFormat("invalid short option character '%c'",
394b9c1b51eSKate Stone                                        short_option);
39545d0e238SEnrico Granata         break;
39645d0e238SEnrico Granata       }
39745d0e238SEnrico Granata 
39845d0e238SEnrico Granata       return error;
39945d0e238SEnrico Granata     }
40045d0e238SEnrico Granata 
401b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
40245d0e238SEnrico Granata       m_help.Clear();
40345d0e238SEnrico Granata       m_long_help.Clear();
40445d0e238SEnrico Granata     }
40545d0e238SEnrico Granata 
40645d0e238SEnrico Granata     OptionValueString m_help;
40745d0e238SEnrico Granata     OptionValueString m_long_help;
40845d0e238SEnrico Granata   };
40945d0e238SEnrico Granata 
41045d0e238SEnrico Granata   OptionGroupOptions m_option_group;
41145d0e238SEnrico Granata   CommandOptions m_command_options;
41245d0e238SEnrico Granata 
41345d0e238SEnrico Granata public:
414b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
41545d0e238SEnrico Granata 
4167428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
417b9c1b51eSKate Stone       : CommandObjectRaw(
418b9c1b51eSKate Stone             interpreter, "command alias",
419a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
420b9c1b51eSKate Stone         m_option_group(), m_command_options() {
42145d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
42245d0e238SEnrico Granata     m_option_group.Finalize();
42345d0e238SEnrico Granata 
424ebc09c36SJim Ingham     SetHelpLong(
425ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
426ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
427b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
428b9c1b51eSKate Stone         R"(
429ea671fbdSKate Stone 
430ea671fbdSKate Stone (lldb) command alias sc script
431ea671fbdSKate Stone 
432ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
433ea671fbdSKate Stone 
434ea671fbdSKate Stone (lldb) command alias bp breakpoint
435ea671fbdSKate Stone 
436b9c1b51eSKate Stone )"
437b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
438ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
439b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
440b9c1b51eSKate Stone         R"(
441ea671fbdSKate Stone 
442ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
443ea671fbdSKate Stone 
444ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
445ea671fbdSKate Stone 
446b9c1b51eSKate Stone )"
447b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
448ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
449ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
450b9c1b51eSKate Stone shows how to create aliases with options:"
451b9c1b51eSKate Stone         R"(
452ea671fbdSKate Stone 
453ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
454ea671fbdSKate Stone 
455b9c1b51eSKate Stone )"
456b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
457ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
458ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
459ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
460ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
461ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
462ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
463ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
464ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
465ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
466b9c1b51eSKate Stone launch' example below)."
467b9c1b51eSKate Stone         R"(
468ea671fbdSKate Stone 
469b9c1b51eSKate Stone )"
470b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
471ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
472b9c1b51eSKate Stone \".cpp\":"
473b9c1b51eSKate Stone         R"(
474ea671fbdSKate Stone 
475ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
476ea671fbdSKate Stone 
477b9c1b51eSKate Stone )"
478b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
479ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
480ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
481b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
482b9c1b51eSKate Stone         R"(
483ea671fbdSKate Stone 
484ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
485ea671fbdSKate Stone (lldb) bfl my-file.c 137
486ea671fbdSKate Stone 
487ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
488ea671fbdSKate Stone 
489ea671fbdSKate Stone Another example:
490ea671fbdSKate Stone 
491ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
492ea671fbdSKate Stone (lldb) pltty /dev/tty0
493ea671fbdSKate Stone 
494ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
495ea671fbdSKate Stone 
496b9c1b51eSKate Stone )"
497b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
498ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
499b9c1b51eSKate Stone rather than using a positional placeholder:"
500b9c1b51eSKate Stone         R"(
501ea671fbdSKate Stone 
502ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
503ea671fbdSKate Stone 
504b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
505ebc09c36SJim Ingham 
506405fe67fSCaroline Tice     CommandArgumentEntry arg1;
507405fe67fSCaroline Tice     CommandArgumentEntry arg2;
508405fe67fSCaroline Tice     CommandArgumentEntry arg3;
509405fe67fSCaroline Tice     CommandArgumentData alias_arg;
510405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
511405fe67fSCaroline Tice     CommandArgumentData options_arg;
512405fe67fSCaroline Tice 
513405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
514405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
515405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
516405fe67fSCaroline Tice 
517b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
518b9c1b51eSKate Stone     // argument entry.
519405fe67fSCaroline Tice     arg1.push_back(alias_arg);
520405fe67fSCaroline Tice 
521405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
522405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
523405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
524405fe67fSCaroline Tice 
525b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
526b9c1b51eSKate Stone     // argument entry.
527405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
528405fe67fSCaroline Tice 
529405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
530405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
531405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
532405fe67fSCaroline Tice 
533b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
534b9c1b51eSKate Stone     // argument entry.
535405fe67fSCaroline Tice     arg3.push_back(options_arg);
536405fe67fSCaroline Tice 
537405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
538405fe67fSCaroline Tice     m_arguments.push_back(arg1);
539405fe67fSCaroline Tice     m_arguments.push_back(arg2);
540405fe67fSCaroline Tice     m_arguments.push_back(arg3);
541ebc09c36SJim Ingham   }
542ebc09c36SJim Ingham 
5436e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
544ebc09c36SJim Ingham 
5455a988416SJim Ingham protected:
546*4d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
547b9c1b51eSKate Stone                  CommandReturnObject &result) override {
548*4d51a902SRaphael Isemann     if (raw_command_line.empty()) {
549d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
55045d0e238SEnrico Granata       return false;
55145d0e238SEnrico Granata     }
55245d0e238SEnrico Granata 
553e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
554e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
55545d0e238SEnrico Granata 
5563a0e1270SRaphael Isemann     OptionsWithRaw args_with_suffix(raw_command_line);
5573a0e1270SRaphael Isemann     const char *remainder = args_with_suffix.GetRawPart().c_str();
55845d0e238SEnrico Granata 
5593a0e1270SRaphael Isemann     if (args_with_suffix.HasArgs())
5603a0e1270SRaphael Isemann       if (!ParseOptionsAndNotify(args_with_suffix.GetArgs(), result,
5613a0e1270SRaphael Isemann                                  m_option_group, exe_ctx))
56245d0e238SEnrico Granata         return false;
56345d0e238SEnrico Granata 
564a01bccdbSZachary Turner     llvm::StringRef raw_command_string(remainder);
565a01bccdbSZachary Turner     Args args(raw_command_string);
566844d2303SCaroline Tice 
56711eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
568d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
569844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
570844d2303SCaroline Tice       return false;
571844d2303SCaroline Tice     }
572844d2303SCaroline Tice 
573844d2303SCaroline Tice     // Get the alias command.
574844d2303SCaroline Tice 
5754574a890SZachary Turner     auto alias_command = args[0].ref;
5764574a890SZachary Turner     if (alias_command.startswith("-")) {
577d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
578b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
579b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
580b9c1b51eSKate Stone                              "a -- at the end of the options");
581d72e412fSEnrico Granata       }
582d72e412fSEnrico Granata       result.SetStatus(eReturnStatusFailed);
583d72e412fSEnrico Granata       return false;
584d72e412fSEnrico Granata     }
585844d2303SCaroline Tice 
586b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
58705097246SAdrian Prantl     // which gets passed to 'Execute', which does the stripping itself.
588844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
589b9c1b51eSKate Stone     if (pos == 0) {
590844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
591844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
592844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
593844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
594b9c1b51eSKate Stone     } else {
595844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
596844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
597844d2303SCaroline Tice       return false;
598844d2303SCaroline Tice     }
599844d2303SCaroline Tice 
600844d2303SCaroline Tice     // Verify that the command is alias-able.
601771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
602b9c1b51eSKate Stone       result.AppendErrorWithFormat(
603b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
6044574a890SZachary Turner           args[0].c_str());
605844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
606844d2303SCaroline Tice       return false;
607844d2303SCaroline Tice     }
608844d2303SCaroline Tice 
609b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
610a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
611a01bccdbSZachary Turner     // name of the command object stripped off the front.
612a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
613b9c1b51eSKate Stone     CommandObject *cmd_obj =
614b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
615844d2303SCaroline Tice 
616b9c1b51eSKate Stone     if (!cmd_obj) {
617b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
618b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
619b9c1b51eSKate Stone                                    "  No alias created.",
620a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
621844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
622844d2303SCaroline Tice       return false;
623b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
624b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
62505097246SAdrian Prantl       // been updated to this point. Therefore can we pass it to the version of
62605097246SAdrian Prantl       // Execute that does not need/expect raw input in the alias.
6275a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
628b9c1b51eSKate Stone     } else {
629b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
630b9c1b51eSKate Stone                                       *cmd_obj, result);
6315a988416SJim Ingham     }
6325a988416SJim Ingham     return result.Succeeded();
6335a988416SJim Ingham   }
6345a988416SJim Ingham 
635a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
636a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
637b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
638b9c1b51eSKate Stone                                 CommandReturnObject &result) {
639844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
640844d2303SCaroline Tice 
641b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
642b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
643844d2303SCaroline Tice 
644b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
645b9c1b51eSKate Stone             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) {
646a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
647a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
648b9c1b51eSKate Stone         result.AppendWarningWithFormat(
649b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
650a01bccdbSZachary Turner             alias_command.str().c_str());
651844d2303SCaroline Tice       }
652b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
653a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
65445d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
65545d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
65645d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
65745d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
658844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
659b9c1b51eSKate Stone       } else {
660472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
661472362e6SCaroline Tice         result.SetStatus(eReturnStatusFailed);
662472362e6SCaroline Tice       }
663212130acSEnrico Granata 
664b9c1b51eSKate Stone     } else {
665212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
666212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
667212130acSEnrico Granata     }
668212130acSEnrico Granata 
669844d2303SCaroline Tice     return result.Succeeded();
670844d2303SCaroline Tice   }
671ebc09c36SJim Ingham 
672b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
673867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
674ebc09c36SJim Ingham 
675b9c1b51eSKate Stone     if (argc < 2) {
676d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
677ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
678ebc09c36SJim Ingham       return false;
679ebc09c36SJim Ingham     }
680ebc09c36SJim Ingham 
6814574a890SZachary Turner     // Save these in std::strings since we're going to shift them off.
6824574a890SZachary Turner     const std::string alias_command(args[0].ref);
6834574a890SZachary Turner     const std::string actual_command(args[1].ref);
684ebc09c36SJim Ingham 
685ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
686ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
687ebc09c36SJim Ingham 
688b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
689b9c1b51eSKate Stone     // object.
690ebc09c36SJim Ingham 
691771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
692b9c1b51eSKate Stone       result.AppendErrorWithFormat(
693b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
694ebc09c36SJim Ingham           alias_command.c_str());
695ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
6964574a890SZachary Turner       return false;
6974574a890SZachary Turner     }
6984574a890SZachary Turner 
699b9c1b51eSKate Stone     CommandObjectSP command_obj_sp(
700a449698cSZachary Turner         m_interpreter.GetCommandSPExact(actual_command, true));
701ebc09c36SJim Ingham     CommandObjectSP subcommand_obj_sp;
702ebc09c36SJim Ingham     bool use_subcommand = false;
7034574a890SZachary Turner     if (!command_obj_sp) {
7044574a890SZachary Turner       result.AppendErrorWithFormat("'%s' is not an existing command.\n",
7054574a890SZachary Turner                                    actual_command.c_str());
7064574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
7074574a890SZachary Turner       return false;
7084574a890SZachary Turner     }
709ebc09c36SJim Ingham     CommandObject *cmd_obj = command_obj_sp.get();
7106e3d8e7fSEugene Zelenko     CommandObject *sub_cmd_obj = nullptr;
711b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
712b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
713ebc09c36SJim Ingham 
71411eb9c64SZachary Turner     while (cmd_obj->IsMultiwordObject() && !args.empty()) {
7154574a890SZachary Turner       auto sub_command = args[0].ref;
71611eb9c64SZachary Turner       assert(!sub_command.empty());
7174574a890SZachary Turner       subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
7184574a890SZachary Turner       if (!subcommand_obj_sp) {
719b9c1b51eSKate Stone         result.AppendErrorWithFormat(
720b9c1b51eSKate Stone             "'%s' is not a valid sub-command of '%s'.  "
721f415eeb4SCaroline Tice             "Unable to create alias.\n",
7224574a890SZachary Turner             args[0].c_str(), actual_command.c_str());
723ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
724ebc09c36SJim Ingham         return false;
725ebc09c36SJim Ingham       }
7264574a890SZachary Turner 
7274574a890SZachary Turner       sub_cmd_obj = subcommand_obj_sp.get();
7284574a890SZachary Turner       use_subcommand = true;
7294574a890SZachary Turner       args.Shift(); // Shift the sub_command word off the argument vector.
7304574a890SZachary Turner       cmd_obj = sub_cmd_obj;
731ebc09c36SJim Ingham     }
732ebc09c36SJim Ingham 
733ebc09c36SJim Ingham     // Verify & handle any options/arguments passed to the alias command
734ebc09c36SJim Ingham 
735212130acSEnrico Granata     std::string args_string;
736212130acSEnrico Granata 
73711eb9c64SZachary Turner     if (!args.empty()) {
738b9c1b51eSKate Stone       CommandObjectSP tmp_sp =
739b9c1b51eSKate Stone           m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false);
740ebc09c36SJim Ingham       if (use_subcommand)
7414574a890SZachary Turner         tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName(),
7424574a890SZachary Turner                                                  false);
743ca90c47eSCaroline Tice 
744ca90c47eSCaroline Tice       args.GetCommandString(args_string);
745867b185dSCaroline Tice     }
746ebc09c36SJim Ingham 
747771ef6d4SMalcolm Parsons     if (m_interpreter.AliasExists(alias_command) ||
748771ef6d4SMalcolm Parsons         m_interpreter.UserCommandExists(alias_command)) {
749b9c1b51eSKate Stone       result.AppendWarningWithFormat(
7504574a890SZachary Turner           "Overwriting existing definition for '%s'.\n", alias_command.c_str());
751ebc09c36SJim Ingham     }
752ebc09c36SJim Ingham 
753b9c1b51eSKate Stone     if (CommandAlias *alias = m_interpreter.AddAlias(
7544574a890SZachary Turner             alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
755771ef6d4SMalcolm Parsons             args_string)) {
75645d0e238SEnrico Granata       if (m_command_options.m_help.OptionWasSet())
75745d0e238SEnrico Granata         alias->SetHelp(m_command_options.m_help.GetCurrentValue());
75845d0e238SEnrico Granata       if (m_command_options.m_long_help.OptionWasSet())
75945d0e238SEnrico Granata         alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
760ebc09c36SJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
761b9c1b51eSKate Stone     } else {
762212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
763212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
764212130acSEnrico Granata       return false;
765212130acSEnrico Granata     }
766ebc09c36SJim Ingham 
767ebc09c36SJim Ingham     return result.Succeeded();
768ebc09c36SJim Ingham   }
769ebc09c36SJim Ingham };
770ebc09c36SJim Ingham 
771ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
772ebc09c36SJim Ingham //-------------------------------------------------------------------------
773ebc09c36SJim Ingham // CommandObjectCommandsUnalias
774ebc09c36SJim Ingham //-------------------------------------------------------------------------
775ebc09c36SJim Ingham 
776b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
777ebc09c36SJim Ingham public:
7787428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
779b9c1b51eSKate Stone       : CommandObjectParsed(
780b9c1b51eSKate Stone             interpreter, "command unalias",
781b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
782b9c1b51eSKate Stone             nullptr) {
783405fe67fSCaroline Tice     CommandArgumentEntry arg;
784405fe67fSCaroline Tice     CommandArgumentData alias_arg;
785405fe67fSCaroline Tice 
786405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
787405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
788405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
789405fe67fSCaroline Tice 
790b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
791b9c1b51eSKate Stone     // argument entry.
792405fe67fSCaroline Tice     arg.push_back(alias_arg);
793405fe67fSCaroline Tice 
794405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
795405fe67fSCaroline Tice     m_arguments.push_back(arg);
796ebc09c36SJim Ingham   }
797ebc09c36SJim Ingham 
7986e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
799ebc09c36SJim Ingham 
8005a988416SJim Ingham protected:
801b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
802ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
803ebc09c36SJim Ingham     CommandObject *cmd_obj;
804ebc09c36SJim Ingham 
80511eb9c64SZachary Turner     if (args.empty()) {
80611eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
80711eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
80811eb9c64SZachary Turner       return false;
80911eb9c64SZachary Turner     }
81011eb9c64SZachary Turner 
8114574a890SZachary Turner     auto command_name = args[0].ref;
812a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
8134574a890SZachary Turner     if (!cmd_obj) {
8144574a890SZachary Turner       result.AppendErrorWithFormat(
8154574a890SZachary Turner           "'%s' is not a known command.\nTry 'help' to see a "
8164574a890SZachary Turner           "current list of commands.\n",
817867e7d17SZachary Turner           args[0].c_str());
8184574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
8194574a890SZachary Turner       return false;
8204574a890SZachary Turner     }
8214574a890SZachary Turner 
822b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
823b9c1b51eSKate Stone       if (cmd_obj->IsRemovable()) {
824b9c1b51eSKate Stone         result.AppendErrorWithFormat(
825b9c1b51eSKate Stone             "'%s' is not an alias, it is a debugger command which can be "
826b9c1b51eSKate Stone             "removed using the 'command delete' command.\n",
827867e7d17SZachary Turner             args[0].c_str());
828b9c1b51eSKate Stone       } else {
829b9c1b51eSKate Stone         result.AppendErrorWithFormat(
830b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
831867e7d17SZachary Turner             args[0].c_str());
832b547278cSGreg Clayton       }
833ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
8344574a890SZachary Turner       return false;
8354574a890SZachary Turner     }
8364574a890SZachary Turner 
837b9c1b51eSKate Stone     if (!m_interpreter.RemoveAlias(command_name)) {
838a7015092SGreg Clayton       if (m_interpreter.AliasExists(command_name))
839b9c1b51eSKate Stone         result.AppendErrorWithFormat(
840867e7d17SZachary Turner             "Error occurred while attempting to unalias '%s'.\n",
841867e7d17SZachary Turner             args[0].c_str());
842ebc09c36SJim Ingham       else
843b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
844867e7d17SZachary Turner                                      args[0].c_str());
845ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
8464574a890SZachary Turner       return false;
847ebc09c36SJim Ingham     }
848ebc09c36SJim Ingham 
8494574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
850ebc09c36SJim Ingham     return result.Succeeded();
851ebc09c36SJim Ingham   }
852ebc09c36SJim Ingham };
853ebc09c36SJim Ingham 
854b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
855b547278cSGreg Clayton //-------------------------------------------------------------------------
856b547278cSGreg Clayton // CommandObjectCommandsDelete
857b547278cSGreg Clayton //-------------------------------------------------------------------------
858b547278cSGreg Clayton 
859b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
860b547278cSGreg Clayton public:
8617428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
862b9c1b51eSKate Stone       : CommandObjectParsed(
863b9c1b51eSKate Stone             interpreter, "command delete",
864b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
865b9c1b51eSKate Stone             nullptr) {
866b547278cSGreg Clayton     CommandArgumentEntry arg;
867b547278cSGreg Clayton     CommandArgumentData alias_arg;
868b547278cSGreg Clayton 
869b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
870b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
871b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
872b547278cSGreg Clayton 
873b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
874b9c1b51eSKate Stone     // argument entry.
875b547278cSGreg Clayton     arg.push_back(alias_arg);
876b547278cSGreg Clayton 
877b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
878b547278cSGreg Clayton     m_arguments.push_back(arg);
879b547278cSGreg Clayton   }
880b547278cSGreg Clayton 
8816e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
882b547278cSGreg Clayton 
883b547278cSGreg Clayton protected:
884b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
885b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
886b547278cSGreg Clayton 
88711eb9c64SZachary Turner     if (args.empty()) {
88811eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
88911eb9c64SZachary Turner                                    "defined regular expression command names",
890a449698cSZachary Turner                                    GetCommandName().str().c_str());
89111eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
89211eb9c64SZachary Turner     }
89311eb9c64SZachary Turner 
8944574a890SZachary Turner     auto command_name = args[0].ref;
8954574a890SZachary Turner     if (!m_interpreter.CommandExists(command_name)) {
89646d4aa21SEnrico Granata       StreamString error_msg_stream;
89746d4aa21SEnrico Granata       const bool generate_apropos = true;
89846d4aa21SEnrico Granata       const bool generate_type_lookup = false;
899b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
9004574a890SZachary Turner           &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
9014574a890SZachary Turner           generate_apropos, generate_type_lookup);
902c156427dSZachary Turner       result.AppendError(error_msg_stream.GetString());
903b547278cSGreg Clayton       result.SetStatus(eReturnStatusFailed);
9044574a890SZachary Turner       return false;
905b547278cSGreg Clayton     }
906b547278cSGreg Clayton 
9074574a890SZachary Turner     if (!m_interpreter.RemoveCommand(command_name)) {
9084574a890SZachary Turner       result.AppendErrorWithFormat(
9094574a890SZachary Turner           "'%s' is a permanent debugger command and cannot be removed.\n",
910867e7d17SZachary Turner           args[0].c_str());
9114574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
9124574a890SZachary Turner       return false;
9134574a890SZachary Turner     }
9144574a890SZachary Turner 
9154574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
9164574a890SZachary Turner     return true;
917b547278cSGreg Clayton   }
918b547278cSGreg Clayton };
919b547278cSGreg Clayton 
920de164aaaSGreg Clayton //-------------------------------------------------------------------------
921de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
922de164aaaSGreg Clayton //-------------------------------------------------------------------------
9231f0f5b5bSZachary Turner 
9241f0f5b5bSZachary Turner static OptionDefinition g_regex_options[] = {
9251f0f5b5bSZachary Turner     // clang-format off
9261f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "help"  , 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The help text to display for this command." },
9271f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "A syntax string showing the typical usage syntax." },
9281f0f5b5bSZachary Turner     // clang-format on
9291f0f5b5bSZachary Turner };
9301f0f5b5bSZachary Turner 
9315a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
932de164aaaSGreg Clayton 
933b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
934b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
935de164aaaSGreg Clayton public:
9367428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
937b9c1b51eSKate Stone       : CommandObjectParsed(
938b9c1b51eSKate Stone             interpreter, "command regex", "Define a custom command in terms of "
939b9c1b51eSKate Stone                                           "existing commands by matching "
940b9c1b51eSKate Stone                                           "regular expressions.",
9410e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
942b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
943b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
944b9c1b51eSKate Stone         m_options() {
945b9c1b51eSKate Stone     SetHelpLong(
946b9c1b51eSKate Stone         R"(
947b9c1b51eSKate Stone )"
948b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
949ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
950b9c1b51eSKate Stone using the regular expression substitution format of:"
951b9c1b51eSKate Stone         R"(
952ea671fbdSKate Stone 
953ea671fbdSKate Stone     s/<regex>/<subst>/
954ea671fbdSKate Stone 
955b9c1b51eSKate Stone )"
956b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
957ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
958b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
959b9c1b51eSKate Stone         R"(
960ea671fbdSKate Stone 
961b9c1b51eSKate Stone )"
962b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
963ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
964ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
965b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
966b9c1b51eSKate Stone         R"(
967ea671fbdSKate Stone 
968ea671fbdSKate Stone EXAMPLES
969ea671fbdSKate Stone 
970b9c1b51eSKate Stone )"
971b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
972ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
973b9c1b51eSKate Stone a number follows 'f':"
974b9c1b51eSKate Stone         R"(
975ea671fbdSKate Stone 
976b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
977de164aaaSGreg Clayton   }
978de164aaaSGreg Clayton 
9796e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
980de164aaaSGreg Clayton 
9815a988416SJim Ingham protected:
982b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
98344d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
984b9c1b51eSKate Stone     if (output_sp) {
985b9c1b51eSKate Stone       output_sp->PutCString("Enter one of more sed substitution commands in "
986b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
987b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
98844d93782SGreg Clayton       output_sp->Flush();
98944d93782SGreg Clayton     }
99044d93782SGreg Clayton   }
99144d93782SGreg Clayton 
992b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
993b9c1b51eSKate Stone                               std::string &data) override {
99444d93782SGreg Clayton     io_handler.SetIsDone(true);
995b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
99644d93782SGreg Clayton       StringList lines;
997b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
99844d93782SGreg Clayton         const size_t num_lines = lines.GetSize();
99944d93782SGreg Clayton         bool check_only = false;
1000b9c1b51eSKate Stone         for (size_t i = 0; i < num_lines; ++i) {
100144d93782SGreg Clayton           llvm::StringRef bytes_strref(lines[i]);
100297206d57SZachary Turner           Status error = AppendRegexSubstitution(bytes_strref, check_only);
1003b9c1b51eSKate Stone           if (error.Fail()) {
1004b9c1b51eSKate Stone             if (!m_interpreter.GetDebugger()
1005b9c1b51eSKate Stone                      .GetCommandInterpreter()
1006b9c1b51eSKate Stone                      .GetBatchCommandMode()) {
1007b9c1b51eSKate Stone               StreamSP out_stream =
1008b9c1b51eSKate Stone                   m_interpreter.GetDebugger().GetAsyncOutputStream();
100944d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
101044d93782SGreg Clayton             }
101144d93782SGreg Clayton           }
101244d93782SGreg Clayton         }
101344d93782SGreg Clayton       }
1014b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
101544d93782SGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
101644d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
101744d93782SGreg Clayton       }
101844d93782SGreg Clayton     }
101944d93782SGreg Clayton   }
102044d93782SGreg Clayton 
1021b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
10225a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
1023b9c1b51eSKate Stone     if (argc == 0) {
1024b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
1025b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
10260e5e5a79SGreg Clayton       result.SetStatus(eReturnStatusFailed);
102711eb9c64SZachary Turner       return false;
102811eb9c64SZachary Turner     }
102911eb9c64SZachary Turner 
103097206d57SZachary Turner     Status error;
10314574a890SZachary Turner     auto name = command[0].ref;
10324574a890SZachary Turner     m_regex_cmd_ap = llvm::make_unique<CommandObjectRegexCommand>(
10334574a890SZachary Turner         m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0,
10344574a890SZachary Turner         true);
10350e5e5a79SGreg Clayton 
1036b9c1b51eSKate Stone     if (argc == 1) {
103744d93782SGreg Clayton       Debugger &debugger = m_interpreter.GetDebugger();
1038e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
103944d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
1040b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
1041b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
104273d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
1043514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
1044514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
1045b9c1b51eSKate Stone           multiple_lines, color_prompt,
1046f6913cd7SGreg Clayton           0, // Don't show line numbers
104744d93782SGreg Clayton           *this));
104844d93782SGreg Clayton 
1049b9c1b51eSKate Stone       if (io_handler_sp) {
105044d93782SGreg Clayton         debugger.PushIOHandler(io_handler_sp);
1051de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1052de164aaaSGreg Clayton       }
1053b9c1b51eSKate Stone     } else {
105497d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
105544d93782SGreg Clayton         bool check_only = false;
105697d2c401SZachary Turner         error = AppendRegexSubstitution(entry.ref, check_only);
10570e5e5a79SGreg Clayton         if (error.Fail())
10580e5e5a79SGreg Clayton           break;
10590e5e5a79SGreg Clayton       }
10600e5e5a79SGreg Clayton 
1061b9c1b51eSKate Stone       if (error.Success()) {
10620e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
10630e5e5a79SGreg Clayton       }
10640e5e5a79SGreg Clayton     }
1065b9c1b51eSKate Stone     if (error.Fail()) {
10660e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
1067de164aaaSGreg Clayton       result.SetStatus(eReturnStatusFailed);
1068de164aaaSGreg Clayton     }
10690e5e5a79SGreg Clayton 
1070de164aaaSGreg Clayton     return result.Succeeded();
1071de164aaaSGreg Clayton   }
1072de164aaaSGreg Clayton 
107397206d57SZachary Turner   Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
1074b9c1b51eSKate Stone                                  bool check_only) {
107597206d57SZachary Turner     Status error;
10760e5e5a79SGreg Clayton 
1077b9c1b51eSKate Stone     if (!m_regex_cmd_ap) {
1078b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1079b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
1080b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10810e5e5a79SGreg Clayton       return error;
1082de164aaaSGreg Clayton     }
10830e5e5a79SGreg Clayton 
10840e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
10850e5e5a79SGreg Clayton 
1086b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
1087b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1088b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
1089b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10900e5e5a79SGreg Clayton       return error;
10910e5e5a79SGreg Clayton     }
10920e5e5a79SGreg Clayton 
1093b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
1094b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
1095b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
1096b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
10970e5e5a79SGreg Clayton       return error;
10980e5e5a79SGreg Clayton     }
10990e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
110005097246SAdrian Prantl     // use the char that follows 's' as the regex separator character so we can
110105097246SAdrian Prantl     // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
11020e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
1103b9c1b51eSKate Stone     const size_t second_separator_char_pos =
1104b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
11050e5e5a79SGreg Clayton 
1106b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
1107b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1108b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
11090e5e5a79SGreg Clayton           separator_char,
11100e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
1111ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
1112b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11130e5e5a79SGreg Clayton       return error;
11140e5e5a79SGreg Clayton     }
11150e5e5a79SGreg Clayton 
1116b9c1b51eSKate Stone     const size_t third_separator_char_pos =
1117b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
11180e5e5a79SGreg Clayton 
1119b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
1120b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1121b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
11220e5e5a79SGreg Clayton           separator_char,
11230e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
1124ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
1125b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11260e5e5a79SGreg Clayton       return error;
11270e5e5a79SGreg Clayton     }
11280e5e5a79SGreg Clayton 
1129b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
113005097246SAdrian Prantl       // Make sure that everything that follows the last regex separator char
1131b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
1132b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
1133b9c1b51eSKate Stone           std::string::npos) {
1134b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
1135b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
1136b9c1b51eSKate Stone             "string: '%.*s'",
1137b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
11380e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
11390e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
11400e5e5a79SGreg Clayton         return error;
11410e5e5a79SGreg Clayton       }
1142b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
1143b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1144b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1145b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11460e5e5a79SGreg Clayton           regex_sed.data());
11470e5e5a79SGreg Clayton       return error;
1148b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
1149b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1150b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1151b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11520e5e5a79SGreg Clayton           regex_sed.data());
11530e5e5a79SGreg Clayton       return error;
11540e5e5a79SGreg Clayton     }
115544d93782SGreg Clayton 
1156b9c1b51eSKate Stone     if (!check_only) {
1157b9c1b51eSKate Stone       std::string regex(regex_sed.substr(first_separator_char_pos + 1,
1158b9c1b51eSKate Stone                                          second_separator_char_pos -
1159b9c1b51eSKate Stone                                              first_separator_char_pos - 1));
1160b9c1b51eSKate Stone       std::string subst(regex_sed.substr(second_separator_char_pos + 1,
1161b9c1b51eSKate Stone                                          third_separator_char_pos -
1162b9c1b51eSKate Stone                                              second_separator_char_pos - 1));
1163b9c1b51eSKate Stone       m_regex_cmd_ap->AddRegexCommand(regex.c_str(), subst.c_str());
116444d93782SGreg Clayton     }
11650e5e5a79SGreg Clayton     return error;
1166de164aaaSGreg Clayton   }
1167de164aaaSGreg Clayton 
1168b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1169b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
1170b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
1171de164aaaSGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
1172de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1173de164aaaSGreg Clayton       }
1174de164aaaSGreg Clayton     }
1175de164aaaSGreg Clayton   }
1176de164aaaSGreg Clayton 
1177de164aaaSGreg Clayton private:
11787b0992d9SGreg Clayton   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_ap;
1179de164aaaSGreg Clayton 
1180b9c1b51eSKate Stone   class CommandOptions : public Options {
1181de164aaaSGreg Clayton   public:
1182b9c1b51eSKate Stone     CommandOptions() : Options() {}
1183de164aaaSGreg Clayton 
11846e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1185de164aaaSGreg Clayton 
118697206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1187b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
118897206d57SZachary Turner       Status error;
11893bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1190de164aaaSGreg Clayton 
1191b9c1b51eSKate Stone       switch (short_option) {
1192de164aaaSGreg Clayton       case 'h':
1193de164aaaSGreg Clayton         m_help.assign(option_arg);
1194de164aaaSGreg Clayton         break;
1195de164aaaSGreg Clayton       case 's':
1196de164aaaSGreg Clayton         m_syntax.assign(option_arg);
1197de164aaaSGreg Clayton         break;
1198de164aaaSGreg Clayton       default:
1199b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1200b9c1b51eSKate Stone                                        short_option);
1201de164aaaSGreg Clayton         break;
1202de164aaaSGreg Clayton       }
1203de164aaaSGreg Clayton 
1204de164aaaSGreg Clayton       return error;
1205de164aaaSGreg Clayton     }
1206de164aaaSGreg Clayton 
1207b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1208de164aaaSGreg Clayton       m_help.clear();
1209de164aaaSGreg Clayton       m_syntax.clear();
1210de164aaaSGreg Clayton     }
1211de164aaaSGreg Clayton 
12121f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
121370602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
12141f0f5b5bSZachary Turner     }
1215de164aaaSGreg Clayton 
121611eb9c64SZachary Turner     // TODO: Convert these functions to return StringRefs.
1217b9c1b51eSKate Stone     const char *GetHelp() {
12186e3d8e7fSEugene Zelenko       return (m_help.empty() ? nullptr : m_help.c_str());
1219de164aaaSGreg Clayton     }
12206e3d8e7fSEugene Zelenko 
1221b9c1b51eSKate Stone     const char *GetSyntax() {
12226e3d8e7fSEugene Zelenko       return (m_syntax.empty() ? nullptr : m_syntax.c_str());
1223de164aaaSGreg Clayton     }
12246e3d8e7fSEugene Zelenko 
1225de164aaaSGreg Clayton   protected:
12266e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
12276e3d8e7fSEugene Zelenko 
1228de164aaaSGreg Clayton     std::string m_help;
1229de164aaaSGreg Clayton     std::string m_syntax;
1230de164aaaSGreg Clayton   };
1231de164aaaSGreg Clayton 
1232b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1233de164aaaSGreg Clayton 
12345a988416SJim Ingham   CommandOptions m_options;
1235de164aaaSGreg Clayton };
1236de164aaaSGreg Clayton 
1237b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1238223383edSEnrico Granata public:
1239b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1240b9c1b51eSKate Stone                               std::string funct, std::string help,
1241b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1242a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1243b9c1b51eSKate Stone         m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) {
1244735152e3SEnrico Granata     if (!help.empty())
1245442f6530SZachary Turner       SetHelp(help);
1246b9c1b51eSKate Stone     else {
1247735152e3SEnrico Granata       StreamString stream;
1248735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1249c156427dSZachary Turner       SetHelp(stream.GetString());
1250735152e3SEnrico Granata     }
1251223383edSEnrico Granata   }
1252223383edSEnrico Granata 
12536e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1254223383edSEnrico Granata 
1255b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
12565a988416SJim Ingham 
1257b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
12585a988416SJim Ingham 
1259b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
12605a988416SJim Ingham 
1261442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1262442f6530SZachary Turner     if (m_fetched_help_long)
1263442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1264442f6530SZachary Turner 
1265fac939e9SEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1266442f6530SZachary Turner     if (!scripter)
1267442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1268442f6530SZachary Turner 
1269fac939e9SEnrico Granata     std::string docstring;
1270442f6530SZachary Turner     m_fetched_help_long =
1271442f6530SZachary Turner         scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1272fac939e9SEnrico Granata     if (!docstring.empty())
1273442f6530SZachary Turner       SetHelpLong(docstring);
1274fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1275fac939e9SEnrico Granata   }
1276fac939e9SEnrico Granata 
12775a988416SJim Ingham protected:
1278*4d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1279b9c1b51eSKate Stone                  CommandReturnObject &result) override {
1280223383edSEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1281223383edSEnrico Granata 
128297206d57SZachary Turner     Status error;
1283223383edSEnrico Granata 
128470f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
128570f11f88SJim Ingham 
1286b9c1b51eSKate Stone     if (!scripter ||
1287b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_function_name.c_str(),
1288b9c1b51eSKate Stone                                          raw_command_line, m_synchro, result,
1289b9c1b51eSKate Stone                                          error, m_exe_ctx)) {
1290223383edSEnrico Granata       result.AppendError(error.AsCString());
1291223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1292b9c1b51eSKate Stone     } else {
129370f11f88SJim Ingham       // Don't change the status if the command already set it...
1294b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1295c156427dSZachary Turner         if (result.GetOutputData().empty())
1296223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
129770f11f88SJim Ingham         else
129870f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
129970f11f88SJim Ingham       }
130070f11f88SJim Ingham     }
1301223383edSEnrico Granata 
1302223383edSEnrico Granata     return result.Succeeded();
1303223383edSEnrico Granata   }
1304223383edSEnrico Granata 
13056e3d8e7fSEugene Zelenko private:
13066e3d8e7fSEugene Zelenko   std::string m_function_name;
13076e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13086e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1309223383edSEnrico Granata };
1310223383edSEnrico Granata 
1311b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
13129fe00e52SEnrico Granata public:
13139fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
13149fe00e52SEnrico Granata                                std::string name,
13150641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1316b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1317a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1318b9c1b51eSKate Stone         m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false),
1319b9c1b51eSKate Stone         m_fetched_help_long(false) {
13209fe00e52SEnrico Granata     StreamString stream;
13219fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
1322c156427dSZachary Turner     SetHelp(stream.GetString());
1323e87764f2SEnrico Granata     if (ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter())
1324e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
13259fe00e52SEnrico Granata   }
13269fe00e52SEnrico Granata 
13276e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
13289fe00e52SEnrico Granata 
1329b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13309fe00e52SEnrico Granata 
1331b9c1b51eSKate Stone   StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; }
13329fe00e52SEnrico Granata 
1333b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13349fe00e52SEnrico Granata 
1335442f6530SZachary Turner   llvm::StringRef GetHelp() override {
1336442f6530SZachary Turner     if (m_fetched_help_short)
1337442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
13386f79bb2dSEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1339442f6530SZachary Turner     if (!scripter)
1340442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
13416f79bb2dSEnrico Granata     std::string docstring;
1342b9c1b51eSKate Stone     m_fetched_help_short =
1343b9c1b51eSKate Stone         scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
13446f79bb2dSEnrico Granata     if (!docstring.empty())
1345442f6530SZachary Turner       SetHelp(docstring);
1346442f6530SZachary Turner 
13476f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
13486f79bb2dSEnrico Granata   }
13496f79bb2dSEnrico Granata 
1350442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1351442f6530SZachary Turner     if (m_fetched_help_long)
1352442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1353442f6530SZachary Turner 
13546f79bb2dSEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1355442f6530SZachary Turner     if (!scripter)
1356442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1357442f6530SZachary Turner 
13586f79bb2dSEnrico Granata     std::string docstring;
1359b9c1b51eSKate Stone     m_fetched_help_long =
1360b9c1b51eSKate Stone         scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
13616f79bb2dSEnrico Granata     if (!docstring.empty())
1362442f6530SZachary Turner       SetHelpLong(docstring);
13639fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
13649fe00e52SEnrico Granata   }
13659fe00e52SEnrico Granata 
13669fe00e52SEnrico Granata protected:
1367*4d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1368b9c1b51eSKate Stone                  CommandReturnObject &result) override {
13699fe00e52SEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
13709fe00e52SEnrico Granata 
137197206d57SZachary Turner     Status error;
13729fe00e52SEnrico Granata 
13739fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
13749fe00e52SEnrico Granata 
1375b9c1b51eSKate Stone     if (!scripter ||
1376b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1377b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
13789fe00e52SEnrico Granata       result.AppendError(error.AsCString());
13799fe00e52SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1380b9c1b51eSKate Stone     } else {
13819fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1382b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1383c156427dSZachary Turner         if (result.GetOutputData().empty())
13849fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
13859fe00e52SEnrico Granata         else
13869fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
13879fe00e52SEnrico Granata       }
13889fe00e52SEnrico Granata     }
13899fe00e52SEnrico Granata 
13909fe00e52SEnrico Granata     return result.Succeeded();
13919fe00e52SEnrico Granata   }
13929fe00e52SEnrico Granata 
13936e3d8e7fSEugene Zelenko private:
13946e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
13956e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13966e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
13976e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
13989fe00e52SEnrico Granata };
13999fe00e52SEnrico Granata 
1400a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1401a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
1402a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1403a9dbf432SEnrico Granata 
14041f0f5b5bSZachary Turner OptionDefinition g_script_import_options[] = {
14051f0f5b5bSZachary Turner     // clang-format off
14061f0f5b5bSZachary 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." },
14071f0f5b5bSZachary Turner     // clang-format on
14081f0f5b5bSZachary Turner };
14091f0f5b5bSZachary Turner 
1410b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
14115a988416SJim Ingham public:
1412b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1413b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1414b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1415b9c1b51eSKate Stone         m_options() {
14165a988416SJim Ingham     CommandArgumentEntry arg1;
14175a988416SJim Ingham     CommandArgumentData cmd_arg;
14185a988416SJim Ingham 
14195a988416SJim Ingham     // Define the first (and only) variant of this arg.
14205a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
14213b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
14225a988416SJim Ingham 
1423b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1424b9c1b51eSKate Stone     // argument entry.
14255a988416SJim Ingham     arg1.push_back(cmd_arg);
14265a988416SJim Ingham 
14275a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14285a988416SJim Ingham     m_arguments.push_back(arg1);
14295a988416SJim Ingham   }
14305a988416SJim Ingham 
14316e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
14325a988416SJim Ingham 
14332443bbd4SRaphael Isemann   int HandleArgumentCompletion(
14342443bbd4SRaphael Isemann       CompletionRequest &request,
14352443bbd4SRaphael Isemann       OptionElementVector &opt_element_vector) override {
14362443bbd4SRaphael Isemann     llvm::StringRef completion_str =
14372443bbd4SRaphael Isemann         request.GetParsedLine()[request.GetCursorIndex()].ref;
14382443bbd4SRaphael Isemann     completion_str = completion_str.take_front(request.GetCursorCharPosition());
14395a988416SJim Ingham 
14402443bbd4SRaphael Isemann     bool word_complete = request.GetWordComplete();
1441b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1442b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
14432443bbd4SRaphael Isemann         completion_str, request.GetMatchStartPoint(),
14442443bbd4SRaphael Isemann         request.GetMaxReturnElements(), nullptr, word_complete,
14452443bbd4SRaphael Isemann         request.GetMatches());
14462443bbd4SRaphael Isemann     request.SetWordComplete(word_complete);
14472443bbd4SRaphael Isemann     return request.GetMatches().GetSize();
14485a988416SJim Ingham   }
14495a988416SJim Ingham 
1450b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14515a988416SJim Ingham 
14525a988416SJim Ingham protected:
1453b9c1b51eSKate Stone   class CommandOptions : public Options {
14540a305db7SEnrico Granata   public:
1455b9c1b51eSKate Stone     CommandOptions() : Options() {}
14560a305db7SEnrico Granata 
14576e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
14580a305db7SEnrico Granata 
145997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1460b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
146197206d57SZachary Turner       Status error;
14623bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
14630a305db7SEnrico Granata 
1464b9c1b51eSKate Stone       switch (short_option) {
14650a305db7SEnrico Granata       case 'r':
14660a305db7SEnrico Granata         m_allow_reload = true;
14670a305db7SEnrico Granata         break;
14680a305db7SEnrico Granata       default:
1469b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1470b9c1b51eSKate Stone                                        short_option);
14710a305db7SEnrico Granata         break;
14720a305db7SEnrico Granata       }
14730a305db7SEnrico Granata 
14740a305db7SEnrico Granata       return error;
14750a305db7SEnrico Granata     }
14760a305db7SEnrico Granata 
1477b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1478e0c70f1bSEnrico Granata       m_allow_reload = true;
14790a305db7SEnrico Granata     }
14800a305db7SEnrico Granata 
14811f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
148270602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
14831f0f5b5bSZachary Turner     }
14840a305db7SEnrico Granata 
14850a305db7SEnrico Granata     // Instance variables to hold the values for command options.
14860a305db7SEnrico Granata 
14870a305db7SEnrico Granata     bool m_allow_reload;
14880a305db7SEnrico Granata   };
14890a305db7SEnrico Granata 
1490b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1491b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1492b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1493b9c1b51eSKate Stone       result.AppendError("only scripting language supported for module "
1494b9c1b51eSKate Stone                          "importing is currently Python");
1495a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1496a9dbf432SEnrico Granata       return false;
1497a9dbf432SEnrico Granata     }
1498a9dbf432SEnrico Granata 
149911eb9c64SZachary Turner     if (command.empty()) {
15003b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1501a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1502a9dbf432SEnrico Granata       return false;
1503a9dbf432SEnrico Granata     }
1504a9dbf432SEnrico Granata 
150511eb9c64SZachary Turner     for (auto &entry : command.entries()) {
150697206d57SZachary Turner       Status error;
1507a9dbf432SEnrico Granata 
1508c9d645d3SGreg Clayton       const bool init_session = true;
1509b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
151011eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
151111eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
151205097246SAdrian Prantl       // script imports" in __lldb_init_module the real fix is to have
151305097246SAdrian Prantl       // recursive commands possible with a CommandInvocation object separate
151405097246SAdrian Prantl       // from the CommandObject itself, so that recursive command invocations
151505097246SAdrian Prantl       // won't stomp on each other (wrt to execution contents, options, and
151605097246SAdrian Prantl       // more)
1517078551c7SEnrico Granata       m_exe_ctx.Clear();
1518b9c1b51eSKate Stone       if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule(
151911eb9c64SZachary Turner               entry.c_str(), m_options.m_allow_reload, init_session, error)) {
1520a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1521b9c1b51eSKate Stone       } else {
1522b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1523b9c1b51eSKate Stone                                      error.AsCString());
1524a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusFailed);
1525a9dbf432SEnrico Granata       }
15263b00e35bSEnrico Granata     }
1527a9dbf432SEnrico Granata 
1528a9dbf432SEnrico Granata     return result.Succeeded();
1529a9dbf432SEnrico Granata   }
15300a305db7SEnrico Granata 
15315a988416SJim Ingham   CommandOptions m_options;
1532a9dbf432SEnrico Granata };
1533223383edSEnrico Granata 
1534223383edSEnrico Granata //-------------------------------------------------------------------------
1535223383edSEnrico Granata // CommandObjectCommandsScriptAdd
1536223383edSEnrico Granata //-------------------------------------------------------------------------
1537223383edSEnrico Granata 
15381f0f5b5bSZachary Turner static OptionEnumValueElement g_script_synchro_type[] = {
15391f0f5b5bSZachary Turner     {eScriptedCommandSynchronicitySynchronous, "synchronous",
15401f0f5b5bSZachary Turner      "Run synchronous"},
15411f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityAsynchronous, "asynchronous",
15421f0f5b5bSZachary Turner      "Run asynchronous"},
15431f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityCurrentValue, "current",
15441f0f5b5bSZachary Turner      "Do not alter current setting"},
15451f0f5b5bSZachary Turner     {0, nullptr, nullptr}};
15461f0f5b5bSZachary Turner 
15471f0f5b5bSZachary Turner static OptionDefinition g_script_add_options[] = {
15481f0f5b5bSZachary Turner     // clang-format off
15491f0f5b5bSZachary 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." },
15501f0f5b5bSZachary 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." },
15511f0f5b5bSZachary Turner   { LLDB_OPT_SET_1,   false, "help"  ,        'h', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeHelpText,                     "The help text to display for this command." },
15521f0f5b5bSZachary 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." },
15531f0f5b5bSZachary Turner     // clang-format on
15541f0f5b5bSZachary Turner };
15551f0f5b5bSZachary Turner 
1556b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1557b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
15585a988416SJim Ingham public:
1559b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1560b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
15615a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
15626e3d8e7fSEugene Zelenko                             nullptr),
1563b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
15645a988416SJim Ingham     CommandArgumentEntry arg1;
15655a988416SJim Ingham     CommandArgumentData cmd_arg;
15665a988416SJim Ingham 
15675a988416SJim Ingham     // Define the first (and only) variant of this arg.
15685a988416SJim Ingham     cmd_arg.arg_type = eArgTypeCommandName;
15695a988416SJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlain;
15705a988416SJim Ingham 
1571b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1572b9c1b51eSKate Stone     // argument entry.
15735a988416SJim Ingham     arg1.push_back(cmd_arg);
15745a988416SJim Ingham 
15755a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
15765a988416SJim Ingham     m_arguments.push_back(arg1);
15775a988416SJim Ingham   }
15785a988416SJim Ingham 
15796e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
15805a988416SJim Ingham 
1581b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
15825a988416SJim Ingham 
15835a988416SJim Ingham protected:
1584b9c1b51eSKate Stone   class CommandOptions : public Options {
1585223383edSEnrico Granata   public:
1586b9c1b51eSKate Stone     CommandOptions()
1587b9c1b51eSKate Stone         : Options(), m_class_name(), m_funct_name(), m_short_help(),
1588b9c1b51eSKate Stone           m_synchronicity(eScriptedCommandSynchronicitySynchronous) {}
1589223383edSEnrico Granata 
15906e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1591223383edSEnrico Granata 
159297206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1593b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
159497206d57SZachary Turner       Status error;
15953bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1596223383edSEnrico Granata 
1597b9c1b51eSKate Stone       switch (short_option) {
1598223383edSEnrico Granata       case 'f':
1599fe11483bSZachary Turner         if (!option_arg.empty())
1600fe11483bSZachary Turner           m_funct_name = option_arg;
1601735152e3SEnrico Granata         break;
16029fe00e52SEnrico Granata       case 'c':
1603fe11483bSZachary Turner         if (!option_arg.empty())
1604fe11483bSZachary Turner           m_class_name = option_arg;
16059fe00e52SEnrico Granata         break;
1606735152e3SEnrico Granata       case 'h':
1607fe11483bSZachary Turner         if (!option_arg.empty())
1608fe11483bSZachary Turner           m_short_help = option_arg;
1609223383edSEnrico Granata         break;
16100a305db7SEnrico Granata       case 's':
1611b9c1b51eSKate Stone         m_synchronicity =
161247cbf4a0SPavel Labath             (ScriptedCommandSynchronicity)OptionArgParser::ToOptionEnum(
1613fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
16140a305db7SEnrico Granata         if (!error.Success())
1615b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1616fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1617fe11483bSZachary Turner               option_arg.str().c_str());
16180a305db7SEnrico Granata         break;
1619223383edSEnrico Granata       default:
1620b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1621b9c1b51eSKate Stone                                        short_option);
1622223383edSEnrico Granata         break;
1623223383edSEnrico Granata       }
1624223383edSEnrico Granata 
1625223383edSEnrico Granata       return error;
1626223383edSEnrico Granata     }
1627223383edSEnrico Granata 
1628b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
16299fe00e52SEnrico Granata       m_class_name.clear();
1630735152e3SEnrico Granata       m_funct_name.clear();
1631735152e3SEnrico Granata       m_short_help.clear();
163244d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1633223383edSEnrico Granata     }
1634223383edSEnrico Granata 
16351f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
163670602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
16371f0f5b5bSZachary Turner     }
1638223383edSEnrico Granata 
1639223383edSEnrico Granata     // Instance variables to hold the values for command options.
1640223383edSEnrico Granata 
16419fe00e52SEnrico Granata     std::string m_class_name;
1642223383edSEnrico Granata     std::string m_funct_name;
1643735152e3SEnrico Granata     std::string m_short_help;
164444d93782SGreg Clayton     ScriptedCommandSynchronicity m_synchronicity;
1645223383edSEnrico Granata   };
1646223383edSEnrico Granata 
1647b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
164844d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1649b9c1b51eSKate Stone     if (output_sp) {
165044d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
165144d93782SGreg Clayton       output_sp->Flush();
1652223383edSEnrico Granata     }
1653223383edSEnrico Granata   }
1654223383edSEnrico Granata 
1655b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1656b9c1b51eSKate Stone                               std::string &data) override {
165744d93782SGreg Clayton     StreamFileSP error_sp = io_handler.GetErrorStreamFile();
165844d93782SGreg Clayton 
165944d93782SGreg Clayton     ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter();
1660b9c1b51eSKate Stone     if (interpreter) {
166144d93782SGreg Clayton 
166244d93782SGreg Clayton       StringList lines;
166344d93782SGreg Clayton       lines.SplitIntoLines(data);
1664b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1665a73b7df7SEnrico Granata         std::string funct_name_str;
1666b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1667b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1668b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1669b9c1b51eSKate Stone                              "add python command.\n");
167044d93782SGreg Clayton             error_sp->Flush();
1671b9c1b51eSKate Stone           } else {
1672223383edSEnrico Granata             // everything should be fine now, let's add this alias
1673223383edSEnrico Granata 
1674b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1675771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
167644d93782SGreg Clayton                 m_synchronicity));
1677223383edSEnrico Granata 
1678b9c1b51eSKate Stone             if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp,
1679b9c1b51eSKate Stone                                               true)) {
1680b9c1b51eSKate Stone               error_sp->Printf("error: unable to add selected command, didn't "
1681b9c1b51eSKate Stone                                "add python command.\n");
168244d93782SGreg Clayton               error_sp->Flush();
1683223383edSEnrico Granata             }
1684223383edSEnrico Granata           }
1685b9c1b51eSKate Stone         } else {
1686b9c1b51eSKate Stone           error_sp->Printf(
1687b9c1b51eSKate Stone               "error: unable to create function, didn't add python command.\n");
168844d93782SGreg Clayton           error_sp->Flush();
168944d93782SGreg Clayton         }
1690b9c1b51eSKate Stone       } else {
169144d93782SGreg Clayton         error_sp->Printf("error: empty function, didn't add python command.\n");
169244d93782SGreg Clayton         error_sp->Flush();
169344d93782SGreg Clayton       }
1694b9c1b51eSKate Stone     } else {
1695b9c1b51eSKate Stone       error_sp->Printf(
1696b9c1b51eSKate Stone           "error: script interpreter missing, didn't add python command.\n");
169744d93782SGreg Clayton       error_sp->Flush();
169844d93782SGreg Clayton     }
169944d93782SGreg Clayton 
170044d93782SGreg Clayton     io_handler.SetIsDone(true);
170144d93782SGreg Clayton   }
1702223383edSEnrico Granata 
17035a988416SJim Ingham protected:
1704b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1705b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1706b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1707b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1708b9c1b51eSKate Stone                          "commands is currently Python");
170999f0b8f9SEnrico Granata       result.SetStatus(eReturnStatusFailed);
171099f0b8f9SEnrico Granata       return false;
171199f0b8f9SEnrico Granata     }
171299f0b8f9SEnrico Granata 
171311eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1714223383edSEnrico Granata       result.AppendError("'command script add' requires one argument");
1715223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1716223383edSEnrico Granata       return false;
1717223383edSEnrico Granata     }
1718223383edSEnrico Granata 
1719735152e3SEnrico Granata     // Store the options in case we get multi-line input
17204574a890SZachary Turner     m_cmd_name = command[0].ref;
1721735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
172244d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1723223383edSEnrico Granata 
1724b9c1b51eSKate Stone     if (m_options.m_class_name.empty()) {
1725b9c1b51eSKate Stone       if (m_options.m_funct_name.empty()) {
1726b9c1b51eSKate Stone         m_interpreter.GetPythonCommandsFromIOHandler(
1727b9c1b51eSKate Stone             "     ",  // Prompt
172844d93782SGreg Clayton             *this,    // IOHandlerDelegate
172944d93782SGreg Clayton             true,     // Run IOHandler in async mode
1730b9c1b51eSKate Stone             nullptr); // Baton for the "io_handler" that will be passed back
1731b9c1b51eSKate Stone                       // into our IOHandlerDelegate functions
1732b9c1b51eSKate Stone       } else {
1733b9c1b51eSKate Stone         CommandObjectSP new_cmd(new CommandObjectPythonFunction(
1734b9c1b51eSKate Stone             m_interpreter, m_cmd_name, m_options.m_funct_name,
1735b9c1b51eSKate Stone             m_options.m_short_help, m_synchronicity));
1736b9c1b51eSKate Stone         if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
1737223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1738b9c1b51eSKate Stone         } else {
1739223383edSEnrico Granata           result.AppendError("cannot add command");
1740223383edSEnrico Granata           result.SetStatus(eReturnStatusFailed);
1741223383edSEnrico Granata         }
1742223383edSEnrico Granata       }
1743b9c1b51eSKate Stone     } else {
1744b9c1b51eSKate Stone       ScriptInterpreter *interpreter =
1745b9c1b51eSKate Stone           GetCommandInterpreter().GetScriptInterpreter();
1746b9c1b51eSKate Stone       if (!interpreter) {
17479fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
17489fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17499fe00e52SEnrico Granata         return false;
17509fe00e52SEnrico Granata       }
17519fe00e52SEnrico Granata 
1752b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1753b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1754b9c1b51eSKate Stone       if (!cmd_obj_sp) {
17559fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
17569fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17579fe00e52SEnrico Granata         return false;
17589fe00e52SEnrico Granata       }
17599fe00e52SEnrico Granata 
1760b9c1b51eSKate Stone       CommandObjectSP new_cmd(new CommandObjectScriptingObject(
1761b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
1762b9c1b51eSKate Stone       if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
17639fe00e52SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1764b9c1b51eSKate Stone       } else {
17659fe00e52SEnrico Granata         result.AppendError("cannot add command");
17669fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17679fe00e52SEnrico Granata       }
17689fe00e52SEnrico Granata     }
1769223383edSEnrico Granata 
1770223383edSEnrico Granata     return result.Succeeded();
1771223383edSEnrico Granata   }
17725a988416SJim Ingham 
17735a988416SJim Ingham   CommandOptions m_options;
177444d93782SGreg Clayton   std::string m_cmd_name;
1775735152e3SEnrico Granata   std::string m_short_help;
177644d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1777223383edSEnrico Granata };
1778223383edSEnrico Granata 
1779223383edSEnrico Granata //-------------------------------------------------------------------------
1780223383edSEnrico Granata // CommandObjectCommandsScriptList
1781223383edSEnrico Granata //-------------------------------------------------------------------------
1782223383edSEnrico Granata 
1783b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1784223383edSEnrico Granata public:
1785b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1786b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1787b9c1b51eSKate Stone                             "List defined scripted commands.", nullptr) {}
1788223383edSEnrico Granata 
17896e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1790223383edSEnrico Granata 
1791b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1792b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1793223383edSEnrico Granata 
1794223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1795223383edSEnrico Granata 
1796223383edSEnrico Granata     return true;
1797223383edSEnrico Granata   }
1798223383edSEnrico Granata };
1799223383edSEnrico Granata 
1800223383edSEnrico Granata //-------------------------------------------------------------------------
1801223383edSEnrico Granata // CommandObjectCommandsScriptClear
1802223383edSEnrico Granata //-------------------------------------------------------------------------
1803223383edSEnrico Granata 
1804b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1805223383edSEnrico Granata public:
1806b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1807b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1808b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1809223383edSEnrico Granata 
18106e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1811223383edSEnrico Granata 
18125a988416SJim Ingham protected:
1813b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1814223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1815223383edSEnrico Granata 
1816223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1817223383edSEnrico Granata 
1818223383edSEnrico Granata     return true;
1819223383edSEnrico Granata   }
1820223383edSEnrico Granata };
1821223383edSEnrico Granata 
1822223383edSEnrico Granata //-------------------------------------------------------------------------
1823223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1824223383edSEnrico Granata //-------------------------------------------------------------------------
1825223383edSEnrico Granata 
1826b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1827223383edSEnrico Granata public:
1828b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1829b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script delete",
1830b9c1b51eSKate Stone                             "Delete a scripted command.", nullptr) {
1831223383edSEnrico Granata     CommandArgumentEntry arg1;
1832223383edSEnrico Granata     CommandArgumentData cmd_arg;
1833223383edSEnrico Granata 
1834223383edSEnrico Granata     // Define the first (and only) variant of this arg.
1835223383edSEnrico Granata     cmd_arg.arg_type = eArgTypeCommandName;
1836223383edSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlain;
1837223383edSEnrico Granata 
1838b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1839b9c1b51eSKate Stone     // argument entry.
1840223383edSEnrico Granata     arg1.push_back(cmd_arg);
1841223383edSEnrico Granata 
1842223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1843223383edSEnrico Granata     m_arguments.push_back(arg1);
1844223383edSEnrico Granata   }
1845223383edSEnrico Granata 
18466e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1847223383edSEnrico Granata 
18485a988416SJim Ingham protected:
1849b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1850223383edSEnrico Granata 
185111eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1852223383edSEnrico Granata       result.AppendError("'command script delete' requires one argument");
1853223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1854223383edSEnrico Granata       return false;
1855223383edSEnrico Granata     }
1856223383edSEnrico Granata 
18574574a890SZachary Turner     auto cmd_name = command[0].ref;
1858223383edSEnrico Granata 
18594574a890SZachary Turner     if (cmd_name.empty() || !m_interpreter.HasUserCommands() ||
18604574a890SZachary Turner         !m_interpreter.UserCommandExists(cmd_name)) {
1861867e7d17SZachary Turner       result.AppendErrorWithFormat("command %s not found", command[0].c_str());
1862223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
18634574a890SZachary Turner       return false;
1864223383edSEnrico Granata     }
1865223383edSEnrico Granata 
18664574a890SZachary Turner     m_interpreter.RemoveUser(cmd_name);
18674574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishResult);
18684574a890SZachary Turner     return true;
1869223383edSEnrico Granata   }
1870223383edSEnrico Granata };
1871223383edSEnrico Granata 
1872223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1873223383edSEnrico Granata 
1874223383edSEnrico Granata //-------------------------------------------------------------------------
1875223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1876223383edSEnrico Granata //-------------------------------------------------------------------------
1877223383edSEnrico Granata 
1878b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1879223383edSEnrico Granata public:
18807428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1881b9c1b51eSKate Stone       : CommandObjectMultiword(
1882b9c1b51eSKate Stone             interpreter, "command script", "Commands for managing custom "
1883b9c1b51eSKate Stone                                            "commands implemented by "
1884b9c1b51eSKate Stone                                            "interpreter scripts.",
1885b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1886b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1887b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1888b9c1b51eSKate Stone     LoadSubCommand(
1889b9c1b51eSKate Stone         "delete",
1890b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1891b9c1b51eSKate Stone     LoadSubCommand(
1892b9c1b51eSKate Stone         "clear",
1893b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1894b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1895b9c1b51eSKate Stone                                interpreter)));
1896b9c1b51eSKate Stone     LoadSubCommand(
1897b9c1b51eSKate Stone         "import",
1898b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1899223383edSEnrico Granata   }
1900223383edSEnrico Granata 
19016e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1902223383edSEnrico Granata };
1903223383edSEnrico Granata 
1904ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
1905ebc09c36SJim Ingham 
1906ebc09c36SJim Ingham //-------------------------------------------------------------------------
1907ebc09c36SJim Ingham // CommandObjectMultiwordCommands
1908ebc09c36SJim Ingham //-------------------------------------------------------------------------
1909ebc09c36SJim Ingham 
1910b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
1911b9c1b51eSKate Stone     CommandInterpreter &interpreter)
1912b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
1913b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
1914b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
1915b9c1b51eSKate Stone   LoadSubCommand("source",
1916b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
1917b9c1b51eSKate Stone   LoadSubCommand("alias",
1918b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
1919b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
1920b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
1921b9c1b51eSKate Stone   LoadSubCommand("delete",
1922b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
1923b9c1b51eSKate Stone   LoadSubCommand(
1924b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
1925b9c1b51eSKate Stone   LoadSubCommand("history", CommandObjectSP(
1926b9c1b51eSKate Stone                                 new CommandObjectCommandsHistory(interpreter)));
1927b9c1b51eSKate Stone   LoadSubCommand(
1928b9c1b51eSKate Stone       "script",
1929b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
1930ebc09c36SJim Ingham }
1931ebc09c36SJim Ingham 
19326e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
1933