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 
446*c5011aedSJim Ingham     if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
447*c5011aedSJim Ingham       result.AppendErrorWithFormat(
448*c5011aedSJim Ingham           "'%s' is a user container command and cannot be overwritten.\n"
449*c5011aedSJim Ingham           "Delete it first with 'command container delete'\n",
450*c5011aedSJim Ingham           args[0].c_str());
451*c5011aedSJim Ingham       return false;
452*c5011aedSJim Ingham     }
453*c5011aedSJim 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 
488b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
489a9448872SJonas Devlieghere             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName())) {
490a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
491a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
492b9c1b51eSKate Stone         result.AppendWarningWithFormat(
493b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
494a01bccdbSZachary Turner             alias_command.str().c_str());
495844d2303SCaroline Tice       }
496b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
497a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
49845d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
49945d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
50045d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
50145d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
502844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
503b9c1b51eSKate Stone       } else {
504472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
505472362e6SCaroline Tice       }
506212130acSEnrico Granata 
507b9c1b51eSKate Stone     } else {
508212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
509212130acSEnrico Granata     }
510212130acSEnrico Granata 
511844d2303SCaroline Tice     return result.Succeeded();
512844d2303SCaroline Tice   }
513ebc09c36SJim Ingham 
514b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
515867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
516ebc09c36SJim Ingham 
517b9c1b51eSKate Stone     if (argc < 2) {
518d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
519ebc09c36SJim Ingham       return false;
520ebc09c36SJim Ingham     }
521ebc09c36SJim Ingham 
5224574a890SZachary Turner     // Save these in std::strings since we're going to shift them off.
523adcd0268SBenjamin Kramer     const std::string alias_command(std::string(args[0].ref()));
524adcd0268SBenjamin Kramer     const std::string actual_command(std::string(args[1].ref()));
525ebc09c36SJim Ingham 
526ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
527ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
528ebc09c36SJim Ingham 
529b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
530b9c1b51eSKate Stone     // object.
531ebc09c36SJim Ingham 
532771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
533b9c1b51eSKate Stone       result.AppendErrorWithFormat(
534b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
535ebc09c36SJim Ingham           alias_command.c_str());
5364574a890SZachary Turner       return false;
5374574a890SZachary Turner     }
5384574a890SZachary Turner 
539*c5011aedSJim Ingham     if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
540*c5011aedSJim Ingham       result.AppendErrorWithFormat(
541*c5011aedSJim Ingham           "'%s' is user container command and cannot be overwritten.\n"
542*c5011aedSJim Ingham           "Delete it first with 'command container delete'",
543*c5011aedSJim Ingham           alias_command.c_str());
544*c5011aedSJim Ingham       return false;
545*c5011aedSJim Ingham     }
546*c5011aedSJim Ingham 
547b9c1b51eSKate Stone     CommandObjectSP command_obj_sp(
548a449698cSZachary Turner         m_interpreter.GetCommandSPExact(actual_command, true));
549ebc09c36SJim Ingham     CommandObjectSP subcommand_obj_sp;
550ebc09c36SJim Ingham     bool use_subcommand = false;
5514574a890SZachary Turner     if (!command_obj_sp) {
5524574a890SZachary Turner       result.AppendErrorWithFormat("'%s' is not an existing command.\n",
5534574a890SZachary Turner                                    actual_command.c_str());
5544574a890SZachary Turner       return false;
5554574a890SZachary Turner     }
556ebc09c36SJim Ingham     CommandObject *cmd_obj = command_obj_sp.get();
5576e3d8e7fSEugene Zelenko     CommandObject *sub_cmd_obj = nullptr;
558b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
559b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
560ebc09c36SJim Ingham 
56111eb9c64SZachary Turner     while (cmd_obj->IsMultiwordObject() && !args.empty()) {
5620d9a201eSRaphael Isemann       auto sub_command = args[0].ref();
56311eb9c64SZachary Turner       assert(!sub_command.empty());
5644574a890SZachary Turner       subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
5654574a890SZachary Turner       if (!subcommand_obj_sp) {
566b9c1b51eSKate Stone         result.AppendErrorWithFormat(
567b9c1b51eSKate Stone             "'%s' is not a valid sub-command of '%s'.  "
568f415eeb4SCaroline Tice             "Unable to create alias.\n",
5694574a890SZachary Turner             args[0].c_str(), actual_command.c_str());
570ebc09c36SJim Ingham         return false;
571ebc09c36SJim Ingham       }
5724574a890SZachary Turner 
5734574a890SZachary Turner       sub_cmd_obj = subcommand_obj_sp.get();
5744574a890SZachary Turner       use_subcommand = true;
5754574a890SZachary Turner       args.Shift(); // Shift the sub_command word off the argument vector.
5764574a890SZachary Turner       cmd_obj = sub_cmd_obj;
577ebc09c36SJim Ingham     }
578ebc09c36SJim Ingham 
579ebc09c36SJim Ingham     // Verify & handle any options/arguments passed to the alias command
580ebc09c36SJim Ingham 
581212130acSEnrico Granata     std::string args_string;
582212130acSEnrico Granata 
58311eb9c64SZachary Turner     if (!args.empty()) {
584b9c1b51eSKate Stone       CommandObjectSP tmp_sp =
585a9448872SJonas Devlieghere           m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName());
586ebc09c36SJim Ingham       if (use_subcommand)
587a9448872SJonas Devlieghere         tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName());
588ca90c47eSCaroline Tice 
589ca90c47eSCaroline Tice       args.GetCommandString(args_string);
590867b185dSCaroline Tice     }
591ebc09c36SJim Ingham 
592771ef6d4SMalcolm Parsons     if (m_interpreter.AliasExists(alias_command) ||
593771ef6d4SMalcolm Parsons         m_interpreter.UserCommandExists(alias_command)) {
594b9c1b51eSKate Stone       result.AppendWarningWithFormat(
5954574a890SZachary Turner           "Overwriting existing definition for '%s'.\n", alias_command.c_str());
596ebc09c36SJim Ingham     }
597ebc09c36SJim Ingham 
598b9c1b51eSKate Stone     if (CommandAlias *alias = m_interpreter.AddAlias(
5994574a890SZachary Turner             alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
600771ef6d4SMalcolm Parsons             args_string)) {
60145d0e238SEnrico Granata       if (m_command_options.m_help.OptionWasSet())
60245d0e238SEnrico Granata         alias->SetHelp(m_command_options.m_help.GetCurrentValue());
60345d0e238SEnrico Granata       if (m_command_options.m_long_help.OptionWasSet())
60445d0e238SEnrico Granata         alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
605ebc09c36SJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
606b9c1b51eSKate Stone     } else {
607212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
608212130acSEnrico Granata       return false;
609212130acSEnrico Granata     }
610ebc09c36SJim Ingham 
611ebc09c36SJim Ingham     return result.Succeeded();
612ebc09c36SJim Ingham   }
613ebc09c36SJim Ingham };
614ebc09c36SJim Ingham 
615ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
616ebc09c36SJim Ingham // CommandObjectCommandsUnalias
617ebc09c36SJim Ingham 
618b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
619ebc09c36SJim Ingham public:
6207428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
621b9c1b51eSKate Stone       : CommandObjectParsed(
622b9c1b51eSKate Stone             interpreter, "command unalias",
623b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
624b9c1b51eSKate Stone             nullptr) {
625405fe67fSCaroline Tice     CommandArgumentEntry arg;
626405fe67fSCaroline Tice     CommandArgumentData alias_arg;
627405fe67fSCaroline Tice 
628405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
629405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
630405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
631405fe67fSCaroline Tice 
632b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
633b9c1b51eSKate Stone     // argument entry.
634405fe67fSCaroline Tice     arg.push_back(alias_arg);
635405fe67fSCaroline Tice 
636405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
637405fe67fSCaroline Tice     m_arguments.push_back(arg);
638ebc09c36SJim Ingham   }
639ebc09c36SJim Ingham 
6406e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
641ebc09c36SJim Ingham 
64231fd64acSGongyu Deng   void
64331fd64acSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
64431fd64acSGongyu Deng                            OptionElementVector &opt_element_vector) override {
64531fd64acSGongyu Deng     if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
64631fd64acSGongyu Deng       return;
64731fd64acSGongyu Deng 
64831fd64acSGongyu Deng     for (const auto &ent : m_interpreter.GetAliases()) {
64931fd64acSGongyu Deng       request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
65031fd64acSGongyu Deng     }
65131fd64acSGongyu Deng   }
65231fd64acSGongyu Deng 
6535a988416SJim Ingham protected:
654b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
655ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
656ebc09c36SJim Ingham     CommandObject *cmd_obj;
657ebc09c36SJim Ingham 
65811eb9c64SZachary Turner     if (args.empty()) {
65911eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
66011eb9c64SZachary Turner       return false;
66111eb9c64SZachary Turner     }
66211eb9c64SZachary Turner 
6630d9a201eSRaphael Isemann     auto command_name = args[0].ref();
664a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
6654574a890SZachary Turner     if (!cmd_obj) {
6664574a890SZachary Turner       result.AppendErrorWithFormat(
6674574a890SZachary Turner           "'%s' is not a known command.\nTry 'help' to see a "
6684574a890SZachary Turner           "current list of commands.\n",
669867e7d17SZachary Turner           args[0].c_str());
6704574a890SZachary Turner       return false;
6714574a890SZachary Turner     }
6724574a890SZachary Turner 
673b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
674b9c1b51eSKate Stone       if (cmd_obj->IsRemovable()) {
675b9c1b51eSKate Stone         result.AppendErrorWithFormat(
676b9c1b51eSKate Stone             "'%s' is not an alias, it is a debugger command which can be "
677b9c1b51eSKate Stone             "removed using the 'command delete' command.\n",
678867e7d17SZachary Turner             args[0].c_str());
679b9c1b51eSKate Stone       } else {
680b9c1b51eSKate Stone         result.AppendErrorWithFormat(
681b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
682867e7d17SZachary Turner             args[0].c_str());
683b547278cSGreg Clayton       }
6844574a890SZachary Turner       return false;
6854574a890SZachary Turner     }
6864574a890SZachary Turner 
687b9c1b51eSKate Stone     if (!m_interpreter.RemoveAlias(command_name)) {
688a7015092SGreg Clayton       if (m_interpreter.AliasExists(command_name))
689b9c1b51eSKate Stone         result.AppendErrorWithFormat(
690867e7d17SZachary Turner             "Error occurred while attempting to unalias '%s'.\n",
691867e7d17SZachary Turner             args[0].c_str());
692ebc09c36SJim Ingham       else
693b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
694867e7d17SZachary Turner                                      args[0].c_str());
6954574a890SZachary Turner       return false;
696ebc09c36SJim Ingham     }
697ebc09c36SJim Ingham 
6984574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
699ebc09c36SJim Ingham     return result.Succeeded();
700ebc09c36SJim Ingham   }
701ebc09c36SJim Ingham };
702ebc09c36SJim Ingham 
703b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
704b547278cSGreg Clayton // CommandObjectCommandsDelete
705b547278cSGreg Clayton 
706b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
707b547278cSGreg Clayton public:
7087428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
709b9c1b51eSKate Stone       : CommandObjectParsed(
710b9c1b51eSKate Stone             interpreter, "command delete",
711b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
712b9c1b51eSKate Stone             nullptr) {
713b547278cSGreg Clayton     CommandArgumentEntry arg;
714b547278cSGreg Clayton     CommandArgumentData alias_arg;
715b547278cSGreg Clayton 
716b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
717b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
718b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
719b547278cSGreg Clayton 
720b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
721b9c1b51eSKate Stone     // argument entry.
722b547278cSGreg Clayton     arg.push_back(alias_arg);
723b547278cSGreg Clayton 
724b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
725b547278cSGreg Clayton     m_arguments.push_back(arg);
726b547278cSGreg Clayton   }
727b547278cSGreg Clayton 
7286e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
729b547278cSGreg Clayton 
73031fd64acSGongyu Deng   void
73131fd64acSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
73231fd64acSGongyu Deng                            OptionElementVector &opt_element_vector) override {
73331fd64acSGongyu Deng     if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
73431fd64acSGongyu Deng       return;
73531fd64acSGongyu Deng 
73631fd64acSGongyu Deng     for (const auto &ent : m_interpreter.GetCommands()) {
73731fd64acSGongyu Deng       if (ent.second->IsRemovable())
73831fd64acSGongyu Deng         request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
73931fd64acSGongyu Deng     }
74031fd64acSGongyu Deng   }
74131fd64acSGongyu Deng 
742b547278cSGreg Clayton protected:
743b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
744b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
745b547278cSGreg Clayton 
74611eb9c64SZachary Turner     if (args.empty()) {
74711eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
74811eb9c64SZachary Turner                                    "defined regular expression command names",
749a449698cSZachary Turner                                    GetCommandName().str().c_str());
750d77ea5b2SRaphael Isemann       return false;
75111eb9c64SZachary Turner     }
75211eb9c64SZachary Turner 
7530d9a201eSRaphael Isemann     auto command_name = args[0].ref();
7544574a890SZachary Turner     if (!m_interpreter.CommandExists(command_name)) {
75546d4aa21SEnrico Granata       StreamString error_msg_stream;
756d5b44036SJonas Devlieghere       const bool generate_upropos = true;
75746d4aa21SEnrico Granata       const bool generate_type_lookup = false;
758b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
7594574a890SZachary Turner           &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
760d5b44036SJonas Devlieghere           generate_upropos, generate_type_lookup);
761c156427dSZachary Turner       result.AppendError(error_msg_stream.GetString());
7624574a890SZachary Turner       return false;
763b547278cSGreg Clayton     }
764b547278cSGreg Clayton 
7654574a890SZachary Turner     if (!m_interpreter.RemoveCommand(command_name)) {
7664574a890SZachary Turner       result.AppendErrorWithFormat(
7674574a890SZachary Turner           "'%s' is a permanent debugger command and cannot be removed.\n",
768867e7d17SZachary Turner           args[0].c_str());
7694574a890SZachary Turner       return false;
7704574a890SZachary Turner     }
7714574a890SZachary Turner 
7724574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
7734574a890SZachary Turner     return true;
774b547278cSGreg Clayton   }
775b547278cSGreg Clayton };
776b547278cSGreg Clayton 
777de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
7781f0f5b5bSZachary Turner 
77964becc11SRaphael Isemann #define LLDB_OPTIONS_regex
78064becc11SRaphael Isemann #include "CommandOptions.inc"
7811f0f5b5bSZachary Turner 
7825a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
783de164aaaSGreg Clayton 
784b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
785b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
786de164aaaSGreg Clayton public:
7877428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
788b9c1b51eSKate Stone       : CommandObjectParsed(
789a925974bSAdrian Prantl             interpreter, "command regex",
790a925974bSAdrian Prantl             "Define a custom command in terms of "
791b9c1b51eSKate Stone             "existing commands by matching "
792b9c1b51eSKate Stone             "regular expressions.",
7930e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
794b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
795b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
796b9c1b51eSKate Stone         m_options() {
797b9c1b51eSKate Stone     SetHelpLong(
798b9c1b51eSKate Stone         R"(
799b9c1b51eSKate Stone )"
800b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
801ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
802b9c1b51eSKate Stone using the regular expression substitution format of:"
803b9c1b51eSKate Stone         R"(
804ea671fbdSKate Stone 
805ea671fbdSKate Stone     s/<regex>/<subst>/
806ea671fbdSKate Stone 
807b9c1b51eSKate Stone )"
808b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
809ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
810b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
811b9c1b51eSKate Stone         R"(
812ea671fbdSKate Stone 
813b9c1b51eSKate Stone )"
814b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
815ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
816ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
817b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
818b9c1b51eSKate Stone         R"(
819ea671fbdSKate Stone 
820ea671fbdSKate Stone EXAMPLES
821ea671fbdSKate Stone 
822b9c1b51eSKate Stone )"
823b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
824ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
825b9c1b51eSKate Stone a number follows 'f':"
826b9c1b51eSKate Stone         R"(
827ea671fbdSKate Stone 
828b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
829de164aaaSGreg Clayton   }
830de164aaaSGreg Clayton 
8316e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
832de164aaaSGreg Clayton 
8335a988416SJim Ingham protected:
8340affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
8357ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
8360affb582SDave Lee     if (output_sp && interactive) {
8370affb582SDave Lee       output_sp->PutCString("Enter one or more sed substitution commands in "
838b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
839b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
84044d93782SGreg Clayton       output_sp->Flush();
84144d93782SGreg Clayton     }
84244d93782SGreg Clayton   }
84344d93782SGreg Clayton 
844b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
845b9c1b51eSKate Stone                               std::string &data) override {
84644d93782SGreg Clayton     io_handler.SetIsDone(true);
847d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
84844d93782SGreg Clayton       StringList lines;
849b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
85044d93782SGreg Clayton         bool check_only = false;
8514c78b788SRaphael Isemann         for (const std::string &line : lines) {
8524c78b788SRaphael Isemann           Status error = AppendRegexSubstitution(line, check_only);
853b9c1b51eSKate Stone           if (error.Fail()) {
85457179860SJonas Devlieghere             if (!GetDebugger().GetCommandInterpreter().GetBatchCommandMode()) {
85557179860SJonas Devlieghere               StreamSP out_stream = GetDebugger().GetAsyncOutputStream();
85644d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
85744d93782SGreg Clayton             }
85844d93782SGreg Clayton           }
85944d93782SGreg Clayton         }
86044d93782SGreg Clayton       }
861d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
862d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
86344d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
86444d93782SGreg Clayton       }
86544d93782SGreg Clayton     }
86644d93782SGreg Clayton   }
86744d93782SGreg Clayton 
868b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
8695a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
870b9c1b51eSKate Stone     if (argc == 0) {
871b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
872b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
87311eb9c64SZachary Turner       return false;
87411eb9c64SZachary Turner     }
87511eb9c64SZachary Turner 
87697206d57SZachary Turner     Status error;
8770d9a201eSRaphael Isemann     auto name = command[0].ref();
878a8f3ae7cSJonas Devlieghere     m_regex_cmd_up = std::make_unique<CommandObjectRegexCommand>(
8794574a890SZachary Turner         m_interpreter, name, m_options.GetHelp(), m_options.GetSyntax(), 10, 0,
8804574a890SZachary Turner         true);
8810e5e5a79SGreg Clayton 
882b9c1b51eSKate Stone     if (argc == 1) {
88357179860SJonas Devlieghere       Debugger &debugger = GetDebugger();
884e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
88544d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
886b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
887b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
88873d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
889514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
890514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
891b9c1b51eSKate Stone           multiple_lines, color_prompt,
892f6913cd7SGreg Clayton           0, // Don't show line numbers
893d77c2e09SJonas Devlieghere           *this, nullptr));
89444d93782SGreg Clayton 
895b9c1b51eSKate Stone       if (io_handler_sp) {
8967ce2de2cSJonas Devlieghere         debugger.RunIOHandlerAsync(io_handler_sp);
897de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
898de164aaaSGreg Clayton       }
899b9c1b51eSKate Stone     } else {
90097d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
90144d93782SGreg Clayton         bool check_only = false;
9020d9a201eSRaphael Isemann         error = AppendRegexSubstitution(entry.ref(), check_only);
9030e5e5a79SGreg Clayton         if (error.Fail())
9040e5e5a79SGreg Clayton           break;
9050e5e5a79SGreg Clayton       }
9060e5e5a79SGreg Clayton 
907b9c1b51eSKate Stone       if (error.Success()) {
9080e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
9090e5e5a79SGreg Clayton       }
9100e5e5a79SGreg Clayton     }
911b9c1b51eSKate Stone     if (error.Fail()) {
9120e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
913de164aaaSGreg Clayton     }
9140e5e5a79SGreg Clayton 
915de164aaaSGreg Clayton     return result.Succeeded();
916de164aaaSGreg Clayton   }
917de164aaaSGreg Clayton 
91897206d57SZachary Turner   Status AppendRegexSubstitution(const llvm::StringRef &regex_sed,
919b9c1b51eSKate Stone                                  bool check_only) {
92097206d57SZachary Turner     Status error;
9210e5e5a79SGreg Clayton 
922d5b44036SJonas Devlieghere     if (!m_regex_cmd_up) {
923b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
924b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
925b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9260e5e5a79SGreg Clayton       return error;
927de164aaaSGreg Clayton     }
9280e5e5a79SGreg Clayton 
9290e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
9300e5e5a79SGreg Clayton 
931b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
932b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
933b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
934b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9350e5e5a79SGreg Clayton       return error;
9360e5e5a79SGreg Clayton     }
9370e5e5a79SGreg Clayton 
938b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
939b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
940b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
941b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
9420e5e5a79SGreg Clayton       return error;
9430e5e5a79SGreg Clayton     }
9440e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
94505097246SAdrian Prantl     // use the char that follows 's' as the regex separator character so we can
94605097246SAdrian Prantl     // have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
9470e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
948b9c1b51eSKate Stone     const size_t second_separator_char_pos =
949b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
9500e5e5a79SGreg Clayton 
951b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
952b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
953b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
9540e5e5a79SGreg Clayton           separator_char,
9550e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
956ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
957b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9580e5e5a79SGreg Clayton       return error;
9590e5e5a79SGreg Clayton     }
9600e5e5a79SGreg Clayton 
961b9c1b51eSKate Stone     const size_t third_separator_char_pos =
962b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
9630e5e5a79SGreg Clayton 
964b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
965b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
966b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
9670e5e5a79SGreg Clayton           separator_char,
9680e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
969ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
970b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
9710e5e5a79SGreg Clayton       return error;
9720e5e5a79SGreg Clayton     }
9730e5e5a79SGreg Clayton 
974b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
97505097246SAdrian Prantl       // Make sure that everything that follows the last regex separator char
976b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
977b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
978b9c1b51eSKate Stone           std::string::npos) {
979b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
980b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
981b9c1b51eSKate Stone             "string: '%.*s'",
982b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
9830e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
9840e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
9850e5e5a79SGreg Clayton         return error;
9860e5e5a79SGreg Clayton       }
987b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
988b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
989b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
990b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
9910e5e5a79SGreg Clayton           regex_sed.data());
9920e5e5a79SGreg Clayton       return error;
993b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
994b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
995b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
996b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
9970e5e5a79SGreg Clayton           regex_sed.data());
9980e5e5a79SGreg Clayton       return error;
9990e5e5a79SGreg Clayton     }
100044d93782SGreg Clayton 
1001b9c1b51eSKate Stone     if (!check_only) {
1002adcd0268SBenjamin Kramer       std::string regex(std::string(regex_sed.substr(
1003adcd0268SBenjamin Kramer           first_separator_char_pos + 1,
1004adcd0268SBenjamin Kramer           second_separator_char_pos - first_separator_char_pos - 1)));
1005adcd0268SBenjamin Kramer       std::string subst(std::string(regex_sed.substr(
1006adcd0268SBenjamin Kramer           second_separator_char_pos + 1,
1007adcd0268SBenjamin Kramer           third_separator_char_pos - second_separator_char_pos - 1)));
100843224195SRaphael Isemann       m_regex_cmd_up->AddRegexCommand(regex, subst);
100944d93782SGreg Clayton     }
10100e5e5a79SGreg Clayton     return error;
1011de164aaaSGreg Clayton   }
1012de164aaaSGreg Clayton 
1013b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1014d5b44036SJonas Devlieghere     if (m_regex_cmd_up) {
1015d5b44036SJonas Devlieghere       if (m_regex_cmd_up->HasRegexEntries()) {
1016d5b44036SJonas Devlieghere         CommandObjectSP cmd_sp(m_regex_cmd_up.release());
1017de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1018de164aaaSGreg Clayton       }
1019de164aaaSGreg Clayton     }
1020de164aaaSGreg Clayton   }
1021de164aaaSGreg Clayton 
1022de164aaaSGreg Clayton private:
1023d5b44036SJonas Devlieghere   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_up;
1024de164aaaSGreg Clayton 
1025b9c1b51eSKate Stone   class CommandOptions : public Options {
1026de164aaaSGreg Clayton   public:
1027b9c1b51eSKate Stone     CommandOptions() : Options() {}
1028de164aaaSGreg Clayton 
10296e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1030de164aaaSGreg Clayton 
103197206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1032b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
103397206d57SZachary Turner       Status error;
10343bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1035de164aaaSGreg Clayton 
1036b9c1b51eSKate Stone       switch (short_option) {
1037de164aaaSGreg Clayton       case 'h':
1038adcd0268SBenjamin Kramer         m_help.assign(std::string(option_arg));
1039de164aaaSGreg Clayton         break;
1040de164aaaSGreg Clayton       case 's':
1041adcd0268SBenjamin Kramer         m_syntax.assign(std::string(option_arg));
1042de164aaaSGreg Clayton         break;
1043de164aaaSGreg Clayton       default:
104436162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
1045de164aaaSGreg Clayton       }
1046de164aaaSGreg Clayton 
1047de164aaaSGreg Clayton       return error;
1048de164aaaSGreg Clayton     }
1049de164aaaSGreg Clayton 
1050b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1051de164aaaSGreg Clayton       m_help.clear();
1052de164aaaSGreg Clayton       m_syntax.clear();
1053de164aaaSGreg Clayton     }
1054de164aaaSGreg Clayton 
10551f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
105670602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
10571f0f5b5bSZachary Turner     }
1058de164aaaSGreg Clayton 
1059daed98e5SShivam Mittal     llvm::StringRef GetHelp() { return m_help; }
10606e3d8e7fSEugene Zelenko 
1061daed98e5SShivam Mittal     llvm::StringRef GetSyntax() { return m_syntax; }
10626e3d8e7fSEugene Zelenko 
1063de164aaaSGreg Clayton   protected:
10646e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
10656e3d8e7fSEugene Zelenko 
1066de164aaaSGreg Clayton     std::string m_help;
1067de164aaaSGreg Clayton     std::string m_syntax;
1068de164aaaSGreg Clayton   };
1069de164aaaSGreg Clayton 
1070b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1071de164aaaSGreg Clayton 
10725a988416SJim Ingham   CommandOptions m_options;
1073de164aaaSGreg Clayton };
1074de164aaaSGreg Clayton 
1075b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1076223383edSEnrico Granata public:
1077b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1078b9c1b51eSKate Stone                               std::string funct, std::string help,
1079b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1080a925974bSAdrian Prantl       : CommandObjectRaw(interpreter, name), m_function_name(funct),
1081a925974bSAdrian Prantl         m_synchro(synch), m_fetched_help_long(false) {
1082735152e3SEnrico Granata     if (!help.empty())
1083442f6530SZachary Turner       SetHelp(help);
1084b9c1b51eSKate Stone     else {
1085735152e3SEnrico Granata       StreamString stream;
1086735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1087c156427dSZachary Turner       SetHelp(stream.GetString());
1088735152e3SEnrico Granata     }
1089223383edSEnrico Granata   }
1090223383edSEnrico Granata 
10916e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1092223383edSEnrico Granata 
1093b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
10945a988416SJim Ingham 
1095b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
10965a988416SJim Ingham 
1097b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
10985a988416SJim Ingham 
1099442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1100442f6530SZachary Turner     if (m_fetched_help_long)
1101442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1102442f6530SZachary Turner 
11032b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1104442f6530SZachary Turner     if (!scripter)
1105442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1106442f6530SZachary Turner 
1107fac939e9SEnrico Granata     std::string docstring;
1108442f6530SZachary Turner     m_fetched_help_long =
1109442f6530SZachary Turner         scripter->GetDocumentationForItem(m_function_name.c_str(), docstring);
1110fac939e9SEnrico Granata     if (!docstring.empty())
1111442f6530SZachary Turner       SetHelpLong(docstring);
1112fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1113fac939e9SEnrico Granata   }
1114fac939e9SEnrico Granata 
11155a988416SJim Ingham protected:
11164d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1117b9c1b51eSKate Stone                  CommandReturnObject &result) override {
11182b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1119223383edSEnrico Granata 
112097206d57SZachary Turner     Status error;
1121223383edSEnrico Granata 
112270f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
112370f11f88SJim Ingham 
1124a925974bSAdrian Prantl     if (!scripter || !scripter->RunScriptBasedCommand(
1125a925974bSAdrian Prantl                          m_function_name.c_str(), raw_command_line, m_synchro,
1126a925974bSAdrian Prantl                          result, error, m_exe_ctx)) {
1127223383edSEnrico Granata       result.AppendError(error.AsCString());
1128b9c1b51eSKate Stone     } else {
112970f11f88SJim Ingham       // Don't change the status if the command already set it...
1130b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1131c156427dSZachary Turner         if (result.GetOutputData().empty())
1132223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
113370f11f88SJim Ingham         else
113470f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
113570f11f88SJim Ingham       }
113670f11f88SJim Ingham     }
1137223383edSEnrico Granata 
1138223383edSEnrico Granata     return result.Succeeded();
1139223383edSEnrico Granata   }
1140223383edSEnrico Granata 
11416e3d8e7fSEugene Zelenko private:
11426e3d8e7fSEugene Zelenko   std::string m_function_name;
11436e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
11446e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1145223383edSEnrico Granata };
1146223383edSEnrico Granata 
1147b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
11489fe00e52SEnrico Granata public:
11499fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
11509fe00e52SEnrico Granata                                std::string name,
11510641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1152b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1153a925974bSAdrian Prantl       : CommandObjectRaw(interpreter, name), m_cmd_obj_sp(cmd_obj_sp),
1154a925974bSAdrian Prantl         m_synchro(synch), m_fetched_help_short(false),
1155b9c1b51eSKate Stone         m_fetched_help_long(false) {
11569fe00e52SEnrico Granata     StreamString stream;
11579fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
1158c156427dSZachary Turner     SetHelp(stream.GetString());
11592b29b432SJonas Devlieghere     if (ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter())
1160e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
11619fe00e52SEnrico Granata   }
11629fe00e52SEnrico Granata 
11636e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
11649fe00e52SEnrico Granata 
1165b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
11669fe00e52SEnrico Granata 
1167b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
11689fe00e52SEnrico Granata 
1169442f6530SZachary Turner   llvm::StringRef GetHelp() override {
1170442f6530SZachary Turner     if (m_fetched_help_short)
1171442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
11722b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1173442f6530SZachary Turner     if (!scripter)
1174442f6530SZachary Turner       return CommandObjectRaw::GetHelp();
11756f79bb2dSEnrico Granata     std::string docstring;
1176b9c1b51eSKate Stone     m_fetched_help_short =
1177b9c1b51eSKate Stone         scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
11786f79bb2dSEnrico Granata     if (!docstring.empty())
1179442f6530SZachary Turner       SetHelp(docstring);
1180442f6530SZachary Turner 
11816f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
11826f79bb2dSEnrico Granata   }
11836f79bb2dSEnrico Granata 
1184442f6530SZachary Turner   llvm::StringRef GetHelpLong() override {
1185442f6530SZachary Turner     if (m_fetched_help_long)
1186442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1187442f6530SZachary Turner 
11882b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
1189442f6530SZachary Turner     if (!scripter)
1190442f6530SZachary Turner       return CommandObjectRaw::GetHelpLong();
1191442f6530SZachary Turner 
11926f79bb2dSEnrico Granata     std::string docstring;
1193b9c1b51eSKate Stone     m_fetched_help_long =
1194b9c1b51eSKate Stone         scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
11956f79bb2dSEnrico Granata     if (!docstring.empty())
1196442f6530SZachary Turner       SetHelpLong(docstring);
11979fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
11989fe00e52SEnrico Granata   }
11999fe00e52SEnrico Granata 
12009fe00e52SEnrico Granata protected:
12014d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
1202b9c1b51eSKate Stone                  CommandReturnObject &result) override {
12032b29b432SJonas Devlieghere     ScriptInterpreter *scripter = GetDebugger().GetScriptInterpreter();
12049fe00e52SEnrico Granata 
120597206d57SZachary Turner     Status error;
12069fe00e52SEnrico Granata 
12079fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
12089fe00e52SEnrico Granata 
1209b9c1b51eSKate Stone     if (!scripter ||
1210b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1211b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
12129fe00e52SEnrico Granata       result.AppendError(error.AsCString());
1213b9c1b51eSKate Stone     } else {
12149fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1215b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1216c156427dSZachary Turner         if (result.GetOutputData().empty())
12179fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
12189fe00e52SEnrico Granata         else
12199fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
12209fe00e52SEnrico Granata       }
12219fe00e52SEnrico Granata     }
12229fe00e52SEnrico Granata 
12239fe00e52SEnrico Granata     return result.Succeeded();
12249fe00e52SEnrico Granata   }
12259fe00e52SEnrico Granata 
12266e3d8e7fSEugene Zelenko private:
12276e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
12286e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
12296e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
12306e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
12319fe00e52SEnrico Granata };
12329fe00e52SEnrico Granata 
1233a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
123464becc11SRaphael Isemann #define LLDB_OPTIONS_script_import
123564becc11SRaphael Isemann #include "CommandOptions.inc"
12361f0f5b5bSZachary Turner 
1237b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
12385a988416SJim Ingham public:
1239b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1240b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1241b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1242b9c1b51eSKate Stone         m_options() {
12435a988416SJim Ingham     CommandArgumentEntry arg1;
12445a988416SJim Ingham     CommandArgumentData cmd_arg;
12455a988416SJim Ingham 
12465a988416SJim Ingham     // Define the first (and only) variant of this arg.
12475a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
12483b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
12495a988416SJim Ingham 
1250b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1251b9c1b51eSKate Stone     // argument entry.
12525a988416SJim Ingham     arg1.push_back(cmd_arg);
12535a988416SJim Ingham 
12545a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
12555a988416SJim Ingham     m_arguments.push_back(arg1);
12565a988416SJim Ingham   }
12575a988416SJim Ingham 
12586e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
12595a988416SJim Ingham 
1260ae34ed2cSRaphael Isemann   void
1261ae34ed2cSRaphael Isemann   HandleArgumentCompletion(CompletionRequest &request,
12622443bbd4SRaphael Isemann                            OptionElementVector &opt_element_vector) override {
1263b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1264b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1265a2e76c0bSRaphael Isemann         request, nullptr);
12665a988416SJim Ingham   }
12675a988416SJim Ingham 
1268b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
12695a988416SJim Ingham 
12705a988416SJim Ingham protected:
1271b9c1b51eSKate Stone   class CommandOptions : public Options {
12720a305db7SEnrico Granata   public:
1273b9c1b51eSKate Stone     CommandOptions() : Options() {}
12740a305db7SEnrico Granata 
12756e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
12760a305db7SEnrico Granata 
127797206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1278b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
127997206d57SZachary Turner       Status error;
12803bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
12810a305db7SEnrico Granata 
1282b9c1b51eSKate Stone       switch (short_option) {
12830a305db7SEnrico Granata       case 'r':
128415625112SJonas Devlieghere         // NO-OP
12850a305db7SEnrico Granata         break;
128600bb397bSJonas Devlieghere       case 'c':
128700bb397bSJonas Devlieghere         relative_to_command_file = true;
128800bb397bSJonas Devlieghere         break;
1289f9517353SJonas Devlieghere       case 's':
1290f9517353SJonas Devlieghere         silent = true;
1291f9517353SJonas Devlieghere         break;
12920a305db7SEnrico Granata       default:
129336162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
12940a305db7SEnrico Granata       }
12950a305db7SEnrico Granata 
12960a305db7SEnrico Granata       return error;
12970a305db7SEnrico Granata     }
12980a305db7SEnrico Granata 
1299b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
130000bb397bSJonas Devlieghere       relative_to_command_file = false;
13010a305db7SEnrico Granata     }
13020a305db7SEnrico Granata 
13031f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
130470602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
13051f0f5b5bSZachary Turner     }
130600bb397bSJonas Devlieghere     bool relative_to_command_file = false;
1307f9517353SJonas Devlieghere     bool silent = false;
13080a305db7SEnrico Granata   };
13090a305db7SEnrico Granata 
1310b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
131111eb9c64SZachary Turner     if (command.empty()) {
13123b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1313a9dbf432SEnrico Granata       return false;
1314a9dbf432SEnrico Granata     }
1315a9dbf432SEnrico Granata 
131600bb397bSJonas Devlieghere     FileSpec source_dir = {};
131700bb397bSJonas Devlieghere     if (m_options.relative_to_command_file) {
131800bb397bSJonas Devlieghere       source_dir = GetDebugger().GetCommandInterpreter().GetCurrentSourceDir();
131900bb397bSJonas Devlieghere       if (!source_dir) {
132000bb397bSJonas Devlieghere         result.AppendError("command script import -c can only be specified "
132100bb397bSJonas Devlieghere                            "from a command file");
132200bb397bSJonas Devlieghere         return false;
132300bb397bSJonas Devlieghere       }
132400bb397bSJonas Devlieghere     }
132500bb397bSJonas Devlieghere 
132611eb9c64SZachary Turner     for (auto &entry : command.entries()) {
132797206d57SZachary Turner       Status error;
1328a9dbf432SEnrico Granata 
1329f9517353SJonas Devlieghere       LoadScriptOptions options;
1330f9517353SJonas Devlieghere       options.SetInitSession(true);
1331f9517353SJonas Devlieghere       options.SetSilent(m_options.silent);
1332f9517353SJonas Devlieghere 
1333b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
133411eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
133511eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
133605097246SAdrian Prantl       // script imports" in __lldb_init_module the real fix is to have
133705097246SAdrian Prantl       // recursive commands possible with a CommandInvocation object separate
133805097246SAdrian Prantl       // from the CommandObject itself, so that recursive command invocations
133905097246SAdrian Prantl       // won't stomp on each other (wrt to execution contents, options, and
134005097246SAdrian Prantl       // more)
1341078551c7SEnrico Granata       m_exe_ctx.Clear();
13422b29b432SJonas Devlieghere       if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
1343f9517353SJonas Devlieghere               entry.c_str(), options, error, /*module_sp=*/nullptr,
1344f9517353SJonas Devlieghere               source_dir)) {
1345a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1346b9c1b51eSKate Stone       } else {
1347b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1348b9c1b51eSKate Stone                                      error.AsCString());
1349a9dbf432SEnrico Granata       }
13503b00e35bSEnrico Granata     }
1351a9dbf432SEnrico Granata 
1352a9dbf432SEnrico Granata     return result.Succeeded();
1353a9dbf432SEnrico Granata   }
13540a305db7SEnrico Granata 
13555a988416SJim Ingham   CommandOptions m_options;
1356a9dbf432SEnrico Granata };
1357223383edSEnrico Granata 
1358223383edSEnrico Granata // CommandObjectCommandsScriptAdd
13598fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_synchro_type[] = {
1360e063ecccSJonas Devlieghere     {
1361e063ecccSJonas Devlieghere         eScriptedCommandSynchronicitySynchronous,
1362e063ecccSJonas Devlieghere         "synchronous",
1363e063ecccSJonas Devlieghere         "Run synchronous",
1364e063ecccSJonas Devlieghere     },
1365e063ecccSJonas Devlieghere     {
1366e063ecccSJonas Devlieghere         eScriptedCommandSynchronicityAsynchronous,
1367e063ecccSJonas Devlieghere         "asynchronous",
1368e063ecccSJonas Devlieghere         "Run asynchronous",
1369e063ecccSJonas Devlieghere     },
1370e063ecccSJonas Devlieghere     {
1371e063ecccSJonas Devlieghere         eScriptedCommandSynchronicityCurrentValue,
1372e063ecccSJonas Devlieghere         "current",
1373e063ecccSJonas Devlieghere         "Do not alter current setting",
1374e063ecccSJonas Devlieghere     },
1375e063ecccSJonas Devlieghere };
13761f0f5b5bSZachary Turner 
13778fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptSynchroType() {
13788fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_synchro_type);
13798fe53c49STatyana Krasnukha }
13808fe53c49STatyana Krasnukha 
138164becc11SRaphael Isemann #define LLDB_OPTIONS_script_add
138264becc11SRaphael Isemann #include "CommandOptions.inc"
13831f0f5b5bSZachary Turner 
1384b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1385b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
13865a988416SJim Ingham public:
1387b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1388b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
13895a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
1390*c5011aedSJim Ingham                             "Add a scripted function as an lldb command. "
1391*c5011aedSJim Ingham                             "If you provide a single argument, the command "
1392*c5011aedSJim Ingham                             "will be added at the root level of the command "
1393*c5011aedSJim Ingham                             "hierarchy.  If there are more arguments they "
1394*c5011aedSJim Ingham                             "must be a path to a user-added container "
1395*c5011aedSJim Ingham                             "command, and the last element will be the new "
1396*c5011aedSJim Ingham                             "command name."),
1397b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
13985a988416SJim Ingham     CommandArgumentEntry arg1;
13995a988416SJim Ingham     CommandArgumentData cmd_arg;
14005a988416SJim Ingham 
1401*c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
1402*c5011aedSJim Ingham     // you want to add.
1403*c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1404*c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
14055a988416SJim Ingham 
1406b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1407b9c1b51eSKate Stone     // argument entry.
14085a988416SJim Ingham     arg1.push_back(cmd_arg);
14095a988416SJim Ingham 
14105a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14115a988416SJim Ingham     m_arguments.push_back(arg1);
14125a988416SJim Ingham   }
14135a988416SJim Ingham 
14146e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
14155a988416SJim Ingham 
1416b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14175a988416SJim Ingham 
1418*c5011aedSJim Ingham   void
1419*c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
1420*c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
1421*c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1422*c5011aedSJim Ingham                                                       opt_element_vector);
1423*c5011aedSJim Ingham   }
1424*c5011aedSJim Ingham 
14255a988416SJim Ingham protected:
1426b9c1b51eSKate Stone   class CommandOptions : public Options {
1427223383edSEnrico Granata   public:
1428b9c1b51eSKate Stone     CommandOptions()
14299494c510SJonas Devlieghere         : Options(), m_class_name(), m_funct_name(), m_short_help() {}
1430223383edSEnrico Granata 
14316e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1432223383edSEnrico Granata 
143397206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1434b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
143597206d57SZachary Turner       Status error;
14363bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1437223383edSEnrico Granata 
1438b9c1b51eSKate Stone       switch (short_option) {
1439223383edSEnrico Granata       case 'f':
1440fe11483bSZachary Turner         if (!option_arg.empty())
1441adcd0268SBenjamin Kramer           m_funct_name = std::string(option_arg);
1442735152e3SEnrico Granata         break;
14439fe00e52SEnrico Granata       case 'c':
1444fe11483bSZachary Turner         if (!option_arg.empty())
1445adcd0268SBenjamin Kramer           m_class_name = std::string(option_arg);
14469fe00e52SEnrico Granata         break;
1447735152e3SEnrico Granata       case 'h':
1448fe11483bSZachary Turner         if (!option_arg.empty())
1449adcd0268SBenjamin Kramer           m_short_help = std::string(option_arg);
1450223383edSEnrico Granata         break;
1451*c5011aedSJim Ingham       case 'o':
1452*c5011aedSJim Ingham         m_overwrite = true;
1453*c5011aedSJim Ingham         break;
14540a305db7SEnrico Granata       case 's':
1455b9c1b51eSKate Stone         m_synchronicity =
145647cbf4a0SPavel Labath             (ScriptedCommandSynchronicity)OptionArgParser::ToOptionEnum(
1457fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
14580a305db7SEnrico Granata         if (!error.Success())
1459b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1460fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1461fe11483bSZachary Turner               option_arg.str().c_str());
14620a305db7SEnrico Granata         break;
1463223383edSEnrico Granata       default:
146436162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
1465223383edSEnrico Granata       }
1466223383edSEnrico Granata 
1467223383edSEnrico Granata       return error;
1468223383edSEnrico Granata     }
1469223383edSEnrico Granata 
1470b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
14719fe00e52SEnrico Granata       m_class_name.clear();
1472735152e3SEnrico Granata       m_funct_name.clear();
1473735152e3SEnrico Granata       m_short_help.clear();
1474*c5011aedSJim Ingham       m_overwrite = false;
147544d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1476223383edSEnrico Granata     }
1477223383edSEnrico Granata 
14781f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
147970602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
14801f0f5b5bSZachary Turner     }
1481223383edSEnrico Granata 
1482223383edSEnrico Granata     // Instance variables to hold the values for command options.
1483223383edSEnrico Granata 
14849fe00e52SEnrico Granata     std::string m_class_name;
1485223383edSEnrico Granata     std::string m_funct_name;
1486735152e3SEnrico Granata     std::string m_short_help;
1487*c5011aedSJim Ingham     bool m_overwrite;
14889494c510SJonas Devlieghere     ScriptedCommandSynchronicity m_synchronicity =
14899494c510SJonas Devlieghere         eScriptedCommandSynchronicitySynchronous;
1490223383edSEnrico Granata   };
1491223383edSEnrico Granata 
14920affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
14937ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
14940affb582SDave Lee     if (output_sp && interactive) {
149544d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
149644d93782SGreg Clayton       output_sp->Flush();
1497223383edSEnrico Granata     }
1498223383edSEnrico Granata   }
1499223383edSEnrico Granata 
1500b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1501b9c1b51eSKate Stone                               std::string &data) override {
15027ca15ba7SLawrence D'Anna     StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
150344d93782SGreg Clayton 
15042b29b432SJonas Devlieghere     ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1505b9c1b51eSKate Stone     if (interpreter) {
150644d93782SGreg Clayton 
150744d93782SGreg Clayton       StringList lines;
150844d93782SGreg Clayton       lines.SplitIntoLines(data);
1509b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1510a73b7df7SEnrico Granata         std::string funct_name_str;
1511b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1512b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1513b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1514b9c1b51eSKate Stone                              "add python command.\n");
151544d93782SGreg Clayton             error_sp->Flush();
1516b9c1b51eSKate Stone           } else {
1517223383edSEnrico Granata             // everything should be fine now, let's add this alias
1518223383edSEnrico Granata 
1519b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1520771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
152144d93782SGreg Clayton                 m_synchronicity));
1522*c5011aedSJim Ingham             if (!m_container) {
1523*c5011aedSJim Ingham               Status error = m_interpreter.AddUserCommand(
1524*c5011aedSJim Ingham                   m_cmd_name, command_obj_sp, m_overwrite);
1525*c5011aedSJim Ingham               if (error.Fail()) {
1526*c5011aedSJim Ingham                 error_sp->Printf("error: unable to add selected command: '%s'",
1527*c5011aedSJim Ingham                                  error.AsCString());
152844d93782SGreg Clayton                 error_sp->Flush();
1529223383edSEnrico Granata               }
1530*c5011aedSJim Ingham             } else {
1531*c5011aedSJim Ingham               llvm::Error llvm_error = m_container->LoadUserSubcommand(
1532*c5011aedSJim Ingham                   m_cmd_name, command_obj_sp, m_overwrite);
1533*c5011aedSJim Ingham               if (llvm_error) {
1534*c5011aedSJim Ingham                 error_sp->Printf("error: unable to add selected command: '%s'",
1535*c5011aedSJim Ingham                                llvm::toString(std::move(llvm_error)).c_str());
1536*c5011aedSJim Ingham                 error_sp->Flush();
1537*c5011aedSJim Ingham               }
1538*c5011aedSJim Ingham             }
1539223383edSEnrico Granata           }
1540b9c1b51eSKate Stone         } else {
1541b9c1b51eSKate Stone           error_sp->Printf(
1542*c5011aedSJim Ingham               "error: unable to create function, didn't add python command\n");
154344d93782SGreg Clayton           error_sp->Flush();
154444d93782SGreg Clayton         }
1545b9c1b51eSKate Stone       } else {
1546*c5011aedSJim Ingham         error_sp->Printf("error: empty function, didn't add python command\n");
154744d93782SGreg Clayton         error_sp->Flush();
154844d93782SGreg Clayton       }
1549b9c1b51eSKate Stone     } else {
1550b9c1b51eSKate Stone       error_sp->Printf(
1551*c5011aedSJim Ingham           "error: script interpreter missing, didn't add python command\n");
155244d93782SGreg Clayton       error_sp->Flush();
155344d93782SGreg Clayton     }
155444d93782SGreg Clayton 
155544d93782SGreg Clayton     io_handler.SetIsDone(true);
155644d93782SGreg Clayton   }
1557223383edSEnrico Granata 
1558b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
155957179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1560b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1561b9c1b51eSKate Stone                          "commands is currently Python");
156299f0b8f9SEnrico Granata       return false;
156399f0b8f9SEnrico Granata     }
156499f0b8f9SEnrico Granata 
1565*c5011aedSJim Ingham     if (command.GetArgumentCount() == 0) {
1566*c5011aedSJim Ingham       result.AppendError("'command script add' requires at least one argument");
1567*c5011aedSJim Ingham       return false;
1568*c5011aedSJim Ingham     }
1569*c5011aedSJim Ingham     // Store the options in case we get multi-line input
1570*c5011aedSJim Ingham     m_overwrite = m_options.m_overwrite;
1571*c5011aedSJim Ingham     Status path_error;
1572*c5011aedSJim Ingham     m_container = GetCommandInterpreter().VerifyUserMultiwordCmdPath(
1573*c5011aedSJim Ingham         command, true, path_error);
1574*c5011aedSJim Ingham 
1575*c5011aedSJim Ingham     if (path_error.Fail()) {
1576*c5011aedSJim Ingham       result.AppendErrorWithFormat("error in command path: %s",
1577*c5011aedSJim Ingham                                    path_error.AsCString());
1578223383edSEnrico Granata       return false;
1579223383edSEnrico Granata     }
1580223383edSEnrico Granata 
1581*c5011aedSJim Ingham     if (!m_container) {
1582*c5011aedSJim Ingham       // This is getting inserted into the root of the interpreter.
1583adcd0268SBenjamin Kramer       m_cmd_name = std::string(command[0].ref());
1584*c5011aedSJim Ingham     } else {
1585*c5011aedSJim Ingham       size_t num_args = command.GetArgumentCount();
1586*c5011aedSJim Ingham       m_cmd_name = std::string(command[num_args - 1].ref());
1587*c5011aedSJim Ingham     }
1588*c5011aedSJim Ingham 
1589735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
159044d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1591223383edSEnrico Granata 
1592*c5011aedSJim Ingham     // Handle the case where we prompt for the script code first:
1593*c5011aedSJim Ingham     if (m_options.m_class_name.empty() && m_options.m_funct_name.empty()) {
1594*c5011aedSJim Ingham       m_interpreter.GetPythonCommandsFromIOHandler("     ", // Prompt
1595a6faf851SJonas Devlieghere                                                    *this);  // IOHandlerDelegate
1596*c5011aedSJim Ingham       return result.Succeeded();
1597*c5011aedSJim Ingham     }
1598*c5011aedSJim Ingham 
1599*c5011aedSJim Ingham     CommandObjectSP new_cmd_sp;
1600*c5011aedSJim Ingham     if (m_options.m_class_name.empty()) {
1601*c5011aedSJim Ingham       new_cmd_sp.reset(new CommandObjectPythonFunction(
1602b9c1b51eSKate Stone           m_interpreter, m_cmd_name, m_options.m_funct_name,
1603b9c1b51eSKate Stone           m_options.m_short_help, m_synchronicity));
1604b9c1b51eSKate Stone     } else {
16052b29b432SJonas Devlieghere       ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1606b9c1b51eSKate Stone       if (!interpreter) {
16079fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
16089fe00e52SEnrico Granata         return false;
16099fe00e52SEnrico Granata       }
16109fe00e52SEnrico Granata 
1611b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1612b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1613b9c1b51eSKate Stone       if (!cmd_obj_sp) {
16149fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
16159fe00e52SEnrico Granata         return false;
16169fe00e52SEnrico Granata       }
16179fe00e52SEnrico Granata 
1618*c5011aedSJim Ingham       new_cmd_sp.reset(new CommandObjectScriptingObject(
1619b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
16209fe00e52SEnrico Granata     }
1621223383edSEnrico Granata 
1622*c5011aedSJim Ingham     // Assume we're going to succeed...
1623*c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1624*c5011aedSJim Ingham     if (!m_container) {
1625*c5011aedSJim Ingham       Status add_error =
1626*c5011aedSJim Ingham           m_interpreter.AddUserCommand(m_cmd_name, new_cmd_sp, m_overwrite);
1627*c5011aedSJim Ingham       if (add_error.Fail())
1628*c5011aedSJim Ingham         result.AppendErrorWithFormat("cannot add command: %s",
1629*c5011aedSJim Ingham                                      add_error.AsCString());
1630*c5011aedSJim Ingham     } else {
1631*c5011aedSJim Ingham       llvm::Error llvm_error =
1632*c5011aedSJim Ingham           m_container->LoadUserSubcommand(m_cmd_name, new_cmd_sp, m_overwrite);
1633*c5011aedSJim Ingham       if (llvm_error)
1634*c5011aedSJim Ingham         result.AppendErrorWithFormat("cannot add command: %s",
1635*c5011aedSJim Ingham                                      llvm::toString(std::move(llvm_error)).c_str());
1636*c5011aedSJim Ingham     }
1637223383edSEnrico Granata     return result.Succeeded();
1638223383edSEnrico Granata   }
16395a988416SJim Ingham 
16405a988416SJim Ingham   CommandOptions m_options;
164144d93782SGreg Clayton   std::string m_cmd_name;
1642*c5011aedSJim Ingham   CommandObjectMultiword *m_container = nullptr;
1643735152e3SEnrico Granata   std::string m_short_help;
1644*c5011aedSJim Ingham   bool m_overwrite;
164544d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1646223383edSEnrico Granata };
1647223383edSEnrico Granata 
1648223383edSEnrico Granata // CommandObjectCommandsScriptList
1649223383edSEnrico Granata 
1650b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1651223383edSEnrico Granata public:
1652b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1653b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1654*c5011aedSJim Ingham                             "List defined top-level scripted commands.",
1655*c5011aedSJim Ingham                             nullptr) {}
1656223383edSEnrico Granata 
16576e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1658223383edSEnrico Granata 
1659b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1660d77ea5b2SRaphael Isemann     if (command.GetArgumentCount() != 0) {
1661d77ea5b2SRaphael Isemann       result.AppendError("'command script list' doesn't take any arguments");
1662d77ea5b2SRaphael Isemann       return false;
1663d77ea5b2SRaphael Isemann     }
1664d77ea5b2SRaphael Isemann 
1665b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1666223383edSEnrico Granata 
1667223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1668223383edSEnrico Granata 
1669223383edSEnrico Granata     return true;
1670223383edSEnrico Granata   }
1671223383edSEnrico Granata };
1672223383edSEnrico Granata 
1673223383edSEnrico Granata // CommandObjectCommandsScriptClear
1674223383edSEnrico Granata 
1675b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1676223383edSEnrico Granata public:
1677b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1678b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1679b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1680223383edSEnrico Granata 
16816e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1682223383edSEnrico Granata 
16835a988416SJim Ingham protected:
1684b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1685d77ea5b2SRaphael Isemann     if (command.GetArgumentCount() != 0) {
1686d77ea5b2SRaphael Isemann       result.AppendError("'command script clear' doesn't take any arguments");
1687d77ea5b2SRaphael Isemann       return false;
1688d77ea5b2SRaphael Isemann     }
1689d77ea5b2SRaphael Isemann 
1690223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1691223383edSEnrico Granata 
1692223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1693223383edSEnrico Granata 
1694223383edSEnrico Granata     return true;
1695223383edSEnrico Granata   }
1696223383edSEnrico Granata };
1697223383edSEnrico Granata 
1698223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1699223383edSEnrico Granata 
1700b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1701223383edSEnrico Granata public:
1702b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1703*c5011aedSJim Ingham       : CommandObjectParsed(
1704*c5011aedSJim Ingham             interpreter, "command script delete",
1705*c5011aedSJim Ingham             "Delete a scripted command by specifying the path to the command.",
1706*c5011aedSJim Ingham             nullptr) {
1707223383edSEnrico Granata     CommandArgumentEntry arg1;
1708223383edSEnrico Granata     CommandArgumentData cmd_arg;
1709223383edSEnrico Granata 
1710*c5011aedSJim Ingham     // This is a list of command names forming the path to the command
1711*c5011aedSJim Ingham     // to be deleted.
1712*c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1713*c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
1714223383edSEnrico Granata 
1715b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1716b9c1b51eSKate Stone     // argument entry.
1717223383edSEnrico Granata     arg1.push_back(cmd_arg);
1718223383edSEnrico Granata 
1719223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1720223383edSEnrico Granata     m_arguments.push_back(arg1);
1721223383edSEnrico Granata   }
1722223383edSEnrico Granata 
17236e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1724223383edSEnrico Granata 
17252e8f304fSGongyu Deng   void
17262e8f304fSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
17272e8f304fSGongyu Deng                            OptionElementVector &opt_element_vector) override {
1728*c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1729*c5011aedSJim Ingham                                                       opt_element_vector);
17302e8f304fSGongyu Deng   }
17312e8f304fSGongyu Deng 
17325a988416SJim Ingham protected:
1733b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1734223383edSEnrico Granata 
1735*c5011aedSJim Ingham     llvm::StringRef root_cmd = command[0].ref();
1736*c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
1737*c5011aedSJim Ingham 
1738*c5011aedSJim Ingham     if (root_cmd.empty()) {
1739*c5011aedSJim Ingham       result.AppendErrorWithFormat("empty root command name");
1740*c5011aedSJim Ingham       return false;
1741*c5011aedSJim Ingham     }
1742*c5011aedSJim Ingham     if (!m_interpreter.HasUserCommands() &&
1743*c5011aedSJim Ingham         !m_interpreter.HasUserMultiwordCommands()) {
1744*c5011aedSJim Ingham       result.AppendErrorWithFormat("can only delete user defined commands, "
1745*c5011aedSJim Ingham                                    "but no user defined commands found");
1746223383edSEnrico Granata       return false;
1747223383edSEnrico Granata     }
1748223383edSEnrico Granata 
1749*c5011aedSJim Ingham     CommandObjectSP cmd_sp = m_interpreter.GetCommandSPExact(root_cmd);
1750*c5011aedSJim Ingham     if (!cmd_sp) {
1751*c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' not found.",
1752*c5011aedSJim Ingham                                    command[0].c_str());
1753*c5011aedSJim Ingham       return false;
1754*c5011aedSJim Ingham     }
1755*c5011aedSJim Ingham     if (!cmd_sp->IsUserCommand()) {
1756*c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' is not a user command.",
1757*c5011aedSJim Ingham                                    command[0].c_str());
1758*c5011aedSJim Ingham       return false;
1759*c5011aedSJim Ingham     }
1760*c5011aedSJim Ingham     if (cmd_sp->GetAsMultiwordCommand() && num_args == 1) {
1761*c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' is a multi-word command.\n "
1762*c5011aedSJim Ingham                                    "Delete with \"command container delete\"",
1763*c5011aedSJim Ingham                                    command[0].c_str());
17644574a890SZachary Turner       return false;
1765223383edSEnrico Granata     }
1766223383edSEnrico Granata 
1767*c5011aedSJim Ingham     if (command.GetArgumentCount() == 1) {
1768*c5011aedSJim Ingham       m_interpreter.RemoveUser(root_cmd);
1769*c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishResult);
1770*c5011aedSJim Ingham       return true;
1771*c5011aedSJim Ingham     }
1772*c5011aedSJim Ingham     // We're deleting a command from a multiword command.  Verify the command
1773*c5011aedSJim Ingham     // path:
1774*c5011aedSJim Ingham     Status error;
1775*c5011aedSJim Ingham     CommandObjectMultiword *container =
1776*c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
1777*c5011aedSJim Ingham                                                            error);
1778*c5011aedSJim Ingham     if (error.Fail()) {
1779*c5011aedSJim Ingham       result.AppendErrorWithFormat("could not resolve command path: %s",
1780*c5011aedSJim Ingham                                    error.AsCString());
1781*c5011aedSJim Ingham       return false;
1782*c5011aedSJim Ingham     }
1783*c5011aedSJim Ingham     if (!container) {
1784*c5011aedSJim Ingham       // This means that command only had a leaf command, so the container is
1785*c5011aedSJim Ingham       // the root.  That should have been handled above.
1786*c5011aedSJim Ingham       result.AppendErrorWithFormat("could not find a container for '%s'",
1787*c5011aedSJim Ingham                                    command[0].c_str());
1788*c5011aedSJim Ingham       return false;
1789*c5011aedSJim Ingham     }
1790*c5011aedSJim Ingham     const char *leaf_cmd = command[num_args - 1].c_str();
1791*c5011aedSJim Ingham     llvm::Error llvm_error = container->RemoveUserSubcommand(leaf_cmd,
1792*c5011aedSJim Ingham                                             /* multiword not okay */ false);
1793*c5011aedSJim Ingham     if (llvm_error) {
1794*c5011aedSJim Ingham       result.AppendErrorWithFormat("could not delete command '%s': %s",
1795*c5011aedSJim Ingham                                    leaf_cmd,
1796*c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
1797*c5011aedSJim Ingham       return false;
1798*c5011aedSJim Ingham     }
1799*c5011aedSJim Ingham 
1800*c5011aedSJim Ingham     Stream &out_stream = result.GetOutputStream();
1801*c5011aedSJim Ingham 
1802*c5011aedSJim Ingham     out_stream << "Deleted command:";
1803*c5011aedSJim Ingham     for (size_t idx = 0; idx < num_args; idx++) {
1804*c5011aedSJim Ingham       out_stream << ' ';
1805*c5011aedSJim Ingham       out_stream << command[idx].c_str();
1806*c5011aedSJim Ingham     }
1807*c5011aedSJim Ingham     out_stream << '\n';
18084574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishResult);
18094574a890SZachary Turner     return true;
1810223383edSEnrico Granata   }
1811223383edSEnrico Granata };
1812223383edSEnrico Granata 
1813223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1814223383edSEnrico Granata 
1815223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1816223383edSEnrico Granata 
1817b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1818223383edSEnrico Granata public:
18197428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1820b9c1b51eSKate Stone       : CommandObjectMultiword(
1821a925974bSAdrian Prantl             interpreter, "command script",
1822a925974bSAdrian Prantl             "Commands for managing custom "
1823b9c1b51eSKate Stone             "commands implemented by "
1824b9c1b51eSKate Stone             "interpreter scripts.",
1825b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1826b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1827b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1828b9c1b51eSKate Stone     LoadSubCommand(
1829b9c1b51eSKate Stone         "delete",
1830b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1831b9c1b51eSKate Stone     LoadSubCommand(
1832b9c1b51eSKate Stone         "clear",
1833b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1834b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1835b9c1b51eSKate Stone                                interpreter)));
1836b9c1b51eSKate Stone     LoadSubCommand(
1837b9c1b51eSKate Stone         "import",
1838b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1839223383edSEnrico Granata   }
1840223383edSEnrico Granata 
18416e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1842223383edSEnrico Granata };
1843223383edSEnrico Granata 
1844*c5011aedSJim Ingham #pragma mark CommandObjectCommandContainer
1845*c5011aedSJim Ingham #define LLDB_OPTIONS_container_add
1846*c5011aedSJim Ingham #include "CommandOptions.inc"
1847*c5011aedSJim Ingham 
1848*c5011aedSJim Ingham class CommandObjectCommandsContainerAdd : public CommandObjectParsed {
1849*c5011aedSJim Ingham public:
1850*c5011aedSJim Ingham   CommandObjectCommandsContainerAdd(CommandInterpreter &interpreter)
1851*c5011aedSJim Ingham       : CommandObjectParsed(
1852*c5011aedSJim Ingham             interpreter, "command container add",
1853*c5011aedSJim Ingham             "Add a container command to lldb.  Adding to built-"
1854*c5011aedSJim Ingham             "in container commands is not allowed.",
1855*c5011aedSJim Ingham             "command container add [[path1]...] container-name") {
1856*c5011aedSJim Ingham     CommandArgumentEntry arg1;
1857*c5011aedSJim Ingham     CommandArgumentData cmd_arg;
1858*c5011aedSJim Ingham 
1859*c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
1860*c5011aedSJim Ingham     // you want to add.
1861*c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1862*c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
1863*c5011aedSJim Ingham 
1864*c5011aedSJim Ingham     // There is only one variant this argument could be; put it into the
1865*c5011aedSJim Ingham     // argument entry.
1866*c5011aedSJim Ingham     arg1.push_back(cmd_arg);
1867*c5011aedSJim Ingham 
1868*c5011aedSJim Ingham     // Push the data for the first argument into the m_arguments vector.
1869*c5011aedSJim Ingham     m_arguments.push_back(arg1);
1870*c5011aedSJim Ingham   }
1871*c5011aedSJim Ingham 
1872*c5011aedSJim Ingham   ~CommandObjectCommandsContainerAdd() override = default;
1873*c5011aedSJim Ingham 
1874*c5011aedSJim Ingham   Options *GetOptions() override { return &m_options; }
1875*c5011aedSJim Ingham 
1876*c5011aedSJim Ingham   void
1877*c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
1878*c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
1879*c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1880*c5011aedSJim Ingham                                                       opt_element_vector);
1881*c5011aedSJim Ingham   }
1882*c5011aedSJim Ingham 
1883*c5011aedSJim Ingham protected:
1884*c5011aedSJim Ingham   class CommandOptions : public Options {
1885*c5011aedSJim Ingham   public:
1886*c5011aedSJim Ingham     CommandOptions() : Options(), m_short_help(), m_long_help() {}
1887*c5011aedSJim Ingham 
1888*c5011aedSJim Ingham     ~CommandOptions() override = default;
1889*c5011aedSJim Ingham 
1890*c5011aedSJim Ingham     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1891*c5011aedSJim Ingham                           ExecutionContext *execution_context) override {
1892*c5011aedSJim Ingham       Status error;
1893*c5011aedSJim Ingham       const int short_option = m_getopt_table[option_idx].val;
1894*c5011aedSJim Ingham 
1895*c5011aedSJim Ingham       switch (short_option) {
1896*c5011aedSJim Ingham       case 'h':
1897*c5011aedSJim Ingham         if (!option_arg.empty())
1898*c5011aedSJim Ingham           m_short_help = std::string(option_arg);
1899*c5011aedSJim Ingham         break;
1900*c5011aedSJim Ingham       case 'o':
1901*c5011aedSJim Ingham         m_overwrite = true;
1902*c5011aedSJim Ingham         break;
1903*c5011aedSJim Ingham       case 'H':
1904*c5011aedSJim Ingham         if (!option_arg.empty())
1905*c5011aedSJim Ingham           m_long_help = std::string(option_arg);
1906*c5011aedSJim Ingham         break;
1907*c5011aedSJim Ingham       default:
1908*c5011aedSJim Ingham         llvm_unreachable("Unimplemented option");
1909*c5011aedSJim Ingham       }
1910*c5011aedSJim Ingham 
1911*c5011aedSJim Ingham       return error;
1912*c5011aedSJim Ingham     }
1913*c5011aedSJim Ingham 
1914*c5011aedSJim Ingham     void OptionParsingStarting(ExecutionContext *execution_context) override {
1915*c5011aedSJim Ingham       m_short_help.clear();
1916*c5011aedSJim Ingham       m_long_help.clear();
1917*c5011aedSJim Ingham       m_overwrite = false;
1918*c5011aedSJim Ingham     }
1919*c5011aedSJim Ingham 
1920*c5011aedSJim Ingham     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1921*c5011aedSJim Ingham       return llvm::makeArrayRef(g_container_add_options);
1922*c5011aedSJim Ingham     }
1923*c5011aedSJim Ingham 
1924*c5011aedSJim Ingham     // Instance variables to hold the values for command options.
1925*c5011aedSJim Ingham 
1926*c5011aedSJim Ingham     std::string m_short_help;
1927*c5011aedSJim Ingham     std::string m_long_help;
1928*c5011aedSJim Ingham     bool m_overwrite = false;
1929*c5011aedSJim Ingham   };
1930*c5011aedSJim Ingham   bool DoExecute(Args &command, CommandReturnObject &result) override {
1931*c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
1932*c5011aedSJim Ingham 
1933*c5011aedSJim Ingham     if (num_args == 0) {
1934*c5011aedSJim Ingham       result.AppendError("no command was specified");
1935*c5011aedSJim Ingham       return false;
1936*c5011aedSJim Ingham     }
1937*c5011aedSJim Ingham 
1938*c5011aedSJim Ingham     if (num_args == 1) {
1939*c5011aedSJim Ingham       // We're adding this as a root command, so use the interpreter.
1940*c5011aedSJim Ingham       const char *cmd_name = command.GetArgumentAtIndex(0);
1941*c5011aedSJim Ingham       auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
1942*c5011aedSJim Ingham           GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
1943*c5011aedSJim Ingham           m_options.m_long_help.c_str()));
1944*c5011aedSJim Ingham       cmd_sp->GetAsMultiwordCommand()->SetRemovable(true);
1945*c5011aedSJim Ingham       Status add_error = GetCommandInterpreter().AddUserCommand(
1946*c5011aedSJim Ingham           cmd_name, cmd_sp, m_options.m_overwrite);
1947*c5011aedSJim Ingham       if (add_error.Fail()) {
1948*c5011aedSJim Ingham         result.AppendErrorWithFormat("error adding command: %s",
1949*c5011aedSJim Ingham                                      add_error.AsCString());
1950*c5011aedSJim Ingham         return false;
1951*c5011aedSJim Ingham       }
1952*c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1953*c5011aedSJim Ingham       return true;
1954*c5011aedSJim Ingham     }
1955*c5011aedSJim Ingham 
1956*c5011aedSJim Ingham     // We're adding this to a subcommand, first find the subcommand:
1957*c5011aedSJim Ingham     Status path_error;
1958*c5011aedSJim Ingham     CommandObjectMultiword *add_to_me =
1959*c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
1960*c5011aedSJim Ingham                                                            path_error);
1961*c5011aedSJim Ingham 
1962*c5011aedSJim Ingham     if (!add_to_me) {
1963*c5011aedSJim Ingham       result.AppendErrorWithFormat("error adding command: %s",
1964*c5011aedSJim Ingham                                    path_error.AsCString());
1965*c5011aedSJim Ingham       return false;
1966*c5011aedSJim Ingham     }
1967*c5011aedSJim Ingham 
1968*c5011aedSJim Ingham     const char *cmd_name = command.GetArgumentAtIndex(num_args - 1);
1969*c5011aedSJim Ingham     auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
1970*c5011aedSJim Ingham         GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
1971*c5011aedSJim Ingham         m_options.m_long_help.c_str()));
1972*c5011aedSJim Ingham     llvm::Error llvm_error =
1973*c5011aedSJim Ingham         add_to_me->LoadUserSubcommand(cmd_name, cmd_sp, m_options.m_overwrite);
1974*c5011aedSJim Ingham     if (llvm_error) {
1975*c5011aedSJim Ingham       result.AppendErrorWithFormat("error adding subcommand: %s",
1976*c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
1977*c5011aedSJim Ingham       return false;
1978*c5011aedSJim Ingham     }
1979*c5011aedSJim Ingham 
1980*c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1981*c5011aedSJim Ingham     return true;
1982*c5011aedSJim Ingham   }
1983*c5011aedSJim Ingham 
1984*c5011aedSJim Ingham private:
1985*c5011aedSJim Ingham   CommandOptions m_options;
1986*c5011aedSJim Ingham };
1987*c5011aedSJim Ingham 
1988*c5011aedSJim Ingham #define LLDB_OPTIONS_multiword_delete
1989*c5011aedSJim Ingham #include "CommandOptions.inc"
1990*c5011aedSJim Ingham class CommandObjectCommandsContainerDelete : public CommandObjectParsed {
1991*c5011aedSJim Ingham public:
1992*c5011aedSJim Ingham   CommandObjectCommandsContainerDelete(CommandInterpreter &interpreter)
1993*c5011aedSJim Ingham       : CommandObjectParsed(
1994*c5011aedSJim Ingham             interpreter, "command container delete",
1995*c5011aedSJim Ingham             "Delete a container command previously added to "
1996*c5011aedSJim Ingham             "lldb.",
1997*c5011aedSJim Ingham             "command container delete [[path1] ...] container-cmd") {
1998*c5011aedSJim Ingham     CommandArgumentEntry arg1;
1999*c5011aedSJim Ingham     CommandArgumentData cmd_arg;
2000*c5011aedSJim Ingham 
2001*c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
2002*c5011aedSJim Ingham     // you want to add.
2003*c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
2004*c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
2005*c5011aedSJim Ingham 
2006*c5011aedSJim Ingham     // There is only one variant this argument could be; put it into the
2007*c5011aedSJim Ingham     // argument entry.
2008*c5011aedSJim Ingham     arg1.push_back(cmd_arg);
2009*c5011aedSJim Ingham 
2010*c5011aedSJim Ingham     // Push the data for the first argument into the m_arguments vector.
2011*c5011aedSJim Ingham     m_arguments.push_back(arg1);
2012*c5011aedSJim Ingham   }
2013*c5011aedSJim Ingham 
2014*c5011aedSJim Ingham   ~CommandObjectCommandsContainerDelete() override = default;
2015*c5011aedSJim Ingham 
2016*c5011aedSJim Ingham   void
2017*c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
2018*c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
2019*c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
2020*c5011aedSJim Ingham                                                       opt_element_vector);
2021*c5011aedSJim Ingham   }
2022*c5011aedSJim Ingham 
2023*c5011aedSJim Ingham protected:
2024*c5011aedSJim Ingham   bool DoExecute(Args &command, CommandReturnObject &result) override {
2025*c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
2026*c5011aedSJim Ingham 
2027*c5011aedSJim Ingham     if (num_args == 0) {
2028*c5011aedSJim Ingham       result.AppendError("No command was specified.");
2029*c5011aedSJim Ingham       return false;
2030*c5011aedSJim Ingham     }
2031*c5011aedSJim Ingham 
2032*c5011aedSJim Ingham     if (num_args == 1) {
2033*c5011aedSJim Ingham       // We're removing a root command, so we need to delete it from the
2034*c5011aedSJim Ingham       // interpreter.
2035*c5011aedSJim Ingham       const char *cmd_name = command.GetArgumentAtIndex(0);
2036*c5011aedSJim Ingham       // Let's do a little more work here so we can do better error reporting.
2037*c5011aedSJim Ingham       CommandInterpreter &interp = GetCommandInterpreter();
2038*c5011aedSJim Ingham       CommandObjectSP cmd_sp = interp.GetCommandSPExact(cmd_name);
2039*c5011aedSJim Ingham       if (!cmd_sp) {
2040*c5011aedSJim Ingham         result.AppendErrorWithFormat("container command %s doesn't exist.",
2041*c5011aedSJim Ingham                                      cmd_name);
2042*c5011aedSJim Ingham         return false;
2043*c5011aedSJim Ingham       }
2044*c5011aedSJim Ingham       if (!cmd_sp->IsUserCommand()) {
2045*c5011aedSJim Ingham         result.AppendErrorWithFormat(
2046*c5011aedSJim Ingham             "container command %s is not a user command", cmd_name);
2047*c5011aedSJim Ingham         return false;
2048*c5011aedSJim Ingham       }
2049*c5011aedSJim Ingham       if (!cmd_sp->GetAsMultiwordCommand()) {
2050*c5011aedSJim Ingham         result.AppendErrorWithFormat("command %s is not a container command",
2051*c5011aedSJim Ingham                                      cmd_name);
2052*c5011aedSJim Ingham         return false;
2053*c5011aedSJim Ingham       }
2054*c5011aedSJim Ingham 
2055*c5011aedSJim Ingham       bool did_remove = GetCommandInterpreter().RemoveUserMultiword(cmd_name);
2056*c5011aedSJim Ingham       if (!did_remove) {
2057*c5011aedSJim Ingham         result.AppendErrorWithFormat("error removing command %s.", cmd_name);
2058*c5011aedSJim Ingham         return false;
2059*c5011aedSJim Ingham       }
2060*c5011aedSJim Ingham 
2061*c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
2062*c5011aedSJim Ingham       return true;
2063*c5011aedSJim Ingham     }
2064*c5011aedSJim Ingham 
2065*c5011aedSJim Ingham     // We're removing a subcommand, first find the subcommand's owner:
2066*c5011aedSJim Ingham     Status path_error;
2067*c5011aedSJim Ingham     CommandObjectMultiword *container =
2068*c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
2069*c5011aedSJim Ingham                                                            path_error);
2070*c5011aedSJim Ingham 
2071*c5011aedSJim Ingham     if (!container) {
2072*c5011aedSJim Ingham       result.AppendErrorWithFormat("error removing container command: %s",
2073*c5011aedSJim Ingham                                    path_error.AsCString());
2074*c5011aedSJim Ingham       return false;
2075*c5011aedSJim Ingham     }
2076*c5011aedSJim Ingham     const char *leaf = command.GetArgumentAtIndex(num_args - 1);
2077*c5011aedSJim Ingham     llvm::Error llvm_error =
2078*c5011aedSJim Ingham         container->RemoveUserSubcommand(leaf, /* multiword okay */ true);
2079*c5011aedSJim Ingham     if (llvm_error) {
2080*c5011aedSJim Ingham       result.AppendErrorWithFormat("error removing container command: %s",
2081*c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
2082*c5011aedSJim Ingham       return false;
2083*c5011aedSJim Ingham     }
2084*c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2085*c5011aedSJim Ingham     return true;
2086*c5011aedSJim Ingham   }
2087*c5011aedSJim Ingham };
2088*c5011aedSJim Ingham 
2089*c5011aedSJim Ingham class CommandObjectCommandContainer : public CommandObjectMultiword {
2090*c5011aedSJim Ingham public:
2091*c5011aedSJim Ingham   CommandObjectCommandContainer(CommandInterpreter &interpreter)
2092*c5011aedSJim Ingham       : CommandObjectMultiword(
2093*c5011aedSJim Ingham             interpreter, "command container",
2094*c5011aedSJim Ingham             "Commands for adding container commands to lldb.  "
2095*c5011aedSJim Ingham             "Container commands are containers for other commands.  You can"
2096*c5011aedSJim Ingham             "add nested container commands by specifying a command path, but "
2097*c5011aedSJim Ingham             "but you can't add commands into the built-in command hierarchy.",
2098*c5011aedSJim Ingham             "command container <subcommand> [<subcommand-options>]") {
2099*c5011aedSJim Ingham     LoadSubCommand("add", CommandObjectSP(new CommandObjectCommandsContainerAdd(
2100*c5011aedSJim Ingham                               interpreter)));
2101*c5011aedSJim Ingham     LoadSubCommand(
2102*c5011aedSJim Ingham         "delete",
2103*c5011aedSJim Ingham         CommandObjectSP(new CommandObjectCommandsContainerDelete(interpreter)));
2104*c5011aedSJim Ingham   }
2105*c5011aedSJim Ingham 
2106*c5011aedSJim Ingham   ~CommandObjectCommandContainer() override = default;
2107*c5011aedSJim Ingham };
2108*c5011aedSJim Ingham 
2109ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
2110ebc09c36SJim Ingham 
2111ebc09c36SJim Ingham // CommandObjectMultiwordCommands
2112ebc09c36SJim Ingham 
2113b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
2114b9c1b51eSKate Stone     CommandInterpreter &interpreter)
2115b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
2116b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
2117b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
2118b9c1b51eSKate Stone   LoadSubCommand("source",
2119b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
2120b9c1b51eSKate Stone   LoadSubCommand("alias",
2121b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
2122b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
2123b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
2124b9c1b51eSKate Stone   LoadSubCommand("delete",
2125b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
2126*c5011aedSJim Ingham   LoadSubCommand("container", CommandObjectSP(new CommandObjectCommandContainer(
2127*c5011aedSJim Ingham                                   interpreter)));
2128b9c1b51eSKate Stone   LoadSubCommand(
2129b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
2130b9c1b51eSKate Stone   LoadSubCommand(
2131b9c1b51eSKate Stone       "script",
2132b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
2133ebc09c36SJim Ingham }
2134ebc09c36SJim Ingham 
21356e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
2136