1696bd635SAlexander Shaposhnikov //===-- CommandObjectCommands.cpp -------------------------------*- C++ -*-===//
2ebc09c36SJim Ingham //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ebc09c36SJim Ingham //
7ebc09c36SJim Ingham //===----------------------------------------------------------------------===//
8ebc09c36SJim Ingham 
90e5e5a79SGreg Clayton #include "llvm/ADT/StringRef.h"
100e5e5a79SGreg Clayton 
116e3d8e7fSEugene Zelenko #include "CommandObjectCommands.h"
1246d4aa21SEnrico Granata #include "CommandObjectHelp.h"
13ebc09c36SJim Ingham #include "lldb/Core/Debugger.h"
1444d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
153eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
167594f14fSEnrico Granata #include "lldb/Interpreter/CommandHistory.h"
17ebc09c36SJim Ingham #include "lldb/Interpreter/CommandInterpreter.h"
18de164aaaSGreg Clayton #include "lldb/Interpreter/CommandObjectRegexCommand.h"
19ebc09c36SJim Ingham #include "lldb/Interpreter/CommandReturnObject.h"
2047cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h"
21012d4fcaSEnrico Granata #include "lldb/Interpreter/OptionValueBoolean.h"
2245d0e238SEnrico Granata #include "lldb/Interpreter/OptionValueString.h"
237594f14fSEnrico Granata #include "lldb/Interpreter/OptionValueUInt64.h"
24ebc09c36SJim Ingham #include "lldb/Interpreter/Options.h"
2599f0b8f9SEnrico Granata #include "lldb/Interpreter/ScriptInterpreter.h"
26145d95c9SPavel Labath #include "lldb/Utility/Args.h"
27573ab909SZachary Turner #include "lldb/Utility/StringList.h"
28ebc09c36SJim Ingham 
29ebc09c36SJim Ingham using namespace lldb;
30ebc09c36SJim Ingham using namespace lldb_private;
31ebc09c36SJim Ingham 
32ebc09c36SJim Ingham // CommandObjectCommandsSource
33ebc09c36SJim Ingham 
348fe53c49STatyana Krasnukha static constexpr OptionDefinition g_history_options[] = {
351f0f5b5bSZachary Turner     // clang-format off
368fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "count",       'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeUnsignedInteger, "How many history commands to print." },
378fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "start-index", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeUnsignedInteger, "Index at which to start printing history commands (or end to mean tail mode)." },
388fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "end-index",   'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeUnsignedInteger, "Index at which to stop printing history commands." },
398fe53c49STatyana Krasnukha   { LLDB_OPT_SET_2, false, "clear",       'C', OptionParser::eNoArgument,       nullptr, {}, 0, eArgTypeBoolean,         "Clears the current command history." },
401f0f5b5bSZachary Turner     // clang-format on
411f0f5b5bSZachary Turner };
421f0f5b5bSZachary Turner 
43b9c1b51eSKate Stone class CommandObjectCommandsHistory : public CommandObjectParsed {
445a988416SJim Ingham public:
45b9c1b51eSKate Stone   CommandObjectCommandsHistory(CommandInterpreter &interpreter)
46b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command history",
47aab5be05SJim Ingham                             "Dump the history of commands in this session.\n"
48aab5be05SJim Ingham                             "Commands in the history list can be run again "
49aab5be05SJim Ingham                             "using \"!<INDEX>\".   \"!-<OFFSET>\" will re-run "
50aab5be05SJim Ingham                             "the command that is <OFFSET> commands from the end"
51aab5be05SJim Ingham                             " of the list (counting the current command).",
526e3d8e7fSEugene Zelenko                             nullptr),
53b9c1b51eSKate Stone         m_options() {}
545a988416SJim Ingham 
556e3d8e7fSEugene Zelenko   ~CommandObjectCommandsHistory() override = default;
565a988416SJim Ingham 
57b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
585a988416SJim Ingham 
595a988416SJim Ingham protected:
60b9c1b51eSKate Stone   class CommandOptions : public Options {
61a5a97ebeSJim Ingham   public:
62b9c1b51eSKate Stone     CommandOptions()
63b9c1b51eSKate Stone         : Options(), m_start_idx(0), m_stop_idx(0), m_count(0), m_clear(false) {
64a5a97ebeSJim Ingham     }
65a5a97ebeSJim Ingham 
666e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
67a5a97ebeSJim Ingham 
6897206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
69b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
7097206d57SZachary Turner       Status error;
713bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
72a5a97ebeSJim Ingham 
73b9c1b51eSKate Stone       switch (short_option) {
74a5a97ebeSJim Ingham       case 'c':
75fe11483bSZachary Turner         error = m_count.SetValueFromString(option_arg, eVarSetOperationAssign);
76a5a97ebeSJim Ingham         break;
77a5a97ebeSJim Ingham       case 's':
78fe11483bSZachary Turner         if (option_arg == "end") {
797594f14fSEnrico Granata           m_start_idx.SetCurrentValue(UINT64_MAX);
807594f14fSEnrico Granata           m_start_idx.SetOptionWasSet();
81b9c1b51eSKate Stone         } else
82fe11483bSZachary Turner           error = m_start_idx.SetValueFromString(option_arg,
83b9c1b51eSKate Stone                                                  eVarSetOperationAssign);
847594f14fSEnrico Granata         break;
857594f14fSEnrico Granata       case 'e':
86fe11483bSZachary Turner         error =
87fe11483bSZachary Turner             m_stop_idx.SetValueFromString(option_arg, eVarSetOperationAssign);
887594f14fSEnrico Granata         break;
8963123b64SEnrico Granata       case 'C':
9063123b64SEnrico Granata         m_clear.SetCurrentValue(true);
9163123b64SEnrico Granata         m_clear.SetOptionWasSet();
92a5a97ebeSJim Ingham         break;
93a5a97ebeSJim Ingham       default:
94b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
95b9c1b51eSKate Stone                                        short_option);
96a5a97ebeSJim Ingham         break;
97a5a97ebeSJim Ingham       }
98a5a97ebeSJim Ingham 
99a5a97ebeSJim Ingham       return error;
100a5a97ebeSJim Ingham     }
101a5a97ebeSJim Ingham 
102b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1037594f14fSEnrico Granata       m_start_idx.Clear();
1047594f14fSEnrico Granata       m_stop_idx.Clear();
1057594f14fSEnrico Granata       m_count.Clear();
10663123b64SEnrico Granata       m_clear.Clear();
107a5a97ebeSJim Ingham     }
108a5a97ebeSJim Ingham 
1091f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
11070602439SZachary Turner       return llvm::makeArrayRef(g_history_options);
1111f0f5b5bSZachary Turner     }
112a5a97ebeSJim Ingham 
113a5a97ebeSJim Ingham     // Instance variables to hold the values for command options.
114a5a97ebeSJim Ingham 
1157594f14fSEnrico Granata     OptionValueUInt64 m_start_idx;
1167594f14fSEnrico Granata     OptionValueUInt64 m_stop_idx;
1177594f14fSEnrico Granata     OptionValueUInt64 m_count;
11863123b64SEnrico Granata     OptionValueBoolean m_clear;
119a5a97ebeSJim Ingham   };
120a5a97ebeSJim Ingham 
121b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
122b9c1b51eSKate Stone     if (m_options.m_clear.GetCurrentValue() &&
123b9c1b51eSKate Stone         m_options.m_clear.OptionWasSet()) {
1247594f14fSEnrico Granata       m_interpreter.GetCommandHistory().Clear();
1257594f14fSEnrico Granata       result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
126b9c1b51eSKate Stone     } else {
127b9c1b51eSKate Stone       if (m_options.m_start_idx.OptionWasSet() &&
128b9c1b51eSKate Stone           m_options.m_stop_idx.OptionWasSet() &&
129b9c1b51eSKate Stone           m_options.m_count.OptionWasSet()) {
130b9c1b51eSKate Stone         result.AppendError("--count, --start-index and --end-index cannot be "
131b9c1b51eSKate Stone                            "all specified in the same invocation");
1327594f14fSEnrico Granata         result.SetStatus(lldb::eReturnStatusFailed);
133b9c1b51eSKate Stone       } else {
134b9c1b51eSKate Stone         std::pair<bool, uint64_t> start_idx(
135b9c1b51eSKate Stone             m_options.m_start_idx.OptionWasSet(),
136b9c1b51eSKate Stone             m_options.m_start_idx.GetCurrentValue());
137b9c1b51eSKate Stone         std::pair<bool, uint64_t> stop_idx(
138b9c1b51eSKate Stone             m_options.m_stop_idx.OptionWasSet(),
139b9c1b51eSKate Stone             m_options.m_stop_idx.GetCurrentValue());
140b9c1b51eSKate Stone         std::pair<bool, uint64_t> count(m_options.m_count.OptionWasSet(),
141b9c1b51eSKate Stone                                         m_options.m_count.GetCurrentValue());
142a5a97ebeSJim Ingham 
1437594f14fSEnrico Granata         const CommandHistory &history(m_interpreter.GetCommandHistory());
1447594f14fSEnrico Granata 
145b9c1b51eSKate Stone         if (start_idx.first && start_idx.second == UINT64_MAX) {
146b9c1b51eSKate Stone           if (count.first) {
1477594f14fSEnrico Granata             start_idx.second = history.GetSize() - count.second;
1487594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
149b9c1b51eSKate Stone           } else if (stop_idx.first) {
1507594f14fSEnrico Granata             start_idx.second = stop_idx.second;
1517594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
152b9c1b51eSKate Stone           } else {
1537594f14fSEnrico Granata             start_idx.second = 0;
1547594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
1557594f14fSEnrico Granata           }
156b9c1b51eSKate Stone         } else {
157b9c1b51eSKate Stone           if (!start_idx.first && !stop_idx.first && !count.first) {
1587594f14fSEnrico Granata             start_idx.second = 0;
1597594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
160b9c1b51eSKate Stone           } else if (start_idx.first) {
161b9c1b51eSKate Stone             if (count.first) {
1627594f14fSEnrico Granata               stop_idx.second = start_idx.second + count.second - 1;
163b9c1b51eSKate Stone             } else if (!stop_idx.first) {
1647594f14fSEnrico Granata               stop_idx.second = history.GetSize() - 1;
1657594f14fSEnrico Granata             }
166b9c1b51eSKate Stone           } else if (stop_idx.first) {
167b9c1b51eSKate Stone             if (count.first) {
1687594f14fSEnrico Granata               if (stop_idx.second >= count.second)
1697594f14fSEnrico Granata                 start_idx.second = stop_idx.second - count.second + 1;
1707594f14fSEnrico Granata               else
1717594f14fSEnrico Granata                 start_idx.second = 0;
1727594f14fSEnrico Granata             }
173b9c1b51eSKate Stone           } else /* if (count.first) */
1747594f14fSEnrico Granata           {
1757594f14fSEnrico Granata             start_idx.second = 0;
1767594f14fSEnrico Granata             stop_idx.second = count.second - 1;
1777594f14fSEnrico Granata           }
1787594f14fSEnrico Granata         }
179b9c1b51eSKate Stone         history.Dump(result.GetOutputStream(), start_idx.second,
180b9c1b51eSKate Stone                      stop_idx.second);
1817594f14fSEnrico Granata       }
1827594f14fSEnrico Granata     }
183a5a97ebeSJim Ingham     return result.Succeeded();
184a5a97ebeSJim Ingham   }
1855a988416SJim Ingham 
1865a988416SJim Ingham   CommandOptions m_options;
187a5a97ebeSJim Ingham };
188a5a97ebeSJim Ingham 
189a5a97ebeSJim Ingham // CommandObjectCommandsSource
190a5a97ebeSJim Ingham 
1918fe53c49STatyana Krasnukha static constexpr OptionDefinition g_source_options[] = {
1921f0f5b5bSZachary Turner     // clang-format off
1938fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "stop-on-error",    'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true, stop executing commands on error." },
1948fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true, stop executing commands on continue." },
1958fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "silent-run",       's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "If true don't echo commands while executing." },
1961f0f5b5bSZachary Turner     // clang-format on
1971f0f5b5bSZachary Turner };
1981f0f5b5bSZachary Turner 
199b9c1b51eSKate Stone class CommandObjectCommandsSource : public CommandObjectParsed {
2005a988416SJim Ingham public:
2017428a18cSKate Stone   CommandObjectCommandsSource(CommandInterpreter &interpreter)
202b9c1b51eSKate Stone       : CommandObjectParsed(
203b9c1b51eSKate Stone             interpreter, "command source",
204b9c1b51eSKate Stone             "Read and execute LLDB commands from the file <filename>.",
2056e3d8e7fSEugene Zelenko             nullptr),
206b9c1b51eSKate Stone         m_options() {
2075a988416SJim Ingham     CommandArgumentEntry arg;
2085a988416SJim Ingham     CommandArgumentData file_arg;
2095a988416SJim Ingham 
2105a988416SJim Ingham     // Define the first (and only) variant of this arg.
2115a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
2125a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
2135a988416SJim Ingham 
214b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
215b9c1b51eSKate Stone     // argument entry.
2165a988416SJim Ingham     arg.push_back(file_arg);
2175a988416SJim Ingham 
2185a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
2195a988416SJim Ingham     m_arguments.push_back(arg);
2205a988416SJim Ingham   }
2215a988416SJim Ingham 
2226e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
2235a988416SJim Ingham 
224b9c1b51eSKate Stone   const char *GetRepeatCommand(Args &current_command_args,
225b9c1b51eSKate Stone                                uint32_t index) override {
2265a988416SJim Ingham     return "";
2275a988416SJim Ingham   }
2285a988416SJim Ingham 
2292443bbd4SRaphael Isemann   int HandleArgumentCompletion(
2302443bbd4SRaphael Isemann       CompletionRequest &request,
2312443bbd4SRaphael Isemann       OptionElementVector &opt_element_vector) override {
232b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
233b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
234a2e76c0bSRaphael Isemann         request, nullptr);
2351a6d7ab5SRaphael Isemann     return request.GetNumberOfMatches();
2365a988416SJim Ingham   }
2375a988416SJim Ingham 
238b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
2395a988416SJim Ingham 
2405a988416SJim Ingham protected:
241b9c1b51eSKate Stone   class CommandOptions : public Options {
242e16c50a1SJim Ingham   public:
243b9c1b51eSKate Stone     CommandOptions()
244b9c1b51eSKate Stone         : Options(), m_stop_on_error(true), m_silent_run(false),
245b9c1b51eSKate Stone           m_stop_on_continue(true) {}
246e16c50a1SJim Ingham 
2476e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
248e16c50a1SJim Ingham 
24997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
250b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
25197206d57SZachary Turner       Status error;
2523bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
253e16c50a1SJim Ingham 
254b9c1b51eSKate Stone       switch (short_option) {
255e16c50a1SJim Ingham       case 'e':
256fe11483bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_arg);
257e16c50a1SJim Ingham         break;
258340b0309SGreg Clayton 
259e16c50a1SJim Ingham       case 'c':
260fe11483bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_arg);
261e16c50a1SJim Ingham         break;
262340b0309SGreg Clayton 
26360986174SMichael Sartain       case 's':
264fe11483bSZachary Turner         error = m_silent_run.SetValueFromString(option_arg);
26560986174SMichael Sartain         break;
266340b0309SGreg Clayton 
267e16c50a1SJim Ingham       default:
268b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
269b9c1b51eSKate Stone                                        short_option);
270e16c50a1SJim Ingham         break;
271e16c50a1SJim Ingham       }
272e16c50a1SJim Ingham 
273e16c50a1SJim Ingham       return error;
274e16c50a1SJim Ingham     }
275e16c50a1SJim Ingham 
276b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
277012d4fcaSEnrico Granata       m_stop_on_error.Clear();
278340b0309SGreg Clayton       m_silent_run.Clear();
279340b0309SGreg Clayton       m_stop_on_continue.Clear();
280e16c50a1SJim Ingham     }
281e16c50a1SJim Ingham 
2821f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
28370602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
2841f0f5b5bSZachary Turner     }
285e16c50a1SJim Ingham 
286e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
287e16c50a1SJim Ingham 
288012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
289340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
290340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
291e16c50a1SJim Ingham   };
292e16c50a1SJim Ingham 
293b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
2944574a890SZachary Turner     if (command.GetArgumentCount() != 1) {
2954574a890SZachary Turner       result.AppendErrorWithFormat(
2964574a890SZachary Turner           "'%s' takes exactly one executable filename argument.\n",
2974574a890SZachary Turner           GetCommandName().str().c_str());
2984574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
2994574a890SZachary Turner       return false;
3004574a890SZachary Turner     }
301ebc09c36SJim Ingham 
3028f3be7a3SJonas Devlieghere     FileSpec cmd_file(command[0].ref);
3038f3be7a3SJonas Devlieghere     FileSystem::Instance().Resolve(cmd_file);
3046e3d8e7fSEugene Zelenko     ExecutionContext *exe_ctx = nullptr; // Just use the default context.
305ebc09c36SJim Ingham 
306340b0309SGreg Clayton     // If any options were set, then use them
307340b0309SGreg Clayton     if (m_options.m_stop_on_error.OptionWasSet() ||
308340b0309SGreg Clayton         m_options.m_silent_run.OptionWasSet() ||
309b9c1b51eSKate Stone         m_options.m_stop_on_continue.OptionWasSet()) {
310340b0309SGreg Clayton       // Use user set settings
31126c7bf93SJim Ingham       CommandInterpreterRunOptions options;
312*1c19b74cSJonas Devlieghere 
313*1c19b74cSJonas Devlieghere       if (m_options.m_stop_on_continue.OptionWasSet())
314*1c19b74cSJonas Devlieghere         options.SetStopOnContinue(
315*1c19b74cSJonas Devlieghere             m_options.m_stop_on_continue.GetCurrentValue());
316*1c19b74cSJonas Devlieghere 
317*1c19b74cSJonas Devlieghere       if (m_options.m_stop_on_error.OptionWasSet())
31826c7bf93SJim Ingham         options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
319c678ed77SStefan Granitz 
320c678ed77SStefan Granitz       // Individual silent setting is override for global command echo settings.
321c678ed77SStefan Granitz       if (m_options.m_silent_run.GetCurrentValue()) {
322c678ed77SStefan Granitz         options.SetSilent(true);
323c678ed77SStefan Granitz       } else {
324c678ed77SStefan Granitz         options.SetPrintResults(true);
325c678ed77SStefan Granitz         options.SetEchoCommands(m_interpreter.GetEchoCommands());
326c678ed77SStefan Granitz         options.SetEchoCommentCommands(m_interpreter.GetEchoCommentCommands());
327c678ed77SStefan Granitz       }
32826c7bf93SJim Ingham 
3294574a890SZachary Turner       m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, result);
330b9c1b51eSKate Stone     } else {
33105097246SAdrian Prantl       // No options were set, inherit any settings from nested "command source"
33205097246SAdrian Prantl       // commands, or set to sane default settings...
33326c7bf93SJim Ingham       CommandInterpreterRunOptions options;
3344574a890SZachary Turner       m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, result);
335ebc09c36SJim Ingham     }
336ebc09c36SJim Ingham     return result.Succeeded();
337ebc09c36SJim Ingham   }
3386e3d8e7fSEugene Zelenko 
3395a988416SJim Ingham   CommandOptions m_options;
340ebc09c36SJim Ingham };
341ebc09c36SJim Ingham 
342ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
343ebc09c36SJim Ingham // CommandObjectCommandsAlias
344ebc09c36SJim Ingham 
3458fe53c49STatyana Krasnukha static constexpr OptionDefinition g_alias_options[] = {
3461f0f5b5bSZachary Turner     // clang-format off
3478fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "help",      'h', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeHelpText, "Help text for this command" },
3488fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeHelpText, "Long help text for this command" },
3491f0f5b5bSZachary Turner     // clang-format on
3501f0f5b5bSZachary Turner };
3511f0f5b5bSZachary Turner 
352b9c1b51eSKate Stone static const char *g_python_command_instructions =
353b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
354be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
35544d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
356be93a35aSEnrico Granata 
357b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
35845d0e238SEnrico Granata protected:
359b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
360ebc09c36SJim Ingham   public:
361b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
36245d0e238SEnrico Granata 
36345d0e238SEnrico Granata     ~CommandOptions() override = default;
36445d0e238SEnrico Granata 
3651f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
36670602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
3671f0f5b5bSZachary Turner     }
36845d0e238SEnrico Granata 
36997206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
370b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
37197206d57SZachary Turner       Status error;
37245d0e238SEnrico Granata 
3731f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
3748cef4b0bSZachary Turner       std::string option_str(option_value);
37545d0e238SEnrico Granata 
376b9c1b51eSKate Stone       switch (short_option) {
37745d0e238SEnrico Granata       case 'h':
3788cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
37945d0e238SEnrico Granata         m_help.SetOptionWasSet();
38045d0e238SEnrico Granata         break;
38145d0e238SEnrico Granata 
38245d0e238SEnrico Granata       case 'H':
3838cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
38445d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
38545d0e238SEnrico Granata         break;
38645d0e238SEnrico Granata 
38745d0e238SEnrico Granata       default:
388b9c1b51eSKate Stone         error.SetErrorStringWithFormat("invalid short option character '%c'",
389b9c1b51eSKate Stone                                        short_option);
39045d0e238SEnrico Granata         break;
39145d0e238SEnrico Granata       }
39245d0e238SEnrico Granata 
39345d0e238SEnrico Granata       return error;
39445d0e238SEnrico Granata     }
39545d0e238SEnrico Granata 
396b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
39745d0e238SEnrico Granata       m_help.Clear();
39845d0e238SEnrico Granata       m_long_help.Clear();
39945d0e238SEnrico Granata     }
40045d0e238SEnrico Granata 
40145d0e238SEnrico Granata     OptionValueString m_help;
40245d0e238SEnrico Granata     OptionValueString m_long_help;
40345d0e238SEnrico Granata   };
40445d0e238SEnrico Granata 
40545d0e238SEnrico Granata   OptionGroupOptions m_option_group;
40645d0e238SEnrico Granata   CommandOptions m_command_options;
40745d0e238SEnrico Granata 
40845d0e238SEnrico Granata public:
409b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
41045d0e238SEnrico Granata 
4117428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
412b9c1b51eSKate Stone       : CommandObjectRaw(
413b9c1b51eSKate Stone             interpreter, "command alias",
414a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
415b9c1b51eSKate Stone         m_option_group(), m_command_options() {
41645d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
41745d0e238SEnrico Granata     m_option_group.Finalize();
41845d0e238SEnrico Granata 
419ebc09c36SJim Ingham     SetHelpLong(
420ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
421ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
422b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
423b9c1b51eSKate Stone         R"(
424ea671fbdSKate Stone 
425ea671fbdSKate Stone (lldb) command alias sc script
426ea671fbdSKate Stone 
427ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
428ea671fbdSKate Stone 
429ea671fbdSKate Stone (lldb) command alias bp breakpoint
430ea671fbdSKate Stone 
431b9c1b51eSKate Stone )"
432b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
433ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
434b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
435b9c1b51eSKate Stone         R"(
436ea671fbdSKate Stone 
437ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
438ea671fbdSKate Stone 
439ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
440ea671fbdSKate Stone 
441b9c1b51eSKate Stone )"
442b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
443ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
444ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
445b9c1b51eSKate Stone shows how to create aliases with options:"
446b9c1b51eSKate Stone         R"(
447ea671fbdSKate Stone 
448ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
449ea671fbdSKate Stone 
450b9c1b51eSKate Stone )"
451b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
452ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
453ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
454ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
455ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
456ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
457ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
458ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
459ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
460ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
461b9c1b51eSKate Stone launch' example below)."
462b9c1b51eSKate Stone         R"(
463ea671fbdSKate Stone 
464b9c1b51eSKate Stone )"
465b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
466ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
467b9c1b51eSKate Stone \".cpp\":"
468b9c1b51eSKate Stone         R"(
469ea671fbdSKate Stone 
470ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
471ea671fbdSKate Stone 
472b9c1b51eSKate Stone )"
473b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
474ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
475ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
476b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
477b9c1b51eSKate Stone         R"(
478ea671fbdSKate Stone 
479ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
480ea671fbdSKate Stone (lldb) bfl my-file.c 137
481ea671fbdSKate Stone 
482ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
483ea671fbdSKate Stone 
484ea671fbdSKate Stone Another example:
485ea671fbdSKate Stone 
486ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
487ea671fbdSKate Stone (lldb) pltty /dev/tty0
488ea671fbdSKate Stone 
489ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
490ea671fbdSKate Stone 
491b9c1b51eSKate Stone )"
492b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
493ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
494b9c1b51eSKate Stone rather than using a positional placeholder:"
495b9c1b51eSKate Stone         R"(
496ea671fbdSKate Stone 
497ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
498ea671fbdSKate Stone 
499b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
500ebc09c36SJim Ingham 
501405fe67fSCaroline Tice     CommandArgumentEntry arg1;
502405fe67fSCaroline Tice     CommandArgumentEntry arg2;
503405fe67fSCaroline Tice     CommandArgumentEntry arg3;
504405fe67fSCaroline Tice     CommandArgumentData alias_arg;
505405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
506405fe67fSCaroline Tice     CommandArgumentData options_arg;
507405fe67fSCaroline Tice 
508405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
509405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
510405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
511405fe67fSCaroline Tice 
512b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
513b9c1b51eSKate Stone     // argument entry.
514405fe67fSCaroline Tice     arg1.push_back(alias_arg);
515405fe67fSCaroline Tice 
516405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
517405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
518405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
519405fe67fSCaroline Tice 
520b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
521b9c1b51eSKate Stone     // argument entry.
522405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
523405fe67fSCaroline Tice 
524405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
525405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
526405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
527405fe67fSCaroline Tice 
528b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
529b9c1b51eSKate Stone     // argument entry.
530405fe67fSCaroline Tice     arg3.push_back(options_arg);
531405fe67fSCaroline Tice 
532405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
533405fe67fSCaroline Tice     m_arguments.push_back(arg1);
534405fe67fSCaroline Tice     m_arguments.push_back(arg2);
535405fe67fSCaroline Tice     m_arguments.push_back(arg3);
536ebc09c36SJim Ingham   }
537ebc09c36SJim Ingham 
5386e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
539ebc09c36SJim Ingham 
5405a988416SJim Ingham protected:
5414d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
542b9c1b51eSKate Stone                  CommandReturnObject &result) override {
5434d51a902SRaphael Isemann     if (raw_command_line.empty()) {
544d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
54545d0e238SEnrico Granata       return false;
54645d0e238SEnrico Granata     }
54745d0e238SEnrico Granata 
548e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
549e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
55045d0e238SEnrico Granata 
5513a0e1270SRaphael Isemann     OptionsWithRaw args_with_suffix(raw_command_line);
5523a0e1270SRaphael Isemann     const char *remainder = args_with_suffix.GetRawPart().c_str();
55345d0e238SEnrico Granata 
5543a0e1270SRaphael Isemann     if (args_with_suffix.HasArgs())
5553a0e1270SRaphael Isemann       if (!ParseOptionsAndNotify(args_with_suffix.GetArgs(), result,
5563a0e1270SRaphael Isemann                                  m_option_group, exe_ctx))
55745d0e238SEnrico Granata         return false;
55845d0e238SEnrico Granata 
559a01bccdbSZachary Turner     llvm::StringRef raw_command_string(remainder);
560a01bccdbSZachary Turner     Args args(raw_command_string);
561844d2303SCaroline Tice 
56211eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
563d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
564844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
565844d2303SCaroline Tice       return false;
566844d2303SCaroline Tice     }
567844d2303SCaroline Tice 
568844d2303SCaroline Tice     // Get the alias command.
569844d2303SCaroline Tice 
5704574a890SZachary Turner     auto alias_command = args[0].ref;
5714574a890SZachary Turner     if (alias_command.startswith("-")) {
572d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
573b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
574b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
575b9c1b51eSKate Stone                              "a -- at the end of the options");
576d72e412fSEnrico Granata       }
577d72e412fSEnrico Granata       result.SetStatus(eReturnStatusFailed);
578d72e412fSEnrico Granata       return false;
579d72e412fSEnrico Granata     }
580844d2303SCaroline Tice 
581b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
58205097246SAdrian Prantl     // which gets passed to 'Execute', which does the stripping itself.
583844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
584b9c1b51eSKate Stone     if (pos == 0) {
585844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
586844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
587844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
588844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
589b9c1b51eSKate Stone     } else {
590844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
591844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
592844d2303SCaroline Tice       return false;
593844d2303SCaroline Tice     }
594844d2303SCaroline Tice 
595844d2303SCaroline Tice     // Verify that the command is alias-able.
596771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
597b9c1b51eSKate Stone       result.AppendErrorWithFormat(
598b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
5994574a890SZachary Turner           args[0].c_str());
600844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
601844d2303SCaroline Tice       return false;
602844d2303SCaroline Tice     }
603844d2303SCaroline Tice 
604b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
605a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
606a01bccdbSZachary Turner     // name of the command object stripped off the front.
607a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
608b9c1b51eSKate Stone     CommandObject *cmd_obj =
609b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
610844d2303SCaroline Tice 
611b9c1b51eSKate Stone     if (!cmd_obj) {
612b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
613b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
614b9c1b51eSKate Stone                                    "  No alias created.",
615a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
616844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
617844d2303SCaroline Tice       return false;
618b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
619b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
62005097246SAdrian Prantl       // been updated to this point. Therefore can we pass it to the version of
62105097246SAdrian Prantl       // Execute that does not need/expect raw input in the alias.
6225a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
623b9c1b51eSKate Stone     } else {
624b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
625b9c1b51eSKate Stone                                       *cmd_obj, result);
6265a988416SJim Ingham     }
6275a988416SJim Ingham     return result.Succeeded();
6285a988416SJim Ingham   }
6295a988416SJim Ingham 
630a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
631a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
632b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
633b9c1b51eSKate Stone                                 CommandReturnObject &result) {
634844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
635844d2303SCaroline Tice 
636b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
637b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
638844d2303SCaroline Tice 
639b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
640b9c1b51eSKate Stone             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) {
641a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
642a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
643b9c1b51eSKate Stone         result.AppendWarningWithFormat(
644b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
645a01bccdbSZachary Turner             alias_command.str().c_str());
646844d2303SCaroline Tice       }
647b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
648a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
64945d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
65045d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
65145d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
65245d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
653844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
654b9c1b51eSKate Stone       } else {
655472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
656472362e6SCaroline Tice         result.SetStatus(eReturnStatusFailed);
657472362e6SCaroline Tice       }
658212130acSEnrico Granata 
659b9c1b51eSKate Stone     } else {
660212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
661212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
662212130acSEnrico Granata     }
663212130acSEnrico Granata 
664844d2303SCaroline Tice     return result.Succeeded();
665844d2303SCaroline Tice   }
666ebc09c36SJim Ingham 
667b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
668867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
669ebc09c36SJim Ingham 
670b9c1b51eSKate Stone     if (argc < 2) {
671d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
672ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
673ebc09c36SJim Ingham       return false;
674ebc09c36SJim Ingham     }
675ebc09c36SJim Ingham 
6764574a890SZachary Turner     // Save these in std::strings since we're going to shift them off.
6774574a890SZachary Turner     const std::string alias_command(args[0].ref);
6784574a890SZachary Turner     const std::string actual_command(args[1].ref);
679ebc09c36SJim Ingham 
680ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
681ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
682ebc09c36SJim Ingham 
683b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
684b9c1b51eSKate Stone     // object.
685ebc09c36SJim Ingham 
686771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
687b9c1b51eSKate Stone       result.AppendErrorWithFormat(
688b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
689ebc09c36SJim Ingham           alias_command.c_str());
690ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
6914574a890SZachary Turner       return false;
6924574a890SZachary Turner     }
6934574a890SZachary Turner 
694b9c1b51eSKate Stone     CommandObjectSP command_obj_sp(
695a449698cSZachary Turner         m_interpreter.GetCommandSPExact(actual_command, true));
696ebc09c36SJim Ingham     CommandObjectSP subcommand_obj_sp;
697ebc09c36SJim Ingham     bool use_subcommand = false;
6984574a890SZachary Turner     if (!command_obj_sp) {
6994574a890SZachary Turner       result.AppendErrorWithFormat("'%s' is not an existing command.\n",
7004574a890SZachary Turner                                    actual_command.c_str());
7014574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
7024574a890SZachary Turner       return false;
7034574a890SZachary Turner     }
704ebc09c36SJim Ingham     CommandObject *cmd_obj = command_obj_sp.get();
7056e3d8e7fSEugene Zelenko     CommandObject *sub_cmd_obj = nullptr;
706b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
707b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
708ebc09c36SJim Ingham 
70911eb9c64SZachary Turner     while (cmd_obj->IsMultiwordObject() && !args.empty()) {
7104574a890SZachary Turner       auto sub_command = args[0].ref;
71111eb9c64SZachary Turner       assert(!sub_command.empty());
7124574a890SZachary Turner       subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
7134574a890SZachary Turner       if (!subcommand_obj_sp) {
714b9c1b51eSKate Stone         result.AppendErrorWithFormat(
715b9c1b51eSKate Stone             "'%s' is not a valid sub-command of '%s'.  "
716f415eeb4SCaroline Tice             "Unable to create alias.\n",
7174574a890SZachary Turner             args[0].c_str(), actual_command.c_str());
718ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
719ebc09c36SJim Ingham         return false;
720ebc09c36SJim Ingham       }
7214574a890SZachary Turner 
7224574a890SZachary Turner       sub_cmd_obj = subcommand_obj_sp.get();
7234574a890SZachary Turner       use_subcommand = true;
7244574a890SZachary Turner       args.Shift(); // Shift the sub_command word off the argument vector.
7254574a890SZachary Turner       cmd_obj = sub_cmd_obj;
726ebc09c36SJim Ingham     }
727ebc09c36SJim Ingham 
728ebc09c36SJim Ingham     // Verify & handle any options/arguments passed to the alias command
729ebc09c36SJim Ingham 
730212130acSEnrico Granata     std::string args_string;
731212130acSEnrico Granata 
73211eb9c64SZachary Turner     if (!args.empty()) {
733b9c1b51eSKate Stone       CommandObjectSP tmp_sp =
734b9c1b51eSKate Stone           m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false);
735ebc09c36SJim Ingham       if (use_subcommand)
7364574a890SZachary Turner         tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName(),
7374574a890SZachary Turner                                                  false);
738ca90c47eSCaroline Tice 
739ca90c47eSCaroline Tice       args.GetCommandString(args_string);
740867b185dSCaroline Tice     }
741ebc09c36SJim Ingham 
742771ef6d4SMalcolm Parsons     if (m_interpreter.AliasExists(alias_command) ||
743771ef6d4SMalcolm Parsons         m_interpreter.UserCommandExists(alias_command)) {
744b9c1b51eSKate Stone       result.AppendWarningWithFormat(
7454574a890SZachary Turner           "Overwriting existing definition for '%s'.\n", alias_command.c_str());
746ebc09c36SJim Ingham     }
747ebc09c36SJim Ingham 
748b9c1b51eSKate Stone     if (CommandAlias *alias = m_interpreter.AddAlias(
7494574a890SZachary Turner             alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
750771ef6d4SMalcolm Parsons             args_string)) {
75145d0e238SEnrico Granata       if (m_command_options.m_help.OptionWasSet())
75245d0e238SEnrico Granata         alias->SetHelp(m_command_options.m_help.GetCurrentValue());
75345d0e238SEnrico Granata       if (m_command_options.m_long_help.OptionWasSet())
75445d0e238SEnrico Granata         alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
755ebc09c36SJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
756b9c1b51eSKate Stone     } else {
757212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
758212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
759212130acSEnrico Granata       return false;
760212130acSEnrico Granata     }
761ebc09c36SJim Ingham 
762ebc09c36SJim Ingham     return result.Succeeded();
763ebc09c36SJim Ingham   }
764ebc09c36SJim Ingham };
765ebc09c36SJim Ingham 
766ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
767ebc09c36SJim Ingham // CommandObjectCommandsUnalias
768ebc09c36SJim Ingham 
769b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
770ebc09c36SJim Ingham public:
7717428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
772b9c1b51eSKate Stone       : CommandObjectParsed(
773b9c1b51eSKate Stone             interpreter, "command unalias",
774b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
775b9c1b51eSKate Stone             nullptr) {
776405fe67fSCaroline Tice     CommandArgumentEntry arg;
777405fe67fSCaroline Tice     CommandArgumentData alias_arg;
778405fe67fSCaroline Tice 
779405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
780405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
781405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
782405fe67fSCaroline Tice 
783b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
784b9c1b51eSKate Stone     // argument entry.
785405fe67fSCaroline Tice     arg.push_back(alias_arg);
786405fe67fSCaroline Tice 
787405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
788405fe67fSCaroline Tice     m_arguments.push_back(arg);
789ebc09c36SJim Ingham   }
790ebc09c36SJim Ingham 
7916e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
792ebc09c36SJim Ingham 
7935a988416SJim Ingham protected:
794b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
795ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
796ebc09c36SJim Ingham     CommandObject *cmd_obj;
797ebc09c36SJim Ingham 
79811eb9c64SZachary Turner     if (args.empty()) {
79911eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
80011eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
80111eb9c64SZachary Turner       return false;
80211eb9c64SZachary Turner     }
80311eb9c64SZachary Turner 
8044574a890SZachary Turner     auto command_name = args[0].ref;
805a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
8064574a890SZachary Turner     if (!cmd_obj) {
8074574a890SZachary Turner       result.AppendErrorWithFormat(
8084574a890SZachary Turner           "'%s' is not a known command.\nTry 'help' to see a "
8094574a890SZachary Turner           "current list of commands.\n",
810867e7d17SZachary Turner           args[0].c_str());
8114574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
8124574a890SZachary Turner       return false;
8134574a890SZachary Turner     }
8144574a890SZachary Turner 
815b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
816b9c1b51eSKate Stone       if (cmd_obj->IsRemovable()) {
817b9c1b51eSKate Stone         result.AppendErrorWithFormat(
818b9c1b51eSKate Stone             "'%s' is not an alias, it is a debugger command which can be "
819b9c1b51eSKate Stone             "removed using the 'command delete' command.\n",
820867e7d17SZachary Turner             args[0].c_str());
821b9c1b51eSKate Stone       } else {
822b9c1b51eSKate Stone         result.AppendErrorWithFormat(
823b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
824867e7d17SZachary Turner             args[0].c_str());
825b547278cSGreg Clayton       }
826ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
8274574a890SZachary Turner       return false;
8284574a890SZachary Turner     }
8294574a890SZachary Turner 
830b9c1b51eSKate Stone     if (!m_interpreter.RemoveAlias(command_name)) {
831a7015092SGreg Clayton       if (m_interpreter.AliasExists(command_name))
832b9c1b51eSKate Stone         result.AppendErrorWithFormat(
833867e7d17SZachary Turner             "Error occurred while attempting to unalias '%s'.\n",
834867e7d17SZachary Turner             args[0].c_str());
835ebc09c36SJim Ingham       else
836b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
837867e7d17SZachary Turner                                      args[0].c_str());
838ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
8394574a890SZachary Turner       return false;
840ebc09c36SJim Ingham     }
841ebc09c36SJim Ingham 
8424574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
843ebc09c36SJim Ingham     return result.Succeeded();
844ebc09c36SJim Ingham   }
845ebc09c36SJim Ingham };
846ebc09c36SJim Ingham 
847b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
848b547278cSGreg Clayton // CommandObjectCommandsDelete
849b547278cSGreg Clayton 
850b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
851b547278cSGreg Clayton public:
8527428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
853b9c1b51eSKate Stone       : CommandObjectParsed(
854b9c1b51eSKate Stone             interpreter, "command delete",
855b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
856b9c1b51eSKate Stone             nullptr) {
857b547278cSGreg Clayton     CommandArgumentEntry arg;
858b547278cSGreg Clayton     CommandArgumentData alias_arg;
859b547278cSGreg Clayton 
860b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
861b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
862b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
863b547278cSGreg Clayton 
864b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
865b9c1b51eSKate Stone     // argument entry.
866b547278cSGreg Clayton     arg.push_back(alias_arg);
867b547278cSGreg Clayton 
868b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
869b547278cSGreg Clayton     m_arguments.push_back(arg);
870b547278cSGreg Clayton   }
871b547278cSGreg Clayton 
8726e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
873b547278cSGreg Clayton 
874b547278cSGreg Clayton protected:
875b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
876b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
877b547278cSGreg Clayton 
87811eb9c64SZachary Turner     if (args.empty()) {
87911eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
88011eb9c64SZachary Turner                                    "defined regular expression command names",
881a449698cSZachary Turner                                    GetCommandName().str().c_str());
88211eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
88311eb9c64SZachary Turner     }
88411eb9c64SZachary Turner 
8854574a890SZachary Turner     auto command_name = args[0].ref;
8864574a890SZachary Turner     if (!m_interpreter.CommandExists(command_name)) {
88746d4aa21SEnrico Granata       StreamString error_msg_stream;
888d5b44036SJonas Devlieghere       const bool generate_upropos = true;
88946d4aa21SEnrico Granata       const bool generate_type_lookup = false;
890b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
8914574a890SZachary Turner           &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
892d5b44036SJonas Devlieghere           generate_upropos, generate_type_lookup);
893c156427dSZachary Turner       result.AppendError(error_msg_stream.GetString());
894b547278cSGreg Clayton       result.SetStatus(eReturnStatusFailed);
8954574a890SZachary Turner       return false;
896b547278cSGreg Clayton     }
897b547278cSGreg Clayton 
8984574a890SZachary Turner     if (!m_interpreter.RemoveCommand(command_name)) {
8994574a890SZachary Turner       result.AppendErrorWithFormat(
9004574a890SZachary Turner           "'%s' is a permanent debugger command and cannot be removed.\n",
901867e7d17SZachary Turner           args[0].c_str());
9024574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
9034574a890SZachary Turner       return false;
9044574a890SZachary Turner     }
9054574a890SZachary Turner 
9064574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
9074574a890SZachary Turner     return true;
908b547278cSGreg Clayton   }
909b547278cSGreg Clayton };
910b547278cSGreg Clayton 
911de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
9121f0f5b5bSZachary Turner 
9138fe53c49STatyana Krasnukha static constexpr OptionDefinition g_regex_options[] = {
9141f0f5b5bSZachary Turner     // clang-format off
9158fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "help"  , 'h', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "The help text to display for this command." },
9168fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "A syntax string showing the typical usage syntax." },
9171f0f5b5bSZachary Turner     // clang-format on
9181f0f5b5bSZachary Turner };
9191f0f5b5bSZachary Turner 
9205a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
921de164aaaSGreg Clayton 
922b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
923b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
924de164aaaSGreg Clayton public:
9257428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
926b9c1b51eSKate Stone       : CommandObjectParsed(
927b9c1b51eSKate Stone             interpreter, "command regex", "Define a custom command in terms of "
928b9c1b51eSKate Stone                                           "existing commands by matching "
929b9c1b51eSKate Stone                                           "regular expressions.",
9300e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
931b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
932b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
933b9c1b51eSKate Stone         m_options() {
934b9c1b51eSKate Stone     SetHelpLong(
935b9c1b51eSKate Stone         R"(
936b9c1b51eSKate Stone )"
937b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
938ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
939b9c1b51eSKate Stone using the regular expression substitution format of:"
940b9c1b51eSKate Stone         R"(
941ea671fbdSKate Stone 
942ea671fbdSKate Stone     s/<regex>/<subst>/
943ea671fbdSKate Stone 
944b9c1b51eSKate Stone )"
945b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
946ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
947b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
948b9c1b51eSKate Stone         R"(
949ea671fbdSKate Stone 
950b9c1b51eSKate Stone )"
951b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
952ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
953ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
954b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
955b9c1b51eSKate Stone         R"(
956ea671fbdSKate Stone 
957ea671fbdSKate Stone EXAMPLES
958ea671fbdSKate Stone 
959b9c1b51eSKate Stone )"
960b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
961ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
962b9c1b51eSKate Stone a number follows 'f':"
963b9c1b51eSKate Stone         R"(
964ea671fbdSKate Stone 
965b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
966de164aaaSGreg Clayton   }
967de164aaaSGreg Clayton 
9686e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
969de164aaaSGreg Clayton 
9705a988416SJim Ingham protected:
9710affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
97244d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
9730affb582SDave Lee     if (output_sp && interactive) {
9740affb582SDave Lee       output_sp->PutCString("Enter one or more sed substitution commands in "
975b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
976b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
97744d93782SGreg Clayton       output_sp->Flush();
97844d93782SGreg Clayton     }
97944d93782SGreg Clayton   }
98044d93782SGreg Clayton 
981b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
982b9c1b51eSKate Stone                               std::string &data) override {
98344d93782SGreg Clayton     io_handler.SetIsDone(true);
984d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
98544d93782SGreg Clayton       StringList lines;
986b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
98744d93782SGreg Clayton         const size_t num_lines = lines.GetSize();
98844d93782SGreg Clayton         bool check_only = false;
989b9c1b51eSKate Stone         for (size_t i = 0; i < num_lines; ++i) {
99044d93782SGreg Clayton           llvm::StringRef bytes_strref(lines[i]);
99197206d57SZachary Turner           Status error = AppendRegexSubstitution(bytes_strref, check_only);
992b9c1b51eSKate Stone           if (error.Fail()) {
99357179860SJonas Devlieghere             if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode()) {
99457179860SJonas Devlieghere               StreamSP out_stream = GetDebugger().GetAsyncOutputStream();
99544d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
99644d93782SGreg Clayton             }
99744d93782SGreg Clayton           }
99844d93782SGreg Clayton         }
99944d93782SGreg Clayton       }
1000d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
1001d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
100244d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
100344d93782SGreg Clayton       }
100444d93782SGreg Clayton     }
100544d93782SGreg Clayton   }
100644d93782SGreg Clayton 
1007b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
10085a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
1009b9c1b51eSKate Stone     if (argc == 0) {
1010b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
1011b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
10120e5e5a79SGreg Clayton       result.SetStatus(eReturnStatusFailed);
101311eb9c64SZachary Turner       return false;
101411eb9c64SZachary Turner     }
101511eb9c64SZachary Turner 
101697206d57SZachary Turner     Status error;
10174574a890SZachary Turner     auto name = command[0].ref;
1018d5b44036SJonas Devlieghere     m_regex_cmd_up = llvm::make_unique<CommandObjectRegexCommand>(
10194574a890SZachary Turner         m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0,
10204574a890SZachary Turner         true);
10210e5e5a79SGreg Clayton 
1022b9c1b51eSKate Stone     if (argc == 1) {
102357179860SJonas Devlieghere       Debugger &debugger = GetDebugger();
1024e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
102544d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
1026b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
1027b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
102873d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
1029514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
1030514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
1031b9c1b51eSKate Stone           multiple_lines, color_prompt,
1032f6913cd7SGreg Clayton           0, // Don't show line numbers
1033d77c2e09SJonas Devlieghere           *this, nullptr));
103444d93782SGreg Clayton 
1035b9c1b51eSKate Stone       if (io_handler_sp) {
103644d93782SGreg Clayton         debugger.PushIOHandler(io_handler_sp);
1037de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1038de164aaaSGreg Clayton       }
1039b9c1b51eSKate Stone     } else {
104097d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
104144d93782SGreg Clayton         bool check_only = false;
104297d2c401SZachary Turner         error = AppendRegexSubstitution(entry.ref, check_only);
10430e5e5a79SGreg Clayton         if (error.Fail())
10440e5e5a79SGreg Clayton           break;
10450e5e5a79SGreg Clayton       }
10460e5e5a79SGreg Clayton 
1047b9c1b51eSKate Stone       if (error.Success()) {
10480e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
10490e5e5a79SGreg Clayton       }
10500e5e5a79SGreg Clayton     }
1051b9c1b51eSKate Stone     if (error.Fail()) {
10520e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
1053de164aaaSGreg Clayton       result.SetStatus(eReturnStatusFailed);
1054de164aaaSGreg Clayton     }
10550e5e5a79SGreg Clayton 
1056de164aaaSGreg Clayton     return result.Succeeded();
1057de164aaaSGreg Clayton   }
1058de164aaaSGreg Clayton 
105997206d57SZachary Turner   Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
1060b9c1b51eSKate Stone                                  bool check_only) {
106197206d57SZachary Turner     Status error;
10620e5e5a79SGreg Clayton 
1063d5b44036SJonas Devlieghere     if (!m_regex_cmd_up) {
1064b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1065b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
1066b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10670e5e5a79SGreg Clayton       return error;
1068de164aaaSGreg Clayton     }
10690e5e5a79SGreg Clayton 
10700e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
10710e5e5a79SGreg Clayton 
1072b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
1073b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1074b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
1075b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10760e5e5a79SGreg Clayton       return error;
10770e5e5a79SGreg Clayton     }
10780e5e5a79SGreg Clayton 
1079b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
1080b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
1081b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
1082b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
10830e5e5a79SGreg Clayton       return error;
10840e5e5a79SGreg Clayton     }
10850e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
108605097246SAdrian Prantl     // use the char that follows 's' as the regex separator character so we can
108705097246SAdrian Prantl     // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
10880e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
1089b9c1b51eSKate Stone     const size_t second_separator_char_pos =
1090b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
10910e5e5a79SGreg Clayton 
1092b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
1093b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1094b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
10950e5e5a79SGreg Clayton           separator_char,
10960e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
1097ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
1098b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10990e5e5a79SGreg Clayton       return error;
11000e5e5a79SGreg Clayton     }
11010e5e5a79SGreg Clayton 
1102b9c1b51eSKate Stone     const size_t third_separator_char_pos =
1103b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
11040e5e5a79SGreg Clayton 
1105b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
1106b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1107b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
11080e5e5a79SGreg Clayton           separator_char,
11090e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
1110ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
1111b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11120e5e5a79SGreg Clayton       return error;
11130e5e5a79SGreg Clayton     }
11140e5e5a79SGreg Clayton 
1115b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
111605097246SAdrian Prantl       // Make sure that everything that follows the last regex separator char
1117b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
1118b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
1119b9c1b51eSKate Stone           std::string::npos) {
1120b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
1121b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
1122b9c1b51eSKate Stone             "string: '%.*s'",
1123b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
11240e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
11250e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
11260e5e5a79SGreg Clayton         return error;
11270e5e5a79SGreg Clayton       }
1128b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
1129b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1130b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1131b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11320e5e5a79SGreg Clayton           regex_sed.data());
11330e5e5a79SGreg Clayton       return error;
1134b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
1135b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1136b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1137b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11380e5e5a79SGreg Clayton           regex_sed.data());
11390e5e5a79SGreg Clayton       return error;
11400e5e5a79SGreg Clayton     }
114144d93782SGreg Clayton 
1142b9c1b51eSKate Stone     if (!check_only) {
1143b9c1b51eSKate Stone       std::string regex(regex_sed.substr(first_separator_char_pos + 1,
1144b9c1b51eSKate Stone                                          second_separator_char_pos -
1145b9c1b51eSKate Stone                                              first_separator_char_pos - 1));
1146b9c1b51eSKate Stone       std::string subst(regex_sed.substr(second_separator_char_pos + 1,
1147b9c1b51eSKate Stone                                          third_separator_char_pos -
1148b9c1b51eSKate Stone                                              second_separator_char_pos - 1));
1149d5b44036SJonas Devlieghere       m_regex_cmd_up->AddRegexCommand(regex.c_str(), subst.c_str());
115044d93782SGreg Clayton     }
11510e5e5a79SGreg Clayton     return error;
1152de164aaaSGreg Clayton   }
1153de164aaaSGreg Clayton 
1154b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1155d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
1156d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
1157d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
1158de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1159de164aaaSGreg Clayton       }
1160de164aaaSGreg Clayton     }
1161de164aaaSGreg Clayton   }
1162de164aaaSGreg Clayton 
1163de164aaaSGreg Clayton private:
1164d5b44036SJonas Devlieghere   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up;
1165de164aaaSGreg Clayton 
1166b9c1b51eSKate Stone   class CommandOptions : public Options {
1167de164aaaSGreg Clayton   public:
1168b9c1b51eSKate Stone     CommandOptions() : Options() {}
1169de164aaaSGreg Clayton 
11706e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1171de164aaaSGreg Clayton 
117297206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1173b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
117497206d57SZachary Turner       Status error;
11753bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1176de164aaaSGreg Clayton 
1177b9c1b51eSKate Stone       switch (short_option) {
1178de164aaaSGreg Clayton       case 'h':
1179de164aaaSGreg Clayton         m_help.assign(option_arg);
1180de164aaaSGreg Clayton         break;
1181de164aaaSGreg Clayton       case 's':
1182de164aaaSGreg Clayton         m_syntax.assign(option_arg);
1183de164aaaSGreg Clayton         break;
1184de164aaaSGreg Clayton       default:
1185b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1186b9c1b51eSKate Stone                                        short_option);
1187de164aaaSGreg Clayton         break;
1188de164aaaSGreg Clayton       }
1189de164aaaSGreg Clayton 
1190de164aaaSGreg Clayton       return error;
1191de164aaaSGreg Clayton     }
1192de164aaaSGreg Clayton 
1193b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1194de164aaaSGreg Clayton       m_help.clear();
1195de164aaaSGreg Clayton       m_syntax.clear();
1196de164aaaSGreg Clayton     }
1197de164aaaSGreg Clayton 
11981f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
119970602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
12001f0f5b5bSZachary Turner     }
1201de164aaaSGreg Clayton 
120211eb9c64SZachary Turner     // TODO: Convert these functions to return StringRefs.
1203b9c1b51eSKate Stone     const char *GetHelp() {
12046e3d8e7fSEugene Zelenko       return (m_help.empty() ? nullptr : m_help.c_str());
1205de164aaaSGreg Clayton     }
12066e3d8e7fSEugene Zelenko 
1207b9c1b51eSKate Stone     const char *GetSyntax() {
12086e3d8e7fSEugene Zelenko       return (m_syntax.empty() ? nullptr : m_syntax.c_str());
1209de164aaaSGreg Clayton     }
12106e3d8e7fSEugene Zelenko 
1211de164aaaSGreg Clayton   protected:
12126e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
12136e3d8e7fSEugene Zelenko 
1214de164aaaSGreg Clayton     std::string m_help;
1215de164aaaSGreg Clayton     std::string m_syntax;
1216de164aaaSGreg Clayton   };
1217de164aaaSGreg Clayton 
1218b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1219de164aaaSGreg Clayton 
12205a988416SJim Ingham   CommandOptions m_options;
1221de164aaaSGreg Clayton };
1222de164aaaSGreg Clayton 
1223b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1224223383edSEnrico Granata public:
1225b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1226b9c1b51eSKate Stone                               std::string funct, std::string help,
1227b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1228a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1229b9c1b51eSKate Stone         m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) {
1230735152e3SEnrico Granata     if (!help.empty())
1231442f6530SZachary Turner       SetHelp(help);
1232b9c1b51eSKate Stone     else {
1233735152e3SEnrico Granata       StreamString stream;
1234735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1235c156427dSZachary Turner       SetHelp(stream.GetString());
1236735152e3SEnrico Granata     }
1237223383edSEnrico Granata   }
1238223383edSEnrico Granata 
12396e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1240223383edSEnrico Granata 
1241b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
12425a988416SJim Ingham 
1243b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
12445a988416SJim Ingham 
1245b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
12465a988416SJim Ingham 
1247442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1248442f6530SZachary Turner     if (m_fetched_help_long)
1249442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1250442f6530SZachary Turner 
12512b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1252442f6530SZachary Turner     if (!scripter)
1253442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1254442f6530SZachary Turner 
1255fac939e9SEnrico Granata     std::string docstring;
1256442f6530SZachary Turner     m_fetched_help_long =
1257442f6530SZachary Turner         scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1258fac939e9SEnrico Granata     if (!docstring.empty())
1259442f6530SZachary Turner       SetHelpLong(docstring);
1260fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1261fac939e9SEnrico Granata   }
1262fac939e9SEnrico Granata 
12635a988416SJim Ingham protected:
12644d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1265b9c1b51eSKate Stone                  CommandReturnObject &result) override {
12662b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1267223383edSEnrico Granata 
126897206d57SZachary Turner     Status error;
1269223383edSEnrico Granata 
127070f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
127170f11f88SJim Ingham 
1272b9c1b51eSKate Stone     if (!scripter ||
1273b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_function_name.c_str(),
1274b9c1b51eSKate Stone                                          raw_command_line, m_synchro, result,
1275b9c1b51eSKate Stone                                          error, m_exe_ctx)) {
1276223383edSEnrico Granata       result.AppendError(error.AsCString());
1277223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1278b9c1b51eSKate Stone     } else {
127970f11f88SJim Ingham       // Don't change the status if the command already set it...
1280b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1281c156427dSZachary Turner         if (result.GetOutputData().empty())
1282223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
128370f11f88SJim Ingham         else
128470f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
128570f11f88SJim Ingham       }
128670f11f88SJim Ingham     }
1287223383edSEnrico Granata 
1288223383edSEnrico Granata     return result.Succeeded();
1289223383edSEnrico Granata   }
1290223383edSEnrico Granata 
12916e3d8e7fSEugene Zelenko private:
12926e3d8e7fSEugene Zelenko   std::string m_function_name;
12936e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
12946e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1295223383edSEnrico Granata };
1296223383edSEnrico Granata 
1297b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
12989fe00e52SEnrico Granata public:
12999fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
13009fe00e52SEnrico Granata                                std::string name,
13010641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1302b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1303a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1304b9c1b51eSKate Stone         m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false),
1305b9c1b51eSKate Stone         m_fetched_help_long(false) {
13069fe00e52SEnrico Granata     StreamString stream;
13079fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
1308c156427dSZachary Turner     SetHelp(stream.GetString());
13092b29b432SJonas Devlieghere     if (ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter())
1310e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
13119fe00e52SEnrico Granata   }
13129fe00e52SEnrico Granata 
13136e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
13149fe00e52SEnrico Granata 
1315b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13169fe00e52SEnrico Granata 
1317b9c1b51eSKate Stone   StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; }
13189fe00e52SEnrico Granata 
1319b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13209fe00e52SEnrico Granata 
1321442f6530SZachary Turner   llvm::StringRef GetHelp() override {
1322442f6530SZachary Turner     if (m_fetched_help_short)
1323442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
13242b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1325442f6530SZachary Turner     if (!scripter)
1326442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
13276f79bb2dSEnrico Granata     std::string docstring;
1328b9c1b51eSKate Stone     m_fetched_help_short =
1329b9c1b51eSKate Stone         scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
13306f79bb2dSEnrico Granata     if (!docstring.empty())
1331442f6530SZachary Turner       SetHelp(docstring);
1332442f6530SZachary Turner 
13336f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
13346f79bb2dSEnrico Granata   }
13356f79bb2dSEnrico Granata 
1336442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1337442f6530SZachary Turner     if (m_fetched_help_long)
1338442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1339442f6530SZachary Turner 
13402b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1341442f6530SZachary Turner     if (!scripter)
1342442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1343442f6530SZachary Turner 
13446f79bb2dSEnrico Granata     std::string docstring;
1345b9c1b51eSKate Stone     m_fetched_help_long =
1346b9c1b51eSKate Stone         scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
13476f79bb2dSEnrico Granata     if (!docstring.empty())
1348442f6530SZachary Turner       SetHelpLong(docstring);
13499fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
13509fe00e52SEnrico Granata   }
13519fe00e52SEnrico Granata 
13529fe00e52SEnrico Granata protected:
13534d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1354b9c1b51eSKate Stone                  CommandReturnObject &result) override {
13552b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
13569fe00e52SEnrico Granata 
135797206d57SZachary Turner     Status error;
13589fe00e52SEnrico Granata 
13599fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
13609fe00e52SEnrico Granata 
1361b9c1b51eSKate Stone     if (!scripter ||
1362b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1363b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
13649fe00e52SEnrico Granata       result.AppendError(error.AsCString());
13659fe00e52SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1366b9c1b51eSKate Stone     } else {
13679fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1368b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1369c156427dSZachary Turner         if (result.GetOutputData().empty())
13709fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
13719fe00e52SEnrico Granata         else
13729fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
13739fe00e52SEnrico Granata       }
13749fe00e52SEnrico Granata     }
13759fe00e52SEnrico Granata 
13769fe00e52SEnrico Granata     return result.Succeeded();
13779fe00e52SEnrico Granata   }
13789fe00e52SEnrico Granata 
13796e3d8e7fSEugene Zelenko private:
13806e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
13816e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13826e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
13836e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
13849fe00e52SEnrico Granata };
13859fe00e52SEnrico Granata 
1386a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
1387a9dbf432SEnrico Granata 
13888fe53c49STatyana Krasnukha static constexpr OptionDefinition g_script_import_options[] = {
13891f0f5b5bSZachary Turner     // clang-format off
13908fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "allow-reload", 'r', OptionParser::eNoArgument, 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." },
13911f0f5b5bSZachary Turner     // clang-format on
13921f0f5b5bSZachary Turner };
13931f0f5b5bSZachary Turner 
1394b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
13955a988416SJim Ingham public:
1396b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1397b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1398b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1399b9c1b51eSKate Stone         m_options() {
14005a988416SJim Ingham     CommandArgumentEntry arg1;
14015a988416SJim Ingham     CommandArgumentData cmd_arg;
14025a988416SJim Ingham 
14035a988416SJim Ingham     // Define the first (and only) variant of this arg.
14045a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
14053b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
14065a988416SJim Ingham 
1407b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1408b9c1b51eSKate Stone     // argument entry.
14095a988416SJim Ingham     arg1.push_back(cmd_arg);
14105a988416SJim Ingham 
14115a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14125a988416SJim Ingham     m_arguments.push_back(arg1);
14135a988416SJim Ingham   }
14145a988416SJim Ingham 
14156e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
14165a988416SJim Ingham 
14172443bbd4SRaphael Isemann   int HandleArgumentCompletion(
14182443bbd4SRaphael Isemann       CompletionRequest &request,
14192443bbd4SRaphael Isemann       OptionElementVector &opt_element_vector) override {
1420b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1421b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1422a2e76c0bSRaphael Isemann         request, nullptr);
14231a6d7ab5SRaphael Isemann     return request.GetNumberOfMatches();
14245a988416SJim Ingham   }
14255a988416SJim Ingham 
1426b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14275a988416SJim Ingham 
14285a988416SJim Ingham protected:
1429b9c1b51eSKate Stone   class CommandOptions : public Options {
14300a305db7SEnrico Granata   public:
1431b9c1b51eSKate Stone     CommandOptions() : Options() {}
14320a305db7SEnrico Granata 
14336e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
14340a305db7SEnrico Granata 
143597206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1436b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
143797206d57SZachary Turner       Status error;
14383bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
14390a305db7SEnrico Granata 
1440b9c1b51eSKate Stone       switch (short_option) {
14410a305db7SEnrico Granata       case 'r':
14420a305db7SEnrico Granata         m_allow_reload = true;
14430a305db7SEnrico Granata         break;
14440a305db7SEnrico Granata       default:
1445b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1446b9c1b51eSKate Stone                                        short_option);
14470a305db7SEnrico Granata         break;
14480a305db7SEnrico Granata       }
14490a305db7SEnrico Granata 
14500a305db7SEnrico Granata       return error;
14510a305db7SEnrico Granata     }
14520a305db7SEnrico Granata 
1453b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1454e0c70f1bSEnrico Granata       m_allow_reload = true;
14550a305db7SEnrico Granata     }
14560a305db7SEnrico Granata 
14571f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
145870602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
14591f0f5b5bSZachary Turner     }
14600a305db7SEnrico Granata 
14610a305db7SEnrico Granata     // Instance variables to hold the values for command options.
14620a305db7SEnrico Granata 
14630a305db7SEnrico Granata     bool m_allow_reload;
14640a305db7SEnrico Granata   };
14650a305db7SEnrico Granata 
1466b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
146757179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1468b9c1b51eSKate Stone       result.AppendError("only scripting language supported for module "
1469b9c1b51eSKate Stone                          "importing is currently Python");
1470a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1471a9dbf432SEnrico Granata       return false;
1472a9dbf432SEnrico Granata     }
1473a9dbf432SEnrico Granata 
147411eb9c64SZachary Turner     if (command.empty()) {
14753b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1476a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1477a9dbf432SEnrico Granata       return false;
1478a9dbf432SEnrico Granata     }
1479a9dbf432SEnrico Granata 
148011eb9c64SZachary Turner     for (auto &entry : command.entries()) {
148197206d57SZachary Turner       Status error;
1482a9dbf432SEnrico Granata 
1483c9d645d3SGreg Clayton       const bool init_session = true;
1484b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
148511eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
148611eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
148705097246SAdrian Prantl       // script imports" in __lldb_init_module the real fix is to have
148805097246SAdrian Prantl       // recursive commands possible with a CommandInvocation object separate
148905097246SAdrian Prantl       // from the CommandObject itself, so that recursive command invocations
149005097246SAdrian Prantl       // won't stomp on each other (wrt to execution contents, options, and
149105097246SAdrian Prantl       // more)
1492078551c7SEnrico Granata       m_exe_ctx.Clear();
14932b29b432SJonas Devlieghere       if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
149411eb9c64SZachary Turner               entry.c_str(), m_options.m_allow_reload, init_session, error)) {
1495a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1496b9c1b51eSKate Stone       } else {
1497b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1498b9c1b51eSKate Stone                                      error.AsCString());
1499a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusFailed);
1500a9dbf432SEnrico Granata       }
15013b00e35bSEnrico Granata     }
1502a9dbf432SEnrico Granata 
1503a9dbf432SEnrico Granata     return result.Succeeded();
1504a9dbf432SEnrico Granata   }
15050a305db7SEnrico Granata 
15065a988416SJim Ingham   CommandOptions m_options;
1507a9dbf432SEnrico Granata };
1508223383edSEnrico Granata 
1509223383edSEnrico Granata // CommandObjectCommandsScriptAdd
15108fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_synchro_type[] = {
15111f0f5b5bSZachary Turner   {eScriptedCommandSynchronicitySynchronous, "synchronous",
15121f0f5b5bSZachary Turner    "Run synchronous"},
15131f0f5b5bSZachary Turner   {eScriptedCommandSynchronicityAsynchronous, "asynchronous",
15141f0f5b5bSZachary Turner    "Run asynchronous"},
15151f0f5b5bSZachary Turner   {eScriptedCommandSynchronicityCurrentValue, "current",
15168fe53c49STatyana Krasnukha    "Do not alter current setting"} };
15171f0f5b5bSZachary Turner 
15188fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptSynchroType() {
15198fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_synchro_type);
15208fe53c49STatyana Krasnukha }
15218fe53c49STatyana Krasnukha 
15228fe53c49STatyana Krasnukha static constexpr OptionDefinition g_script_add_options[] = {
15231f0f5b5bSZachary Turner     // clang-format off
15248fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1,   false, "function",      'f', OptionParser::eRequiredArgument, nullptr, {},                  0, eArgTypePythonFunction,               "Name of the Python function to bind to this command name." },
15258fe53c49STatyana Krasnukha   { LLDB_OPT_SET_2,   false, "class",         'c', OptionParser::eRequiredArgument, nullptr, {},                  0, eArgTypePythonClass,                  "Name of the Python class to bind to this command name." },
15268fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1,   false, "help"  ,        'h', OptionParser::eRequiredArgument, nullptr, {},                  0, eArgTypeHelpText,                     "The help text to display for this command." },
15278fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "synchronicity", 's', OptionParser::eRequiredArgument, nullptr, ScriptSynchroType(), 0, eArgTypeScriptedCommandSynchronicity, "Set the synchronicity of this command's executions with regard to LLDB event system." },
15281f0f5b5bSZachary Turner     // clang-format on
15291f0f5b5bSZachary Turner };
15301f0f5b5bSZachary Turner 
1531b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1532b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
15335a988416SJim Ingham public:
1534b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1535b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
15365a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
15376e3d8e7fSEugene Zelenko                             nullptr),
1538b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
15395a988416SJim Ingham     CommandArgumentEntry arg1;
15405a988416SJim Ingham     CommandArgumentData cmd_arg;
15415a988416SJim Ingham 
15425a988416SJim Ingham     // Define the first (and only) variant of this arg.
15435a988416SJim Ingham     cmd_arg.arg_type = eArgTypeCommandName;
15445a988416SJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlain;
15455a988416SJim Ingham 
1546b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1547b9c1b51eSKate Stone     // argument entry.
15485a988416SJim Ingham     arg1.push_back(cmd_arg);
15495a988416SJim Ingham 
15505a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
15515a988416SJim Ingham     m_arguments.push_back(arg1);
15525a988416SJim Ingham   }
15535a988416SJim Ingham 
15546e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
15555a988416SJim Ingham 
1556b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
15575a988416SJim Ingham 
15585a988416SJim Ingham protected:
1559b9c1b51eSKate Stone   class CommandOptions : public Options {
1560223383edSEnrico Granata   public:
1561b9c1b51eSKate Stone     CommandOptions()
1562b9c1b51eSKate Stone         : Options(), m_class_name(), m_funct_name(), m_short_help(),
1563b9c1b51eSKate Stone           m_synchronicity(eScriptedCommandSynchronicitySynchronous) {}
1564223383edSEnrico Granata 
15656e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1566223383edSEnrico Granata 
156797206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1568b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
156997206d57SZachary Turner       Status error;
15703bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1571223383edSEnrico Granata 
1572b9c1b51eSKate Stone       switch (short_option) {
1573223383edSEnrico Granata       case 'f':
1574fe11483bSZachary Turner         if (!option_arg.empty())
1575fe11483bSZachary Turner           m_funct_name = option_arg;
1576735152e3SEnrico Granata         break;
15779fe00e52SEnrico Granata       case 'c':
1578fe11483bSZachary Turner         if (!option_arg.empty())
1579fe11483bSZachary Turner           m_class_name = option_arg;
15809fe00e52SEnrico Granata         break;
1581735152e3SEnrico Granata       case 'h':
1582fe11483bSZachary Turner         if (!option_arg.empty())
1583fe11483bSZachary Turner           m_short_help = option_arg;
1584223383edSEnrico Granata         break;
15850a305db7SEnrico Granata       case 's':
1586b9c1b51eSKate Stone         m_synchronicity =
158747cbf4a0SPavel Labath             (ScriptedCommandSynchronicity)OptionArgParser::ToOptionEnum(
1588fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
15890a305db7SEnrico Granata         if (!error.Success())
1590b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1591fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1592fe11483bSZachary Turner               option_arg.str().c_str());
15930a305db7SEnrico Granata         break;
1594223383edSEnrico Granata       default:
1595b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1596b9c1b51eSKate Stone                                        short_option);
1597223383edSEnrico Granata         break;
1598223383edSEnrico Granata       }
1599223383edSEnrico Granata 
1600223383edSEnrico Granata       return error;
1601223383edSEnrico Granata     }
1602223383edSEnrico Granata 
1603b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
16049fe00e52SEnrico Granata       m_class_name.clear();
1605735152e3SEnrico Granata       m_funct_name.clear();
1606735152e3SEnrico Granata       m_short_help.clear();
160744d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1608223383edSEnrico Granata     }
1609223383edSEnrico Granata 
16101f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
161170602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
16121f0f5b5bSZachary Turner     }
1613223383edSEnrico Granata 
1614223383edSEnrico Granata     // Instance variables to hold the values for command options.
1615223383edSEnrico Granata 
16169fe00e52SEnrico Granata     std::string m_class_name;
1617223383edSEnrico Granata     std::string m_funct_name;
1618735152e3SEnrico Granata     std::string m_short_help;
161944d93782SGreg Clayton     ScriptedCommandSynchronicity m_synchronicity;
1620223383edSEnrico Granata   };
1621223383edSEnrico Granata 
16220affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
162344d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
16240affb582SDave Lee     if (output_sp && interactive) {
162544d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
162644d93782SGreg Clayton       output_sp->Flush();
1627223383edSEnrico Granata     }
1628223383edSEnrico Granata   }
1629223383edSEnrico Granata 
1630b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1631b9c1b51eSKate Stone                               std::string &data) override {
163244d93782SGreg Clayton     StreamFileSP error_sp = io_handler.GetErrorStreamFile();
163344d93782SGreg Clayton 
16342b29b432SJonas Devlieghere     ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1635b9c1b51eSKate Stone     if (interpreter) {
163644d93782SGreg Clayton 
163744d93782SGreg Clayton       StringList lines;
163844d93782SGreg Clayton       lines.SplitIntoLines(data);
1639b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1640a73b7df7SEnrico Granata         std::string funct_name_str;
1641b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1642b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1643b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1644b9c1b51eSKate Stone                              "add python command.\n");
164544d93782SGreg Clayton             error_sp->Flush();
1646b9c1b51eSKate Stone           } else {
1647223383edSEnrico Granata             // everything should be fine now, let's add this alias
1648223383edSEnrico Granata 
1649b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1650771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
165144d93782SGreg Clayton                 m_synchronicity));
1652223383edSEnrico Granata 
1653b9c1b51eSKate Stone             if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp,
1654b9c1b51eSKate Stone                                               true)) {
1655b9c1b51eSKate Stone               error_sp->Printf("error: unable to add selected command, didn't "
1656b9c1b51eSKate Stone                                "add python command.\n");
165744d93782SGreg Clayton               error_sp->Flush();
1658223383edSEnrico Granata             }
1659223383edSEnrico Granata           }
1660b9c1b51eSKate Stone         } else {
1661b9c1b51eSKate Stone           error_sp->Printf(
1662b9c1b51eSKate Stone               "error: unable to create function, didn't add python command.\n");
166344d93782SGreg Clayton           error_sp->Flush();
166444d93782SGreg Clayton         }
1665b9c1b51eSKate Stone       } else {
166644d93782SGreg Clayton         error_sp->Printf("error: empty function, didn't add python command.\n");
166744d93782SGreg Clayton         error_sp->Flush();
166844d93782SGreg Clayton       }
1669b9c1b51eSKate Stone     } else {
1670b9c1b51eSKate Stone       error_sp->Printf(
1671b9c1b51eSKate Stone           "error: script interpreter missing, didn't add python command.\n");
167244d93782SGreg Clayton       error_sp->Flush();
167344d93782SGreg Clayton     }
167444d93782SGreg Clayton 
167544d93782SGreg Clayton     io_handler.SetIsDone(true);
167644d93782SGreg Clayton   }
1677223383edSEnrico Granata 
16785a988416SJim Ingham protected:
1679b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
168057179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1681b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1682b9c1b51eSKate Stone                          "commands is currently Python");
168399f0b8f9SEnrico Granata       result.SetStatus(eReturnStatusFailed);
168499f0b8f9SEnrico Granata       return false;
168599f0b8f9SEnrico Granata     }
168699f0b8f9SEnrico Granata 
168711eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1688223383edSEnrico Granata       result.AppendError("'command script add' requires one argument");
1689223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1690223383edSEnrico Granata       return false;
1691223383edSEnrico Granata     }
1692223383edSEnrico Granata 
1693735152e3SEnrico Granata     // Store the options in case we get multi-line input
16944574a890SZachary Turner     m_cmd_name = command[0].ref;
1695735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
169644d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1697223383edSEnrico Granata 
1698b9c1b51eSKate Stone     if (m_options.m_class_name.empty()) {
1699b9c1b51eSKate Stone       if (m_options.m_funct_name.empty()) {
1700b9c1b51eSKate Stone         m_interpreter.GetPythonCommandsFromIOHandler(
1701b9c1b51eSKate Stone             "     ",  // Prompt
170244d93782SGreg Clayton             *this,    // IOHandlerDelegate
170344d93782SGreg Clayton             true,     // Run IOHandler in async mode
1704b9c1b51eSKate Stone             nullptr); // Baton for the "io_handler" that will be passed back
1705b9c1b51eSKate Stone                       // into our IOHandlerDelegate functions
1706b9c1b51eSKate Stone       } else {
1707b9c1b51eSKate Stone         CommandObjectSP new_cmd(new CommandObjectPythonFunction(
1708b9c1b51eSKate Stone             m_interpreter, m_cmd_name, m_options.m_funct_name,
1709b9c1b51eSKate Stone             m_options.m_short_help, m_synchronicity));
1710b9c1b51eSKate Stone         if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
1711223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1712b9c1b51eSKate Stone         } else {
1713223383edSEnrico Granata           result.AppendError("cannot add command");
1714223383edSEnrico Granata           result.SetStatus(eReturnStatusFailed);
1715223383edSEnrico Granata         }
1716223383edSEnrico Granata       }
1717b9c1b51eSKate Stone     } else {
17182b29b432SJonas Devlieghere       ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1719b9c1b51eSKate Stone       if (!interpreter) {
17209fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
17219fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17229fe00e52SEnrico Granata         return false;
17239fe00e52SEnrico Granata       }
17249fe00e52SEnrico Granata 
1725b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1726b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1727b9c1b51eSKate Stone       if (!cmd_obj_sp) {
17289fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
17299fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17309fe00e52SEnrico Granata         return false;
17319fe00e52SEnrico Granata       }
17329fe00e52SEnrico Granata 
1733b9c1b51eSKate Stone       CommandObjectSP new_cmd(new CommandObjectScriptingObject(
1734b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
1735b9c1b51eSKate Stone       if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
17369fe00e52SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1737b9c1b51eSKate Stone       } else {
17389fe00e52SEnrico Granata         result.AppendError("cannot add command");
17399fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17409fe00e52SEnrico Granata       }
17419fe00e52SEnrico Granata     }
1742223383edSEnrico Granata 
1743223383edSEnrico Granata     return result.Succeeded();
1744223383edSEnrico Granata   }
17455a988416SJim Ingham 
17465a988416SJim Ingham   CommandOptions m_options;
174744d93782SGreg Clayton   std::string m_cmd_name;
1748735152e3SEnrico Granata   std::string m_short_help;
174944d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1750223383edSEnrico Granata };
1751223383edSEnrico Granata 
1752223383edSEnrico Granata // CommandObjectCommandsScriptList
1753223383edSEnrico Granata 
1754b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1755223383edSEnrico Granata public:
1756b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1757b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1758b9c1b51eSKate Stone                             "List defined scripted commands.", nullptr) {}
1759223383edSEnrico Granata 
17606e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1761223383edSEnrico Granata 
1762b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1763b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1764223383edSEnrico Granata 
1765223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1766223383edSEnrico Granata 
1767223383edSEnrico Granata     return true;
1768223383edSEnrico Granata   }
1769223383edSEnrico Granata };
1770223383edSEnrico Granata 
1771223383edSEnrico Granata // CommandObjectCommandsScriptClear
1772223383edSEnrico Granata 
1773b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1774223383edSEnrico Granata public:
1775b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1776b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1777b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1778223383edSEnrico Granata 
17796e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1780223383edSEnrico Granata 
17815a988416SJim Ingham protected:
1782b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1783223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1784223383edSEnrico Granata 
1785223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1786223383edSEnrico Granata 
1787223383edSEnrico Granata     return true;
1788223383edSEnrico Granata   }
1789223383edSEnrico Granata };
1790223383edSEnrico Granata 
1791223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1792223383edSEnrico Granata 
1793b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1794223383edSEnrico Granata public:
1795b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1796b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script delete",
1797b9c1b51eSKate Stone                             "Delete a scripted command.", nullptr) {
1798223383edSEnrico Granata     CommandArgumentEntry arg1;
1799223383edSEnrico Granata     CommandArgumentData cmd_arg;
1800223383edSEnrico Granata 
1801223383edSEnrico Granata     // Define the first (and only) variant of this arg.
1802223383edSEnrico Granata     cmd_arg.arg_type = eArgTypeCommandName;
1803223383edSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlain;
1804223383edSEnrico Granata 
1805b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1806b9c1b51eSKate Stone     // argument entry.
1807223383edSEnrico Granata     arg1.push_back(cmd_arg);
1808223383edSEnrico Granata 
1809223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1810223383edSEnrico Granata     m_arguments.push_back(arg1);
1811223383edSEnrico Granata   }
1812223383edSEnrico Granata 
18136e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1814223383edSEnrico Granata 
18155a988416SJim Ingham protected:
1816b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1817223383edSEnrico Granata 
181811eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1819223383edSEnrico Granata       result.AppendError("'command script delete' requires one argument");
1820223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1821223383edSEnrico Granata       return false;
1822223383edSEnrico Granata     }
1823223383edSEnrico Granata 
18244574a890SZachary Turner     auto cmd_name = command[0].ref;
1825223383edSEnrico Granata 
18264574a890SZachary Turner     if (cmd_name.empty() || !m_interpreter.HasUserCommands() ||
18274574a890SZachary Turner         !m_interpreter.UserCommandExists(cmd_name)) {
1828867e7d17SZachary Turner       result.AppendErrorWithFormat("command %s not found", command[0].c_str());
1829223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
18304574a890SZachary Turner       return false;
1831223383edSEnrico Granata     }
1832223383edSEnrico Granata 
18334574a890SZachary Turner     m_interpreter.RemoveUser(cmd_name);
18344574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishResult);
18354574a890SZachary Turner     return true;
1836223383edSEnrico Granata   }
1837223383edSEnrico Granata };
1838223383edSEnrico Granata 
1839223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1840223383edSEnrico Granata 
1841223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1842223383edSEnrico Granata 
1843b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1844223383edSEnrico Granata public:
18457428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1846b9c1b51eSKate Stone       : CommandObjectMultiword(
1847b9c1b51eSKate Stone             interpreter, "command script", "Commands for managing custom "
1848b9c1b51eSKate Stone                                            "commands implemented by "
1849b9c1b51eSKate Stone                                            "interpreter scripts.",
1850b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1851b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1852b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1853b9c1b51eSKate Stone     LoadSubCommand(
1854b9c1b51eSKate Stone         "delete",
1855b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1856b9c1b51eSKate Stone     LoadSubCommand(
1857b9c1b51eSKate Stone         "clear",
1858b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1859b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1860b9c1b51eSKate Stone                                interpreter)));
1861b9c1b51eSKate Stone     LoadSubCommand(
1862b9c1b51eSKate Stone         "import",
1863b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1864223383edSEnrico Granata   }
1865223383edSEnrico Granata 
18666e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1867223383edSEnrico Granata };
1868223383edSEnrico Granata 
1869ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
1870ebc09c36SJim Ingham 
1871ebc09c36SJim Ingham // CommandObjectMultiwordCommands
1872ebc09c36SJim Ingham 
1873b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
1874b9c1b51eSKate Stone     CommandInterpreter &interpreter)
1875b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
1876b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
1877b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
1878b9c1b51eSKate Stone   LoadSubCommand("source",
1879b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
1880b9c1b51eSKate Stone   LoadSubCommand("alias",
1881b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
1882b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
1883b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
1884b9c1b51eSKate Stone   LoadSubCommand("delete",
1885b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
1886b9c1b51eSKate Stone   LoadSubCommand(
1887b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
1888b9c1b51eSKate Stone   LoadSubCommand("history", CommandObjectSP(
1889b9c1b51eSKate Stone                                 new CommandObjectCommandsHistory(interpreter)));
1890b9c1b51eSKate Stone   LoadSubCommand(
1891b9c1b51eSKate Stone       "script",
1892b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
1893ebc09c36SJim Ingham }
1894ebc09c36SJim Ingham 
18956e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
1896