180814287SRaphael Isemann //===-- CommandObjectCommands.cpp -----------------------------------------===//
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 
96e3d8e7fSEugene Zelenko #include "CommandObjectCommands.h"
1046d4aa21SEnrico Granata #include "CommandObjectHelp.h"
119390b346SJonas Devlieghere #include "CommandObjectRegexCommand.h"
12ebc09c36SJim Ingham #include "lldb/Core/Debugger.h"
1344d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
147594f14fSEnrico Granata #include "lldb/Interpreter/CommandHistory.h"
15ebc09c36SJim Ingham #include "lldb/Interpreter/CommandInterpreter.h"
16ebc09c36SJim Ingham #include "lldb/Interpreter/CommandReturnObject.h"
1747cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h"
18012d4fcaSEnrico Granata #include "lldb/Interpreter/OptionValueBoolean.h"
1945d0e238SEnrico Granata #include "lldb/Interpreter/OptionValueString.h"
207594f14fSEnrico Granata #include "lldb/Interpreter/OptionValueUInt64.h"
21ebc09c36SJim Ingham #include "lldb/Interpreter/Options.h"
2299f0b8f9SEnrico Granata #include "lldb/Interpreter/ScriptInterpreter.h"
23145d95c9SPavel Labath #include "lldb/Utility/Args.h"
24573ab909SZachary Turner #include "lldb/Utility/StringList.h"
259390b346SJonas Devlieghere #include "llvm/ADT/StringRef.h"
26ebc09c36SJim Ingham 
27ebc09c36SJim Ingham using namespace lldb;
28ebc09c36SJim Ingham using namespace lldb_private;
29ebc09c36SJim Ingham 
30ebc09c36SJim Ingham // CommandObjectCommandsSource
31ebc09c36SJim Ingham 
3264becc11SRaphael Isemann #define LLDB_OPTIONS_source
3364becc11SRaphael Isemann #include "CommandOptions.inc"
341f0f5b5bSZachary Turner 
35b9c1b51eSKate Stone class CommandObjectCommandsSource : public CommandObjectParsed {
365a988416SJim Ingham public:
377428a18cSKate Stone   CommandObjectCommandsSource(CommandInterpreter &interpreter)
38b9c1b51eSKate Stone       : CommandObjectParsed(
39b9c1b51eSKate Stone             interpreter, "command source",
40b9c1b51eSKate Stone             "Read and execute LLDB commands from the file <filename>.",
416e3d8e7fSEugene Zelenko             nullptr),
42b9c1b51eSKate Stone         m_options() {
435a988416SJim Ingham     CommandArgumentEntry arg;
445a988416SJim Ingham     CommandArgumentData file_arg;
455a988416SJim Ingham 
465a988416SJim Ingham     // Define the first (and only) variant of this arg.
475a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
485a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
495a988416SJim Ingham 
50b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
51b9c1b51eSKate Stone     // argument entry.
525a988416SJim Ingham     arg.push_back(file_arg);
535a988416SJim Ingham 
545a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
555a988416SJim Ingham     m_arguments.push_back(arg);
565a988416SJim Ingham   }
575a988416SJim Ingham 
586e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
595a988416SJim Ingham 
60b9c1b51eSKate Stone   const char *GetRepeatCommand(Args &current_command_args,
61b9c1b51eSKate Stone                                uint32_t index) override {
625a988416SJim Ingham     return "";
635a988416SJim Ingham   }
645a988416SJim Ingham 
65ae34ed2cSRaphael Isemann   void
66ae34ed2cSRaphael Isemann   HandleArgumentCompletion(CompletionRequest &request,
672443bbd4SRaphael Isemann                            OptionElementVector &opt_element_vector) override {
68b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
69b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
70a2e76c0bSRaphael Isemann         request, nullptr);
715a988416SJim Ingham   }
725a988416SJim Ingham 
73b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
745a988416SJim Ingham 
755a988416SJim Ingham protected:
76b9c1b51eSKate Stone   class CommandOptions : public Options {
77e16c50a1SJim Ingham   public:
78b9c1b51eSKate Stone     CommandOptions()
79b9c1b51eSKate Stone         : Options(), m_stop_on_error(true), m_silent_run(false),
803bf3b966SJim Ingham           m_stop_on_continue(true), m_cmd_relative_to_command_file(false) {}
81e16c50a1SJim Ingham 
826e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
83e16c50a1SJim Ingham 
8497206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
85b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
8697206d57SZachary Turner       Status error;
873bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
88e16c50a1SJim Ingham 
89b9c1b51eSKate Stone       switch (short_option) {
90e16c50a1SJim Ingham       case 'e':
91fe11483bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_arg);
92e16c50a1SJim Ingham         break;
93340b0309SGreg Clayton 
94e16c50a1SJim Ingham       case 'c':
95fe11483bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_arg);
96e16c50a1SJim Ingham         break;
97340b0309SGreg Clayton 
983bf3b966SJim Ingham       case 'C':
993bf3b966SJim Ingham         m_cmd_relative_to_command_file = true;
1003bf3b966SJim Ingham         break;
1013bf3b966SJim Ingham 
10260986174SMichael Sartain       case 's':
103fe11483bSZachary Turner         error = m_silent_run.SetValueFromString(option_arg);
10460986174SMichael Sartain         break;
105340b0309SGreg Clayton 
106e16c50a1SJim Ingham       default:
10736162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
108e16c50a1SJim Ingham       }
109e16c50a1SJim Ingham 
110e16c50a1SJim Ingham       return error;
111e16c50a1SJim Ingham     }
112e16c50a1SJim Ingham 
113b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
114012d4fcaSEnrico Granata       m_stop_on_error.Clear();
115340b0309SGreg Clayton       m_silent_run.Clear();
116340b0309SGreg Clayton       m_stop_on_continue.Clear();
1173bf3b966SJim Ingham       m_cmd_relative_to_command_file.Clear();
118e16c50a1SJim Ingham     }
119e16c50a1SJim Ingham 
1201f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
12170602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
1221f0f5b5bSZachary Turner     }
123e16c50a1SJim Ingham 
124e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
125e16c50a1SJim Ingham 
126012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
127340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
128340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
1293bf3b966SJim Ingham     OptionValueBoolean m_cmd_relative_to_command_file;
130e16c50a1SJim Ingham   };
131e16c50a1SJim Ingham 
132b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1334574a890SZachary Turner     if (command.GetArgumentCount() != 1) {
1344574a890SZachary Turner       result.AppendErrorWithFormat(
1354574a890SZachary Turner           "'%s' takes exactly one executable filename argument.\n",
1364574a890SZachary Turner           GetCommandName().str().c_str());
1374574a890SZachary Turner       return false;
1384574a890SZachary Turner     }
139ebc09c36SJim Ingham 
1403bf3b966SJim Ingham     FileSpec source_dir = {};
1413bf3b966SJim Ingham     if (m_options.m_cmd_relative_to_command_file) {
1423bf3b966SJim Ingham       source_dir = GetDebugger().GetCommandInterpreter().GetCurrentSourceDir();
1433bf3b966SJim Ingham       if (!source_dir) {
1443bf3b966SJim Ingham         result.AppendError("command source -C can only be specified "
1453bf3b966SJim Ingham                            "from a command file");
1463bf3b966SJim Ingham         result.SetStatus(eReturnStatusFailed);
1473bf3b966SJim Ingham         return false;
1483bf3b966SJim Ingham       }
1493bf3b966SJim Ingham     }
1503bf3b966SJim Ingham 
1510d9a201eSRaphael Isemann     FileSpec cmd_file(command[0].ref());
1523bf3b966SJim Ingham     if (source_dir) {
1533bf3b966SJim Ingham       // Prepend the source_dir to the cmd_file path:
1543bf3b966SJim Ingham       if (!cmd_file.IsRelative()) {
1553bf3b966SJim Ingham         result.AppendError("command source -C can only be used "
1563bf3b966SJim Ingham                            "with a relative path.");
1573bf3b966SJim Ingham         result.SetStatus(eReturnStatusFailed);
1583bf3b966SJim Ingham         return false;
1593bf3b966SJim Ingham       }
1603bf3b966SJim Ingham       cmd_file.MakeAbsolute(source_dir);
1613bf3b966SJim Ingham     }
1623bf3b966SJim Ingham 
1638f3be7a3SJonas Devlieghere     FileSystem::Instance().Resolve(cmd_file);
164ebc09c36SJim Ingham 
16536de94cfSTatyana Krasnukha     CommandInterpreterRunOptions options;
166340b0309SGreg Clayton     // If any options were set, then use them
167340b0309SGreg Clayton     if (m_options.m_stop_on_error.OptionWasSet() ||
168340b0309SGreg Clayton         m_options.m_silent_run.OptionWasSet() ||
169b9c1b51eSKate Stone         m_options.m_stop_on_continue.OptionWasSet()) {
1701c19b74cSJonas Devlieghere       if (m_options.m_stop_on_continue.OptionWasSet())
1711c19b74cSJonas Devlieghere         options.SetStopOnContinue(
1721c19b74cSJonas Devlieghere             m_options.m_stop_on_continue.GetCurrentValue());
1731c19b74cSJonas Devlieghere 
1741c19b74cSJonas Devlieghere       if (m_options.m_stop_on_error.OptionWasSet())
17526c7bf93SJim Ingham         options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
176c678ed77SStefan Granitz 
177c678ed77SStefan Granitz       // Individual silent setting is override for global command echo settings.
178c678ed77SStefan Granitz       if (m_options.m_silent_run.GetCurrentValue()) {
179c678ed77SStefan Granitz         options.SetSilent(true);
180c678ed77SStefan Granitz       } else {
181c678ed77SStefan Granitz         options.SetPrintResults(true);
182c0b48ab6SJonas Devlieghere         options.SetPrintErrors(true);
183c678ed77SStefan Granitz         options.SetEchoCommands(m_interpreter.GetEchoCommands());
184c678ed77SStefan Granitz         options.SetEchoCommentCommands(m_interpreter.GetEchoCommentCommands());
185c678ed77SStefan Granitz       }
186122a4ebdSPavel Labath     }
18736de94cfSTatyana Krasnukha 
18836de94cfSTatyana Krasnukha     m_interpreter.HandleCommandsFromFile(cmd_file, options, result);
189ebc09c36SJim Ingham     return result.Succeeded();
190ebc09c36SJim Ingham   }
1916e3d8e7fSEugene Zelenko 
1925a988416SJim Ingham   CommandOptions m_options;
193ebc09c36SJim Ingham };
194ebc09c36SJim Ingham 
195ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
196ebc09c36SJim Ingham // CommandObjectCommandsAlias
197ebc09c36SJim Ingham 
19864becc11SRaphael Isemann #define LLDB_OPTIONS_alias
19964becc11SRaphael Isemann #include "CommandOptions.inc"
2001f0f5b5bSZachary Turner 
201b9c1b51eSKate Stone static const char *g_python_command_instructions =
202b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
203be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
20444d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
205be93a35aSEnrico Granata 
206b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
20745d0e238SEnrico Granata protected:
208b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
209ebc09c36SJim Ingham   public:
210b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
21145d0e238SEnrico Granata 
21245d0e238SEnrico Granata     ~CommandOptions() override = default;
21345d0e238SEnrico Granata 
2141f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
21570602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
2161f0f5b5bSZachary Turner     }
21745d0e238SEnrico Granata 
21897206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
219b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
22097206d57SZachary Turner       Status error;
22145d0e238SEnrico Granata 
2221f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
2238cef4b0bSZachary Turner       std::string option_str(option_value);
22445d0e238SEnrico Granata 
225b9c1b51eSKate Stone       switch (short_option) {
22645d0e238SEnrico Granata       case 'h':
2278cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
22845d0e238SEnrico Granata         m_help.SetOptionWasSet();
22945d0e238SEnrico Granata         break;
23045d0e238SEnrico Granata 
23145d0e238SEnrico Granata       case 'H':
2328cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
23345d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
23445d0e238SEnrico Granata         break;
23545d0e238SEnrico Granata 
23645d0e238SEnrico Granata       default:
23736162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
23845d0e238SEnrico Granata       }
23945d0e238SEnrico Granata 
24045d0e238SEnrico Granata       return error;
24145d0e238SEnrico Granata     }
24245d0e238SEnrico Granata 
243b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
24445d0e238SEnrico Granata       m_help.Clear();
24545d0e238SEnrico Granata       m_long_help.Clear();
24645d0e238SEnrico Granata     }
24745d0e238SEnrico Granata 
24845d0e238SEnrico Granata     OptionValueString m_help;
24945d0e238SEnrico Granata     OptionValueString m_long_help;
25045d0e238SEnrico Granata   };
25145d0e238SEnrico Granata 
25245d0e238SEnrico Granata   OptionGroupOptions m_option_group;
25345d0e238SEnrico Granata   CommandOptions m_command_options;
25445d0e238SEnrico Granata 
25545d0e238SEnrico Granata public:
256b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
25745d0e238SEnrico Granata 
2587428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
259b9c1b51eSKate Stone       : CommandObjectRaw(
260b9c1b51eSKate Stone             interpreter, "command alias",
261a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
262b9c1b51eSKate Stone         m_option_group(), m_command_options() {
26345d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
26445d0e238SEnrico Granata     m_option_group.Finalize();
26545d0e238SEnrico Granata 
266ebc09c36SJim Ingham     SetHelpLong(
267ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
268ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
269b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
270b9c1b51eSKate Stone         R"(
271ea671fbdSKate Stone 
272ea671fbdSKate Stone (lldb) command alias sc script
273ea671fbdSKate Stone 
274ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
275ea671fbdSKate Stone 
276ea671fbdSKate Stone (lldb) command alias bp breakpoint
277ea671fbdSKate Stone 
278b9c1b51eSKate Stone )"
279b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
280ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
281b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
282b9c1b51eSKate Stone         R"(
283ea671fbdSKate Stone 
284ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
285ea671fbdSKate Stone 
286ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
287ea671fbdSKate Stone 
288b9c1b51eSKate Stone )"
289b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
290ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
291ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
292b9c1b51eSKate Stone shows how to create aliases with options:"
293b9c1b51eSKate Stone         R"(
294ea671fbdSKate Stone 
295ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
296ea671fbdSKate Stone 
297b9c1b51eSKate Stone )"
298b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
299ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
300ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
301ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
302ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
303ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
304ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
305ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
306ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
307ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
308b9c1b51eSKate Stone launch' example below)."
309b9c1b51eSKate Stone         R"(
310ea671fbdSKate Stone 
311b9c1b51eSKate Stone )"
312b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
313ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
314b9c1b51eSKate Stone \".cpp\":"
315b9c1b51eSKate Stone         R"(
316ea671fbdSKate Stone 
317ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
318ea671fbdSKate Stone 
319b9c1b51eSKate Stone )"
320b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
321ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
322ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
323b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
324b9c1b51eSKate Stone         R"(
325ea671fbdSKate Stone 
326ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
327ea671fbdSKate Stone (lldb) bfl my-file.c 137
328ea671fbdSKate Stone 
329ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
330ea671fbdSKate Stone 
331ea671fbdSKate Stone Another example:
332ea671fbdSKate Stone 
333ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
334ea671fbdSKate Stone (lldb) pltty /dev/tty0
335ea671fbdSKate Stone 
336ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
337ea671fbdSKate Stone 
338b9c1b51eSKate Stone )"
339b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
340ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
341b9c1b51eSKate Stone rather than using a positional placeholder:"
342b9c1b51eSKate Stone         R"(
343ea671fbdSKate Stone 
344ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
345ea671fbdSKate Stone 
346b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
347ebc09c36SJim Ingham 
348405fe67fSCaroline Tice     CommandArgumentEntry arg1;
349405fe67fSCaroline Tice     CommandArgumentEntry arg2;
350405fe67fSCaroline Tice     CommandArgumentEntry arg3;
351405fe67fSCaroline Tice     CommandArgumentData alias_arg;
352405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
353405fe67fSCaroline Tice     CommandArgumentData options_arg;
354405fe67fSCaroline Tice 
355405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
356405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
357405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
358405fe67fSCaroline Tice 
359b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
360b9c1b51eSKate Stone     // argument entry.
361405fe67fSCaroline Tice     arg1.push_back(alias_arg);
362405fe67fSCaroline Tice 
363405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
364405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
365405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
366405fe67fSCaroline Tice 
367b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
368b9c1b51eSKate Stone     // argument entry.
369405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
370405fe67fSCaroline Tice 
371405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
372405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
373405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
374405fe67fSCaroline Tice 
375b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
376b9c1b51eSKate Stone     // argument entry.
377405fe67fSCaroline Tice     arg3.push_back(options_arg);
378405fe67fSCaroline Tice 
379405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
380405fe67fSCaroline Tice     m_arguments.push_back(arg1);
381405fe67fSCaroline Tice     m_arguments.push_back(arg2);
382405fe67fSCaroline Tice     m_arguments.push_back(arg3);
383ebc09c36SJim Ingham   }
384ebc09c36SJim Ingham 
3856e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
386ebc09c36SJim Ingham 
3875a988416SJim Ingham protected:
3884d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
389b9c1b51eSKate Stone                  CommandReturnObject &result) override {
3904d51a902SRaphael Isemann     if (raw_command_line.empty()) {
391d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
39245d0e238SEnrico Granata       return false;
39345d0e238SEnrico Granata     }
39445d0e238SEnrico Granata 
395e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
396e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
39745d0e238SEnrico Granata 
3983a0e1270SRaphael Isemann     OptionsWithRaw args_with_suffix(raw_command_line);
39945d0e238SEnrico Granata 
4003a0e1270SRaphael Isemann     if (args_with_suffix.HasArgs())
4013a0e1270SRaphael Isemann       if (!ParseOptionsAndNotify(args_with_suffix.GetArgs(), result,
4023a0e1270SRaphael Isemann                                  m_option_group, exe_ctx))
40345d0e238SEnrico Granata         return false;
40445d0e238SEnrico Granata 
405daed98e5SShivam Mittal     llvm::StringRef raw_command_string = args_with_suffix.GetRawPart();
406a01bccdbSZachary Turner     Args args(raw_command_string);
407844d2303SCaroline Tice 
40811eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
409d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
410844d2303SCaroline Tice       return false;
411844d2303SCaroline Tice     }
412844d2303SCaroline Tice 
413844d2303SCaroline Tice     // Get the alias command.
414844d2303SCaroline Tice 
4150d9a201eSRaphael Isemann     auto alias_command = args[0].ref();
4164574a890SZachary Turner     if (alias_command.startswith("-")) {
417d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
418b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
419b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
420b9c1b51eSKate Stone                              "a -- at the end of the options");
421d72e412fSEnrico Granata       }
422d72e412fSEnrico Granata       return false;
423d72e412fSEnrico Granata     }
424844d2303SCaroline Tice 
425b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
42605097246SAdrian Prantl     // which gets passed to 'Execute', which does the stripping itself.
427844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
428b9c1b51eSKate Stone     if (pos == 0) {
429844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
430844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
431844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
432844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
433b9c1b51eSKate Stone     } else {
434844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
435844d2303SCaroline Tice       return false;
436844d2303SCaroline Tice     }
437844d2303SCaroline Tice 
438844d2303SCaroline Tice     // Verify that the command is alias-able.
439771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
440b9c1b51eSKate Stone       result.AppendErrorWithFormat(
441b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
4424574a890SZachary Turner           args[0].c_str());
443844d2303SCaroline Tice       return false;
444844d2303SCaroline Tice     }
445844d2303SCaroline Tice 
446c5011aedSJim Ingham     if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
447c5011aedSJim Ingham       result.AppendErrorWithFormat(
448c5011aedSJim Ingham           "'%s' is a user container command and cannot be overwritten.\n"
449c5011aedSJim Ingham           "Delete it first with 'command container delete'\n",
450c5011aedSJim Ingham           args[0].c_str());
451c5011aedSJim Ingham       return false;
452c5011aedSJim Ingham     }
453c5011aedSJim Ingham 
454b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
455a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
456a01bccdbSZachary Turner     // name of the command object stripped off the front.
457a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
458b9c1b51eSKate Stone     CommandObject *cmd_obj =
459b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
460844d2303SCaroline Tice 
461b9c1b51eSKate Stone     if (!cmd_obj) {
462b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
463b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
464b9c1b51eSKate Stone                                    "  No alias created.",
465a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
466844d2303SCaroline Tice       return false;
467b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
468b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
46905097246SAdrian Prantl       // been updated to this point. Therefore can we pass it to the version of
47005097246SAdrian Prantl       // Execute that does not need/expect raw input in the alias.
4715a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
472b9c1b51eSKate Stone     } else {
473b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
474b9c1b51eSKate Stone                                       *cmd_obj, result);
4755a988416SJim Ingham     }
4765a988416SJim Ingham     return result.Succeeded();
4775a988416SJim Ingham   }
4785a988416SJim Ingham 
479a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
480a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
481b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
482b9c1b51eSKate Stone                                 CommandReturnObject &result) {
483844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
484844d2303SCaroline Tice 
485b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
486b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
487844d2303SCaroline Tice 
488*b9515041SDave Lee     const bool include_aliases = true;
489*b9515041SDave Lee     if (CommandObjectSP cmd_obj_sp = m_interpreter.GetCommandSPExact(
490*b9515041SDave Lee             cmd_obj.GetCommandName(), include_aliases)) {
491a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
492a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
493b9c1b51eSKate Stone         result.AppendWarningWithFormat(
494b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
495a01bccdbSZachary Turner             alias_command.str().c_str());
496844d2303SCaroline Tice       }
497b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
498a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
49945d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
50045d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
50145d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
50245d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
503844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
504b9c1b51eSKate Stone       } else {
505472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
506472362e6SCaroline Tice       }
507212130acSEnrico Granata 
508b9c1b51eSKate Stone     } else {
509212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
510212130acSEnrico Granata     }
511212130acSEnrico Granata 
512844d2303SCaroline Tice     return result.Succeeded();
513844d2303SCaroline Tice   }
514ebc09c36SJim Ingham 
515b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
516867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
517ebc09c36SJim Ingham 
518b9c1b51eSKate Stone     if (argc < 2) {
519d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
520ebc09c36SJim Ingham       return false;
521ebc09c36SJim Ingham     }
522ebc09c36SJim Ingham 
5234574a890SZachary Turner     // Save these in std::strings since we're going to shift them off.
524adcd0268SBenjamin Kramer     const std::string alias_command(std::string(args[0].ref()));
525adcd0268SBenjamin Kramer     const std::string actual_command(std::string(args[1].ref()));
526ebc09c36SJim Ingham 
527ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
528ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
529ebc09c36SJim Ingham 
530b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
531b9c1b51eSKate Stone     // object.
532ebc09c36SJim Ingham 
533771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
534b9c1b51eSKate Stone       result.AppendErrorWithFormat(
535b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
536ebc09c36SJim Ingham           alias_command.c_str());
5374574a890SZachary Turner       return false;
5384574a890SZachary Turner     }
5394574a890SZachary Turner 
540c5011aedSJim Ingham     if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
541c5011aedSJim Ingham       result.AppendErrorWithFormat(
542c5011aedSJim Ingham           "'%s' is user container command and cannot be overwritten.\n"
543c5011aedSJim Ingham           "Delete it first with 'command container delete'",
544c5011aedSJim Ingham           alias_command.c_str());
545c5011aedSJim Ingham       return false;
546c5011aedSJim Ingham     }
547c5011aedSJim Ingham 
548b9c1b51eSKate Stone     CommandObjectSP command_obj_sp(
549a449698cSZachary Turner         m_interpreter.GetCommandSPExact(actual_command, true));
550ebc09c36SJim Ingham     CommandObjectSP subcommand_obj_sp;
551ebc09c36SJim Ingham     bool use_subcommand = false;
5524574a890SZachary Turner     if (!command_obj_sp) {
5534574a890SZachary Turner       result.AppendErrorWithFormat("'%s' is not an existing command.\n",
5544574a890SZachary Turner                                    actual_command.c_str());
5554574a890SZachary Turner       return false;
5564574a890SZachary Turner     }
557ebc09c36SJim Ingham     CommandObject *cmd_obj = command_obj_sp.get();
5586e3d8e7fSEugene Zelenko     CommandObject *sub_cmd_obj = nullptr;
559b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
560b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
561ebc09c36SJim Ingham 
56211eb9c64SZachary Turner     while (cmd_obj->IsMultiwordObject() && !args.empty()) {
5630d9a201eSRaphael Isemann       auto sub_command = args[0].ref();
56411eb9c64SZachary Turner       assert(!sub_command.empty());
5654574a890SZachary Turner       subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
5664574a890SZachary Turner       if (!subcommand_obj_sp) {
567b9c1b51eSKate Stone         result.AppendErrorWithFormat(
568b9c1b51eSKate Stone             "'%s' is not a valid sub-command of '%s'.  "
569f415eeb4SCaroline Tice             "Unable to create alias.\n",
5704574a890SZachary Turner             args[0].c_str(), actual_command.c_str());
571ebc09c36SJim Ingham         return false;
572ebc09c36SJim Ingham       }
5734574a890SZachary Turner 
5744574a890SZachary Turner       sub_cmd_obj = subcommand_obj_sp.get();
5754574a890SZachary Turner       use_subcommand = true;
5764574a890SZachary Turner       args.Shift(); // Shift the sub_command word off the argument vector.
5774574a890SZachary Turner       cmd_obj = sub_cmd_obj;
578ebc09c36SJim Ingham     }
579ebc09c36SJim Ingham 
580ebc09c36SJim Ingham     // Verify & handle any options/arguments passed to the alias command
581ebc09c36SJim Ingham 
582212130acSEnrico Granata     std::string args_string;
583212130acSEnrico Granata 
58411eb9c64SZachary Turner     if (!args.empty()) {
585b9c1b51eSKate Stone       CommandObjectSP tmp_sp =
586a9448872SJonas Devlieghere           m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName());
587ebc09c36SJim Ingham       if (use_subcommand)
588a9448872SJonas Devlieghere         tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName());
589ca90c47eSCaroline Tice 
590ca90c47eSCaroline Tice       args.GetCommandString(args_string);
591867b185dSCaroline Tice     }
592ebc09c36SJim Ingham 
593771ef6d4SMalcolm Parsons     if (m_interpreter.AliasExists(alias_command) ||
594771ef6d4SMalcolm Parsons         m_interpreter.UserCommandExists(alias_command)) {
595b9c1b51eSKate Stone       result.AppendWarningWithFormat(
5964574a890SZachary Turner           "Overwriting existing definition for '%s'.\n", alias_command.c_str());
597ebc09c36SJim Ingham     }
598ebc09c36SJim Ingham 
599b9c1b51eSKate Stone     if (CommandAlias *alias = m_interpreter.AddAlias(
6004574a890SZachary Turner             alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
601771ef6d4SMalcolm Parsons             args_string)) {
60245d0e238SEnrico Granata       if (m_command_options.m_help.OptionWasSet())
60345d0e238SEnrico Granata         alias->SetHelp(m_command_options.m_help.GetCurrentValue());
60445d0e238SEnrico Granata       if (m_command_options.m_long_help.OptionWasSet())
60545d0e238SEnrico Granata         alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
606ebc09c36SJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
607b9c1b51eSKate Stone     } else {
608212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
609212130acSEnrico Granata       return false;
610212130acSEnrico Granata     }
611ebc09c36SJim Ingham 
612ebc09c36SJim Ingham     return result.Succeeded();
613ebc09c36SJim Ingham   }
614ebc09c36SJim Ingham };
615ebc09c36SJim Ingham 
616ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
617ebc09c36SJim Ingham // CommandObjectCommandsUnalias
618ebc09c36SJim Ingham 
619b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
620ebc09c36SJim Ingham public:
6217428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
622b9c1b51eSKate Stone       : CommandObjectParsed(
623b9c1b51eSKate Stone             interpreter, "command unalias",
624b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
625b9c1b51eSKate Stone             nullptr) {
626405fe67fSCaroline Tice     CommandArgumentEntry arg;
627405fe67fSCaroline Tice     CommandArgumentData alias_arg;
628405fe67fSCaroline Tice 
629405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
630405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
631405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
632405fe67fSCaroline Tice 
633b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
634b9c1b51eSKate Stone     // argument entry.
635405fe67fSCaroline Tice     arg.push_back(alias_arg);
636405fe67fSCaroline Tice 
637405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
638405fe67fSCaroline Tice     m_arguments.push_back(arg);
639ebc09c36SJim Ingham   }
640ebc09c36SJim Ingham 
6416e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
642ebc09c36SJim Ingham 
64331fd64acSGongyu Deng   void
64431fd64acSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
64531fd64acSGongyu Deng                            OptionElementVector &opt_element_vector) override {
64631fd64acSGongyu Deng     if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
64731fd64acSGongyu Deng       return;
64831fd64acSGongyu Deng 
64931fd64acSGongyu Deng     for (const auto &ent : m_interpreter.GetAliases()) {
65031fd64acSGongyu Deng       request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
65131fd64acSGongyu Deng     }
65231fd64acSGongyu Deng   }
65331fd64acSGongyu Deng 
6545a988416SJim Ingham protected:
655b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
656ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
657ebc09c36SJim Ingham     CommandObject *cmd_obj;
658ebc09c36SJim Ingham 
65911eb9c64SZachary Turner     if (args.empty()) {
66011eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
66111eb9c64SZachary Turner       return false;
66211eb9c64SZachary Turner     }
66311eb9c64SZachary Turner 
6640d9a201eSRaphael Isemann     auto command_name = args[0].ref();
665a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
6664574a890SZachary Turner     if (!cmd_obj) {
6674574a890SZachary Turner       result.AppendErrorWithFormat(
6684574a890SZachary Turner           "'%s' is not a known command.\nTry 'help' to see a "
6694574a890SZachary Turner           "current list of commands.\n",
670867e7d17SZachary Turner           args[0].c_str());
6714574a890SZachary Turner       return false;
6724574a890SZachary Turner     }
6734574a890SZachary Turner 
674b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
675b9c1b51eSKate Stone       if (cmd_obj->IsRemovable()) {
676b9c1b51eSKate Stone         result.AppendErrorWithFormat(
677b9c1b51eSKate Stone             "'%s' is not an alias, it is a debugger command which can be "
678b9c1b51eSKate Stone             "removed using the 'command delete' command.\n",
679867e7d17SZachary Turner             args[0].c_str());
680b9c1b51eSKate Stone       } else {
681b9c1b51eSKate Stone         result.AppendErrorWithFormat(
682b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
683867e7d17SZachary Turner             args[0].c_str());
684b547278cSGreg Clayton       }
6854574a890SZachary Turner       return false;
6864574a890SZachary Turner     }
6874574a890SZachary Turner 
688b9c1b51eSKate Stone     if (!m_interpreter.RemoveAlias(command_name)) {
689a7015092SGreg Clayton       if (m_interpreter.AliasExists(command_name))
690b9c1b51eSKate Stone         result.AppendErrorWithFormat(
691867e7d17SZachary Turner             "Error occurred while attempting to unalias '%s'.\n",
692867e7d17SZachary Turner             args[0].c_str());
693ebc09c36SJim Ingham       else
694b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
695867e7d17SZachary Turner                                      args[0].c_str());
6964574a890SZachary Turner       return false;
697ebc09c36SJim Ingham     }
698ebc09c36SJim Ingham 
6994574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
700ebc09c36SJim Ingham     return result.Succeeded();
701ebc09c36SJim Ingham   }
702ebc09c36SJim Ingham };
703ebc09c36SJim Ingham 
704b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
705b547278cSGreg Clayton // CommandObjectCommandsDelete
706b547278cSGreg Clayton 
707b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
708b547278cSGreg Clayton public:
7097428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
710b9c1b51eSKate Stone       : CommandObjectParsed(
711b9c1b51eSKate Stone             interpreter, "command delete",
712b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
713b9c1b51eSKate Stone             nullptr) {
714b547278cSGreg Clayton     CommandArgumentEntry arg;
715b547278cSGreg Clayton     CommandArgumentData alias_arg;
716b547278cSGreg Clayton 
717b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
718b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
719b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
720b547278cSGreg Clayton 
721b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
722b9c1b51eSKate Stone     // argument entry.
723b547278cSGreg Clayton     arg.push_back(alias_arg);
724b547278cSGreg Clayton 
725b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
726b547278cSGreg Clayton     m_arguments.push_back(arg);
727b547278cSGreg Clayton   }
728b547278cSGreg Clayton 
7296e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
730b547278cSGreg Clayton 
73131fd64acSGongyu Deng   void
73231fd64acSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
73331fd64acSGongyu Deng                            OptionElementVector &opt_element_vector) override {
73431fd64acSGongyu Deng     if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
73531fd64acSGongyu Deng       return;
73631fd64acSGongyu Deng 
73731fd64acSGongyu Deng     for (const auto &ent : m_interpreter.GetCommands()) {
73831fd64acSGongyu Deng       if (ent.second->IsRemovable())
73931fd64acSGongyu Deng         request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
74031fd64acSGongyu Deng     }
74131fd64acSGongyu Deng   }
74231fd64acSGongyu Deng 
743b547278cSGreg Clayton protected:
744b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
745b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
746b547278cSGreg Clayton 
74711eb9c64SZachary Turner     if (args.empty()) {
74811eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
74911eb9c64SZachary Turner                                    "defined regular expression command names",
750a449698cSZachary Turner                                    GetCommandName().str().c_str());
751d77ea5b2SRaphael Isemann       return false;
75211eb9c64SZachary Turner     }
75311eb9c64SZachary Turner 
7540d9a201eSRaphael Isemann     auto command_name = args[0].ref();
7554574a890SZachary Turner     if (!m_interpreter.CommandExists(command_name)) {
75646d4aa21SEnrico Granata       StreamString error_msg_stream;
757d5b44036SJonas Devlieghere       const bool generate_upropos = true;
75846d4aa21SEnrico Granata       const bool generate_type_lookup = false;
759b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
7604574a890SZachary Turner           &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
761d5b44036SJonas Devlieghere           generate_upropos, generate_type_lookup);
762c156427dSZachary Turner       result.AppendError(error_msg_stream.GetString());
7634574a890SZachary Turner       return false;
764b547278cSGreg Clayton     }
765b547278cSGreg Clayton 
7664574a890SZachary Turner     if (!m_interpreter.RemoveCommand(command_name)) {
7674574a890SZachary Turner       result.AppendErrorWithFormat(
7684574a890SZachary Turner           "'%s' is a permanent debugger command and cannot be removed.\n",
769867e7d17SZachary Turner           args[0].c_str());
7704574a890SZachary Turner       return false;
7714574a890SZachary Turner     }
7724574a890SZachary Turner 
7734574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
7744574a890SZachary Turner     return true;
775b547278cSGreg Clayton   }
776b547278cSGreg Clayton };
777b547278cSGreg Clayton 
778de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
7791f0f5b5bSZachary Turner 
78064becc11SRaphael Isemann #define LLDB_OPTIONS_regex
78164becc11SRaphael Isemann #include "CommandOptions.inc"
7821f0f5b5bSZachary Turner 
7835a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
784de164aaaSGreg Clayton 
785b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
786b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
787de164aaaSGreg Clayton public:
7887428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
789b9c1b51eSKate Stone       : CommandObjectParsed(
790a925974bSAdrian Prantl             interpreter, "command regex",
791a925974bSAdrian Prantl             "Define a custom command in terms of "
792b9c1b51eSKate Stone             "existing commands by matching "
793b9c1b51eSKate Stone             "regular expressions.",
7940e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
795b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
796b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
797b9c1b51eSKate Stone         m_options() {
798b9c1b51eSKate Stone     SetHelpLong(
799b9c1b51eSKate Stone         R"(
800b9c1b51eSKate Stone )"
801b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
802ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
803b9c1b51eSKate Stone using the regular expression substitution format of:"
804b9c1b51eSKate Stone         R"(
805ea671fbdSKate Stone 
806ea671fbdSKate Stone     s/<regex>/<subst>/
807ea671fbdSKate Stone 
808b9c1b51eSKate Stone )"
809b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
810ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
811b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
812b9c1b51eSKate Stone         R"(
813ea671fbdSKate Stone 
814b9c1b51eSKate Stone )"
815b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
816ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
817ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
818b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
819b9c1b51eSKate Stone         R"(
820ea671fbdSKate Stone 
821ea671fbdSKate Stone EXAMPLES
822ea671fbdSKate Stone 
823b9c1b51eSKate Stone )"
824b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
825ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
826b9c1b51eSKate Stone a number follows 'f':"
827b9c1b51eSKate Stone         R"(
828ea671fbdSKate Stone 
829b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
830de164aaaSGreg Clayton   }
831de164aaaSGreg Clayton 
8326e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
833de164aaaSGreg Clayton 
8345a988416SJim Ingham protected:
8350affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
8367ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
8370affb582SDave Lee     if (output_sp && interactive) {
8380affb582SDave Lee       output_sp->PutCString("Enter one or more sed substitution commands in "
839b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
840b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
84144d93782SGreg Clayton       output_sp->Flush();
84244d93782SGreg Clayton     }
84344d93782SGreg Clayton   }
84444d93782SGreg Clayton 
845b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
846b9c1b51eSKate Stone                               std::string &data) override {
84744d93782SGreg Clayton     io_handler.SetIsDone(true);
848d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
84944d93782SGreg Clayton       StringList lines;
850b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
85144d93782SGreg Clayton         bool check_only = false;
8524c78b788SRaphael Isemann         for (const std::string &line : lines) {
8534c78b788SRaphael Isemann           Status error = AppendRegexSubstitution(line, check_only);
854b9c1b51eSKate Stone           if (error.Fail()) {
85557179860SJonas Devlieghere             if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode()) {
85657179860SJonas Devlieghere               StreamSP out_stream = GetDebugger().GetAsyncOutputStream();
85744d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
85844d93782SGreg Clayton             }
85944d93782SGreg Clayton           }
86044d93782SGreg Clayton         }
86144d93782SGreg Clayton       }
862d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
863d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
86444d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
86544d93782SGreg Clayton       }
86644d93782SGreg Clayton     }
86744d93782SGreg Clayton   }
86844d93782SGreg Clayton 
869b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
8705a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
871b9c1b51eSKate Stone     if (argc == 0) {
872b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
873b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
87411eb9c64SZachary Turner       return false;
87511eb9c64SZachary Turner     }
87611eb9c64SZachary Turner 
87797206d57SZachary Turner     Status error;
8780d9a201eSRaphael Isemann     auto name = command[0].ref();
879a8f3ae7cSJonas Devlieghere     m_regex_cmd_up = std::make_unique<CommandObjectRegexCommand>(
8804574a890SZachary Turner         m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0,
8814574a890SZachary Turner         true);
8820e5e5a79SGreg Clayton 
883b9c1b51eSKate Stone     if (argc == 1) {
88457179860SJonas Devlieghere       Debugger &debugger = GetDebugger();
885e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
88644d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
887b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
888b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
88973d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
890514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
891514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
892b9c1b51eSKate Stone           multiple_lines, color_prompt,
893f6913cd7SGreg Clayton           0, // Don't show line numbers
894d77c2e09SJonas Devlieghere           *this, nullptr));
89544d93782SGreg Clayton 
896b9c1b51eSKate Stone       if (io_handler_sp) {
8977ce2de2cSJonas Devlieghere         debugger.RunIOHandlerAsync(io_handler_sp);
898de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
899de164aaaSGreg Clayton       }
900b9c1b51eSKate Stone     } else {
90197d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
90244d93782SGreg Clayton         bool check_only = false;
9030d9a201eSRaphael Isemann         error = AppendRegexSubstitution(entry.ref(), check_only);
9040e5e5a79SGreg Clayton         if (error.Fail())
9050e5e5a79SGreg Clayton           break;
9060e5e5a79SGreg Clayton       }
9070e5e5a79SGreg Clayton 
908b9c1b51eSKate Stone       if (error.Success()) {
9090e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
9100e5e5a79SGreg Clayton       }
9110e5e5a79SGreg Clayton     }
912b9c1b51eSKate Stone     if (error.Fail()) {
9130e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
914de164aaaSGreg Clayton     }
9150e5e5a79SGreg Clayton 
916de164aaaSGreg Clayton     return result.Succeeded();
917de164aaaSGreg Clayton   }
918de164aaaSGreg Clayton 
91997206d57SZachary Turner   Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
920b9c1b51eSKate Stone                                  bool check_only) {
92197206d57SZachary Turner     Status error;
9220e5e5a79SGreg Clayton 
923d5b44036SJonas Devlieghere     if (!m_regex_cmd_up) {
924b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
925b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
926b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9270e5e5a79SGreg Clayton       return error;
928de164aaaSGreg Clayton     }
9290e5e5a79SGreg Clayton 
9300e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
9310e5e5a79SGreg Clayton 
932b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
933b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
934b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
935b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9360e5e5a79SGreg Clayton       return error;
9370e5e5a79SGreg Clayton     }
9380e5e5a79SGreg Clayton 
939b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
940b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
941b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
942b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
9430e5e5a79SGreg Clayton       return error;
9440e5e5a79SGreg Clayton     }
9450e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
94605097246SAdrian Prantl     // use the char that follows 's' as the regex separator character so we can
94705097246SAdrian Prantl     // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
9480e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
949b9c1b51eSKate Stone     const size_t second_separator_char_pos =
950b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
9510e5e5a79SGreg Clayton 
952b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
953b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
954b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
9550e5e5a79SGreg Clayton           separator_char,
9560e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
957ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
958b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9590e5e5a79SGreg Clayton       return error;
9600e5e5a79SGreg Clayton     }
9610e5e5a79SGreg Clayton 
962b9c1b51eSKate Stone     const size_t third_separator_char_pos =
963b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
9640e5e5a79SGreg Clayton 
965b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
966b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
967b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
9680e5e5a79SGreg Clayton           separator_char,
9690e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
970ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
971b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9720e5e5a79SGreg Clayton       return error;
9730e5e5a79SGreg Clayton     }
9740e5e5a79SGreg Clayton 
975b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
97605097246SAdrian Prantl       // Make sure that everything that follows the last regex separator char
977b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
978b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
979b9c1b51eSKate Stone           std::string::npos) {
980b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
981b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
982b9c1b51eSKate Stone             "string: '%.*s'",
983b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
9840e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
9850e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
9860e5e5a79SGreg Clayton         return error;
9870e5e5a79SGreg Clayton       }
988b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
989b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
990b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
991b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
9920e5e5a79SGreg Clayton           regex_sed.data());
9930e5e5a79SGreg Clayton       return error;
994b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
995b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
996b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
997b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
9980e5e5a79SGreg Clayton           regex_sed.data());
9990e5e5a79SGreg Clayton       return error;
10000e5e5a79SGreg Clayton     }
100144d93782SGreg Clayton 
1002b9c1b51eSKate Stone     if (!check_only) {
1003adcd0268SBenjamin Kramer       std::string regex(std::string(regex_sed.substr(
1004adcd0268SBenjamin Kramer           first_separator_char_pos + 1,
1005adcd0268SBenjamin Kramer           second_separator_char_pos - first_separator_char_pos - 1)));
1006adcd0268SBenjamin Kramer       std::string subst(std::string(regex_sed.substr(
1007adcd0268SBenjamin Kramer           second_separator_char_pos + 1,
1008adcd0268SBenjamin Kramer           third_separator_char_pos - second_separator_char_pos - 1)));
100943224195SRaphael Isemann       m_regex_cmd_up->AddRegexCommand(regex, subst);
101044d93782SGreg Clayton     }
10110e5e5a79SGreg Clayton     return error;
1012de164aaaSGreg Clayton   }
1013de164aaaSGreg Clayton 
1014b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1015d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
1016d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
1017d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
1018de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1019de164aaaSGreg Clayton       }
1020de164aaaSGreg Clayton     }
1021de164aaaSGreg Clayton   }
1022de164aaaSGreg Clayton 
1023de164aaaSGreg Clayton private:
1024d5b44036SJonas Devlieghere   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up;
1025de164aaaSGreg Clayton 
1026b9c1b51eSKate Stone   class CommandOptions : public Options {
1027de164aaaSGreg Clayton   public:
1028b9c1b51eSKate Stone     CommandOptions() : Options() {}
1029de164aaaSGreg Clayton 
10306e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1031de164aaaSGreg Clayton 
103297206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1033b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
103497206d57SZachary Turner       Status error;
10353bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1036de164aaaSGreg Clayton 
1037b9c1b51eSKate Stone       switch (short_option) {
1038de164aaaSGreg Clayton       case 'h':
1039adcd0268SBenjamin Kramer         m_help.assign(std::string(option_arg));
1040de164aaaSGreg Clayton         break;
1041de164aaaSGreg Clayton       case 's':
1042adcd0268SBenjamin Kramer         m_syntax.assign(std::string(option_arg));
1043de164aaaSGreg Clayton         break;
1044de164aaaSGreg Clayton       default:
104536162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
1046de164aaaSGreg Clayton       }
1047de164aaaSGreg Clayton 
1048de164aaaSGreg Clayton       return error;
1049de164aaaSGreg Clayton     }
1050de164aaaSGreg Clayton 
1051b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1052de164aaaSGreg Clayton       m_help.clear();
1053de164aaaSGreg Clayton       m_syntax.clear();
1054de164aaaSGreg Clayton     }
1055de164aaaSGreg Clayton 
10561f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
105770602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
10581f0f5b5bSZachary Turner     }
1059de164aaaSGreg Clayton 
1060daed98e5SShivam Mittal     llvm::StringRef GetHelp() { return m_help; }
10616e3d8e7fSEugene Zelenko 
1062daed98e5SShivam Mittal     llvm::StringRef GetSyntax() { return m_syntax; }
10636e3d8e7fSEugene Zelenko 
1064de164aaaSGreg Clayton   protected:
10656e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
10666e3d8e7fSEugene Zelenko 
1067de164aaaSGreg Clayton     std::string m_help;
1068de164aaaSGreg Clayton     std::string m_syntax;
1069de164aaaSGreg Clayton   };
1070de164aaaSGreg Clayton 
1071b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1072de164aaaSGreg Clayton 
10735a988416SJim Ingham   CommandOptions m_options;
1074de164aaaSGreg Clayton };
1075de164aaaSGreg Clayton 
1076b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1077223383edSEnrico Granata public:
1078b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1079b9c1b51eSKate Stone                               std::string funct, std::string help,
1080b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1081a925974bSAdrian Prantl       : CommandObjectRaw(interpreter, name), m_function_name(funct),
1082a925974bSAdrian Prantl         m_synchro(synch), m_fetched_help_long(false) {
1083735152e3SEnrico Granata     if (!help.empty())
1084442f6530SZachary Turner       SetHelp(help);
1085b9c1b51eSKate Stone     else {
1086735152e3SEnrico Granata       StreamString stream;
1087735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1088c156427dSZachary Turner       SetHelp(stream.GetString());
1089735152e3SEnrico Granata     }
1090223383edSEnrico Granata   }
1091223383edSEnrico Granata 
10926e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1093223383edSEnrico Granata 
1094b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
10955a988416SJim Ingham 
1096b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
10975a988416SJim Ingham 
1098b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
10995a988416SJim Ingham 
1100442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1101442f6530SZachary Turner     if (m_fetched_help_long)
1102442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1103442f6530SZachary Turner 
11042b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1105442f6530SZachary Turner     if (!scripter)
1106442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1107442f6530SZachary Turner 
1108fac939e9SEnrico Granata     std::string docstring;
1109442f6530SZachary Turner     m_fetched_help_long =
1110442f6530SZachary Turner         scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1111fac939e9SEnrico Granata     if (!docstring.empty())
1112442f6530SZachary Turner       SetHelpLong(docstring);
1113fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1114fac939e9SEnrico Granata   }
1115fac939e9SEnrico Granata 
11165a988416SJim Ingham protected:
11174d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1118b9c1b51eSKate Stone                  CommandReturnObject &result) override {
11192b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1120223383edSEnrico Granata 
112197206d57SZachary Turner     Status error;
1122223383edSEnrico Granata 
112370f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
112470f11f88SJim Ingham 
1125a925974bSAdrian Prantl     if (!scripter || !scripter->RunScriptBasedCommand(
1126a925974bSAdrian Prantl                          m_function_name.c_str(), raw_command_line, m_synchro,
1127a925974bSAdrian Prantl                          result, error, m_exe_ctx)) {
1128223383edSEnrico Granata       result.AppendError(error.AsCString());
1129b9c1b51eSKate Stone     } else {
113070f11f88SJim Ingham       // Don't change the status if the command already set it...
1131b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1132c156427dSZachary Turner         if (result.GetOutputData().empty())
1133223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
113470f11f88SJim Ingham         else
113570f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
113670f11f88SJim Ingham       }
113770f11f88SJim Ingham     }
1138223383edSEnrico Granata 
1139223383edSEnrico Granata     return result.Succeeded();
1140223383edSEnrico Granata   }
1141223383edSEnrico Granata 
11426e3d8e7fSEugene Zelenko private:
11436e3d8e7fSEugene Zelenko   std::string m_function_name;
11446e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
11456e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1146223383edSEnrico Granata };
1147223383edSEnrico Granata 
1148b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
11499fe00e52SEnrico Granata public:
11509fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
11519fe00e52SEnrico Granata                                std::string name,
11520641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1153b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1154a925974bSAdrian Prantl       : CommandObjectRaw(interpreter, name), m_cmd_obj_sp(cmd_obj_sp),
1155a925974bSAdrian Prantl         m_synchro(synch), m_fetched_help_short(false),
1156b9c1b51eSKate Stone         m_fetched_help_long(false) {
11579fe00e52SEnrico Granata     StreamString stream;
11589fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
1159c156427dSZachary Turner     SetHelp(stream.GetString());
11602b29b432SJonas Devlieghere     if (ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter())
1161e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
11629fe00e52SEnrico Granata   }
11639fe00e52SEnrico Granata 
11646e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
11659fe00e52SEnrico Granata 
1166b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
11679fe00e52SEnrico Granata 
1168b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
11699fe00e52SEnrico Granata 
1170442f6530SZachary Turner   llvm::StringRef GetHelp() override {
1171442f6530SZachary Turner     if (m_fetched_help_short)
1172442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
11732b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1174442f6530SZachary Turner     if (!scripter)
1175442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
11766f79bb2dSEnrico Granata     std::string docstring;
1177b9c1b51eSKate Stone     m_fetched_help_short =
1178b9c1b51eSKate Stone         scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
11796f79bb2dSEnrico Granata     if (!docstring.empty())
1180442f6530SZachary Turner       SetHelp(docstring);
1181442f6530SZachary Turner 
11826f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
11836f79bb2dSEnrico Granata   }
11846f79bb2dSEnrico Granata 
1185442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1186442f6530SZachary Turner     if (m_fetched_help_long)
1187442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1188442f6530SZachary Turner 
11892b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1190442f6530SZachary Turner     if (!scripter)
1191442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1192442f6530SZachary Turner 
11936f79bb2dSEnrico Granata     std::string docstring;
1194b9c1b51eSKate Stone     m_fetched_help_long =
1195b9c1b51eSKate Stone         scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
11966f79bb2dSEnrico Granata     if (!docstring.empty())
1197442f6530SZachary Turner       SetHelpLong(docstring);
11989fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
11999fe00e52SEnrico Granata   }
12009fe00e52SEnrico Granata 
12019fe00e52SEnrico Granata protected:
12024d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1203b9c1b51eSKate Stone                  CommandReturnObject &result) override {
12042b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
12059fe00e52SEnrico Granata 
120697206d57SZachary Turner     Status error;
12079fe00e52SEnrico Granata 
12089fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
12099fe00e52SEnrico Granata 
1210b9c1b51eSKate Stone     if (!scripter ||
1211b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1212b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
12139fe00e52SEnrico Granata       result.AppendError(error.AsCString());
1214b9c1b51eSKate Stone     } else {
12159fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1216b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1217c156427dSZachary Turner         if (result.GetOutputData().empty())
12189fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
12199fe00e52SEnrico Granata         else
12209fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
12219fe00e52SEnrico Granata       }
12229fe00e52SEnrico Granata     }
12239fe00e52SEnrico Granata 
12249fe00e52SEnrico Granata     return result.Succeeded();
12259fe00e52SEnrico Granata   }
12269fe00e52SEnrico Granata 
12276e3d8e7fSEugene Zelenko private:
12286e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
12296e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
12306e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
12316e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
12329fe00e52SEnrico Granata };
12339fe00e52SEnrico Granata 
1234a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
123564becc11SRaphael Isemann #define LLDB_OPTIONS_script_import
123664becc11SRaphael Isemann #include "CommandOptions.inc"
12371f0f5b5bSZachary Turner 
1238b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
12395a988416SJim Ingham public:
1240b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1241b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1242b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1243b9c1b51eSKate Stone         m_options() {
12445a988416SJim Ingham     CommandArgumentEntry arg1;
12455a988416SJim Ingham     CommandArgumentData cmd_arg;
12465a988416SJim Ingham 
12475a988416SJim Ingham     // Define the first (and only) variant of this arg.
12485a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
12493b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
12505a988416SJim Ingham 
1251b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1252b9c1b51eSKate Stone     // argument entry.
12535a988416SJim Ingham     arg1.push_back(cmd_arg);
12545a988416SJim Ingham 
12555a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
12565a988416SJim Ingham     m_arguments.push_back(arg1);
12575a988416SJim Ingham   }
12585a988416SJim Ingham 
12596e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
12605a988416SJim Ingham 
1261ae34ed2cSRaphael Isemann   void
1262ae34ed2cSRaphael Isemann   HandleArgumentCompletion(CompletionRequest &request,
12632443bbd4SRaphael Isemann                            OptionElementVector &opt_element_vector) override {
1264b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1265b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1266a2e76c0bSRaphael Isemann         request, nullptr);
12675a988416SJim Ingham   }
12685a988416SJim Ingham 
1269b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
12705a988416SJim Ingham 
12715a988416SJim Ingham protected:
1272b9c1b51eSKate Stone   class CommandOptions : public Options {
12730a305db7SEnrico Granata   public:
1274b9c1b51eSKate Stone     CommandOptions() : Options() {}
12750a305db7SEnrico Granata 
12766e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
12770a305db7SEnrico Granata 
127897206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1279b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
128097206d57SZachary Turner       Status error;
12813bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
12820a305db7SEnrico Granata 
1283b9c1b51eSKate Stone       switch (short_option) {
12840a305db7SEnrico Granata       case 'r':
128515625112SJonas Devlieghere         // NO-OP
12860a305db7SEnrico Granata         break;
128700bb397bSJonas Devlieghere       case 'c':
128800bb397bSJonas Devlieghere         relative_to_command_file = true;
128900bb397bSJonas Devlieghere         break;
1290f9517353SJonas Devlieghere       case 's':
1291f9517353SJonas Devlieghere         silent = true;
1292f9517353SJonas Devlieghere         break;
12930a305db7SEnrico Granata       default:
129436162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
12950a305db7SEnrico Granata       }
12960a305db7SEnrico Granata 
12970a305db7SEnrico Granata       return error;
12980a305db7SEnrico Granata     }
12990a305db7SEnrico Granata 
1300b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
130100bb397bSJonas Devlieghere       relative_to_command_file = false;
13020a305db7SEnrico Granata     }
13030a305db7SEnrico Granata 
13041f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
130570602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
13061f0f5b5bSZachary Turner     }
130700bb397bSJonas Devlieghere     bool relative_to_command_file = false;
1308f9517353SJonas Devlieghere     bool silent = false;
13090a305db7SEnrico Granata   };
13100a305db7SEnrico Granata 
1311b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
131211eb9c64SZachary Turner     if (command.empty()) {
13133b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1314a9dbf432SEnrico Granata       return false;
1315a9dbf432SEnrico Granata     }
1316a9dbf432SEnrico Granata 
131700bb397bSJonas Devlieghere     FileSpec source_dir = {};
131800bb397bSJonas Devlieghere     if (m_options.relative_to_command_file) {
131900bb397bSJonas Devlieghere       source_dir = GetDebugger().GetCommandInterpreter().GetCurrentSourceDir();
132000bb397bSJonas Devlieghere       if (!source_dir) {
132100bb397bSJonas Devlieghere         result.AppendError("command script import -c can only be specified "
132200bb397bSJonas Devlieghere                            "from a command file");
132300bb397bSJonas Devlieghere         return false;
132400bb397bSJonas Devlieghere       }
132500bb397bSJonas Devlieghere     }
132600bb397bSJonas Devlieghere 
132711eb9c64SZachary Turner     for (auto &entry : command.entries()) {
132897206d57SZachary Turner       Status error;
1329a9dbf432SEnrico Granata 
1330f9517353SJonas Devlieghere       LoadScriptOptions options;
1331f9517353SJonas Devlieghere       options.SetInitSession(true);
1332f9517353SJonas Devlieghere       options.SetSilent(m_options.silent);
1333f9517353SJonas Devlieghere 
1334b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
133511eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
133611eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
133705097246SAdrian Prantl       // script imports" in __lldb_init_module the real fix is to have
133805097246SAdrian Prantl       // recursive commands possible with a CommandInvocation object separate
133905097246SAdrian Prantl       // from the CommandObject itself, so that recursive command invocations
134005097246SAdrian Prantl       // won't stomp on each other (wrt to execution contents, options, and
134105097246SAdrian Prantl       // more)
1342078551c7SEnrico Granata       m_exe_ctx.Clear();
13432b29b432SJonas Devlieghere       if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
1344f9517353SJonas Devlieghere               entry.c_str(), options, error, /*module_sp=*/nullptr,
1345f9517353SJonas Devlieghere               source_dir)) {
1346a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1347b9c1b51eSKate Stone       } else {
1348b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1349b9c1b51eSKate Stone                                      error.AsCString());
1350a9dbf432SEnrico Granata       }
13513b00e35bSEnrico Granata     }
1352a9dbf432SEnrico Granata 
1353a9dbf432SEnrico Granata     return result.Succeeded();
1354a9dbf432SEnrico Granata   }
13550a305db7SEnrico Granata 
13565a988416SJim Ingham   CommandOptions m_options;
1357a9dbf432SEnrico Granata };
1358223383edSEnrico Granata 
1359223383edSEnrico Granata // CommandObjectCommandsScriptAdd
13608fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_synchro_type[] = {
1361e063ecccSJonas Devlieghere     {
1362e063ecccSJonas Devlieghere         eScriptedCommandSynchronicitySynchronous,
1363e063ecccSJonas Devlieghere         "synchronous",
1364e063ecccSJonas Devlieghere         "Run synchronous",
1365e063ecccSJonas Devlieghere     },
1366e063ecccSJonas Devlieghere     {
1367e063ecccSJonas Devlieghere         eScriptedCommandSynchronicityAsynchronous,
1368e063ecccSJonas Devlieghere         "asynchronous",
1369e063ecccSJonas Devlieghere         "Run asynchronous",
1370e063ecccSJonas Devlieghere     },
1371e063ecccSJonas Devlieghere     {
1372e063ecccSJonas Devlieghere         eScriptedCommandSynchronicityCurrentValue,
1373e063ecccSJonas Devlieghere         "current",
1374e063ecccSJonas Devlieghere         "Do not alter current setting",
1375e063ecccSJonas Devlieghere     },
1376e063ecccSJonas Devlieghere };
13771f0f5b5bSZachary Turner 
13788fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptSynchroType() {
13798fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_synchro_type);
13808fe53c49STatyana Krasnukha }
13818fe53c49STatyana Krasnukha 
138264becc11SRaphael Isemann #define LLDB_OPTIONS_script_add
138364becc11SRaphael Isemann #include "CommandOptions.inc"
13841f0f5b5bSZachary Turner 
1385b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1386b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
13875a988416SJim Ingham public:
1388b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1389b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
13905a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
1391c5011aedSJim Ingham                             "Add a scripted function as an lldb command. "
1392c5011aedSJim Ingham                             "If you provide a single argument, the command "
1393c5011aedSJim Ingham                             "will be added at the root level of the command "
1394c5011aedSJim Ingham                             "hierarchy.  If there are more arguments they "
1395c5011aedSJim Ingham                             "must be a path to a user-added container "
1396c5011aedSJim Ingham                             "command, and the last element will be the new "
1397c5011aedSJim Ingham                             "command name."),
1398b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
13995a988416SJim Ingham     CommandArgumentEntry arg1;
14005a988416SJim Ingham     CommandArgumentData cmd_arg;
14015a988416SJim Ingham 
1402c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
1403c5011aedSJim Ingham     // you want to add.
1404c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1405c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
14065a988416SJim Ingham 
1407b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1408b9c1b51eSKate Stone     // argument entry.
14095a988416SJim Ingham     arg1.push_back(cmd_arg);
14105a988416SJim Ingham 
14115a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14125a988416SJim Ingham     m_arguments.push_back(arg1);
14135a988416SJim Ingham   }
14145a988416SJim Ingham 
14156e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
14165a988416SJim Ingham 
1417b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14185a988416SJim Ingham 
1419c5011aedSJim Ingham   void
1420c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
1421c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
1422c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1423c5011aedSJim Ingham                                                       opt_element_vector);
1424c5011aedSJim Ingham   }
1425c5011aedSJim Ingham 
14265a988416SJim Ingham protected:
1427b9c1b51eSKate Stone   class CommandOptions : public Options {
1428223383edSEnrico Granata   public:
1429b9c1b51eSKate Stone     CommandOptions()
14309494c510SJonas Devlieghere         : Options(), m_class_name(), m_funct_name(), m_short_help() {}
1431223383edSEnrico Granata 
14326e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1433223383edSEnrico Granata 
143497206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1435b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
143697206d57SZachary Turner       Status error;
14373bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1438223383edSEnrico Granata 
1439b9c1b51eSKate Stone       switch (short_option) {
1440223383edSEnrico Granata       case 'f':
1441fe11483bSZachary Turner         if (!option_arg.empty())
1442adcd0268SBenjamin Kramer           m_funct_name = std::string(option_arg);
1443735152e3SEnrico Granata         break;
14449fe00e52SEnrico Granata       case 'c':
1445fe11483bSZachary Turner         if (!option_arg.empty())
1446adcd0268SBenjamin Kramer           m_class_name = std::string(option_arg);
14479fe00e52SEnrico Granata         break;
1448735152e3SEnrico Granata       case 'h':
1449fe11483bSZachary Turner         if (!option_arg.empty())
1450adcd0268SBenjamin Kramer           m_short_help = std::string(option_arg);
1451223383edSEnrico Granata         break;
1452c5011aedSJim Ingham       case 'o':
1453c5011aedSJim Ingham         m_overwrite = true;
1454c5011aedSJim Ingham         break;
14550a305db7SEnrico Granata       case 's':
1456b9c1b51eSKate Stone         m_synchronicity =
145747cbf4a0SPavel Labath             (ScriptedCommandSynchronicity)OptionArgParser::ToOptionEnum(
1458fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
14590a305db7SEnrico Granata         if (!error.Success())
1460b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1461fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1462fe11483bSZachary Turner               option_arg.str().c_str());
14630a305db7SEnrico Granata         break;
1464223383edSEnrico Granata       default:
146536162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
1466223383edSEnrico Granata       }
1467223383edSEnrico Granata 
1468223383edSEnrico Granata       return error;
1469223383edSEnrico Granata     }
1470223383edSEnrico Granata 
1471b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
14729fe00e52SEnrico Granata       m_class_name.clear();
1473735152e3SEnrico Granata       m_funct_name.clear();
1474735152e3SEnrico Granata       m_short_help.clear();
1475c5011aedSJim Ingham       m_overwrite = false;
147644d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1477223383edSEnrico Granata     }
1478223383edSEnrico Granata 
14791f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
148070602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
14811f0f5b5bSZachary Turner     }
1482223383edSEnrico Granata 
1483223383edSEnrico Granata     // Instance variables to hold the values for command options.
1484223383edSEnrico Granata 
14859fe00e52SEnrico Granata     std::string m_class_name;
1486223383edSEnrico Granata     std::string m_funct_name;
1487735152e3SEnrico Granata     std::string m_short_help;
1488c5011aedSJim Ingham     bool m_overwrite;
14899494c510SJonas Devlieghere     ScriptedCommandSynchronicity m_synchronicity =
14909494c510SJonas Devlieghere         eScriptedCommandSynchronicitySynchronous;
1491223383edSEnrico Granata   };
1492223383edSEnrico Granata 
14930affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
14947ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
14950affb582SDave Lee     if (output_sp && interactive) {
149644d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
149744d93782SGreg Clayton       output_sp->Flush();
1498223383edSEnrico Granata     }
1499223383edSEnrico Granata   }
1500223383edSEnrico Granata 
1501b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1502b9c1b51eSKate Stone                               std::string &data) override {
15037ca15ba7SLawrence D'Anna     StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
150444d93782SGreg Clayton 
15052b29b432SJonas Devlieghere     ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1506b9c1b51eSKate Stone     if (interpreter) {
150744d93782SGreg Clayton 
150844d93782SGreg Clayton       StringList lines;
150944d93782SGreg Clayton       lines.SplitIntoLines(data);
1510b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1511a73b7df7SEnrico Granata         std::string funct_name_str;
1512b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1513b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1514b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1515b9c1b51eSKate Stone                              "add python command.\n");
151644d93782SGreg Clayton             error_sp->Flush();
1517b9c1b51eSKate Stone           } else {
1518223383edSEnrico Granata             // everything should be fine now, let's add this alias
1519223383edSEnrico Granata 
1520b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1521771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
152244d93782SGreg Clayton                 m_synchronicity));
1523c5011aedSJim Ingham             if (!m_container) {
1524c5011aedSJim Ingham               Status error = m_interpreter.AddUserCommand(
1525c5011aedSJim Ingham                   m_cmd_name, command_obj_sp, m_overwrite);
1526c5011aedSJim Ingham               if (error.Fail()) {
1527c5011aedSJim Ingham                 error_sp->Printf("error: unable to add selected command: '%s'",
1528c5011aedSJim Ingham                                  error.AsCString());
152944d93782SGreg Clayton                 error_sp->Flush();
1530223383edSEnrico Granata               }
1531c5011aedSJim Ingham             } else {
1532c5011aedSJim Ingham               llvm::Error llvm_error = m_container->LoadUserSubcommand(
1533c5011aedSJim Ingham                   m_cmd_name, command_obj_sp, m_overwrite);
1534c5011aedSJim Ingham               if (llvm_error) {
1535c5011aedSJim Ingham                 error_sp->Printf("error: unable to add selected command: '%s'",
1536c5011aedSJim Ingham                                llvm::toString(std::move(llvm_error)).c_str());
1537c5011aedSJim Ingham                 error_sp->Flush();
1538c5011aedSJim Ingham               }
1539c5011aedSJim Ingham             }
1540223383edSEnrico Granata           }
1541b9c1b51eSKate Stone         } else {
1542b9c1b51eSKate Stone           error_sp->Printf(
1543c5011aedSJim Ingham               "error: unable to create function, didn't add python command\n");
154444d93782SGreg Clayton           error_sp->Flush();
154544d93782SGreg Clayton         }
1546b9c1b51eSKate Stone       } else {
1547c5011aedSJim Ingham         error_sp->Printf("error: empty function, didn't add python command\n");
154844d93782SGreg Clayton         error_sp->Flush();
154944d93782SGreg Clayton       }
1550b9c1b51eSKate Stone     } else {
1551b9c1b51eSKate Stone       error_sp->Printf(
1552c5011aedSJim Ingham           "error: script interpreter missing, didn't add python command\n");
155344d93782SGreg Clayton       error_sp->Flush();
155444d93782SGreg Clayton     }
155544d93782SGreg Clayton 
155644d93782SGreg Clayton     io_handler.SetIsDone(true);
155744d93782SGreg Clayton   }
1558223383edSEnrico Granata 
1559b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
156057179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1561b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1562b9c1b51eSKate Stone                          "commands is currently Python");
156399f0b8f9SEnrico Granata       return false;
156499f0b8f9SEnrico Granata     }
156599f0b8f9SEnrico Granata 
1566c5011aedSJim Ingham     if (command.GetArgumentCount() == 0) {
1567c5011aedSJim Ingham       result.AppendError("'command script add' requires at least one argument");
1568c5011aedSJim Ingham       return false;
1569c5011aedSJim Ingham     }
1570c5011aedSJim Ingham     // Store the options in case we get multi-line input
1571c5011aedSJim Ingham     m_overwrite = m_options.m_overwrite;
1572c5011aedSJim Ingham     Status path_error;
1573c5011aedSJim Ingham     m_container = GetCommandInterpreter().VerifyUserMultiwordCmdPath(
1574c5011aedSJim Ingham         command, true, path_error);
1575c5011aedSJim Ingham 
1576c5011aedSJim Ingham     if (path_error.Fail()) {
1577c5011aedSJim Ingham       result.AppendErrorWithFormat("error in command path: %s",
1578c5011aedSJim Ingham                                    path_error.AsCString());
1579223383edSEnrico Granata       return false;
1580223383edSEnrico Granata     }
1581223383edSEnrico Granata 
1582c5011aedSJim Ingham     if (!m_container) {
1583c5011aedSJim Ingham       // This is getting inserted into the root of the interpreter.
1584adcd0268SBenjamin Kramer       m_cmd_name = std::string(command[0].ref());
1585c5011aedSJim Ingham     } else {
1586c5011aedSJim Ingham       size_t num_args = command.GetArgumentCount();
1587c5011aedSJim Ingham       m_cmd_name = std::string(command[num_args - 1].ref());
1588c5011aedSJim Ingham     }
1589c5011aedSJim Ingham 
1590735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
159144d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1592223383edSEnrico Granata 
1593c5011aedSJim Ingham     // Handle the case where we prompt for the script code first:
1594c5011aedSJim Ingham     if (m_options.m_class_name.empty() && m_options.m_funct_name.empty()) {
1595c5011aedSJim Ingham       m_interpreter.GetPythonCommandsFromIOHandler("     ", // Prompt
1596a6faf851SJonas Devlieghere                                                    *this);  // IOHandlerDelegate
1597c5011aedSJim Ingham       return result.Succeeded();
1598c5011aedSJim Ingham     }
1599c5011aedSJim Ingham 
1600c5011aedSJim Ingham     CommandObjectSP new_cmd_sp;
1601c5011aedSJim Ingham     if (m_options.m_class_name.empty()) {
1602c5011aedSJim Ingham       new_cmd_sp.reset(new CommandObjectPythonFunction(
1603b9c1b51eSKate Stone           m_interpreter, m_cmd_name, m_options.m_funct_name,
1604b9c1b51eSKate Stone           m_options.m_short_help, m_synchronicity));
1605b9c1b51eSKate Stone     } else {
16062b29b432SJonas Devlieghere       ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1607b9c1b51eSKate Stone       if (!interpreter) {
16089fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
16099fe00e52SEnrico Granata         return false;
16109fe00e52SEnrico Granata       }
16119fe00e52SEnrico Granata 
1612b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1613b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1614b9c1b51eSKate Stone       if (!cmd_obj_sp) {
16159fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
16169fe00e52SEnrico Granata         return false;
16179fe00e52SEnrico Granata       }
16189fe00e52SEnrico Granata 
1619c5011aedSJim Ingham       new_cmd_sp.reset(new CommandObjectScriptingObject(
1620b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
16219fe00e52SEnrico Granata     }
1622223383edSEnrico Granata 
1623c5011aedSJim Ingham     // Assume we're going to succeed...
1624c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1625c5011aedSJim Ingham     if (!m_container) {
1626c5011aedSJim Ingham       Status add_error =
1627c5011aedSJim Ingham           m_interpreter.AddUserCommand(m_cmd_name, new_cmd_sp, m_overwrite);
1628c5011aedSJim Ingham       if (add_error.Fail())
1629c5011aedSJim Ingham         result.AppendErrorWithFormat("cannot add command: %s",
1630c5011aedSJim Ingham                                      add_error.AsCString());
1631c5011aedSJim Ingham     } else {
1632c5011aedSJim Ingham       llvm::Error llvm_error =
1633c5011aedSJim Ingham           m_container->LoadUserSubcommand(m_cmd_name, new_cmd_sp, m_overwrite);
1634c5011aedSJim Ingham       if (llvm_error)
1635c5011aedSJim Ingham         result.AppendErrorWithFormat("cannot add command: %s",
1636c5011aedSJim Ingham                                      llvm::toString(std::move(llvm_error)).c_str());
1637c5011aedSJim Ingham     }
1638223383edSEnrico Granata     return result.Succeeded();
1639223383edSEnrico Granata   }
16405a988416SJim Ingham 
16415a988416SJim Ingham   CommandOptions m_options;
164244d93782SGreg Clayton   std::string m_cmd_name;
1643c5011aedSJim Ingham   CommandObjectMultiword *m_container = nullptr;
1644735152e3SEnrico Granata   std::string m_short_help;
1645c5011aedSJim Ingham   bool m_overwrite;
164644d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1647223383edSEnrico Granata };
1648223383edSEnrico Granata 
1649223383edSEnrico Granata // CommandObjectCommandsScriptList
1650223383edSEnrico Granata 
1651b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1652223383edSEnrico Granata public:
1653b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1654b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1655c5011aedSJim Ingham                             "List defined top-level scripted commands.",
1656c5011aedSJim Ingham                             nullptr) {}
1657223383edSEnrico Granata 
16586e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1659223383edSEnrico Granata 
1660b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1661d77ea5b2SRaphael Isemann     if (command.GetArgumentCount() != 0) {
1662d77ea5b2SRaphael Isemann       result.AppendError("'command script list' doesn't take any arguments");
1663d77ea5b2SRaphael Isemann       return false;
1664d77ea5b2SRaphael Isemann     }
1665d77ea5b2SRaphael Isemann 
1666b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1667223383edSEnrico Granata 
1668223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1669223383edSEnrico Granata 
1670223383edSEnrico Granata     return true;
1671223383edSEnrico Granata   }
1672223383edSEnrico Granata };
1673223383edSEnrico Granata 
1674223383edSEnrico Granata // CommandObjectCommandsScriptClear
1675223383edSEnrico Granata 
1676b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1677223383edSEnrico Granata public:
1678b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1679b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1680b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1681223383edSEnrico Granata 
16826e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1683223383edSEnrico Granata 
16845a988416SJim Ingham protected:
1685b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1686d77ea5b2SRaphael Isemann     if (command.GetArgumentCount() != 0) {
1687d77ea5b2SRaphael Isemann       result.AppendError("'command script clear' doesn't take any arguments");
1688d77ea5b2SRaphael Isemann       return false;
1689d77ea5b2SRaphael Isemann     }
1690d77ea5b2SRaphael Isemann 
1691223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1692223383edSEnrico Granata 
1693223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1694223383edSEnrico Granata 
1695223383edSEnrico Granata     return true;
1696223383edSEnrico Granata   }
1697223383edSEnrico Granata };
1698223383edSEnrico Granata 
1699223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1700223383edSEnrico Granata 
1701b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1702223383edSEnrico Granata public:
1703b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1704c5011aedSJim Ingham       : CommandObjectParsed(
1705c5011aedSJim Ingham             interpreter, "command script delete",
1706c5011aedSJim Ingham             "Delete a scripted command by specifying the path to the command.",
1707c5011aedSJim Ingham             nullptr) {
1708223383edSEnrico Granata     CommandArgumentEntry arg1;
1709223383edSEnrico Granata     CommandArgumentData cmd_arg;
1710223383edSEnrico Granata 
1711c5011aedSJim Ingham     // This is a list of command names forming the path to the command
1712c5011aedSJim Ingham     // to be deleted.
1713c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1714c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
1715223383edSEnrico Granata 
1716b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1717b9c1b51eSKate Stone     // argument entry.
1718223383edSEnrico Granata     arg1.push_back(cmd_arg);
1719223383edSEnrico Granata 
1720223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1721223383edSEnrico Granata     m_arguments.push_back(arg1);
1722223383edSEnrico Granata   }
1723223383edSEnrico Granata 
17246e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1725223383edSEnrico Granata 
17262e8f304fSGongyu Deng   void
17272e8f304fSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
17282e8f304fSGongyu Deng                            OptionElementVector &opt_element_vector) override {
1729c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1730c5011aedSJim Ingham                                                       opt_element_vector);
17312e8f304fSGongyu Deng   }
17322e8f304fSGongyu Deng 
17335a988416SJim Ingham protected:
1734b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1735223383edSEnrico Granata 
1736c5011aedSJim Ingham     llvm::StringRef root_cmd = command[0].ref();
1737c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
1738c5011aedSJim Ingham 
1739c5011aedSJim Ingham     if (root_cmd.empty()) {
1740c5011aedSJim Ingham       result.AppendErrorWithFormat("empty root command name");
1741c5011aedSJim Ingham       return false;
1742c5011aedSJim Ingham     }
1743c5011aedSJim Ingham     if (!m_interpreter.HasUserCommands() &&
1744c5011aedSJim Ingham         !m_interpreter.HasUserMultiwordCommands()) {
1745c5011aedSJim Ingham       result.AppendErrorWithFormat("can only delete user defined commands, "
1746c5011aedSJim Ingham                                    "but no user defined commands found");
1747223383edSEnrico Granata       return false;
1748223383edSEnrico Granata     }
1749223383edSEnrico Granata 
1750c5011aedSJim Ingham     CommandObjectSP cmd_sp = m_interpreter.GetCommandSPExact(root_cmd);
1751c5011aedSJim Ingham     if (!cmd_sp) {
1752c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' not found.",
1753c5011aedSJim Ingham                                    command[0].c_str());
1754c5011aedSJim Ingham       return false;
1755c5011aedSJim Ingham     }
1756c5011aedSJim Ingham     if (!cmd_sp->IsUserCommand()) {
1757c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' is not a user command.",
1758c5011aedSJim Ingham                                    command[0].c_str());
1759c5011aedSJim Ingham       return false;
1760c5011aedSJim Ingham     }
1761c5011aedSJim Ingham     if (cmd_sp->GetAsMultiwordCommand() && num_args == 1) {
1762c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' is a multi-word command.\n "
1763c5011aedSJim Ingham                                    "Delete with \"command container delete\"",
1764c5011aedSJim Ingham                                    command[0].c_str());
17654574a890SZachary Turner       return false;
1766223383edSEnrico Granata     }
1767223383edSEnrico Granata 
1768c5011aedSJim Ingham     if (command.GetArgumentCount() == 1) {
1769c5011aedSJim Ingham       m_interpreter.RemoveUser(root_cmd);
1770c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishResult);
1771c5011aedSJim Ingham       return true;
1772c5011aedSJim Ingham     }
1773c5011aedSJim Ingham     // We're deleting a command from a multiword command.  Verify the command
1774c5011aedSJim Ingham     // path:
1775c5011aedSJim Ingham     Status error;
1776c5011aedSJim Ingham     CommandObjectMultiword *container =
1777c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
1778c5011aedSJim Ingham                                                            error);
1779c5011aedSJim Ingham     if (error.Fail()) {
1780c5011aedSJim Ingham       result.AppendErrorWithFormat("could not resolve command path: %s",
1781c5011aedSJim Ingham                                    error.AsCString());
1782c5011aedSJim Ingham       return false;
1783c5011aedSJim Ingham     }
1784c5011aedSJim Ingham     if (!container) {
1785c5011aedSJim Ingham       // This means that command only had a leaf command, so the container is
1786c5011aedSJim Ingham       // the root.  That should have been handled above.
1787c5011aedSJim Ingham       result.AppendErrorWithFormat("could not find a container for '%s'",
1788c5011aedSJim Ingham                                    command[0].c_str());
1789c5011aedSJim Ingham       return false;
1790c5011aedSJim Ingham     }
1791c5011aedSJim Ingham     const char *leaf_cmd = command[num_args - 1].c_str();
1792c5011aedSJim Ingham     llvm::Error llvm_error = container->RemoveUserSubcommand(leaf_cmd,
1793c5011aedSJim Ingham                                             /* multiword not okay */ false);
1794c5011aedSJim Ingham     if (llvm_error) {
1795c5011aedSJim Ingham       result.AppendErrorWithFormat("could not delete command '%s': %s",
1796c5011aedSJim Ingham                                    leaf_cmd,
1797c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
1798c5011aedSJim Ingham       return false;
1799c5011aedSJim Ingham     }
1800c5011aedSJim Ingham 
1801c5011aedSJim Ingham     Stream &out_stream = result.GetOutputStream();
1802c5011aedSJim Ingham 
1803c5011aedSJim Ingham     out_stream << "Deleted command:";
1804c5011aedSJim Ingham     for (size_t idx = 0; idx < num_args; idx++) {
1805c5011aedSJim Ingham       out_stream << ' ';
1806c5011aedSJim Ingham       out_stream << command[idx].c_str();
1807c5011aedSJim Ingham     }
1808c5011aedSJim Ingham     out_stream << '\n';
18094574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishResult);
18104574a890SZachary Turner     return true;
1811223383edSEnrico Granata   }
1812223383edSEnrico Granata };
1813223383edSEnrico Granata 
1814223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1815223383edSEnrico Granata 
1816223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1817223383edSEnrico Granata 
1818b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1819223383edSEnrico Granata public:
18207428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1821b9c1b51eSKate Stone       : CommandObjectMultiword(
1822a925974bSAdrian Prantl             interpreter, "command script",
1823a925974bSAdrian Prantl             "Commands for managing custom "
1824b9c1b51eSKate Stone             "commands implemented by "
1825b9c1b51eSKate Stone             "interpreter scripts.",
1826b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1827b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1828b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1829b9c1b51eSKate Stone     LoadSubCommand(
1830b9c1b51eSKate Stone         "delete",
1831b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1832b9c1b51eSKate Stone     LoadSubCommand(
1833b9c1b51eSKate Stone         "clear",
1834b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1835b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1836b9c1b51eSKate Stone                                interpreter)));
1837b9c1b51eSKate Stone     LoadSubCommand(
1838b9c1b51eSKate Stone         "import",
1839b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1840223383edSEnrico Granata   }
1841223383edSEnrico Granata 
18426e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1843223383edSEnrico Granata };
1844223383edSEnrico Granata 
1845c5011aedSJim Ingham #pragma mark CommandObjectCommandContainer
1846c5011aedSJim Ingham #define LLDB_OPTIONS_container_add
1847c5011aedSJim Ingham #include "CommandOptions.inc"
1848c5011aedSJim Ingham 
1849c5011aedSJim Ingham class CommandObjectCommandsContainerAdd : public CommandObjectParsed {
1850c5011aedSJim Ingham public:
1851c5011aedSJim Ingham   CommandObjectCommandsContainerAdd(CommandInterpreter &interpreter)
1852c5011aedSJim Ingham       : CommandObjectParsed(
1853c5011aedSJim Ingham             interpreter, "command container add",
1854c5011aedSJim Ingham             "Add a container command to lldb.  Adding to built-"
1855c5011aedSJim Ingham             "in container commands is not allowed.",
1856c5011aedSJim Ingham             "command container add [[path1]...] container-name") {
1857c5011aedSJim Ingham     CommandArgumentEntry arg1;
1858c5011aedSJim Ingham     CommandArgumentData cmd_arg;
1859c5011aedSJim Ingham 
1860c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
1861c5011aedSJim Ingham     // you want to add.
1862c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1863c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
1864c5011aedSJim Ingham 
1865c5011aedSJim Ingham     // There is only one variant this argument could be; put it into the
1866c5011aedSJim Ingham     // argument entry.
1867c5011aedSJim Ingham     arg1.push_back(cmd_arg);
1868c5011aedSJim Ingham 
1869c5011aedSJim Ingham     // Push the data for the first argument into the m_arguments vector.
1870c5011aedSJim Ingham     m_arguments.push_back(arg1);
1871c5011aedSJim Ingham   }
1872c5011aedSJim Ingham 
1873c5011aedSJim Ingham   ~CommandObjectCommandsContainerAdd() override = default;
1874c5011aedSJim Ingham 
1875c5011aedSJim Ingham   Options *GetOptions() override { return &m_options; }
1876c5011aedSJim Ingham 
1877c5011aedSJim Ingham   void
1878c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
1879c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
1880c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1881c5011aedSJim Ingham                                                       opt_element_vector);
1882c5011aedSJim Ingham   }
1883c5011aedSJim Ingham 
1884c5011aedSJim Ingham protected:
1885c5011aedSJim Ingham   class CommandOptions : public Options {
1886c5011aedSJim Ingham   public:
1887c5011aedSJim Ingham     CommandOptions() : Options(), m_short_help(), m_long_help() {}
1888c5011aedSJim Ingham 
1889c5011aedSJim Ingham     ~CommandOptions() override = default;
1890c5011aedSJim Ingham 
1891c5011aedSJim Ingham     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1892c5011aedSJim Ingham                           ExecutionContext *execution_context) override {
1893c5011aedSJim Ingham       Status error;
1894c5011aedSJim Ingham       const int short_option = m_getopt_table[option_idx].val;
1895c5011aedSJim Ingham 
1896c5011aedSJim Ingham       switch (short_option) {
1897c5011aedSJim Ingham       case 'h':
1898c5011aedSJim Ingham         if (!option_arg.empty())
1899c5011aedSJim Ingham           m_short_help = std::string(option_arg);
1900c5011aedSJim Ingham         break;
1901c5011aedSJim Ingham       case 'o':
1902c5011aedSJim Ingham         m_overwrite = true;
1903c5011aedSJim Ingham         break;
1904c5011aedSJim Ingham       case 'H':
1905c5011aedSJim Ingham         if (!option_arg.empty())
1906c5011aedSJim Ingham           m_long_help = std::string(option_arg);
1907c5011aedSJim Ingham         break;
1908c5011aedSJim Ingham       default:
1909c5011aedSJim Ingham         llvm_unreachable("Unimplemented option");
1910c5011aedSJim Ingham       }
1911c5011aedSJim Ingham 
1912c5011aedSJim Ingham       return error;
1913c5011aedSJim Ingham     }
1914c5011aedSJim Ingham 
1915c5011aedSJim Ingham     void OptionParsingStarting(ExecutionContext *execution_context) override {
1916c5011aedSJim Ingham       m_short_help.clear();
1917c5011aedSJim Ingham       m_long_help.clear();
1918c5011aedSJim Ingham       m_overwrite = false;
1919c5011aedSJim Ingham     }
1920c5011aedSJim Ingham 
1921c5011aedSJim Ingham     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1922c5011aedSJim Ingham       return llvm::makeArrayRef(g_container_add_options);
1923c5011aedSJim Ingham     }
1924c5011aedSJim Ingham 
1925c5011aedSJim Ingham     // Instance variables to hold the values for command options.
1926c5011aedSJim Ingham 
1927c5011aedSJim Ingham     std::string m_short_help;
1928c5011aedSJim Ingham     std::string m_long_help;
1929c5011aedSJim Ingham     bool m_overwrite = false;
1930c5011aedSJim Ingham   };
1931c5011aedSJim Ingham   bool DoExecute(Args &command, CommandReturnObject &result) override {
1932c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
1933c5011aedSJim Ingham 
1934c5011aedSJim Ingham     if (num_args == 0) {
1935c5011aedSJim Ingham       result.AppendError("no command was specified");
1936c5011aedSJim Ingham       return false;
1937c5011aedSJim Ingham     }
1938c5011aedSJim Ingham 
1939c5011aedSJim Ingham     if (num_args == 1) {
1940c5011aedSJim Ingham       // We're adding this as a root command, so use the interpreter.
1941c5011aedSJim Ingham       const char *cmd_name = command.GetArgumentAtIndex(0);
1942c5011aedSJim Ingham       auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
1943c5011aedSJim Ingham           GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
1944c5011aedSJim Ingham           m_options.m_long_help.c_str()));
1945c5011aedSJim Ingham       cmd_sp->GetAsMultiwordCommand()->SetRemovable(true);
1946c5011aedSJim Ingham       Status add_error = GetCommandInterpreter().AddUserCommand(
1947c5011aedSJim Ingham           cmd_name, cmd_sp, m_options.m_overwrite);
1948c5011aedSJim Ingham       if (add_error.Fail()) {
1949c5011aedSJim Ingham         result.AppendErrorWithFormat("error adding command: %s",
1950c5011aedSJim Ingham                                      add_error.AsCString());
1951c5011aedSJim Ingham         return false;
1952c5011aedSJim Ingham       }
1953c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1954c5011aedSJim Ingham       return true;
1955c5011aedSJim Ingham     }
1956c5011aedSJim Ingham 
1957c5011aedSJim Ingham     // We're adding this to a subcommand, first find the subcommand:
1958c5011aedSJim Ingham     Status path_error;
1959c5011aedSJim Ingham     CommandObjectMultiword *add_to_me =
1960c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
1961c5011aedSJim Ingham                                                            path_error);
1962c5011aedSJim Ingham 
1963c5011aedSJim Ingham     if (!add_to_me) {
1964c5011aedSJim Ingham       result.AppendErrorWithFormat("error adding command: %s",
1965c5011aedSJim Ingham                                    path_error.AsCString());
1966c5011aedSJim Ingham       return false;
1967c5011aedSJim Ingham     }
1968c5011aedSJim Ingham 
1969c5011aedSJim Ingham     const char *cmd_name = command.GetArgumentAtIndex(num_args - 1);
1970c5011aedSJim Ingham     auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
1971c5011aedSJim Ingham         GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
1972c5011aedSJim Ingham         m_options.m_long_help.c_str()));
1973c5011aedSJim Ingham     llvm::Error llvm_error =
1974c5011aedSJim Ingham         add_to_me->LoadUserSubcommand(cmd_name, cmd_sp, m_options.m_overwrite);
1975c5011aedSJim Ingham     if (llvm_error) {
1976c5011aedSJim Ingham       result.AppendErrorWithFormat("error adding subcommand: %s",
1977c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
1978c5011aedSJim Ingham       return false;
1979c5011aedSJim Ingham     }
1980c5011aedSJim Ingham 
1981c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1982c5011aedSJim Ingham     return true;
1983c5011aedSJim Ingham   }
1984c5011aedSJim Ingham 
1985c5011aedSJim Ingham private:
1986c5011aedSJim Ingham   CommandOptions m_options;
1987c5011aedSJim Ingham };
1988c5011aedSJim Ingham 
1989c5011aedSJim Ingham #define LLDB_OPTIONS_multiword_delete
1990c5011aedSJim Ingham #include "CommandOptions.inc"
1991c5011aedSJim Ingham class CommandObjectCommandsContainerDelete : public CommandObjectParsed {
1992c5011aedSJim Ingham public:
1993c5011aedSJim Ingham   CommandObjectCommandsContainerDelete(CommandInterpreter &interpreter)
1994c5011aedSJim Ingham       : CommandObjectParsed(
1995c5011aedSJim Ingham             interpreter, "command container delete",
1996c5011aedSJim Ingham             "Delete a container command previously added to "
1997c5011aedSJim Ingham             "lldb.",
1998c5011aedSJim Ingham             "command container delete [[path1] ...] container-cmd") {
1999c5011aedSJim Ingham     CommandArgumentEntry arg1;
2000c5011aedSJim Ingham     CommandArgumentData cmd_arg;
2001c5011aedSJim Ingham 
2002c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
2003c5011aedSJim Ingham     // you want to add.
2004c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
2005c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
2006c5011aedSJim Ingham 
2007c5011aedSJim Ingham     // There is only one variant this argument could be; put it into the
2008c5011aedSJim Ingham     // argument entry.
2009c5011aedSJim Ingham     arg1.push_back(cmd_arg);
2010c5011aedSJim Ingham 
2011c5011aedSJim Ingham     // Push the data for the first argument into the m_arguments vector.
2012c5011aedSJim Ingham     m_arguments.push_back(arg1);
2013c5011aedSJim Ingham   }
2014c5011aedSJim Ingham 
2015c5011aedSJim Ingham   ~CommandObjectCommandsContainerDelete() override = default;
2016c5011aedSJim Ingham 
2017c5011aedSJim Ingham   void
2018c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
2019c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
2020c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
2021c5011aedSJim Ingham                                                       opt_element_vector);
2022c5011aedSJim Ingham   }
2023c5011aedSJim Ingham 
2024c5011aedSJim Ingham protected:
2025c5011aedSJim Ingham   bool DoExecute(Args &command, CommandReturnObject &result) override {
2026c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
2027c5011aedSJim Ingham 
2028c5011aedSJim Ingham     if (num_args == 0) {
2029c5011aedSJim Ingham       result.AppendError("No command was specified.");
2030c5011aedSJim Ingham       return false;
2031c5011aedSJim Ingham     }
2032c5011aedSJim Ingham 
2033c5011aedSJim Ingham     if (num_args == 1) {
2034c5011aedSJim Ingham       // We're removing a root command, so we need to delete it from the
2035c5011aedSJim Ingham       // interpreter.
2036c5011aedSJim Ingham       const char *cmd_name = command.GetArgumentAtIndex(0);
2037c5011aedSJim Ingham       // Let's do a little more work here so we can do better error reporting.
2038c5011aedSJim Ingham       CommandInterpreter &interp = GetCommandInterpreter();
2039c5011aedSJim Ingham       CommandObjectSP cmd_sp = interp.GetCommandSPExact(cmd_name);
2040c5011aedSJim Ingham       if (!cmd_sp) {
2041c5011aedSJim Ingham         result.AppendErrorWithFormat("container command %s doesn't exist.",
2042c5011aedSJim Ingham                                      cmd_name);
2043c5011aedSJim Ingham         return false;
2044c5011aedSJim Ingham       }
2045c5011aedSJim Ingham       if (!cmd_sp->IsUserCommand()) {
2046c5011aedSJim Ingham         result.AppendErrorWithFormat(
2047c5011aedSJim Ingham             "container command %s is not a user command", cmd_name);
2048c5011aedSJim Ingham         return false;
2049c5011aedSJim Ingham       }
2050c5011aedSJim Ingham       if (!cmd_sp->GetAsMultiwordCommand()) {
2051c5011aedSJim Ingham         result.AppendErrorWithFormat("command %s is not a container command",
2052c5011aedSJim Ingham                                      cmd_name);
2053c5011aedSJim Ingham         return false;
2054c5011aedSJim Ingham       }
2055c5011aedSJim Ingham 
2056c5011aedSJim Ingham       bool did_remove = GetCommandInterpreter().RemoveUserMultiword(cmd_name);
2057c5011aedSJim Ingham       if (!did_remove) {
2058c5011aedSJim Ingham         result.AppendErrorWithFormat("error removing command %s.", cmd_name);
2059c5011aedSJim Ingham         return false;
2060c5011aedSJim Ingham       }
2061c5011aedSJim Ingham 
2062c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
2063c5011aedSJim Ingham       return true;
2064c5011aedSJim Ingham     }
2065c5011aedSJim Ingham 
2066c5011aedSJim Ingham     // We're removing a subcommand, first find the subcommand's owner:
2067c5011aedSJim Ingham     Status path_error;
2068c5011aedSJim Ingham     CommandObjectMultiword *container =
2069c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
2070c5011aedSJim Ingham                                                            path_error);
2071c5011aedSJim Ingham 
2072c5011aedSJim Ingham     if (!container) {
2073c5011aedSJim Ingham       result.AppendErrorWithFormat("error removing container command: %s",
2074c5011aedSJim Ingham                                    path_error.AsCString());
2075c5011aedSJim Ingham       return false;
2076c5011aedSJim Ingham     }
2077c5011aedSJim Ingham     const char *leaf = command.GetArgumentAtIndex(num_args - 1);
2078c5011aedSJim Ingham     llvm::Error llvm_error =
2079c5011aedSJim Ingham         container->RemoveUserSubcommand(leaf, /* multiword okay */ true);
2080c5011aedSJim Ingham     if (llvm_error) {
2081c5011aedSJim Ingham       result.AppendErrorWithFormat("error removing container command: %s",
2082c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
2083c5011aedSJim Ingham       return false;
2084c5011aedSJim Ingham     }
2085c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2086c5011aedSJim Ingham     return true;
2087c5011aedSJim Ingham   }
2088c5011aedSJim Ingham };
2089c5011aedSJim Ingham 
2090c5011aedSJim Ingham class CommandObjectCommandContainer : public CommandObjectMultiword {
2091c5011aedSJim Ingham public:
2092c5011aedSJim Ingham   CommandObjectCommandContainer(CommandInterpreter &interpreter)
2093c5011aedSJim Ingham       : CommandObjectMultiword(
2094c5011aedSJim Ingham             interpreter, "command container",
2095c5011aedSJim Ingham             "Commands for adding container commands to lldb.  "
2096c5011aedSJim Ingham             "Container commands are containers for other commands.  You can"
2097c5011aedSJim Ingham             "add nested container commands by specifying a command path, but "
2098c5011aedSJim Ingham             "but you can't add commands into the built-in command hierarchy.",
2099c5011aedSJim Ingham             "command container <subcommand> [<subcommand-options>]") {
2100c5011aedSJim Ingham     LoadSubCommand("add", CommandObjectSP(new CommandObjectCommandsContainerAdd(
2101c5011aedSJim Ingham                               interpreter)));
2102c5011aedSJim Ingham     LoadSubCommand(
2103c5011aedSJim Ingham         "delete",
2104c5011aedSJim Ingham         CommandObjectSP(new CommandObjectCommandsContainerDelete(interpreter)));
2105c5011aedSJim Ingham   }
2106c5011aedSJim Ingham 
2107c5011aedSJim Ingham   ~CommandObjectCommandContainer() override = default;
2108c5011aedSJim Ingham };
2109c5011aedSJim Ingham 
2110ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
2111ebc09c36SJim Ingham 
2112ebc09c36SJim Ingham // CommandObjectMultiwordCommands
2113ebc09c36SJim Ingham 
2114b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
2115b9c1b51eSKate Stone     CommandInterpreter &interpreter)
2116b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
2117b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
2118b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
2119b9c1b51eSKate Stone   LoadSubCommand("source",
2120b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
2121b9c1b51eSKate Stone   LoadSubCommand("alias",
2122b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
2123b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
2124b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
2125b9c1b51eSKate Stone   LoadSubCommand("delete",
2126b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
2127c5011aedSJim Ingham   LoadSubCommand("container", CommandObjectSP(new CommandObjectCommandContainer(
2128c5011aedSJim Ingham                                   interpreter)));
2129b9c1b51eSKate Stone   LoadSubCommand(
2130b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
2131b9c1b51eSKate Stone   LoadSubCommand(
2132b9c1b51eSKate Stone       "script",
2133b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
2134ebc09c36SJim Ingham }
2135ebc09c36SJim Ingham 
21366e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
2137