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;
3121c19b74cSJonas Devlieghere 
3131c19b74cSJonas Devlieghere       if (m_options.m_stop_on_continue.OptionWasSet())
3141c19b74cSJonas Devlieghere         options.SetStopOnContinue(
3151c19b74cSJonas Devlieghere             m_options.m_stop_on_continue.GetCurrentValue());
3161c19b74cSJonas Devlieghere 
3171c19b74cSJonas 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);
325*c0b48ab6SJonas Devlieghere         options.SetPrintErrors(true);
326c678ed77SStefan Granitz         options.SetEchoCommands(m_interpreter.GetEchoCommands());
327c678ed77SStefan Granitz         options.SetEchoCommentCommands(m_interpreter.GetEchoCommentCommands());
328c678ed77SStefan Granitz       }
32926c7bf93SJim Ingham 
3304574a890SZachary Turner       m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, result);
331b9c1b51eSKate Stone     } else {
33205097246SAdrian Prantl       // No options were set, inherit any settings from nested "command source"
33305097246SAdrian Prantl       // commands, or set to sane default settings...
33426c7bf93SJim Ingham       CommandInterpreterRunOptions options;
3354574a890SZachary Turner       m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options, result);
336ebc09c36SJim Ingham     }
337ebc09c36SJim Ingham     return result.Succeeded();
338ebc09c36SJim Ingham   }
3396e3d8e7fSEugene Zelenko 
3405a988416SJim Ingham   CommandOptions m_options;
341ebc09c36SJim Ingham };
342ebc09c36SJim Ingham 
343ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
344ebc09c36SJim Ingham // CommandObjectCommandsAlias
345ebc09c36SJim Ingham 
3468fe53c49STatyana Krasnukha static constexpr OptionDefinition g_alias_options[] = {
3471f0f5b5bSZachary Turner     // clang-format off
3488fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "help",      'h', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeHelpText, "Help text for this command" },
3498fe53c49STatyana Krasnukha   { LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeHelpText, "Long help text for this command" },
3501f0f5b5bSZachary Turner     // clang-format on
3511f0f5b5bSZachary Turner };
3521f0f5b5bSZachary Turner 
353b9c1b51eSKate Stone static const char *g_python_command_instructions =
354b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
355be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
35644d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
357be93a35aSEnrico Granata 
358b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
35945d0e238SEnrico Granata protected:
360b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
361ebc09c36SJim Ingham   public:
362b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
36345d0e238SEnrico Granata 
36445d0e238SEnrico Granata     ~CommandOptions() override = default;
36545d0e238SEnrico Granata 
3661f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
36770602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
3681f0f5b5bSZachary Turner     }
36945d0e238SEnrico Granata 
37097206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
371b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
37297206d57SZachary Turner       Status error;
37345d0e238SEnrico Granata 
3741f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
3758cef4b0bSZachary Turner       std::string option_str(option_value);
37645d0e238SEnrico Granata 
377b9c1b51eSKate Stone       switch (short_option) {
37845d0e238SEnrico Granata       case 'h':
3798cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
38045d0e238SEnrico Granata         m_help.SetOptionWasSet();
38145d0e238SEnrico Granata         break;
38245d0e238SEnrico Granata 
38345d0e238SEnrico Granata       case 'H':
3848cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
38545d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
38645d0e238SEnrico Granata         break;
38745d0e238SEnrico Granata 
38845d0e238SEnrico Granata       default:
389b9c1b51eSKate Stone         error.SetErrorStringWithFormat("invalid short option character '%c'",
390b9c1b51eSKate Stone                                        short_option);
39145d0e238SEnrico Granata         break;
39245d0e238SEnrico Granata       }
39345d0e238SEnrico Granata 
39445d0e238SEnrico Granata       return error;
39545d0e238SEnrico Granata     }
39645d0e238SEnrico Granata 
397b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
39845d0e238SEnrico Granata       m_help.Clear();
39945d0e238SEnrico Granata       m_long_help.Clear();
40045d0e238SEnrico Granata     }
40145d0e238SEnrico Granata 
40245d0e238SEnrico Granata     OptionValueString m_help;
40345d0e238SEnrico Granata     OptionValueString m_long_help;
40445d0e238SEnrico Granata   };
40545d0e238SEnrico Granata 
40645d0e238SEnrico Granata   OptionGroupOptions m_option_group;
40745d0e238SEnrico Granata   CommandOptions m_command_options;
40845d0e238SEnrico Granata 
40945d0e238SEnrico Granata public:
410b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
41145d0e238SEnrico Granata 
4127428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
413b9c1b51eSKate Stone       : CommandObjectRaw(
414b9c1b51eSKate Stone             interpreter, "command alias",
415a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
416b9c1b51eSKate Stone         m_option_group(), m_command_options() {
41745d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
41845d0e238SEnrico Granata     m_option_group.Finalize();
41945d0e238SEnrico Granata 
420ebc09c36SJim Ingham     SetHelpLong(
421ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
422ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
423b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
424b9c1b51eSKate Stone         R"(
425ea671fbdSKate Stone 
426ea671fbdSKate Stone (lldb) command alias sc script
427ea671fbdSKate Stone 
428ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
429ea671fbdSKate Stone 
430ea671fbdSKate Stone (lldb) command alias bp breakpoint
431ea671fbdSKate Stone 
432b9c1b51eSKate Stone )"
433b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
434ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
435b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
436b9c1b51eSKate Stone         R"(
437ea671fbdSKate Stone 
438ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
439ea671fbdSKate Stone 
440ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
441ea671fbdSKate Stone 
442b9c1b51eSKate Stone )"
443b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
444ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
445ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
446b9c1b51eSKate Stone shows how to create aliases with options:"
447b9c1b51eSKate Stone         R"(
448ea671fbdSKate Stone 
449ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
450ea671fbdSKate Stone 
451b9c1b51eSKate Stone )"
452b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
453ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
454ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
455ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
456ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
457ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
458ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
459ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
460ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
461ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
462b9c1b51eSKate Stone launch' example below)."
463b9c1b51eSKate Stone         R"(
464ea671fbdSKate Stone 
465b9c1b51eSKate Stone )"
466b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
467ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
468b9c1b51eSKate Stone \".cpp\":"
469b9c1b51eSKate Stone         R"(
470ea671fbdSKate Stone 
471ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
472ea671fbdSKate Stone 
473b9c1b51eSKate Stone )"
474b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
475ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
476ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
477b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
478b9c1b51eSKate Stone         R"(
479ea671fbdSKate Stone 
480ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
481ea671fbdSKate Stone (lldb) bfl my-file.c 137
482ea671fbdSKate Stone 
483ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
484ea671fbdSKate Stone 
485ea671fbdSKate Stone Another example:
486ea671fbdSKate Stone 
487ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
488ea671fbdSKate Stone (lldb) pltty /dev/tty0
489ea671fbdSKate Stone 
490ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
491ea671fbdSKate Stone 
492b9c1b51eSKate Stone )"
493b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
494ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
495b9c1b51eSKate Stone rather than using a positional placeholder:"
496b9c1b51eSKate Stone         R"(
497ea671fbdSKate Stone 
498ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
499ea671fbdSKate Stone 
500b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
501ebc09c36SJim Ingham 
502405fe67fSCaroline Tice     CommandArgumentEntry arg1;
503405fe67fSCaroline Tice     CommandArgumentEntry arg2;
504405fe67fSCaroline Tice     CommandArgumentEntry arg3;
505405fe67fSCaroline Tice     CommandArgumentData alias_arg;
506405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
507405fe67fSCaroline Tice     CommandArgumentData options_arg;
508405fe67fSCaroline Tice 
509405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
510405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
511405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
512405fe67fSCaroline Tice 
513b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
514b9c1b51eSKate Stone     // argument entry.
515405fe67fSCaroline Tice     arg1.push_back(alias_arg);
516405fe67fSCaroline Tice 
517405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
518405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
519405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
520405fe67fSCaroline Tice 
521b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
522b9c1b51eSKate Stone     // argument entry.
523405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
524405fe67fSCaroline Tice 
525405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
526405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
527405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
528405fe67fSCaroline Tice 
529b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
530b9c1b51eSKate Stone     // argument entry.
531405fe67fSCaroline Tice     arg3.push_back(options_arg);
532405fe67fSCaroline Tice 
533405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
534405fe67fSCaroline Tice     m_arguments.push_back(arg1);
535405fe67fSCaroline Tice     m_arguments.push_back(arg2);
536405fe67fSCaroline Tice     m_arguments.push_back(arg3);
537ebc09c36SJim Ingham   }
538ebc09c36SJim Ingham 
5396e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
540ebc09c36SJim Ingham 
5415a988416SJim Ingham protected:
5424d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
543b9c1b51eSKate Stone                  CommandReturnObject &result) override {
5444d51a902SRaphael Isemann     if (raw_command_line.empty()) {
545d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
54645d0e238SEnrico Granata       return false;
54745d0e238SEnrico Granata     }
54845d0e238SEnrico Granata 
549e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
550e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
55145d0e238SEnrico Granata 
5523a0e1270SRaphael Isemann     OptionsWithRaw args_with_suffix(raw_command_line);
5533a0e1270SRaphael Isemann     const char *remainder = args_with_suffix.GetRawPart().c_str();
55445d0e238SEnrico Granata 
5553a0e1270SRaphael Isemann     if (args_with_suffix.HasArgs())
5563a0e1270SRaphael Isemann       if (!ParseOptionsAndNotify(args_with_suffix.GetArgs(), result,
5573a0e1270SRaphael Isemann                                  m_option_group, exe_ctx))
55845d0e238SEnrico Granata         return false;
55945d0e238SEnrico Granata 
560a01bccdbSZachary Turner     llvm::StringRef raw_command_string(remainder);
561a01bccdbSZachary Turner     Args args(raw_command_string);
562844d2303SCaroline Tice 
56311eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
564d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
565844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
566844d2303SCaroline Tice       return false;
567844d2303SCaroline Tice     }
568844d2303SCaroline Tice 
569844d2303SCaroline Tice     // Get the alias command.
570844d2303SCaroline Tice 
5714574a890SZachary Turner     auto alias_command = args[0].ref;
5724574a890SZachary Turner     if (alias_command.startswith("-")) {
573d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
574b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
575b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
576b9c1b51eSKate Stone                              "a -- at the end of the options");
577d72e412fSEnrico Granata       }
578d72e412fSEnrico Granata       result.SetStatus(eReturnStatusFailed);
579d72e412fSEnrico Granata       return false;
580d72e412fSEnrico Granata     }
581844d2303SCaroline Tice 
582b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
58305097246SAdrian Prantl     // which gets passed to 'Execute', which does the stripping itself.
584844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
585b9c1b51eSKate Stone     if (pos == 0) {
586844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
587844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
588844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
589844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
590b9c1b51eSKate Stone     } else {
591844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
592844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
593844d2303SCaroline Tice       return false;
594844d2303SCaroline Tice     }
595844d2303SCaroline Tice 
596844d2303SCaroline Tice     // Verify that the command is alias-able.
597771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
598b9c1b51eSKate Stone       result.AppendErrorWithFormat(
599b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
6004574a890SZachary Turner           args[0].c_str());
601844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
602844d2303SCaroline Tice       return false;
603844d2303SCaroline Tice     }
604844d2303SCaroline Tice 
605b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
606a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
607a01bccdbSZachary Turner     // name of the command object stripped off the front.
608a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
609b9c1b51eSKate Stone     CommandObject *cmd_obj =
610b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
611844d2303SCaroline Tice 
612b9c1b51eSKate Stone     if (!cmd_obj) {
613b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
614b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
615b9c1b51eSKate Stone                                    "  No alias created.",
616a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
617844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
618844d2303SCaroline Tice       return false;
619b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
620b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
62105097246SAdrian Prantl       // been updated to this point. Therefore can we pass it to the version of
62205097246SAdrian Prantl       // Execute that does not need/expect raw input in the alias.
6235a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
624b9c1b51eSKate Stone     } else {
625b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
626b9c1b51eSKate Stone                                       *cmd_obj, result);
6275a988416SJim Ingham     }
6285a988416SJim Ingham     return result.Succeeded();
6295a988416SJim Ingham   }
6305a988416SJim Ingham 
631a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
632a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
633b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
634b9c1b51eSKate Stone                                 CommandReturnObject &result) {
635844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
636844d2303SCaroline Tice 
637b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
638b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
639844d2303SCaroline Tice 
640b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
641b9c1b51eSKate Stone             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) {
642a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
643a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
644b9c1b51eSKate Stone         result.AppendWarningWithFormat(
645b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
646a01bccdbSZachary Turner             alias_command.str().c_str());
647844d2303SCaroline Tice       }
648b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
649a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
65045d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
65145d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
65245d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
65345d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
654844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
655b9c1b51eSKate Stone       } else {
656472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
657472362e6SCaroline Tice         result.SetStatus(eReturnStatusFailed);
658472362e6SCaroline Tice       }
659212130acSEnrico Granata 
660b9c1b51eSKate Stone     } else {
661212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
662212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
663212130acSEnrico Granata     }
664212130acSEnrico Granata 
665844d2303SCaroline Tice     return result.Succeeded();
666844d2303SCaroline Tice   }
667ebc09c36SJim Ingham 
668b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
669867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
670ebc09c36SJim Ingham 
671b9c1b51eSKate Stone     if (argc < 2) {
672d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
673ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
674ebc09c36SJim Ingham       return false;
675ebc09c36SJim Ingham     }
676ebc09c36SJim Ingham 
6774574a890SZachary Turner     // Save these in std::strings since we're going to shift them off.
6784574a890SZachary Turner     const std::string alias_command(args[0].ref);
6794574a890SZachary Turner     const std::string actual_command(args[1].ref);
680ebc09c36SJim Ingham 
681ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
682ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
683ebc09c36SJim Ingham 
684b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
685b9c1b51eSKate Stone     // object.
686ebc09c36SJim Ingham 
687771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
688b9c1b51eSKate Stone       result.AppendErrorWithFormat(
689b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
690ebc09c36SJim Ingham           alias_command.c_str());
691ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
6924574a890SZachary Turner       return false;
6934574a890SZachary Turner     }
6944574a890SZachary Turner 
695b9c1b51eSKate Stone     CommandObjectSP command_obj_sp(
696a449698cSZachary Turner         m_interpreter.GetCommandSPExact(actual_command, true));
697ebc09c36SJim Ingham     CommandObjectSP subcommand_obj_sp;
698ebc09c36SJim Ingham     bool use_subcommand = false;
6994574a890SZachary Turner     if (!command_obj_sp) {
7004574a890SZachary Turner       result.AppendErrorWithFormat("'%s' is not an existing command.\n",
7014574a890SZachary Turner                                    actual_command.c_str());
7024574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
7034574a890SZachary Turner       return false;
7044574a890SZachary Turner     }
705ebc09c36SJim Ingham     CommandObject *cmd_obj = command_obj_sp.get();
7066e3d8e7fSEugene Zelenko     CommandObject *sub_cmd_obj = nullptr;
707b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
708b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
709ebc09c36SJim Ingham 
71011eb9c64SZachary Turner     while (cmd_obj->IsMultiwordObject() && !args.empty()) {
7114574a890SZachary Turner       auto sub_command = args[0].ref;
71211eb9c64SZachary Turner       assert(!sub_command.empty());
7134574a890SZachary Turner       subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
7144574a890SZachary Turner       if (!subcommand_obj_sp) {
715b9c1b51eSKate Stone         result.AppendErrorWithFormat(
716b9c1b51eSKate Stone             "'%s' is not a valid sub-command of '%s'.  "
717f415eeb4SCaroline Tice             "Unable to create alias.\n",
7184574a890SZachary Turner             args[0].c_str(), actual_command.c_str());
719ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
720ebc09c36SJim Ingham         return false;
721ebc09c36SJim Ingham       }
7224574a890SZachary Turner 
7234574a890SZachary Turner       sub_cmd_obj = subcommand_obj_sp.get();
7244574a890SZachary Turner       use_subcommand = true;
7254574a890SZachary Turner       args.Shift(); // Shift the sub_command word off the argument vector.
7264574a890SZachary Turner       cmd_obj = sub_cmd_obj;
727ebc09c36SJim Ingham     }
728ebc09c36SJim Ingham 
729ebc09c36SJim Ingham     // Verify & handle any options/arguments passed to the alias command
730ebc09c36SJim Ingham 
731212130acSEnrico Granata     std::string args_string;
732212130acSEnrico Granata 
73311eb9c64SZachary Turner     if (!args.empty()) {
734b9c1b51eSKate Stone       CommandObjectSP tmp_sp =
735b9c1b51eSKate Stone           m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false);
736ebc09c36SJim Ingham       if (use_subcommand)
7374574a890SZachary Turner         tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName(),
7384574a890SZachary Turner                                                  false);
739ca90c47eSCaroline Tice 
740ca90c47eSCaroline Tice       args.GetCommandString(args_string);
741867b185dSCaroline Tice     }
742ebc09c36SJim Ingham 
743771ef6d4SMalcolm Parsons     if (m_interpreter.AliasExists(alias_command) ||
744771ef6d4SMalcolm Parsons         m_interpreter.UserCommandExists(alias_command)) {
745b9c1b51eSKate Stone       result.AppendWarningWithFormat(
7464574a890SZachary Turner           "Overwriting existing definition for '%s'.\n", alias_command.c_str());
747ebc09c36SJim Ingham     }
748ebc09c36SJim Ingham 
749b9c1b51eSKate Stone     if (CommandAlias *alias = m_interpreter.AddAlias(
7504574a890SZachary Turner             alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
751771ef6d4SMalcolm Parsons             args_string)) {
75245d0e238SEnrico Granata       if (m_command_options.m_help.OptionWasSet())
75345d0e238SEnrico Granata         alias->SetHelp(m_command_options.m_help.GetCurrentValue());
75445d0e238SEnrico Granata       if (m_command_options.m_long_help.OptionWasSet())
75545d0e238SEnrico Granata         alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
756ebc09c36SJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
757b9c1b51eSKate Stone     } else {
758212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
759212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
760212130acSEnrico Granata       return false;
761212130acSEnrico Granata     }
762ebc09c36SJim Ingham 
763ebc09c36SJim Ingham     return result.Succeeded();
764ebc09c36SJim Ingham   }
765ebc09c36SJim Ingham };
766ebc09c36SJim Ingham 
767ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
768ebc09c36SJim Ingham // CommandObjectCommandsUnalias
769ebc09c36SJim Ingham 
770b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
771ebc09c36SJim Ingham public:
7727428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
773b9c1b51eSKate Stone       : CommandObjectParsed(
774b9c1b51eSKate Stone             interpreter, "command unalias",
775b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
776b9c1b51eSKate Stone             nullptr) {
777405fe67fSCaroline Tice     CommandArgumentEntry arg;
778405fe67fSCaroline Tice     CommandArgumentData alias_arg;
779405fe67fSCaroline Tice 
780405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
781405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
782405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
783405fe67fSCaroline Tice 
784b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
785b9c1b51eSKate Stone     // argument entry.
786405fe67fSCaroline Tice     arg.push_back(alias_arg);
787405fe67fSCaroline Tice 
788405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
789405fe67fSCaroline Tice     m_arguments.push_back(arg);
790ebc09c36SJim Ingham   }
791ebc09c36SJim Ingham 
7926e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
793ebc09c36SJim Ingham 
7945a988416SJim Ingham protected:
795b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
796ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
797ebc09c36SJim Ingham     CommandObject *cmd_obj;
798ebc09c36SJim Ingham 
79911eb9c64SZachary Turner     if (args.empty()) {
80011eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
80111eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
80211eb9c64SZachary Turner       return false;
80311eb9c64SZachary Turner     }
80411eb9c64SZachary Turner 
8054574a890SZachary Turner     auto command_name = args[0].ref;
806a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
8074574a890SZachary Turner     if (!cmd_obj) {
8084574a890SZachary Turner       result.AppendErrorWithFormat(
8094574a890SZachary Turner           "'%s' is not a known command.\nTry 'help' to see a "
8104574a890SZachary Turner           "current list of commands.\n",
811867e7d17SZachary Turner           args[0].c_str());
8124574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
8134574a890SZachary Turner       return false;
8144574a890SZachary Turner     }
8154574a890SZachary Turner 
816b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
817b9c1b51eSKate Stone       if (cmd_obj->IsRemovable()) {
818b9c1b51eSKate Stone         result.AppendErrorWithFormat(
819b9c1b51eSKate Stone             "'%s' is not an alias, it is a debugger command which can be "
820b9c1b51eSKate Stone             "removed using the 'command delete' command.\n",
821867e7d17SZachary Turner             args[0].c_str());
822b9c1b51eSKate Stone       } else {
823b9c1b51eSKate Stone         result.AppendErrorWithFormat(
824b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
825867e7d17SZachary Turner             args[0].c_str());
826b547278cSGreg Clayton       }
827ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
8284574a890SZachary Turner       return false;
8294574a890SZachary Turner     }
8304574a890SZachary Turner 
831b9c1b51eSKate Stone     if (!m_interpreter.RemoveAlias(command_name)) {
832a7015092SGreg Clayton       if (m_interpreter.AliasExists(command_name))
833b9c1b51eSKate Stone         result.AppendErrorWithFormat(
834867e7d17SZachary Turner             "Error occurred while attempting to unalias '%s'.\n",
835867e7d17SZachary Turner             args[0].c_str());
836ebc09c36SJim Ingham       else
837b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
838867e7d17SZachary Turner                                      args[0].c_str());
839ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
8404574a890SZachary Turner       return false;
841ebc09c36SJim Ingham     }
842ebc09c36SJim Ingham 
8434574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
844ebc09c36SJim Ingham     return result.Succeeded();
845ebc09c36SJim Ingham   }
846ebc09c36SJim Ingham };
847ebc09c36SJim Ingham 
848b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
849b547278cSGreg Clayton // CommandObjectCommandsDelete
850b547278cSGreg Clayton 
851b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
852b547278cSGreg Clayton public:
8537428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
854b9c1b51eSKate Stone       : CommandObjectParsed(
855b9c1b51eSKate Stone             interpreter, "command delete",
856b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
857b9c1b51eSKate Stone             nullptr) {
858b547278cSGreg Clayton     CommandArgumentEntry arg;
859b547278cSGreg Clayton     CommandArgumentData alias_arg;
860b547278cSGreg Clayton 
861b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
862b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
863b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
864b547278cSGreg Clayton 
865b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
866b9c1b51eSKate Stone     // argument entry.
867b547278cSGreg Clayton     arg.push_back(alias_arg);
868b547278cSGreg Clayton 
869b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
870b547278cSGreg Clayton     m_arguments.push_back(arg);
871b547278cSGreg Clayton   }
872b547278cSGreg Clayton 
8736e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
874b547278cSGreg Clayton 
875b547278cSGreg Clayton protected:
876b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
877b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
878b547278cSGreg Clayton 
87911eb9c64SZachary Turner     if (args.empty()) {
88011eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
88111eb9c64SZachary Turner                                    "defined regular expression command names",
882a449698cSZachary Turner                                    GetCommandName().str().c_str());
88311eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
88411eb9c64SZachary Turner     }
88511eb9c64SZachary Turner 
8864574a890SZachary Turner     auto command_name = args[0].ref;
8874574a890SZachary Turner     if (!m_interpreter.CommandExists(command_name)) {
88846d4aa21SEnrico Granata       StreamString error_msg_stream;
889d5b44036SJonas Devlieghere       const bool generate_upropos = true;
89046d4aa21SEnrico Granata       const bool generate_type_lookup = false;
891b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
8924574a890SZachary Turner           &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
893d5b44036SJonas Devlieghere           generate_upropos, generate_type_lookup);
894c156427dSZachary Turner       result.AppendError(error_msg_stream.GetString());
895b547278cSGreg Clayton       result.SetStatus(eReturnStatusFailed);
8964574a890SZachary Turner       return false;
897b547278cSGreg Clayton     }
898b547278cSGreg Clayton 
8994574a890SZachary Turner     if (!m_interpreter.RemoveCommand(command_name)) {
9004574a890SZachary Turner       result.AppendErrorWithFormat(
9014574a890SZachary Turner           "'%s' is a permanent debugger command and cannot be removed.\n",
902867e7d17SZachary Turner           args[0].c_str());
9034574a890SZachary Turner       result.SetStatus(eReturnStatusFailed);
9044574a890SZachary Turner       return false;
9054574a890SZachary Turner     }
9064574a890SZachary Turner 
9074574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
9084574a890SZachary Turner     return true;
909b547278cSGreg Clayton   }
910b547278cSGreg Clayton };
911b547278cSGreg Clayton 
912de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
9131f0f5b5bSZachary Turner 
9148fe53c49STatyana Krasnukha static constexpr OptionDefinition g_regex_options[] = {
9151f0f5b5bSZachary Turner     // clang-format off
9168fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "help"  , 'h', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "The help text to display for this command." },
9178fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "A syntax string showing the typical usage syntax." },
9181f0f5b5bSZachary Turner     // clang-format on
9191f0f5b5bSZachary Turner };
9201f0f5b5bSZachary Turner 
9215a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
922de164aaaSGreg Clayton 
923b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
924b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
925de164aaaSGreg Clayton public:
9267428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
927b9c1b51eSKate Stone       : CommandObjectParsed(
928b9c1b51eSKate Stone             interpreter, "command regex", "Define a custom command in terms of "
929b9c1b51eSKate Stone                                           "existing commands by matching "
930b9c1b51eSKate Stone                                           "regular expressions.",
9310e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
932b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
933b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
934b9c1b51eSKate Stone         m_options() {
935b9c1b51eSKate Stone     SetHelpLong(
936b9c1b51eSKate Stone         R"(
937b9c1b51eSKate Stone )"
938b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
939ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
940b9c1b51eSKate Stone using the regular expression substitution format of:"
941b9c1b51eSKate Stone         R"(
942ea671fbdSKate Stone 
943ea671fbdSKate Stone     s/<regex>/<subst>/
944ea671fbdSKate Stone 
945b9c1b51eSKate Stone )"
946b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
947ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
948b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
949b9c1b51eSKate Stone         R"(
950ea671fbdSKate Stone 
951b9c1b51eSKate Stone )"
952b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
953ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
954ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
955b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
956b9c1b51eSKate Stone         R"(
957ea671fbdSKate Stone 
958ea671fbdSKate Stone EXAMPLES
959ea671fbdSKate Stone 
960b9c1b51eSKate Stone )"
961b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
962ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
963b9c1b51eSKate Stone a number follows 'f':"
964b9c1b51eSKate Stone         R"(
965ea671fbdSKate Stone 
966b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
967de164aaaSGreg Clayton   }
968de164aaaSGreg Clayton 
9696e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
970de164aaaSGreg Clayton 
9715a988416SJim Ingham protected:
9720affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
97344d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
9740affb582SDave Lee     if (output_sp && interactive) {
9750affb582SDave Lee       output_sp->PutCString("Enter one or more sed substitution commands in "
976b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
977b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
97844d93782SGreg Clayton       output_sp->Flush();
97944d93782SGreg Clayton     }
98044d93782SGreg Clayton   }
98144d93782SGreg Clayton 
982b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
983b9c1b51eSKate Stone                               std::string &data) override {
98444d93782SGreg Clayton     io_handler.SetIsDone(true);
985d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
98644d93782SGreg Clayton       StringList lines;
987b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
98844d93782SGreg Clayton         const size_t num_lines = lines.GetSize();
98944d93782SGreg Clayton         bool check_only = false;
990b9c1b51eSKate Stone         for (size_t i = 0; i < num_lines; ++i) {
99144d93782SGreg Clayton           llvm::StringRef bytes_strref(lines[i]);
99297206d57SZachary Turner           Status error = AppendRegexSubstitution(bytes_strref, check_only);
993b9c1b51eSKate Stone           if (error.Fail()) {
99457179860SJonas Devlieghere             if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode()) {
99557179860SJonas Devlieghere               StreamSP out_stream = GetDebugger().GetAsyncOutputStream();
99644d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
99744d93782SGreg Clayton             }
99844d93782SGreg Clayton           }
99944d93782SGreg Clayton         }
100044d93782SGreg Clayton       }
1001d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
1002d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
100344d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
100444d93782SGreg Clayton       }
100544d93782SGreg Clayton     }
100644d93782SGreg Clayton   }
100744d93782SGreg Clayton 
1008b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
10095a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
1010b9c1b51eSKate Stone     if (argc == 0) {
1011b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
1012b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
10130e5e5a79SGreg Clayton       result.SetStatus(eReturnStatusFailed);
101411eb9c64SZachary Turner       return false;
101511eb9c64SZachary Turner     }
101611eb9c64SZachary Turner 
101797206d57SZachary Turner     Status error;
10184574a890SZachary Turner     auto name = command[0].ref;
1019d5b44036SJonas Devlieghere     m_regex_cmd_up = llvm::make_unique<CommandObjectRegexCommand>(
10204574a890SZachary Turner         m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0,
10214574a890SZachary Turner         true);
10220e5e5a79SGreg Clayton 
1023b9c1b51eSKate Stone     if (argc == 1) {
102457179860SJonas Devlieghere       Debugger &debugger = GetDebugger();
1025e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
102644d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
1027b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
1028b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
102973d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
1030514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
1031514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
1032b9c1b51eSKate Stone           multiple_lines, color_prompt,
1033f6913cd7SGreg Clayton           0, // Don't show line numbers
1034d77c2e09SJonas Devlieghere           *this, nullptr));
103544d93782SGreg Clayton 
1036b9c1b51eSKate Stone       if (io_handler_sp) {
103744d93782SGreg Clayton         debugger.PushIOHandler(io_handler_sp);
1038de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1039de164aaaSGreg Clayton       }
1040b9c1b51eSKate Stone     } else {
104197d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
104244d93782SGreg Clayton         bool check_only = false;
104397d2c401SZachary Turner         error = AppendRegexSubstitution(entry.ref, check_only);
10440e5e5a79SGreg Clayton         if (error.Fail())
10450e5e5a79SGreg Clayton           break;
10460e5e5a79SGreg Clayton       }
10470e5e5a79SGreg Clayton 
1048b9c1b51eSKate Stone       if (error.Success()) {
10490e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
10500e5e5a79SGreg Clayton       }
10510e5e5a79SGreg Clayton     }
1052b9c1b51eSKate Stone     if (error.Fail()) {
10530e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
1054de164aaaSGreg Clayton       result.SetStatus(eReturnStatusFailed);
1055de164aaaSGreg Clayton     }
10560e5e5a79SGreg Clayton 
1057de164aaaSGreg Clayton     return result.Succeeded();
1058de164aaaSGreg Clayton   }
1059de164aaaSGreg Clayton 
106097206d57SZachary Turner   Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
1061b9c1b51eSKate Stone                                  bool check_only) {
106297206d57SZachary Turner     Status error;
10630e5e5a79SGreg Clayton 
1064d5b44036SJonas Devlieghere     if (!m_regex_cmd_up) {
1065b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1066b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
1067b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10680e5e5a79SGreg Clayton       return error;
1069de164aaaSGreg Clayton     }
10700e5e5a79SGreg Clayton 
10710e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
10720e5e5a79SGreg Clayton 
1073b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
1074b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1075b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
1076b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
10770e5e5a79SGreg Clayton       return error;
10780e5e5a79SGreg Clayton     }
10790e5e5a79SGreg Clayton 
1080b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
1081b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
1082b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
1083b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
10840e5e5a79SGreg Clayton       return error;
10850e5e5a79SGreg Clayton     }
10860e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
108705097246SAdrian Prantl     // use the char that follows 's' as the regex separator character so we can
108805097246SAdrian Prantl     // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
10890e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
1090b9c1b51eSKate Stone     const size_t second_separator_char_pos =
1091b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
10920e5e5a79SGreg Clayton 
1093b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
1094b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1095b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
10960e5e5a79SGreg Clayton           separator_char,
10970e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
1098ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
1099b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11000e5e5a79SGreg Clayton       return error;
11010e5e5a79SGreg Clayton     }
11020e5e5a79SGreg Clayton 
1103b9c1b51eSKate Stone     const size_t third_separator_char_pos =
1104b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
11050e5e5a79SGreg Clayton 
1106b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
1107b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1108b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
11090e5e5a79SGreg Clayton           separator_char,
11100e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
1111ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
1112b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11130e5e5a79SGreg Clayton       return error;
11140e5e5a79SGreg Clayton     }
11150e5e5a79SGreg Clayton 
1116b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
111705097246SAdrian Prantl       // Make sure that everything that follows the last regex separator char
1118b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
1119b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
1120b9c1b51eSKate Stone           std::string::npos) {
1121b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
1122b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
1123b9c1b51eSKate Stone             "string: '%.*s'",
1124b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
11250e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
11260e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
11270e5e5a79SGreg Clayton         return error;
11280e5e5a79SGreg Clayton       }
1129b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
1130b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1131b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1132b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11330e5e5a79SGreg Clayton           regex_sed.data());
11340e5e5a79SGreg Clayton       return error;
1135b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
1136b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1137b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1138b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11390e5e5a79SGreg Clayton           regex_sed.data());
11400e5e5a79SGreg Clayton       return error;
11410e5e5a79SGreg Clayton     }
114244d93782SGreg Clayton 
1143b9c1b51eSKate Stone     if (!check_only) {
1144b9c1b51eSKate Stone       std::string regex(regex_sed.substr(first_separator_char_pos + 1,
1145b9c1b51eSKate Stone                                          second_separator_char_pos -
1146b9c1b51eSKate Stone                                              first_separator_char_pos - 1));
1147b9c1b51eSKate Stone       std::string subst(regex_sed.substr(second_separator_char_pos + 1,
1148b9c1b51eSKate Stone                                          third_separator_char_pos -
1149b9c1b51eSKate Stone                                              second_separator_char_pos - 1));
1150d5b44036SJonas Devlieghere       m_regex_cmd_up->AddRegexCommand(regex.c_str(), subst.c_str());
115144d93782SGreg Clayton     }
11520e5e5a79SGreg Clayton     return error;
1153de164aaaSGreg Clayton   }
1154de164aaaSGreg Clayton 
1155b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1156d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
1157d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
1158d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
1159de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1160de164aaaSGreg Clayton       }
1161de164aaaSGreg Clayton     }
1162de164aaaSGreg Clayton   }
1163de164aaaSGreg Clayton 
1164de164aaaSGreg Clayton private:
1165d5b44036SJonas Devlieghere   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up;
1166de164aaaSGreg Clayton 
1167b9c1b51eSKate Stone   class CommandOptions : public Options {
1168de164aaaSGreg Clayton   public:
1169b9c1b51eSKate Stone     CommandOptions() : Options() {}
1170de164aaaSGreg Clayton 
11716e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1172de164aaaSGreg Clayton 
117397206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1174b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
117597206d57SZachary Turner       Status error;
11763bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1177de164aaaSGreg Clayton 
1178b9c1b51eSKate Stone       switch (short_option) {
1179de164aaaSGreg Clayton       case 'h':
1180de164aaaSGreg Clayton         m_help.assign(option_arg);
1181de164aaaSGreg Clayton         break;
1182de164aaaSGreg Clayton       case 's':
1183de164aaaSGreg Clayton         m_syntax.assign(option_arg);
1184de164aaaSGreg Clayton         break;
1185de164aaaSGreg Clayton       default:
1186b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1187b9c1b51eSKate Stone                                        short_option);
1188de164aaaSGreg Clayton         break;
1189de164aaaSGreg Clayton       }
1190de164aaaSGreg Clayton 
1191de164aaaSGreg Clayton       return error;
1192de164aaaSGreg Clayton     }
1193de164aaaSGreg Clayton 
1194b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1195de164aaaSGreg Clayton       m_help.clear();
1196de164aaaSGreg Clayton       m_syntax.clear();
1197de164aaaSGreg Clayton     }
1198de164aaaSGreg Clayton 
11991f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
120070602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
12011f0f5b5bSZachary Turner     }
1202de164aaaSGreg Clayton 
120311eb9c64SZachary Turner     // TODO: Convert these functions to return StringRefs.
1204b9c1b51eSKate Stone     const char *GetHelp() {
12056e3d8e7fSEugene Zelenko       return (m_help.empty() ? nullptr : m_help.c_str());
1206de164aaaSGreg Clayton     }
12076e3d8e7fSEugene Zelenko 
1208b9c1b51eSKate Stone     const char *GetSyntax() {
12096e3d8e7fSEugene Zelenko       return (m_syntax.empty() ? nullptr : m_syntax.c_str());
1210de164aaaSGreg Clayton     }
12116e3d8e7fSEugene Zelenko 
1212de164aaaSGreg Clayton   protected:
12136e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
12146e3d8e7fSEugene Zelenko 
1215de164aaaSGreg Clayton     std::string m_help;
1216de164aaaSGreg Clayton     std::string m_syntax;
1217de164aaaSGreg Clayton   };
1218de164aaaSGreg Clayton 
1219b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1220de164aaaSGreg Clayton 
12215a988416SJim Ingham   CommandOptions m_options;
1222de164aaaSGreg Clayton };
1223de164aaaSGreg Clayton 
1224b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1225223383edSEnrico Granata public:
1226b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1227b9c1b51eSKate Stone                               std::string funct, std::string help,
1228b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1229a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1230b9c1b51eSKate Stone         m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) {
1231735152e3SEnrico Granata     if (!help.empty())
1232442f6530SZachary Turner       SetHelp(help);
1233b9c1b51eSKate Stone     else {
1234735152e3SEnrico Granata       StreamString stream;
1235735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1236c156427dSZachary Turner       SetHelp(stream.GetString());
1237735152e3SEnrico Granata     }
1238223383edSEnrico Granata   }
1239223383edSEnrico Granata 
12406e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1241223383edSEnrico Granata 
1242b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
12435a988416SJim Ingham 
1244b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
12455a988416SJim Ingham 
1246b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
12475a988416SJim Ingham 
1248442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1249442f6530SZachary Turner     if (m_fetched_help_long)
1250442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1251442f6530SZachary Turner 
12522b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1253442f6530SZachary Turner     if (!scripter)
1254442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1255442f6530SZachary Turner 
1256fac939e9SEnrico Granata     std::string docstring;
1257442f6530SZachary Turner     m_fetched_help_long =
1258442f6530SZachary Turner         scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1259fac939e9SEnrico Granata     if (!docstring.empty())
1260442f6530SZachary Turner       SetHelpLong(docstring);
1261fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1262fac939e9SEnrico Granata   }
1263fac939e9SEnrico Granata 
12645a988416SJim Ingham protected:
12654d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1266b9c1b51eSKate Stone                  CommandReturnObject &result) override {
12672b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1268223383edSEnrico Granata 
126997206d57SZachary Turner     Status error;
1270223383edSEnrico Granata 
127170f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
127270f11f88SJim Ingham 
1273b9c1b51eSKate Stone     if (!scripter ||
1274b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_function_name.c_str(),
1275b9c1b51eSKate Stone                                          raw_command_line, m_synchro, result,
1276b9c1b51eSKate Stone                                          error, m_exe_ctx)) {
1277223383edSEnrico Granata       result.AppendError(error.AsCString());
1278223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1279b9c1b51eSKate Stone     } else {
128070f11f88SJim Ingham       // Don't change the status if the command already set it...
1281b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1282c156427dSZachary Turner         if (result.GetOutputData().empty())
1283223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
128470f11f88SJim Ingham         else
128570f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
128670f11f88SJim Ingham       }
128770f11f88SJim Ingham     }
1288223383edSEnrico Granata 
1289223383edSEnrico Granata     return result.Succeeded();
1290223383edSEnrico Granata   }
1291223383edSEnrico Granata 
12926e3d8e7fSEugene Zelenko private:
12936e3d8e7fSEugene Zelenko   std::string m_function_name;
12946e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
12956e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1296223383edSEnrico Granata };
1297223383edSEnrico Granata 
1298b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
12999fe00e52SEnrico Granata public:
13009fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
13019fe00e52SEnrico Granata                                std::string name,
13020641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1303b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1304a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1305b9c1b51eSKate Stone         m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false),
1306b9c1b51eSKate Stone         m_fetched_help_long(false) {
13079fe00e52SEnrico Granata     StreamString stream;
13089fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
1309c156427dSZachary Turner     SetHelp(stream.GetString());
13102b29b432SJonas Devlieghere     if (ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter())
1311e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
13129fe00e52SEnrico Granata   }
13139fe00e52SEnrico Granata 
13146e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
13159fe00e52SEnrico Granata 
1316b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13179fe00e52SEnrico Granata 
1318b9c1b51eSKate Stone   StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; }
13199fe00e52SEnrico Granata 
1320b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13219fe00e52SEnrico Granata 
1322442f6530SZachary Turner   llvm::StringRef GetHelp() override {
1323442f6530SZachary Turner     if (m_fetched_help_short)
1324442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
13252b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1326442f6530SZachary Turner     if (!scripter)
1327442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
13286f79bb2dSEnrico Granata     std::string docstring;
1329b9c1b51eSKate Stone     m_fetched_help_short =
1330b9c1b51eSKate Stone         scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
13316f79bb2dSEnrico Granata     if (!docstring.empty())
1332442f6530SZachary Turner       SetHelp(docstring);
1333442f6530SZachary Turner 
13346f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
13356f79bb2dSEnrico Granata   }
13366f79bb2dSEnrico Granata 
1337442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1338442f6530SZachary Turner     if (m_fetched_help_long)
1339442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1340442f6530SZachary Turner 
13412b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1342442f6530SZachary Turner     if (!scripter)
1343442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1344442f6530SZachary Turner 
13456f79bb2dSEnrico Granata     std::string docstring;
1346b9c1b51eSKate Stone     m_fetched_help_long =
1347b9c1b51eSKate Stone         scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
13486f79bb2dSEnrico Granata     if (!docstring.empty())
1349442f6530SZachary Turner       SetHelpLong(docstring);
13509fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
13519fe00e52SEnrico Granata   }
13529fe00e52SEnrico Granata 
13539fe00e52SEnrico Granata protected:
13544d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1355b9c1b51eSKate Stone                  CommandReturnObject &result) override {
13562b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
13579fe00e52SEnrico Granata 
135897206d57SZachary Turner     Status error;
13599fe00e52SEnrico Granata 
13609fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
13619fe00e52SEnrico Granata 
1362b9c1b51eSKate Stone     if (!scripter ||
1363b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1364b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
13659fe00e52SEnrico Granata       result.AppendError(error.AsCString());
13669fe00e52SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1367b9c1b51eSKate Stone     } else {
13689fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1369b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1370c156427dSZachary Turner         if (result.GetOutputData().empty())
13719fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
13729fe00e52SEnrico Granata         else
13739fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
13749fe00e52SEnrico Granata       }
13759fe00e52SEnrico Granata     }
13769fe00e52SEnrico Granata 
13779fe00e52SEnrico Granata     return result.Succeeded();
13789fe00e52SEnrico Granata   }
13799fe00e52SEnrico Granata 
13806e3d8e7fSEugene Zelenko private:
13816e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
13826e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13836e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
13846e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
13859fe00e52SEnrico Granata };
13869fe00e52SEnrico Granata 
1387a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
1388a9dbf432SEnrico Granata 
13898fe53c49STatyana Krasnukha static constexpr OptionDefinition g_script_import_options[] = {
13901f0f5b5bSZachary Turner     // clang-format off
13918fe53c49STatyana 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." },
13921f0f5b5bSZachary Turner     // clang-format on
13931f0f5b5bSZachary Turner };
13941f0f5b5bSZachary Turner 
1395b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
13965a988416SJim Ingham public:
1397b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1398b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1399b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1400b9c1b51eSKate Stone         m_options() {
14015a988416SJim Ingham     CommandArgumentEntry arg1;
14025a988416SJim Ingham     CommandArgumentData cmd_arg;
14035a988416SJim Ingham 
14045a988416SJim Ingham     // Define the first (and only) variant of this arg.
14055a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
14063b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
14075a988416SJim Ingham 
1408b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1409b9c1b51eSKate Stone     // argument entry.
14105a988416SJim Ingham     arg1.push_back(cmd_arg);
14115a988416SJim Ingham 
14125a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14135a988416SJim Ingham     m_arguments.push_back(arg1);
14145a988416SJim Ingham   }
14155a988416SJim Ingham 
14166e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
14175a988416SJim Ingham 
14182443bbd4SRaphael Isemann   int HandleArgumentCompletion(
14192443bbd4SRaphael Isemann       CompletionRequest &request,
14202443bbd4SRaphael Isemann       OptionElementVector &opt_element_vector) override {
1421b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1422b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1423a2e76c0bSRaphael Isemann         request, nullptr);
14241a6d7ab5SRaphael Isemann     return request.GetNumberOfMatches();
14255a988416SJim Ingham   }
14265a988416SJim Ingham 
1427b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14285a988416SJim Ingham 
14295a988416SJim Ingham protected:
1430b9c1b51eSKate Stone   class CommandOptions : public Options {
14310a305db7SEnrico Granata   public:
1432b9c1b51eSKate Stone     CommandOptions() : Options() {}
14330a305db7SEnrico Granata 
14346e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
14350a305db7SEnrico Granata 
143697206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1437b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
143897206d57SZachary Turner       Status error;
14393bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
14400a305db7SEnrico Granata 
1441b9c1b51eSKate Stone       switch (short_option) {
14420a305db7SEnrico Granata       case 'r':
14430a305db7SEnrico Granata         m_allow_reload = true;
14440a305db7SEnrico Granata         break;
14450a305db7SEnrico Granata       default:
1446b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1447b9c1b51eSKate Stone                                        short_option);
14480a305db7SEnrico Granata         break;
14490a305db7SEnrico Granata       }
14500a305db7SEnrico Granata 
14510a305db7SEnrico Granata       return error;
14520a305db7SEnrico Granata     }
14530a305db7SEnrico Granata 
1454b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1455e0c70f1bSEnrico Granata       m_allow_reload = true;
14560a305db7SEnrico Granata     }
14570a305db7SEnrico Granata 
14581f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
145970602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
14601f0f5b5bSZachary Turner     }
14610a305db7SEnrico Granata 
14620a305db7SEnrico Granata     // Instance variables to hold the values for command options.
14630a305db7SEnrico Granata 
14640a305db7SEnrico Granata     bool m_allow_reload;
14650a305db7SEnrico Granata   };
14660a305db7SEnrico Granata 
1467b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
146857179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1469b9c1b51eSKate Stone       result.AppendError("only scripting language supported for module "
1470b9c1b51eSKate Stone                          "importing is currently Python");
1471a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1472a9dbf432SEnrico Granata       return false;
1473a9dbf432SEnrico Granata     }
1474a9dbf432SEnrico Granata 
147511eb9c64SZachary Turner     if (command.empty()) {
14763b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1477a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1478a9dbf432SEnrico Granata       return false;
1479a9dbf432SEnrico Granata     }
1480a9dbf432SEnrico Granata 
148111eb9c64SZachary Turner     for (auto &entry : command.entries()) {
148297206d57SZachary Turner       Status error;
1483a9dbf432SEnrico Granata 
1484c9d645d3SGreg Clayton       const bool init_session = true;
1485b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
148611eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
148711eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
148805097246SAdrian Prantl       // script imports" in __lldb_init_module the real fix is to have
148905097246SAdrian Prantl       // recursive commands possible with a CommandInvocation object separate
149005097246SAdrian Prantl       // from the CommandObject itself, so that recursive command invocations
149105097246SAdrian Prantl       // won't stomp on each other (wrt to execution contents, options, and
149205097246SAdrian Prantl       // more)
1493078551c7SEnrico Granata       m_exe_ctx.Clear();
14942b29b432SJonas Devlieghere       if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
149511eb9c64SZachary Turner               entry.c_str(), m_options.m_allow_reload, init_session, error)) {
1496a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1497b9c1b51eSKate Stone       } else {
1498b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1499b9c1b51eSKate Stone                                      error.AsCString());
1500a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusFailed);
1501a9dbf432SEnrico Granata       }
15023b00e35bSEnrico Granata     }
1503a9dbf432SEnrico Granata 
1504a9dbf432SEnrico Granata     return result.Succeeded();
1505a9dbf432SEnrico Granata   }
15060a305db7SEnrico Granata 
15075a988416SJim Ingham   CommandOptions m_options;
1508a9dbf432SEnrico Granata };
1509223383edSEnrico Granata 
1510223383edSEnrico Granata // CommandObjectCommandsScriptAdd
15118fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_synchro_type[] = {
15121f0f5b5bSZachary Turner   {eScriptedCommandSynchronicitySynchronous, "synchronous",
15131f0f5b5bSZachary Turner    "Run synchronous"},
15141f0f5b5bSZachary Turner   {eScriptedCommandSynchronicityAsynchronous, "asynchronous",
15151f0f5b5bSZachary Turner    "Run asynchronous"},
15161f0f5b5bSZachary Turner   {eScriptedCommandSynchronicityCurrentValue, "current",
15178fe53c49STatyana Krasnukha    "Do not alter current setting"} };
15181f0f5b5bSZachary Turner 
15198fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptSynchroType() {
15208fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_synchro_type);
15218fe53c49STatyana Krasnukha }
15228fe53c49STatyana Krasnukha 
15238fe53c49STatyana Krasnukha static constexpr OptionDefinition g_script_add_options[] = {
15241f0f5b5bSZachary Turner     // clang-format off
15258fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1,   false, "function",      'f', OptionParser::eRequiredArgument, nullptr, {},                  0, eArgTypePythonFunction,               "Name of the Python function to bind to this command name." },
15268fe53c49STatyana Krasnukha   { LLDB_OPT_SET_2,   false, "class",         'c', OptionParser::eRequiredArgument, nullptr, {},                  0, eArgTypePythonClass,                  "Name of the Python class to bind to this command name." },
15278fe53c49STatyana Krasnukha   { LLDB_OPT_SET_1,   false, "help"  ,        'h', OptionParser::eRequiredArgument, nullptr, {},                  0, eArgTypeHelpText,                     "The help text to display for this command." },
15288fe53c49STatyana 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." },
15291f0f5b5bSZachary Turner     // clang-format on
15301f0f5b5bSZachary Turner };
15311f0f5b5bSZachary Turner 
1532b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1533b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
15345a988416SJim Ingham public:
1535b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1536b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
15375a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
15386e3d8e7fSEugene Zelenko                             nullptr),
1539b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
15405a988416SJim Ingham     CommandArgumentEntry arg1;
15415a988416SJim Ingham     CommandArgumentData cmd_arg;
15425a988416SJim Ingham 
15435a988416SJim Ingham     // Define the first (and only) variant of this arg.
15445a988416SJim Ingham     cmd_arg.arg_type = eArgTypeCommandName;
15455a988416SJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlain;
15465a988416SJim Ingham 
1547b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1548b9c1b51eSKate Stone     // argument entry.
15495a988416SJim Ingham     arg1.push_back(cmd_arg);
15505a988416SJim Ingham 
15515a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
15525a988416SJim Ingham     m_arguments.push_back(arg1);
15535a988416SJim Ingham   }
15545a988416SJim Ingham 
15556e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
15565a988416SJim Ingham 
1557b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
15585a988416SJim Ingham 
15595a988416SJim Ingham protected:
1560b9c1b51eSKate Stone   class CommandOptions : public Options {
1561223383edSEnrico Granata   public:
1562b9c1b51eSKate Stone     CommandOptions()
1563b9c1b51eSKate Stone         : Options(), m_class_name(), m_funct_name(), m_short_help(),
1564b9c1b51eSKate Stone           m_synchronicity(eScriptedCommandSynchronicitySynchronous) {}
1565223383edSEnrico Granata 
15666e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1567223383edSEnrico Granata 
156897206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1569b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
157097206d57SZachary Turner       Status error;
15713bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1572223383edSEnrico Granata 
1573b9c1b51eSKate Stone       switch (short_option) {
1574223383edSEnrico Granata       case 'f':
1575fe11483bSZachary Turner         if (!option_arg.empty())
1576fe11483bSZachary Turner           m_funct_name = option_arg;
1577735152e3SEnrico Granata         break;
15789fe00e52SEnrico Granata       case 'c':
1579fe11483bSZachary Turner         if (!option_arg.empty())
1580fe11483bSZachary Turner           m_class_name = option_arg;
15819fe00e52SEnrico Granata         break;
1582735152e3SEnrico Granata       case 'h':
1583fe11483bSZachary Turner         if (!option_arg.empty())
1584fe11483bSZachary Turner           m_short_help = option_arg;
1585223383edSEnrico Granata         break;
15860a305db7SEnrico Granata       case 's':
1587b9c1b51eSKate Stone         m_synchronicity =
158847cbf4a0SPavel Labath             (ScriptedCommandSynchronicity)OptionArgParser::ToOptionEnum(
1589fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
15900a305db7SEnrico Granata         if (!error.Success())
1591b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1592fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1593fe11483bSZachary Turner               option_arg.str().c_str());
15940a305db7SEnrico Granata         break;
1595223383edSEnrico Granata       default:
1596b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1597b9c1b51eSKate Stone                                        short_option);
1598223383edSEnrico Granata         break;
1599223383edSEnrico Granata       }
1600223383edSEnrico Granata 
1601223383edSEnrico Granata       return error;
1602223383edSEnrico Granata     }
1603223383edSEnrico Granata 
1604b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
16059fe00e52SEnrico Granata       m_class_name.clear();
1606735152e3SEnrico Granata       m_funct_name.clear();
1607735152e3SEnrico Granata       m_short_help.clear();
160844d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1609223383edSEnrico Granata     }
1610223383edSEnrico Granata 
16111f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
161270602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
16131f0f5b5bSZachary Turner     }
1614223383edSEnrico Granata 
1615223383edSEnrico Granata     // Instance variables to hold the values for command options.
1616223383edSEnrico Granata 
16179fe00e52SEnrico Granata     std::string m_class_name;
1618223383edSEnrico Granata     std::string m_funct_name;
1619735152e3SEnrico Granata     std::string m_short_help;
162044d93782SGreg Clayton     ScriptedCommandSynchronicity m_synchronicity;
1621223383edSEnrico Granata   };
1622223383edSEnrico Granata 
16230affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
162444d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
16250affb582SDave Lee     if (output_sp && interactive) {
162644d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
162744d93782SGreg Clayton       output_sp->Flush();
1628223383edSEnrico Granata     }
1629223383edSEnrico Granata   }
1630223383edSEnrico Granata 
1631b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1632b9c1b51eSKate Stone                               std::string &data) override {
163344d93782SGreg Clayton     StreamFileSP error_sp = io_handler.GetErrorStreamFile();
163444d93782SGreg Clayton 
16352b29b432SJonas Devlieghere     ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1636b9c1b51eSKate Stone     if (interpreter) {
163744d93782SGreg Clayton 
163844d93782SGreg Clayton       StringList lines;
163944d93782SGreg Clayton       lines.SplitIntoLines(data);
1640b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1641a73b7df7SEnrico Granata         std::string funct_name_str;
1642b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1643b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1644b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1645b9c1b51eSKate Stone                              "add python command.\n");
164644d93782SGreg Clayton             error_sp->Flush();
1647b9c1b51eSKate Stone           } else {
1648223383edSEnrico Granata             // everything should be fine now, let's add this alias
1649223383edSEnrico Granata 
1650b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1651771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
165244d93782SGreg Clayton                 m_synchronicity));
1653223383edSEnrico Granata 
1654b9c1b51eSKate Stone             if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp,
1655b9c1b51eSKate Stone                                               true)) {
1656b9c1b51eSKate Stone               error_sp->Printf("error: unable to add selected command, didn't "
1657b9c1b51eSKate Stone                                "add python command.\n");
165844d93782SGreg Clayton               error_sp->Flush();
1659223383edSEnrico Granata             }
1660223383edSEnrico Granata           }
1661b9c1b51eSKate Stone         } else {
1662b9c1b51eSKate Stone           error_sp->Printf(
1663b9c1b51eSKate Stone               "error: unable to create function, didn't add python command.\n");
166444d93782SGreg Clayton           error_sp->Flush();
166544d93782SGreg Clayton         }
1666b9c1b51eSKate Stone       } else {
166744d93782SGreg Clayton         error_sp->Printf("error: empty function, didn't add python command.\n");
166844d93782SGreg Clayton         error_sp->Flush();
166944d93782SGreg Clayton       }
1670b9c1b51eSKate Stone     } else {
1671b9c1b51eSKate Stone       error_sp->Printf(
1672b9c1b51eSKate Stone           "error: script interpreter missing, didn't add python command.\n");
167344d93782SGreg Clayton       error_sp->Flush();
167444d93782SGreg Clayton     }
167544d93782SGreg Clayton 
167644d93782SGreg Clayton     io_handler.SetIsDone(true);
167744d93782SGreg Clayton   }
1678223383edSEnrico Granata 
16795a988416SJim Ingham protected:
1680b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
168157179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1682b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1683b9c1b51eSKate Stone                          "commands is currently Python");
168499f0b8f9SEnrico Granata       result.SetStatus(eReturnStatusFailed);
168599f0b8f9SEnrico Granata       return false;
168699f0b8f9SEnrico Granata     }
168799f0b8f9SEnrico Granata 
168811eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1689223383edSEnrico Granata       result.AppendError("'command script add' requires one argument");
1690223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1691223383edSEnrico Granata       return false;
1692223383edSEnrico Granata     }
1693223383edSEnrico Granata 
1694735152e3SEnrico Granata     // Store the options in case we get multi-line input
16954574a890SZachary Turner     m_cmd_name = command[0].ref;
1696735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
169744d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1698223383edSEnrico Granata 
1699b9c1b51eSKate Stone     if (m_options.m_class_name.empty()) {
1700b9c1b51eSKate Stone       if (m_options.m_funct_name.empty()) {
1701b9c1b51eSKate Stone         m_interpreter.GetPythonCommandsFromIOHandler(
1702b9c1b51eSKate Stone             "     ",  // Prompt
170344d93782SGreg Clayton             *this,    // IOHandlerDelegate
170444d93782SGreg Clayton             true,     // Run IOHandler in async mode
1705b9c1b51eSKate Stone             nullptr); // Baton for the "io_handler" that will be passed back
1706b9c1b51eSKate Stone                       // into our IOHandlerDelegate functions
1707b9c1b51eSKate Stone       } else {
1708b9c1b51eSKate Stone         CommandObjectSP new_cmd(new CommandObjectPythonFunction(
1709b9c1b51eSKate Stone             m_interpreter, m_cmd_name, m_options.m_funct_name,
1710b9c1b51eSKate Stone             m_options.m_short_help, m_synchronicity));
1711b9c1b51eSKate Stone         if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
1712223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1713b9c1b51eSKate Stone         } else {
1714223383edSEnrico Granata           result.AppendError("cannot add command");
1715223383edSEnrico Granata           result.SetStatus(eReturnStatusFailed);
1716223383edSEnrico Granata         }
1717223383edSEnrico Granata       }
1718b9c1b51eSKate Stone     } else {
17192b29b432SJonas Devlieghere       ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1720b9c1b51eSKate Stone       if (!interpreter) {
17219fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
17229fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17239fe00e52SEnrico Granata         return false;
17249fe00e52SEnrico Granata       }
17259fe00e52SEnrico Granata 
1726b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1727b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1728b9c1b51eSKate Stone       if (!cmd_obj_sp) {
17299fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
17309fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17319fe00e52SEnrico Granata         return false;
17329fe00e52SEnrico Granata       }
17339fe00e52SEnrico Granata 
1734b9c1b51eSKate Stone       CommandObjectSP new_cmd(new CommandObjectScriptingObject(
1735b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
1736b9c1b51eSKate Stone       if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
17379fe00e52SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1738b9c1b51eSKate Stone       } else {
17399fe00e52SEnrico Granata         result.AppendError("cannot add command");
17409fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17419fe00e52SEnrico Granata       }
17429fe00e52SEnrico Granata     }
1743223383edSEnrico Granata 
1744223383edSEnrico Granata     return result.Succeeded();
1745223383edSEnrico Granata   }
17465a988416SJim Ingham 
17475a988416SJim Ingham   CommandOptions m_options;
174844d93782SGreg Clayton   std::string m_cmd_name;
1749735152e3SEnrico Granata   std::string m_short_help;
175044d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1751223383edSEnrico Granata };
1752223383edSEnrico Granata 
1753223383edSEnrico Granata // CommandObjectCommandsScriptList
1754223383edSEnrico Granata 
1755b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1756223383edSEnrico Granata public:
1757b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1758b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1759b9c1b51eSKate Stone                             "List defined scripted commands.", nullptr) {}
1760223383edSEnrico Granata 
17616e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1762223383edSEnrico Granata 
1763b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1764b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1765223383edSEnrico Granata 
1766223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1767223383edSEnrico Granata 
1768223383edSEnrico Granata     return true;
1769223383edSEnrico Granata   }
1770223383edSEnrico Granata };
1771223383edSEnrico Granata 
1772223383edSEnrico Granata // CommandObjectCommandsScriptClear
1773223383edSEnrico Granata 
1774b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1775223383edSEnrico Granata public:
1776b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1777b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1778b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1779223383edSEnrico Granata 
17806e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1781223383edSEnrico Granata 
17825a988416SJim Ingham protected:
1783b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1784223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1785223383edSEnrico Granata 
1786223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1787223383edSEnrico Granata 
1788223383edSEnrico Granata     return true;
1789223383edSEnrico Granata   }
1790223383edSEnrico Granata };
1791223383edSEnrico Granata 
1792223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1793223383edSEnrico Granata 
1794b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1795223383edSEnrico Granata public:
1796b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1797b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script delete",
1798b9c1b51eSKate Stone                             "Delete a scripted command.", nullptr) {
1799223383edSEnrico Granata     CommandArgumentEntry arg1;
1800223383edSEnrico Granata     CommandArgumentData cmd_arg;
1801223383edSEnrico Granata 
1802223383edSEnrico Granata     // Define the first (and only) variant of this arg.
1803223383edSEnrico Granata     cmd_arg.arg_type = eArgTypeCommandName;
1804223383edSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlain;
1805223383edSEnrico Granata 
1806b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1807b9c1b51eSKate Stone     // argument entry.
1808223383edSEnrico Granata     arg1.push_back(cmd_arg);
1809223383edSEnrico Granata 
1810223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1811223383edSEnrico Granata     m_arguments.push_back(arg1);
1812223383edSEnrico Granata   }
1813223383edSEnrico Granata 
18146e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1815223383edSEnrico Granata 
18165a988416SJim Ingham protected:
1817b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1818223383edSEnrico Granata 
181911eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1820223383edSEnrico Granata       result.AppendError("'command script delete' requires one argument");
1821223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1822223383edSEnrico Granata       return false;
1823223383edSEnrico Granata     }
1824223383edSEnrico Granata 
18254574a890SZachary Turner     auto cmd_name = command[0].ref;
1826223383edSEnrico Granata 
18274574a890SZachary Turner     if (cmd_name.empty() || !m_interpreter.HasUserCommands() ||
18284574a890SZachary Turner         !m_interpreter.UserCommandExists(cmd_name)) {
1829867e7d17SZachary Turner       result.AppendErrorWithFormat("command %s not found", command[0].c_str());
1830223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
18314574a890SZachary Turner       return false;
1832223383edSEnrico Granata     }
1833223383edSEnrico Granata 
18344574a890SZachary Turner     m_interpreter.RemoveUser(cmd_name);
18354574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishResult);
18364574a890SZachary Turner     return true;
1837223383edSEnrico Granata   }
1838223383edSEnrico Granata };
1839223383edSEnrico Granata 
1840223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1841223383edSEnrico Granata 
1842223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1843223383edSEnrico Granata 
1844b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1845223383edSEnrico Granata public:
18467428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1847b9c1b51eSKate Stone       : CommandObjectMultiword(
1848b9c1b51eSKate Stone             interpreter, "command script", "Commands for managing custom "
1849b9c1b51eSKate Stone                                            "commands implemented by "
1850b9c1b51eSKate Stone                                            "interpreter scripts.",
1851b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1852b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1853b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1854b9c1b51eSKate Stone     LoadSubCommand(
1855b9c1b51eSKate Stone         "delete",
1856b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1857b9c1b51eSKate Stone     LoadSubCommand(
1858b9c1b51eSKate Stone         "clear",
1859b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1860b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1861b9c1b51eSKate Stone                                interpreter)));
1862b9c1b51eSKate Stone     LoadSubCommand(
1863b9c1b51eSKate Stone         "import",
1864b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1865223383edSEnrico Granata   }
1866223383edSEnrico Granata 
18676e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1868223383edSEnrico Granata };
1869223383edSEnrico Granata 
1870ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
1871ebc09c36SJim Ingham 
1872ebc09c36SJim Ingham // CommandObjectMultiwordCommands
1873ebc09c36SJim Ingham 
1874b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
1875b9c1b51eSKate Stone     CommandInterpreter &interpreter)
1876b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
1877b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
1878b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
1879b9c1b51eSKate Stone   LoadSubCommand("source",
1880b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
1881b9c1b51eSKate Stone   LoadSubCommand("alias",
1882b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
1883b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
1884b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
1885b9c1b51eSKate Stone   LoadSubCommand("delete",
1886b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
1887b9c1b51eSKate Stone   LoadSubCommand(
1888b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
1889b9c1b51eSKate Stone   LoadSubCommand("history", CommandObjectSP(
1890b9c1b51eSKate Stone                                 new CommandObjectCommandsHistory(interpreter)));
1891b9c1b51eSKate Stone   LoadSubCommand(
1892b9c1b51eSKate Stone       "script",
1893b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
1894ebc09c36SJim Ingham }
1895ebc09c36SJim Ingham 
18966e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
1897