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>.",
41abb0ed44SKazu Hirata             nullptr) {
425a988416SJim Ingham     CommandArgumentEntry arg;
435a988416SJim Ingham     CommandArgumentData file_arg;
445a988416SJim Ingham 
455a988416SJim Ingham     // Define the first (and only) variant of this arg.
465a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
475a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
485a988416SJim Ingham 
49b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
50b9c1b51eSKate Stone     // argument entry.
515a988416SJim Ingham     arg.push_back(file_arg);
525a988416SJim Ingham 
535a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
545a988416SJim Ingham     m_arguments.push_back(arg);
555a988416SJim Ingham   }
565a988416SJim Ingham 
576e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
585a988416SJim Ingham 
59635f03feSJim Ingham   llvm::Optional<std::string> GetRepeatCommand(Args &current_command_args,
60b9c1b51eSKate Stone                                                uint32_t index) override {
61635f03feSJim Ingham     return std::string("");
625a988416SJim Ingham   }
635a988416SJim Ingham 
64ae34ed2cSRaphael Isemann   void
65ae34ed2cSRaphael Isemann   HandleArgumentCompletion(CompletionRequest &request,
662443bbd4SRaphael Isemann                            OptionElementVector &opt_element_vector) override {
67b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
68b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
69a2e76c0bSRaphael Isemann         request, nullptr);
705a988416SJim Ingham   }
715a988416SJim Ingham 
72b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
735a988416SJim Ingham 
745a988416SJim Ingham protected:
75b9c1b51eSKate Stone   class CommandOptions : public Options {
76e16c50a1SJim Ingham   public:
77b9c1b51eSKate Stone     CommandOptions()
78abb0ed44SKazu Hirata         : m_stop_on_error(true), m_silent_run(false), m_stop_on_continue(true),
79abb0ed44SKazu Hirata           m_cmd_relative_to_command_file(false) {}
80e16c50a1SJim Ingham 
816e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
82e16c50a1SJim Ingham 
8397206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
84b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
8597206d57SZachary Turner       Status error;
863bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
87e16c50a1SJim Ingham 
88b9c1b51eSKate Stone       switch (short_option) {
89e16c50a1SJim Ingham       case 'e':
90fe11483bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_arg);
91e16c50a1SJim Ingham         break;
92340b0309SGreg Clayton 
93e16c50a1SJim Ingham       case 'c':
94fe11483bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_arg);
95e16c50a1SJim Ingham         break;
96340b0309SGreg Clayton 
973bf3b966SJim Ingham       case 'C':
983bf3b966SJim Ingham         m_cmd_relative_to_command_file = true;
993bf3b966SJim Ingham         break;
1003bf3b966SJim Ingham 
10160986174SMichael Sartain       case 's':
102fe11483bSZachary Turner         error = m_silent_run.SetValueFromString(option_arg);
10360986174SMichael Sartain         break;
104340b0309SGreg Clayton 
105e16c50a1SJim Ingham       default:
10636162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
107e16c50a1SJim Ingham       }
108e16c50a1SJim Ingham 
109e16c50a1SJim Ingham       return error;
110e16c50a1SJim Ingham     }
111e16c50a1SJim Ingham 
112b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
113012d4fcaSEnrico Granata       m_stop_on_error.Clear();
114340b0309SGreg Clayton       m_silent_run.Clear();
115340b0309SGreg Clayton       m_stop_on_continue.Clear();
1163bf3b966SJim Ingham       m_cmd_relative_to_command_file.Clear();
117e16c50a1SJim Ingham     }
118e16c50a1SJim Ingham 
1191f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
12070602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
1211f0f5b5bSZachary Turner     }
122e16c50a1SJim Ingham 
123e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
124e16c50a1SJim Ingham 
125012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
126340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
127340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
1283bf3b966SJim Ingham     OptionValueBoolean m_cmd_relative_to_command_file;
129e16c50a1SJim Ingham   };
130e16c50a1SJim Ingham 
131b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1324574a890SZachary Turner     if (command.GetArgumentCount() != 1) {
1334574a890SZachary Turner       result.AppendErrorWithFormat(
1344574a890SZachary Turner           "'%s' takes exactly one executable filename argument.\n",
1354574a890SZachary Turner           GetCommandName().str().c_str());
1364574a890SZachary Turner       return false;
1374574a890SZachary Turner     }
138ebc09c36SJim Ingham 
1393bf3b966SJim Ingham     FileSpec source_dir = {};
1403bf3b966SJim Ingham     if (m_options.m_cmd_relative_to_command_file) {
1413bf3b966SJim Ingham       source_dir = GetDebugger().GetCommandInterpreter().GetCurrentSourceDir();
1423bf3b966SJim Ingham       if (!source_dir) {
1433bf3b966SJim Ingham         result.AppendError("command source -C can only be specified "
1443bf3b966SJim Ingham                            "from a command file");
1453bf3b966SJim Ingham         result.SetStatus(eReturnStatusFailed);
1463bf3b966SJim Ingham         return false;
1473bf3b966SJim Ingham       }
1483bf3b966SJim Ingham     }
1493bf3b966SJim Ingham 
1500d9a201eSRaphael Isemann     FileSpec cmd_file(command[0].ref());
1513bf3b966SJim Ingham     if (source_dir) {
1523bf3b966SJim Ingham       // Prepend the source_dir to the cmd_file path:
1533bf3b966SJim Ingham       if (!cmd_file.IsRelative()) {
1543bf3b966SJim Ingham         result.AppendError("command source -C can only be used "
1553bf3b966SJim Ingham                            "with a relative path.");
1563bf3b966SJim Ingham         result.SetStatus(eReturnStatusFailed);
1573bf3b966SJim Ingham         return false;
1583bf3b966SJim Ingham       }
1593bf3b966SJim Ingham       cmd_file.MakeAbsolute(source_dir);
1603bf3b966SJim Ingham     }
1613bf3b966SJim Ingham 
1628f3be7a3SJonas Devlieghere     FileSystem::Instance().Resolve(cmd_file);
163ebc09c36SJim Ingham 
16436de94cfSTatyana Krasnukha     CommandInterpreterRunOptions options;
165340b0309SGreg Clayton     // If any options were set, then use them
166340b0309SGreg Clayton     if (m_options.m_stop_on_error.OptionWasSet() ||
167340b0309SGreg Clayton         m_options.m_silent_run.OptionWasSet() ||
168b9c1b51eSKate Stone         m_options.m_stop_on_continue.OptionWasSet()) {
1691c19b74cSJonas Devlieghere       if (m_options.m_stop_on_continue.OptionWasSet())
1701c19b74cSJonas Devlieghere         options.SetStopOnContinue(
1711c19b74cSJonas Devlieghere             m_options.m_stop_on_continue.GetCurrentValue());
1721c19b74cSJonas Devlieghere 
1731c19b74cSJonas Devlieghere       if (m_options.m_stop_on_error.OptionWasSet())
17426c7bf93SJim Ingham         options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
175c678ed77SStefan Granitz 
176c678ed77SStefan Granitz       // Individual silent setting is override for global command echo settings.
177c678ed77SStefan Granitz       if (m_options.m_silent_run.GetCurrentValue()) {
178c678ed77SStefan Granitz         options.SetSilent(true);
179c678ed77SStefan Granitz       } else {
180c678ed77SStefan Granitz         options.SetPrintResults(true);
181c0b48ab6SJonas Devlieghere         options.SetPrintErrors(true);
182c678ed77SStefan Granitz         options.SetEchoCommands(m_interpreter.GetEchoCommands());
183c678ed77SStefan Granitz         options.SetEchoCommentCommands(m_interpreter.GetEchoCommentCommands());
184c678ed77SStefan Granitz       }
185122a4ebdSPavel Labath     }
18636de94cfSTatyana Krasnukha 
18736de94cfSTatyana Krasnukha     m_interpreter.HandleCommandsFromFile(cmd_file, options, result);
188ebc09c36SJim Ingham     return result.Succeeded();
189ebc09c36SJim Ingham   }
1906e3d8e7fSEugene Zelenko 
1915a988416SJim Ingham   CommandOptions m_options;
192ebc09c36SJim Ingham };
193ebc09c36SJim Ingham 
194ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
195ebc09c36SJim Ingham // CommandObjectCommandsAlias
196ebc09c36SJim Ingham 
19764becc11SRaphael Isemann #define LLDB_OPTIONS_alias
19864becc11SRaphael Isemann #include "CommandOptions.inc"
1991f0f5b5bSZachary Turner 
200b9c1b51eSKate Stone static const char *g_python_command_instructions =
201b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
202be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
20344d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
204be93a35aSEnrico Granata 
205b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
20645d0e238SEnrico Granata protected:
207b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
208ebc09c36SJim Ingham   public:
20924f9a2f5SShafik Yaghmour     CommandOptions() = default;
21045d0e238SEnrico Granata 
21145d0e238SEnrico Granata     ~CommandOptions() override = default;
21245d0e238SEnrico Granata 
2131f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
21470602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
2151f0f5b5bSZachary Turner     }
21645d0e238SEnrico Granata 
21797206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
218b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
21997206d57SZachary Turner       Status error;
22045d0e238SEnrico Granata 
2211f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
2228cef4b0bSZachary Turner       std::string option_str(option_value);
22345d0e238SEnrico Granata 
224b9c1b51eSKate Stone       switch (short_option) {
22545d0e238SEnrico Granata       case 'h':
2268cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
22745d0e238SEnrico Granata         m_help.SetOptionWasSet();
22845d0e238SEnrico Granata         break;
22945d0e238SEnrico Granata 
23045d0e238SEnrico Granata       case 'H':
2318cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
23245d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
23345d0e238SEnrico Granata         break;
23445d0e238SEnrico Granata 
23545d0e238SEnrico Granata       default:
23636162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
23745d0e238SEnrico Granata       }
23845d0e238SEnrico Granata 
23945d0e238SEnrico Granata       return error;
24045d0e238SEnrico Granata     }
24145d0e238SEnrico Granata 
242b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
24345d0e238SEnrico Granata       m_help.Clear();
24445d0e238SEnrico Granata       m_long_help.Clear();
24545d0e238SEnrico Granata     }
24645d0e238SEnrico Granata 
24745d0e238SEnrico Granata     OptionValueString m_help;
24845d0e238SEnrico Granata     OptionValueString m_long_help;
24945d0e238SEnrico Granata   };
25045d0e238SEnrico Granata 
25145d0e238SEnrico Granata   OptionGroupOptions m_option_group;
25245d0e238SEnrico Granata   CommandOptions m_command_options;
25345d0e238SEnrico Granata 
25445d0e238SEnrico Granata public:
255b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
25645d0e238SEnrico Granata 
2577428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
258b9c1b51eSKate Stone       : CommandObjectRaw(
259b9c1b51eSKate Stone             interpreter, "command alias",
260abb0ed44SKazu Hirata             "Define a custom command in terms of an existing command.") {
26145d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
26245d0e238SEnrico Granata     m_option_group.Finalize();
26345d0e238SEnrico Granata 
264ebc09c36SJim Ingham     SetHelpLong(
265ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
266ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
267b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
268b9c1b51eSKate Stone         R"(
269ea671fbdSKate Stone 
270ea671fbdSKate Stone (lldb) command alias sc script
271ea671fbdSKate Stone 
272ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
273ea671fbdSKate Stone 
274ea671fbdSKate Stone (lldb) command alias bp breakpoint
275ea671fbdSKate Stone 
276b9c1b51eSKate Stone )"
277b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
278ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
279b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
280b9c1b51eSKate Stone         R"(
281ea671fbdSKate Stone 
282ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
283ea671fbdSKate Stone 
284ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
285ea671fbdSKate Stone 
286b9c1b51eSKate Stone )"
287b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
288ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
289ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
290b9c1b51eSKate Stone shows how to create aliases with options:"
291b9c1b51eSKate Stone         R"(
292ea671fbdSKate Stone 
293ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
294ea671fbdSKate Stone 
295b9c1b51eSKate Stone )"
296b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
297ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
298ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
299ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
300ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
301ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
302ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
303ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
304ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
305ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
306b9c1b51eSKate Stone launch' example below)."
307b9c1b51eSKate Stone         R"(
308ea671fbdSKate Stone 
309b9c1b51eSKate Stone )"
310b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
311ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
312b9c1b51eSKate Stone \".cpp\":"
313b9c1b51eSKate Stone         R"(
314ea671fbdSKate Stone 
315ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
316ea671fbdSKate Stone 
317b9c1b51eSKate Stone )"
318b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
319ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
320ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
321b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
322b9c1b51eSKate Stone         R"(
323ea671fbdSKate Stone 
324ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
325ea671fbdSKate Stone (lldb) bfl my-file.c 137
326ea671fbdSKate Stone 
327ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
328ea671fbdSKate Stone 
329ea671fbdSKate Stone Another example:
330ea671fbdSKate Stone 
331ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
332ea671fbdSKate Stone (lldb) pltty /dev/tty0
333ea671fbdSKate Stone 
334ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
335ea671fbdSKate Stone 
336b9c1b51eSKate Stone )"
337b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
338ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
339b9c1b51eSKate Stone rather than using a positional placeholder:"
340b9c1b51eSKate Stone         R"(
341ea671fbdSKate Stone 
342ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
343ea671fbdSKate Stone 
344b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
345ebc09c36SJim Ingham 
346405fe67fSCaroline Tice     CommandArgumentEntry arg1;
347405fe67fSCaroline Tice     CommandArgumentEntry arg2;
348405fe67fSCaroline Tice     CommandArgumentEntry arg3;
349405fe67fSCaroline Tice     CommandArgumentData alias_arg;
350405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
351405fe67fSCaroline Tice     CommandArgumentData options_arg;
352405fe67fSCaroline Tice 
353405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
354405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
355405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
356405fe67fSCaroline Tice 
357b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
358b9c1b51eSKate Stone     // argument entry.
359405fe67fSCaroline Tice     arg1.push_back(alias_arg);
360405fe67fSCaroline Tice 
361405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
362405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
363405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
364405fe67fSCaroline Tice 
365b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
366b9c1b51eSKate Stone     // argument entry.
367405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
368405fe67fSCaroline Tice 
369405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
370405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
371405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
372405fe67fSCaroline Tice 
373b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
374b9c1b51eSKate Stone     // argument entry.
375405fe67fSCaroline Tice     arg3.push_back(options_arg);
376405fe67fSCaroline Tice 
377405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
378405fe67fSCaroline Tice     m_arguments.push_back(arg1);
379405fe67fSCaroline Tice     m_arguments.push_back(arg2);
380405fe67fSCaroline Tice     m_arguments.push_back(arg3);
381ebc09c36SJim Ingham   }
382ebc09c36SJim Ingham 
3836e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
384ebc09c36SJim Ingham 
3855a988416SJim Ingham protected:
3864d51a902SRaphael Isemann   bool DoExecute(llvm::StringRef raw_command_line,
387b9c1b51eSKate Stone                  CommandReturnObject &result) override {
3884d51a902SRaphael Isemann     if (raw_command_line.empty()) {
389d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
39045d0e238SEnrico Granata       return false;
39145d0e238SEnrico Granata     }
39245d0e238SEnrico Granata 
393e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
394e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
39545d0e238SEnrico Granata 
3963a0e1270SRaphael Isemann     OptionsWithRaw args_with_suffix(raw_command_line);
39745d0e238SEnrico Granata 
3983a0e1270SRaphael Isemann     if (args_with_suffix.HasArgs())
3993a0e1270SRaphael Isemann       if (!ParseOptionsAndNotify(args_with_suffix.GetArgs(), result,
4003a0e1270SRaphael Isemann                                  m_option_group, exe_ctx))
40145d0e238SEnrico Granata         return false;
40245d0e238SEnrico Granata 
403daed98e5SShivam Mittal     llvm::StringRef raw_command_string = args_with_suffix.GetRawPart();
404a01bccdbSZachary Turner     Args args(raw_command_string);
405844d2303SCaroline Tice 
40611eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
407d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
408844d2303SCaroline Tice       return false;
409844d2303SCaroline Tice     }
410844d2303SCaroline Tice 
411844d2303SCaroline Tice     // Get the alias command.
412844d2303SCaroline Tice 
4130d9a201eSRaphael Isemann     auto alias_command = args[0].ref();
4144574a890SZachary Turner     if (alias_command.startswith("-")) {
415d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
416b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
417b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
418b9c1b51eSKate Stone                              "a -- at the end of the options");
419d72e412fSEnrico Granata       }
420d72e412fSEnrico Granata       return false;
421d72e412fSEnrico Granata     }
422844d2303SCaroline Tice 
423b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
42405097246SAdrian Prantl     // which gets passed to 'Execute', which does the stripping itself.
425844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
426b9c1b51eSKate Stone     if (pos == 0) {
427844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
428844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
429844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
430844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
431b9c1b51eSKate Stone     } else {
432844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
433844d2303SCaroline Tice       return false;
434844d2303SCaroline Tice     }
435844d2303SCaroline Tice 
436844d2303SCaroline Tice     // Verify that the command is alias-able.
437771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
438b9c1b51eSKate Stone       result.AppendErrorWithFormat(
439b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
4404574a890SZachary Turner           args[0].c_str());
441844d2303SCaroline Tice       return false;
442844d2303SCaroline Tice     }
443844d2303SCaroline Tice 
444c5011aedSJim Ingham     if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
445c5011aedSJim Ingham       result.AppendErrorWithFormat(
446c5011aedSJim Ingham           "'%s' is a user container command and cannot be overwritten.\n"
447c5011aedSJim Ingham           "Delete it first with 'command container delete'\n",
448c5011aedSJim Ingham           args[0].c_str());
449c5011aedSJim Ingham       return false;
450c5011aedSJim Ingham     }
451c5011aedSJim Ingham 
452b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
453a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
454a01bccdbSZachary Turner     // name of the command object stripped off the front.
455a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
456b9c1b51eSKate Stone     CommandObject *cmd_obj =
457b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
458844d2303SCaroline Tice 
459b9c1b51eSKate Stone     if (!cmd_obj) {
460b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
461b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
462b9c1b51eSKate Stone                                    "  No alias created.",
463a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
464844d2303SCaroline Tice       return false;
465b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
466b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
46705097246SAdrian Prantl       // been updated to this point. Therefore can we pass it to the version of
46805097246SAdrian Prantl       // Execute that does not need/expect raw input in the alias.
4695a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
470b9c1b51eSKate Stone     } else {
471b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
472b9c1b51eSKate Stone                                       *cmd_obj, result);
4735a988416SJim Ingham     }
4745a988416SJim Ingham     return result.Succeeded();
4755a988416SJim Ingham   }
4765a988416SJim Ingham 
477a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
478a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
479b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
480b9c1b51eSKate Stone                                 CommandReturnObject &result) {
481844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
482844d2303SCaroline Tice 
483b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
484b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
485844d2303SCaroline Tice 
486b9515041SDave Lee     const bool include_aliases = true;
487b9515041SDave Lee     if (CommandObjectSP cmd_obj_sp = m_interpreter.GetCommandSPExact(
488b9515041SDave Lee             cmd_obj.GetCommandName(), include_aliases)) {
489a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
490a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
491b9c1b51eSKate Stone         result.AppendWarningWithFormat(
492b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
493a01bccdbSZachary Turner             alias_command.str().c_str());
494844d2303SCaroline Tice       }
495b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
496a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
49745d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
49845d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
49945d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
50045d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
501844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
502b9c1b51eSKate Stone       } else {
503472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
504472362e6SCaroline Tice       }
505212130acSEnrico Granata 
506b9c1b51eSKate Stone     } else {
507212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
508212130acSEnrico Granata     }
509212130acSEnrico Granata 
510844d2303SCaroline Tice     return result.Succeeded();
511844d2303SCaroline Tice   }
512ebc09c36SJim Ingham 
513b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
514867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
515ebc09c36SJim Ingham 
516b9c1b51eSKate Stone     if (argc < 2) {
517d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
518ebc09c36SJim Ingham       return false;
519ebc09c36SJim Ingham     }
520ebc09c36SJim Ingham 
5214574a890SZachary Turner     // Save these in std::strings since we're going to shift them off.
522adcd0268SBenjamin Kramer     const std::string alias_command(std::string(args[0].ref()));
523adcd0268SBenjamin Kramer     const std::string actual_command(std::string(args[1].ref()));
524ebc09c36SJim Ingham 
525ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
526ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
527ebc09c36SJim Ingham 
528b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
529b9c1b51eSKate Stone     // object.
530ebc09c36SJim Ingham 
531771ef6d4SMalcolm Parsons     if (m_interpreter.CommandExists(alias_command)) {
532b9c1b51eSKate Stone       result.AppendErrorWithFormat(
533b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
534ebc09c36SJim Ingham           alias_command.c_str());
5354574a890SZachary Turner       return false;
5364574a890SZachary Turner     }
5374574a890SZachary Turner 
538c5011aedSJim Ingham     if (m_interpreter.UserMultiwordCommandExists(alias_command)) {
539c5011aedSJim Ingham       result.AppendErrorWithFormat(
540c5011aedSJim Ingham           "'%s' is user container command and cannot be overwritten.\n"
541c5011aedSJim Ingham           "Delete it first with 'command container delete'",
542c5011aedSJim Ingham           alias_command.c_str());
543c5011aedSJim Ingham       return false;
544c5011aedSJim Ingham     }
545c5011aedSJim Ingham 
546b9c1b51eSKate Stone     CommandObjectSP command_obj_sp(
547a449698cSZachary Turner         m_interpreter.GetCommandSPExact(actual_command, true));
548ebc09c36SJim Ingham     CommandObjectSP subcommand_obj_sp;
549ebc09c36SJim Ingham     bool use_subcommand = false;
5504574a890SZachary Turner     if (!command_obj_sp) {
5514574a890SZachary Turner       result.AppendErrorWithFormat("'%s' is not an existing command.\n",
5524574a890SZachary Turner                                    actual_command.c_str());
5534574a890SZachary Turner       return false;
5544574a890SZachary Turner     }
555ebc09c36SJim Ingham     CommandObject *cmd_obj = command_obj_sp.get();
5566e3d8e7fSEugene Zelenko     CommandObject *sub_cmd_obj = nullptr;
557b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
558b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
559ebc09c36SJim Ingham 
56011eb9c64SZachary Turner     while (cmd_obj->IsMultiwordObject() && !args.empty()) {
5610d9a201eSRaphael Isemann       auto sub_command = args[0].ref();
56211eb9c64SZachary Turner       assert(!sub_command.empty());
5634574a890SZachary Turner       subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command);
5644574a890SZachary Turner       if (!subcommand_obj_sp) {
565b9c1b51eSKate Stone         result.AppendErrorWithFormat(
566b9c1b51eSKate Stone             "'%s' is not a valid sub-command of '%s'.  "
567f415eeb4SCaroline Tice             "Unable to create alias.\n",
5684574a890SZachary Turner             args[0].c_str(), actual_command.c_str());
569ebc09c36SJim Ingham         return false;
570ebc09c36SJim Ingham       }
5714574a890SZachary Turner 
5724574a890SZachary Turner       sub_cmd_obj = subcommand_obj_sp.get();
5734574a890SZachary Turner       use_subcommand = true;
5744574a890SZachary Turner       args.Shift(); // Shift the sub_command word off the argument vector.
5754574a890SZachary Turner       cmd_obj = sub_cmd_obj;
576ebc09c36SJim Ingham     }
577ebc09c36SJim Ingham 
578ebc09c36SJim Ingham     // Verify & handle any options/arguments passed to the alias command
579ebc09c36SJim Ingham 
580212130acSEnrico Granata     std::string args_string;
581212130acSEnrico Granata 
58211eb9c64SZachary Turner     if (!args.empty()) {
583b9c1b51eSKate Stone       CommandObjectSP tmp_sp =
584a9448872SJonas Devlieghere           m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName());
585ebc09c36SJim Ingham       if (use_subcommand)
586a9448872SJonas Devlieghere         tmp_sp = m_interpreter.GetCommandSPExact(sub_cmd_obj->GetCommandName());
587ca90c47eSCaroline Tice 
588ca90c47eSCaroline Tice       args.GetCommandString(args_string);
589867b185dSCaroline Tice     }
590ebc09c36SJim Ingham 
591771ef6d4SMalcolm Parsons     if (m_interpreter.AliasExists(alias_command) ||
592771ef6d4SMalcolm Parsons         m_interpreter.UserCommandExists(alias_command)) {
593b9c1b51eSKate Stone       result.AppendWarningWithFormat(
5944574a890SZachary Turner           "Overwriting existing definition for '%s'.\n", alias_command.c_str());
595ebc09c36SJim Ingham     }
596ebc09c36SJim Ingham 
597b9c1b51eSKate Stone     if (CommandAlias *alias = m_interpreter.AddAlias(
5984574a890SZachary Turner             alias_command, use_subcommand ? subcommand_obj_sp : command_obj_sp,
599771ef6d4SMalcolm Parsons             args_string)) {
60045d0e238SEnrico Granata       if (m_command_options.m_help.OptionWasSet())
60145d0e238SEnrico Granata         alias->SetHelp(m_command_options.m_help.GetCurrentValue());
60245d0e238SEnrico Granata       if (m_command_options.m_long_help.OptionWasSet())
60345d0e238SEnrico Granata         alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
604ebc09c36SJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
605b9c1b51eSKate Stone     } else {
606212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
607212130acSEnrico Granata       return false;
608212130acSEnrico Granata     }
609ebc09c36SJim Ingham 
610ebc09c36SJim Ingham     return result.Succeeded();
611ebc09c36SJim Ingham   }
612ebc09c36SJim Ingham };
613ebc09c36SJim Ingham 
614ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
615ebc09c36SJim Ingham // CommandObjectCommandsUnalias
616ebc09c36SJim Ingham 
617b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
618ebc09c36SJim Ingham public:
6197428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
620b9c1b51eSKate Stone       : CommandObjectParsed(
621b9c1b51eSKate Stone             interpreter, "command unalias",
622b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
623b9c1b51eSKate Stone             nullptr) {
624405fe67fSCaroline Tice     CommandArgumentEntry arg;
625405fe67fSCaroline Tice     CommandArgumentData alias_arg;
626405fe67fSCaroline Tice 
627405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
628405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
629405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
630405fe67fSCaroline Tice 
631b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
632b9c1b51eSKate Stone     // argument entry.
633405fe67fSCaroline Tice     arg.push_back(alias_arg);
634405fe67fSCaroline Tice 
635405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
636405fe67fSCaroline Tice     m_arguments.push_back(arg);
637ebc09c36SJim Ingham   }
638ebc09c36SJim Ingham 
6396e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
640ebc09c36SJim Ingham 
64131fd64acSGongyu Deng   void
64231fd64acSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
64331fd64acSGongyu Deng                            OptionElementVector &opt_element_vector) override {
64431fd64acSGongyu Deng     if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
64531fd64acSGongyu Deng       return;
64631fd64acSGongyu Deng 
64731fd64acSGongyu Deng     for (const auto &ent : m_interpreter.GetAliases()) {
64831fd64acSGongyu Deng       request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
64931fd64acSGongyu Deng     }
65031fd64acSGongyu Deng   }
65131fd64acSGongyu Deng 
6525a988416SJim Ingham protected:
653b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
654ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
655ebc09c36SJim Ingham     CommandObject *cmd_obj;
656ebc09c36SJim Ingham 
65711eb9c64SZachary Turner     if (args.empty()) {
65811eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
65911eb9c64SZachary Turner       return false;
66011eb9c64SZachary Turner     }
66111eb9c64SZachary Turner 
6620d9a201eSRaphael Isemann     auto command_name = args[0].ref();
663a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
6644574a890SZachary Turner     if (!cmd_obj) {
6654574a890SZachary Turner       result.AppendErrorWithFormat(
6664574a890SZachary Turner           "'%s' is not a known command.\nTry 'help' to see a "
6674574a890SZachary Turner           "current list of commands.\n",
668867e7d17SZachary Turner           args[0].c_str());
6694574a890SZachary Turner       return false;
6704574a890SZachary Turner     }
6714574a890SZachary Turner 
672b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
673b9c1b51eSKate Stone       if (cmd_obj->IsRemovable()) {
674b9c1b51eSKate Stone         result.AppendErrorWithFormat(
675b9c1b51eSKate Stone             "'%s' is not an alias, it is a debugger command which can be "
676b9c1b51eSKate Stone             "removed using the 'command delete' command.\n",
677867e7d17SZachary Turner             args[0].c_str());
678b9c1b51eSKate Stone       } else {
679b9c1b51eSKate Stone         result.AppendErrorWithFormat(
680b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
681867e7d17SZachary Turner             args[0].c_str());
682b547278cSGreg Clayton       }
6834574a890SZachary Turner       return false;
6844574a890SZachary Turner     }
6854574a890SZachary Turner 
686b9c1b51eSKate Stone     if (!m_interpreter.RemoveAlias(command_name)) {
687a7015092SGreg Clayton       if (m_interpreter.AliasExists(command_name))
688b9c1b51eSKate Stone         result.AppendErrorWithFormat(
689867e7d17SZachary Turner             "Error occurred while attempting to unalias '%s'.\n",
690867e7d17SZachary Turner             args[0].c_str());
691ebc09c36SJim Ingham       else
692b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
693867e7d17SZachary Turner                                      args[0].c_str());
6944574a890SZachary Turner       return false;
695ebc09c36SJim Ingham     }
696ebc09c36SJim Ingham 
6974574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
698ebc09c36SJim Ingham     return result.Succeeded();
699ebc09c36SJim Ingham   }
700ebc09c36SJim Ingham };
701ebc09c36SJim Ingham 
702b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
703b547278cSGreg Clayton // CommandObjectCommandsDelete
704b547278cSGreg Clayton 
705b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
706b547278cSGreg Clayton public:
7077428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
708b9c1b51eSKate Stone       : CommandObjectParsed(
709b9c1b51eSKate Stone             interpreter, "command delete",
710b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
711b9c1b51eSKate Stone             nullptr) {
712b547278cSGreg Clayton     CommandArgumentEntry arg;
713b547278cSGreg Clayton     CommandArgumentData alias_arg;
714b547278cSGreg Clayton 
715b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
716b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
717b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
718b547278cSGreg Clayton 
719b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
720b9c1b51eSKate Stone     // argument entry.
721b547278cSGreg Clayton     arg.push_back(alias_arg);
722b547278cSGreg Clayton 
723b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
724b547278cSGreg Clayton     m_arguments.push_back(arg);
725b547278cSGreg Clayton   }
726b547278cSGreg Clayton 
7276e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
728b547278cSGreg Clayton 
72931fd64acSGongyu Deng   void
73031fd64acSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
73131fd64acSGongyu Deng                            OptionElementVector &opt_element_vector) override {
73231fd64acSGongyu Deng     if (!m_interpreter.HasCommands() || request.GetCursorIndex() != 0)
73331fd64acSGongyu Deng       return;
73431fd64acSGongyu Deng 
73531fd64acSGongyu Deng     for (const auto &ent : m_interpreter.GetCommands()) {
73631fd64acSGongyu Deng       if (ent.second->IsRemovable())
73731fd64acSGongyu Deng         request.TryCompleteCurrentArg(ent.first, ent.second->GetHelp());
73831fd64acSGongyu Deng     }
73931fd64acSGongyu Deng   }
74031fd64acSGongyu Deng 
741b547278cSGreg Clayton protected:
742b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
743b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
744b547278cSGreg Clayton 
74511eb9c64SZachary Turner     if (args.empty()) {
74611eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
74711eb9c64SZachary Turner                                    "defined regular expression command names",
748a449698cSZachary Turner                                    GetCommandName().str().c_str());
749d77ea5b2SRaphael Isemann       return false;
75011eb9c64SZachary Turner     }
75111eb9c64SZachary Turner 
7520d9a201eSRaphael Isemann     auto command_name = args[0].ref();
7534574a890SZachary Turner     if (!m_interpreter.CommandExists(command_name)) {
75446d4aa21SEnrico Granata       StreamString error_msg_stream;
755d5b44036SJonas Devlieghere       const bool generate_upropos = true;
75646d4aa21SEnrico Granata       const bool generate_type_lookup = false;
757b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
7584574a890SZachary Turner           &error_msg_stream, command_name, llvm::StringRef(), llvm::StringRef(),
759d5b44036SJonas Devlieghere           generate_upropos, generate_type_lookup);
760c156427dSZachary Turner       result.AppendError(error_msg_stream.GetString());
7614574a890SZachary Turner       return false;
762b547278cSGreg Clayton     }
763b547278cSGreg Clayton 
7644574a890SZachary Turner     if (!m_interpreter.RemoveCommand(command_name)) {
7654574a890SZachary Turner       result.AppendErrorWithFormat(
7664574a890SZachary Turner           "'%s' is a permanent debugger command and cannot be removed.\n",
767867e7d17SZachary Turner           args[0].c_str());
7684574a890SZachary Turner       return false;
7694574a890SZachary Turner     }
7704574a890SZachary Turner 
7714574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishNoResult);
7724574a890SZachary Turner     return true;
773b547278cSGreg Clayton   }
774b547278cSGreg Clayton };
775b547278cSGreg Clayton 
776de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
7771f0f5b5bSZachary Turner 
77864becc11SRaphael Isemann #define LLDB_OPTIONS_regex
77964becc11SRaphael Isemann #include "CommandOptions.inc"
7801f0f5b5bSZachary Turner 
7815a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
782de164aaaSGreg Clayton 
783b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
784b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
785de164aaaSGreg Clayton public:
7867428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
787b9c1b51eSKate Stone       : CommandObjectParsed(
788a925974bSAdrian Prantl             interpreter, "command regex",
789a925974bSAdrian Prantl             "Define a custom command in terms of "
790b9c1b51eSKate Stone             "existing commands by matching "
791b9c1b51eSKate Stone             "regular expressions.",
7920e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
793b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
794abb0ed44SKazu Hirata                                    IOHandlerDelegate::Completion::LLDBCommand) {
795b9c1b51eSKate Stone     SetHelpLong(
796b9c1b51eSKate Stone         R"(
797b9c1b51eSKate Stone )"
798b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
799ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
800b9c1b51eSKate Stone using the regular expression substitution format of:"
801b9c1b51eSKate Stone         R"(
802ea671fbdSKate Stone 
803ea671fbdSKate Stone     s/<regex>/<subst>/
804ea671fbdSKate Stone 
805b9c1b51eSKate Stone )"
806b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
807ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
808b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
809b9c1b51eSKate Stone         R"(
810ea671fbdSKate Stone 
811b9c1b51eSKate Stone )"
812b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
813ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
814ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
815b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
816b9c1b51eSKate Stone         R"(
817ea671fbdSKate Stone 
818ea671fbdSKate Stone EXAMPLES
819ea671fbdSKate Stone 
820b9c1b51eSKate Stone )"
821b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
822ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
823b9c1b51eSKate Stone a number follows 'f':"
824b9c1b51eSKate Stone         R"(
825ea671fbdSKate Stone 
826b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
827*c1b07d61SJim Ingham     CommandArgumentData thread_arg{eArgTypeSEDStylePair, eArgRepeatOptional};
828*c1b07d61SJim Ingham     m_arguments.push_back({thread_arg});
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:
102724f9a2f5SShafik Yaghmour     CommandOptions() = default;
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),
108128c878aeSShafik Yaghmour         m_synchro(synch) {
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;
114428c878aeSShafik Yaghmour   bool m_fetched_help_long = false;
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",
1241abb0ed44SKazu Hirata                             "Import a scripting module in LLDB.", nullptr) {
12425a988416SJim Ingham     CommandArgumentEntry arg1;
12435a988416SJim Ingham     CommandArgumentData cmd_arg;
12445a988416SJim Ingham 
12455a988416SJim Ingham     // Define the first (and only) variant of this arg.
12465a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
12473b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
12485a988416SJim Ingham 
1249b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1250b9c1b51eSKate Stone     // argument entry.
12515a988416SJim Ingham     arg1.push_back(cmd_arg);
12525a988416SJim Ingham 
12535a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
12545a988416SJim Ingham     m_arguments.push_back(arg1);
12555a988416SJim Ingham   }
12565a988416SJim Ingham 
12576e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
12585a988416SJim Ingham 
1259ae34ed2cSRaphael Isemann   void
1260ae34ed2cSRaphael Isemann   HandleArgumentCompletion(CompletionRequest &request,
12612443bbd4SRaphael Isemann                            OptionElementVector &opt_element_vector) override {
1262b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1263b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1264a2e76c0bSRaphael Isemann         request, nullptr);
12655a988416SJim Ingham   }
12665a988416SJim Ingham 
1267b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
12685a988416SJim Ingham 
12695a988416SJim Ingham protected:
1270b9c1b51eSKate Stone   class CommandOptions : public Options {
12710a305db7SEnrico Granata   public:
127224f9a2f5SShafik Yaghmour     CommandOptions() = default;
12730a305db7SEnrico Granata 
12746e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
12750a305db7SEnrico Granata 
127697206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1277b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
127897206d57SZachary Turner       Status error;
12793bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
12800a305db7SEnrico Granata 
1281b9c1b51eSKate Stone       switch (short_option) {
12820a305db7SEnrico Granata       case 'r':
128315625112SJonas Devlieghere         // NO-OP
12840a305db7SEnrico Granata         break;
128500bb397bSJonas Devlieghere       case 'c':
128600bb397bSJonas Devlieghere         relative_to_command_file = true;
128700bb397bSJonas Devlieghere         break;
1288f9517353SJonas Devlieghere       case 's':
1289f9517353SJonas Devlieghere         silent = true;
1290f9517353SJonas Devlieghere         break;
12910a305db7SEnrico Granata       default:
129236162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
12930a305db7SEnrico Granata       }
12940a305db7SEnrico Granata 
12950a305db7SEnrico Granata       return error;
12960a305db7SEnrico Granata     }
12970a305db7SEnrico Granata 
1298b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
129900bb397bSJonas Devlieghere       relative_to_command_file = false;
13000a305db7SEnrico Granata     }
13010a305db7SEnrico Granata 
13021f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
130370602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
13041f0f5b5bSZachary Turner     }
130500bb397bSJonas Devlieghere     bool relative_to_command_file = false;
1306f9517353SJonas Devlieghere     bool silent = false;
13070a305db7SEnrico Granata   };
13080a305db7SEnrico Granata 
1309b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
131011eb9c64SZachary Turner     if (command.empty()) {
13113b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1312a9dbf432SEnrico Granata       return false;
1313a9dbf432SEnrico Granata     }
1314a9dbf432SEnrico Granata 
131500bb397bSJonas Devlieghere     FileSpec source_dir = {};
131600bb397bSJonas Devlieghere     if (m_options.relative_to_command_file) {
131700bb397bSJonas Devlieghere       source_dir = GetDebugger().GetCommandInterpreter().GetCurrentSourceDir();
131800bb397bSJonas Devlieghere       if (!source_dir) {
131900bb397bSJonas Devlieghere         result.AppendError("command script import -c can only be specified "
132000bb397bSJonas Devlieghere                            "from a command file");
132100bb397bSJonas Devlieghere         return false;
132200bb397bSJonas Devlieghere       }
132300bb397bSJonas Devlieghere     }
132400bb397bSJonas Devlieghere 
132511eb9c64SZachary Turner     for (auto &entry : command.entries()) {
132697206d57SZachary Turner       Status error;
1327a9dbf432SEnrico Granata 
1328f9517353SJonas Devlieghere       LoadScriptOptions options;
1329f9517353SJonas Devlieghere       options.SetInitSession(true);
1330f9517353SJonas Devlieghere       options.SetSilent(m_options.silent);
1331f9517353SJonas Devlieghere 
1332b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
133311eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
133411eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
133505097246SAdrian Prantl       // script imports" in __lldb_init_module the real fix is to have
133605097246SAdrian Prantl       // recursive commands possible with a CommandInvocation object separate
133705097246SAdrian Prantl       // from the CommandObject itself, so that recursive command invocations
133805097246SAdrian Prantl       // won't stomp on each other (wrt to execution contents, options, and
133905097246SAdrian Prantl       // more)
1340078551c7SEnrico Granata       m_exe_ctx.Clear();
13412b29b432SJonas Devlieghere       if (GetDebugger().GetScriptInterpreter()->LoadScriptingModule(
1342f9517353SJonas Devlieghere               entry.c_str(), options, error, /*module_sp=*/nullptr,
1343f9517353SJonas Devlieghere               source_dir)) {
1344a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1345b9c1b51eSKate Stone       } else {
1346b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1347b9c1b51eSKate Stone                                      error.AsCString());
1348a9dbf432SEnrico Granata       }
13493b00e35bSEnrico Granata     }
1350a9dbf432SEnrico Granata 
1351a9dbf432SEnrico Granata     return result.Succeeded();
1352a9dbf432SEnrico Granata   }
13530a305db7SEnrico Granata 
13545a988416SJim Ingham   CommandOptions m_options;
1355a9dbf432SEnrico Granata };
1356223383edSEnrico Granata 
1357223383edSEnrico Granata // CommandObjectCommandsScriptAdd
13588fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_script_synchro_type[] = {
1359e063ecccSJonas Devlieghere     {
1360e063ecccSJonas Devlieghere         eScriptedCommandSynchronicitySynchronous,
1361e063ecccSJonas Devlieghere         "synchronous",
1362e063ecccSJonas Devlieghere         "Run synchronous",
1363e063ecccSJonas Devlieghere     },
1364e063ecccSJonas Devlieghere     {
1365e063ecccSJonas Devlieghere         eScriptedCommandSynchronicityAsynchronous,
1366e063ecccSJonas Devlieghere         "asynchronous",
1367e063ecccSJonas Devlieghere         "Run asynchronous",
1368e063ecccSJonas Devlieghere     },
1369e063ecccSJonas Devlieghere     {
1370e063ecccSJonas Devlieghere         eScriptedCommandSynchronicityCurrentValue,
1371e063ecccSJonas Devlieghere         "current",
1372e063ecccSJonas Devlieghere         "Do not alter current setting",
1373e063ecccSJonas Devlieghere     },
1374e063ecccSJonas Devlieghere };
13751f0f5b5bSZachary Turner 
13768fe53c49STatyana Krasnukha static constexpr OptionEnumValues ScriptSynchroType() {
13778fe53c49STatyana Krasnukha   return OptionEnumValues(g_script_synchro_type);
13788fe53c49STatyana Krasnukha }
13798fe53c49STatyana Krasnukha 
138064becc11SRaphael Isemann #define LLDB_OPTIONS_script_add
138164becc11SRaphael Isemann #include "CommandOptions.inc"
13821f0f5b5bSZachary Turner 
1383b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1384b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
13855a988416SJim Ingham public:
1386b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1387b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
13885a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
1389c5011aedSJim Ingham                             "Add a scripted function as an lldb command. "
1390c5011aedSJim Ingham                             "If you provide a single argument, the command "
1391c5011aedSJim Ingham                             "will be added at the root level of the command "
1392c5011aedSJim Ingham                             "hierarchy.  If there are more arguments they "
1393c5011aedSJim Ingham                             "must be a path to a user-added container "
1394c5011aedSJim Ingham                             "command, and the last element will be the new "
1395c5011aedSJim Ingham                             "command name."),
1396abb0ed44SKazu Hirata         IOHandlerDelegateMultiline("DONE") {
13975a988416SJim Ingham     CommandArgumentEntry arg1;
13985a988416SJim Ingham     CommandArgumentData cmd_arg;
13995a988416SJim Ingham 
1400c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
1401c5011aedSJim Ingham     // you want to add.
1402c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1403c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
14045a988416SJim Ingham 
1405b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1406b9c1b51eSKate Stone     // argument entry.
14075a988416SJim Ingham     arg1.push_back(cmd_arg);
14085a988416SJim Ingham 
14095a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14105a988416SJim Ingham     m_arguments.push_back(arg1);
14115a988416SJim Ingham   }
14125a988416SJim Ingham 
14136e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
14145a988416SJim Ingham 
1415b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14165a988416SJim Ingham 
1417c5011aedSJim Ingham   void
1418c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
1419c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
1420c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1421c5011aedSJim Ingham                                                       opt_element_vector);
1422c5011aedSJim Ingham   }
1423c5011aedSJim Ingham 
14245a988416SJim Ingham protected:
1425b9c1b51eSKate Stone   class CommandOptions : public Options {
1426223383edSEnrico Granata   public:
142724f9a2f5SShafik Yaghmour     CommandOptions() = default;
1428223383edSEnrico Granata 
14296e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1430223383edSEnrico Granata 
143197206d57SZachary Turner     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1432b9c1b51eSKate Stone                           ExecutionContext *execution_context) override {
143397206d57SZachary Turner       Status error;
14343bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1435223383edSEnrico Granata 
1436b9c1b51eSKate Stone       switch (short_option) {
1437223383edSEnrico Granata       case 'f':
1438fe11483bSZachary Turner         if (!option_arg.empty())
1439adcd0268SBenjamin Kramer           m_funct_name = std::string(option_arg);
1440735152e3SEnrico Granata         break;
14419fe00e52SEnrico Granata       case 'c':
1442fe11483bSZachary Turner         if (!option_arg.empty())
1443adcd0268SBenjamin Kramer           m_class_name = std::string(option_arg);
14449fe00e52SEnrico Granata         break;
1445735152e3SEnrico Granata       case 'h':
1446fe11483bSZachary Turner         if (!option_arg.empty())
1447adcd0268SBenjamin Kramer           m_short_help = std::string(option_arg);
1448223383edSEnrico Granata         break;
1449c5011aedSJim Ingham       case 'o':
14501f7b58f2SJim Ingham         m_overwrite_lazy = eLazyBoolYes;
1451c5011aedSJim Ingham         break;
14520a305db7SEnrico Granata       case 's':
1453b9c1b51eSKate Stone         m_synchronicity =
145447cbf4a0SPavel Labath             (ScriptedCommandSynchronicity)OptionArgParser::ToOptionEnum(
1455fe11483bSZachary Turner                 option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
14560a305db7SEnrico Granata         if (!error.Success())
1457b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1458fe11483bSZachary Turner               "unrecognized value for synchronicity '%s'",
1459fe11483bSZachary Turner               option_arg.str().c_str());
14600a305db7SEnrico Granata         break;
1461223383edSEnrico Granata       default:
146236162014SRaphael Isemann         llvm_unreachable("Unimplemented option");
1463223383edSEnrico Granata       }
1464223383edSEnrico Granata 
1465223383edSEnrico Granata       return error;
1466223383edSEnrico Granata     }
1467223383edSEnrico Granata 
1468b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
14699fe00e52SEnrico Granata       m_class_name.clear();
1470735152e3SEnrico Granata       m_funct_name.clear();
1471735152e3SEnrico Granata       m_short_help.clear();
14721f7b58f2SJim Ingham       m_overwrite_lazy = eLazyBoolCalculate;
147344d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1474223383edSEnrico Granata     }
1475223383edSEnrico Granata 
14761f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
147770602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
14781f0f5b5bSZachary Turner     }
1479223383edSEnrico Granata 
1480223383edSEnrico Granata     // Instance variables to hold the values for command options.
1481223383edSEnrico Granata 
14829fe00e52SEnrico Granata     std::string m_class_name;
1483223383edSEnrico Granata     std::string m_funct_name;
1484735152e3SEnrico Granata     std::string m_short_help;
14852a84a861SMartin Storsjö     LazyBool m_overwrite_lazy = eLazyBoolCalculate;
14869494c510SJonas Devlieghere     ScriptedCommandSynchronicity m_synchronicity =
14879494c510SJonas Devlieghere         eScriptedCommandSynchronicitySynchronous;
1488223383edSEnrico Granata   };
1489223383edSEnrico Granata 
14900affb582SDave Lee   void IOHandlerActivated(IOHandler &io_handler, bool interactive) override {
14917ca15ba7SLawrence D'Anna     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
14920affb582SDave Lee     if (output_sp && interactive) {
149344d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
149444d93782SGreg Clayton       output_sp->Flush();
1495223383edSEnrico Granata     }
1496223383edSEnrico Granata   }
1497223383edSEnrico Granata 
1498b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1499b9c1b51eSKate Stone                               std::string &data) override {
15007ca15ba7SLawrence D'Anna     StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
150144d93782SGreg Clayton 
15022b29b432SJonas Devlieghere     ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1503b9c1b51eSKate Stone     if (interpreter) {
150444d93782SGreg Clayton       StringList lines;
150544d93782SGreg Clayton       lines.SplitIntoLines(data);
1506b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1507a73b7df7SEnrico Granata         std::string funct_name_str;
1508b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1509b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1510b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1511b9c1b51eSKate Stone                              "add python command.\n");
151244d93782SGreg Clayton             error_sp->Flush();
1513b9c1b51eSKate Stone           } else {
1514223383edSEnrico Granata             // everything should be fine now, let's add this alias
1515223383edSEnrico Granata 
1516b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1517771ef6d4SMalcolm Parsons                 m_interpreter, m_cmd_name, funct_name_str, m_short_help,
151844d93782SGreg Clayton                 m_synchronicity));
1519c5011aedSJim Ingham             if (!m_container) {
1520c5011aedSJim Ingham               Status error = m_interpreter.AddUserCommand(
1521c5011aedSJim Ingham                   m_cmd_name, command_obj_sp, m_overwrite);
1522c5011aedSJim Ingham               if (error.Fail()) {
1523c5011aedSJim Ingham                 error_sp->Printf("error: unable to add selected command: '%s'",
1524c5011aedSJim Ingham                                  error.AsCString());
152544d93782SGreg Clayton                 error_sp->Flush();
1526223383edSEnrico Granata               }
1527c5011aedSJim Ingham             } else {
1528c5011aedSJim Ingham               llvm::Error llvm_error = m_container->LoadUserSubcommand(
1529c5011aedSJim Ingham                   m_cmd_name, command_obj_sp, m_overwrite);
1530c5011aedSJim Ingham               if (llvm_error) {
1531c5011aedSJim Ingham                 error_sp->Printf("error: unable to add selected command: '%s'",
1532c5011aedSJim Ingham                                llvm::toString(std::move(llvm_error)).c_str());
1533c5011aedSJim Ingham                 error_sp->Flush();
1534c5011aedSJim Ingham               }
1535c5011aedSJim Ingham             }
1536223383edSEnrico Granata           }
1537b9c1b51eSKate Stone         } else {
1538b9c1b51eSKate Stone           error_sp->Printf(
1539c5011aedSJim Ingham               "error: unable to create function, didn't add python command\n");
154044d93782SGreg Clayton           error_sp->Flush();
154144d93782SGreg Clayton         }
1542b9c1b51eSKate Stone       } else {
1543c5011aedSJim Ingham         error_sp->Printf("error: empty function, didn't add python command\n");
154444d93782SGreg Clayton         error_sp->Flush();
154544d93782SGreg Clayton       }
1546b9c1b51eSKate Stone     } else {
1547b9c1b51eSKate Stone       error_sp->Printf(
1548c5011aedSJim Ingham           "error: script interpreter missing, didn't add python command\n");
154944d93782SGreg Clayton       error_sp->Flush();
155044d93782SGreg Clayton     }
155144d93782SGreg Clayton 
155244d93782SGreg Clayton     io_handler.SetIsDone(true);
155344d93782SGreg Clayton   }
1554223383edSEnrico Granata 
1555b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
155657179860SJonas Devlieghere     if (GetDebugger().GetScriptLanguage() != lldb::eScriptLanguagePython) {
1557b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1558b9c1b51eSKate Stone                          "commands is currently Python");
155999f0b8f9SEnrico Granata       return false;
156099f0b8f9SEnrico Granata     }
156199f0b8f9SEnrico Granata 
1562c5011aedSJim Ingham     if (command.GetArgumentCount() == 0) {
1563c5011aedSJim Ingham       result.AppendError("'command script add' requires at least one argument");
1564c5011aedSJim Ingham       return false;
1565c5011aedSJim Ingham     }
15661f7b58f2SJim Ingham     // Store the options in case we get multi-line input, also figure out the
15671f7b58f2SJim Ingham     // default if not user supplied:
15681f7b58f2SJim Ingham     switch (m_options.m_overwrite_lazy) {
15691f7b58f2SJim Ingham       case eLazyBoolCalculate:
15701f7b58f2SJim Ingham         m_overwrite = !GetDebugger().GetCommandInterpreter().GetRequireCommandOverwrite();
15711f7b58f2SJim Ingham         break;
15721f7b58f2SJim Ingham       case eLazyBoolYes:
15731f7b58f2SJim Ingham         m_overwrite = true;
15741f7b58f2SJim Ingham         break;
15751f7b58f2SJim Ingham       case eLazyBoolNo:
15761f7b58f2SJim Ingham         m_overwrite = false;
15771f7b58f2SJim Ingham     }
15781f7b58f2SJim Ingham 
1579c5011aedSJim Ingham     Status path_error;
1580c5011aedSJim Ingham     m_container = GetCommandInterpreter().VerifyUserMultiwordCmdPath(
1581c5011aedSJim Ingham         command, true, path_error);
1582c5011aedSJim Ingham 
1583c5011aedSJim Ingham     if (path_error.Fail()) {
1584c5011aedSJim Ingham       result.AppendErrorWithFormat("error in command path: %s",
1585c5011aedSJim Ingham                                    path_error.AsCString());
1586223383edSEnrico Granata       return false;
1587223383edSEnrico Granata     }
1588223383edSEnrico Granata 
1589c5011aedSJim Ingham     if (!m_container) {
1590c5011aedSJim Ingham       // This is getting inserted into the root of the interpreter.
1591adcd0268SBenjamin Kramer       m_cmd_name = std::string(command[0].ref());
1592c5011aedSJim Ingham     } else {
1593c5011aedSJim Ingham       size_t num_args = command.GetArgumentCount();
1594c5011aedSJim Ingham       m_cmd_name = std::string(command[num_args - 1].ref());
1595c5011aedSJim Ingham     }
1596c5011aedSJim Ingham 
1597735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
159844d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1599223383edSEnrico Granata 
1600c5011aedSJim Ingham     // Handle the case where we prompt for the script code first:
1601c5011aedSJim Ingham     if (m_options.m_class_name.empty() && m_options.m_funct_name.empty()) {
1602c5011aedSJim Ingham       m_interpreter.GetPythonCommandsFromIOHandler("     ", // Prompt
1603a6faf851SJonas Devlieghere                                                    *this);  // IOHandlerDelegate
1604c5011aedSJim Ingham       return result.Succeeded();
1605c5011aedSJim Ingham     }
1606c5011aedSJim Ingham 
1607c5011aedSJim Ingham     CommandObjectSP new_cmd_sp;
1608c5011aedSJim Ingham     if (m_options.m_class_name.empty()) {
1609c5011aedSJim Ingham       new_cmd_sp.reset(new CommandObjectPythonFunction(
1610b9c1b51eSKate Stone           m_interpreter, m_cmd_name, m_options.m_funct_name,
1611b9c1b51eSKate Stone           m_options.m_short_help, m_synchronicity));
1612b9c1b51eSKate Stone     } else {
16132b29b432SJonas Devlieghere       ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();
1614b9c1b51eSKate Stone       if (!interpreter) {
16159fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
16169fe00e52SEnrico Granata         return false;
16179fe00e52SEnrico Granata       }
16189fe00e52SEnrico Granata 
1619b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1620b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1621b9c1b51eSKate Stone       if (!cmd_obj_sp) {
16229fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
16239fe00e52SEnrico Granata         return false;
16249fe00e52SEnrico Granata       }
16259fe00e52SEnrico Granata 
1626c5011aedSJim Ingham       new_cmd_sp.reset(new CommandObjectScriptingObject(
1627b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
16289fe00e52SEnrico Granata     }
1629223383edSEnrico Granata 
1630c5011aedSJim Ingham     // Assume we're going to succeed...
1631c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1632c5011aedSJim Ingham     if (!m_container) {
1633c5011aedSJim Ingham       Status add_error =
1634c5011aedSJim Ingham           m_interpreter.AddUserCommand(m_cmd_name, new_cmd_sp, m_overwrite);
1635c5011aedSJim Ingham       if (add_error.Fail())
1636c5011aedSJim Ingham         result.AppendErrorWithFormat("cannot add command: %s",
1637c5011aedSJim Ingham                                      add_error.AsCString());
1638c5011aedSJim Ingham     } else {
1639c5011aedSJim Ingham       llvm::Error llvm_error =
1640c5011aedSJim Ingham           m_container->LoadUserSubcommand(m_cmd_name, new_cmd_sp, m_overwrite);
1641c5011aedSJim Ingham       if (llvm_error)
1642c5011aedSJim Ingham         result.AppendErrorWithFormat("cannot add command: %s",
1643c5011aedSJim Ingham                                      llvm::toString(std::move(llvm_error)).c_str());
1644c5011aedSJim Ingham     }
1645223383edSEnrico Granata     return result.Succeeded();
1646223383edSEnrico Granata   }
16475a988416SJim Ingham 
16485a988416SJim Ingham   CommandOptions m_options;
164944d93782SGreg Clayton   std::string m_cmd_name;
1650c5011aedSJim Ingham   CommandObjectMultiword *m_container = nullptr;
1651735152e3SEnrico Granata   std::string m_short_help;
16522a84a861SMartin Storsjö   bool m_overwrite = false;
1653e4a03b26SJonas Devlieghere   ScriptedCommandSynchronicity m_synchronicity =
1654e4a03b26SJonas Devlieghere       eScriptedCommandSynchronicitySynchronous;
1655223383edSEnrico Granata };
1656223383edSEnrico Granata 
1657223383edSEnrico Granata // CommandObjectCommandsScriptList
1658223383edSEnrico Granata 
1659b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1660223383edSEnrico Granata public:
1661b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1662b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1663c5011aedSJim Ingham                             "List defined top-level scripted commands.",
1664c5011aedSJim Ingham                             nullptr) {}
1665223383edSEnrico Granata 
16666e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1667223383edSEnrico Granata 
1668b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1669b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1670223383edSEnrico Granata 
1671223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1672223383edSEnrico Granata 
1673223383edSEnrico Granata     return true;
1674223383edSEnrico Granata   }
1675223383edSEnrico Granata };
1676223383edSEnrico Granata 
1677223383edSEnrico Granata // CommandObjectCommandsScriptClear
1678223383edSEnrico Granata 
1679b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1680223383edSEnrico Granata public:
1681b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1682b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1683b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1684223383edSEnrico Granata 
16856e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1686223383edSEnrico Granata 
16875a988416SJim Ingham protected:
1688b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1689223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1690223383edSEnrico Granata 
1691223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1692223383edSEnrico Granata 
1693223383edSEnrico Granata     return true;
1694223383edSEnrico Granata   }
1695223383edSEnrico Granata };
1696223383edSEnrico Granata 
1697223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1698223383edSEnrico Granata 
1699b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1700223383edSEnrico Granata public:
1701b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1702c5011aedSJim Ingham       : CommandObjectParsed(
1703c5011aedSJim Ingham             interpreter, "command script delete",
1704c5011aedSJim Ingham             "Delete a scripted command by specifying the path to the command.",
1705c5011aedSJim Ingham             nullptr) {
1706223383edSEnrico Granata     CommandArgumentEntry arg1;
1707223383edSEnrico Granata     CommandArgumentData cmd_arg;
1708223383edSEnrico Granata 
1709c5011aedSJim Ingham     // This is a list of command names forming the path to the command
1710c5011aedSJim Ingham     // to be deleted.
1711c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1712c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
1713223383edSEnrico Granata 
1714b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1715b9c1b51eSKate Stone     // argument entry.
1716223383edSEnrico Granata     arg1.push_back(cmd_arg);
1717223383edSEnrico Granata 
1718223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1719223383edSEnrico Granata     m_arguments.push_back(arg1);
1720223383edSEnrico Granata   }
1721223383edSEnrico Granata 
17226e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1723223383edSEnrico Granata 
17242e8f304fSGongyu Deng   void
17252e8f304fSGongyu Deng   HandleArgumentCompletion(CompletionRequest &request,
17262e8f304fSGongyu Deng                            OptionElementVector &opt_element_vector) override {
1727c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1728c5011aedSJim Ingham                                                       opt_element_vector);
17292e8f304fSGongyu Deng   }
17302e8f304fSGongyu Deng 
17315a988416SJim Ingham protected:
1732b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1733223383edSEnrico Granata 
1734c5011aedSJim Ingham     llvm::StringRef root_cmd = command[0].ref();
1735c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
1736c5011aedSJim Ingham 
1737c5011aedSJim Ingham     if (root_cmd.empty()) {
1738c5011aedSJim Ingham       result.AppendErrorWithFormat("empty root command name");
1739c5011aedSJim Ingham       return false;
1740c5011aedSJim Ingham     }
1741c5011aedSJim Ingham     if (!m_interpreter.HasUserCommands() &&
1742c5011aedSJim Ingham         !m_interpreter.HasUserMultiwordCommands()) {
1743c5011aedSJim Ingham       result.AppendErrorWithFormat("can only delete user defined commands, "
1744c5011aedSJim Ingham                                    "but no user defined commands found");
1745223383edSEnrico Granata       return false;
1746223383edSEnrico Granata     }
1747223383edSEnrico Granata 
1748c5011aedSJim Ingham     CommandObjectSP cmd_sp = m_interpreter.GetCommandSPExact(root_cmd);
1749c5011aedSJim Ingham     if (!cmd_sp) {
1750c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' not found.",
1751c5011aedSJim Ingham                                    command[0].c_str());
1752c5011aedSJim Ingham       return false;
1753c5011aedSJim Ingham     }
1754c5011aedSJim Ingham     if (!cmd_sp->IsUserCommand()) {
1755c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' is not a user command.",
1756c5011aedSJim Ingham                                    command[0].c_str());
1757c5011aedSJim Ingham       return false;
1758c5011aedSJim Ingham     }
1759c5011aedSJim Ingham     if (cmd_sp->GetAsMultiwordCommand() && num_args == 1) {
1760c5011aedSJim Ingham       result.AppendErrorWithFormat("command '%s' is a multi-word command.\n "
1761c5011aedSJim Ingham                                    "Delete with \"command container delete\"",
1762c5011aedSJim Ingham                                    command[0].c_str());
17634574a890SZachary Turner       return false;
1764223383edSEnrico Granata     }
1765223383edSEnrico Granata 
1766c5011aedSJim Ingham     if (command.GetArgumentCount() == 1) {
1767c5011aedSJim Ingham       m_interpreter.RemoveUser(root_cmd);
1768c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishResult);
1769c5011aedSJim Ingham       return true;
1770c5011aedSJim Ingham     }
1771c5011aedSJim Ingham     // We're deleting a command from a multiword command.  Verify the command
1772c5011aedSJim Ingham     // path:
1773c5011aedSJim Ingham     Status error;
1774c5011aedSJim Ingham     CommandObjectMultiword *container =
1775c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
1776c5011aedSJim Ingham                                                            error);
1777c5011aedSJim Ingham     if (error.Fail()) {
1778c5011aedSJim Ingham       result.AppendErrorWithFormat("could not resolve command path: %s",
1779c5011aedSJim Ingham                                    error.AsCString());
1780c5011aedSJim Ingham       return false;
1781c5011aedSJim Ingham     }
1782c5011aedSJim Ingham     if (!container) {
1783c5011aedSJim Ingham       // This means that command only had a leaf command, so the container is
1784c5011aedSJim Ingham       // the root.  That should have been handled above.
1785c5011aedSJim Ingham       result.AppendErrorWithFormat("could not find a container for '%s'",
1786c5011aedSJim Ingham                                    command[0].c_str());
1787c5011aedSJim Ingham       return false;
1788c5011aedSJim Ingham     }
1789c5011aedSJim Ingham     const char *leaf_cmd = command[num_args - 1].c_str();
1790c5011aedSJim Ingham     llvm::Error llvm_error = container->RemoveUserSubcommand(leaf_cmd,
1791c5011aedSJim Ingham                                             /* multiword not okay */ false);
1792c5011aedSJim Ingham     if (llvm_error) {
1793c5011aedSJim Ingham       result.AppendErrorWithFormat("could not delete command '%s': %s",
1794c5011aedSJim Ingham                                    leaf_cmd,
1795c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
1796c5011aedSJim Ingham       return false;
1797c5011aedSJim Ingham     }
1798c5011aedSJim Ingham 
1799c5011aedSJim Ingham     Stream &out_stream = result.GetOutputStream();
1800c5011aedSJim Ingham 
1801c5011aedSJim Ingham     out_stream << "Deleted command:";
1802c5011aedSJim Ingham     for (size_t idx = 0; idx < num_args; idx++) {
1803c5011aedSJim Ingham       out_stream << ' ';
1804c5011aedSJim Ingham       out_stream << command[idx].c_str();
1805c5011aedSJim Ingham     }
1806c5011aedSJim Ingham     out_stream << '\n';
18074574a890SZachary Turner     result.SetStatus(eReturnStatusSuccessFinishResult);
18084574a890SZachary Turner     return true;
1809223383edSEnrico Granata   }
1810223383edSEnrico Granata };
1811223383edSEnrico Granata 
1812223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1813223383edSEnrico Granata 
1814223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1815223383edSEnrico Granata 
1816b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1817223383edSEnrico Granata public:
18187428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1819b9c1b51eSKate Stone       : CommandObjectMultiword(
1820a925974bSAdrian Prantl             interpreter, "command script",
1821a925974bSAdrian Prantl             "Commands for managing custom "
1822b9c1b51eSKate Stone             "commands implemented by "
1823b9c1b51eSKate Stone             "interpreter scripts.",
1824b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1825b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1826b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1827b9c1b51eSKate Stone     LoadSubCommand(
1828b9c1b51eSKate Stone         "delete",
1829b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1830b9c1b51eSKate Stone     LoadSubCommand(
1831b9c1b51eSKate Stone         "clear",
1832b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1833b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1834b9c1b51eSKate Stone                                interpreter)));
1835b9c1b51eSKate Stone     LoadSubCommand(
1836b9c1b51eSKate Stone         "import",
1837b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1838223383edSEnrico Granata   }
1839223383edSEnrico Granata 
18406e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1841223383edSEnrico Granata };
1842223383edSEnrico Granata 
1843c5011aedSJim Ingham #pragma mark CommandObjectCommandContainer
1844c5011aedSJim Ingham #define LLDB_OPTIONS_container_add
1845c5011aedSJim Ingham #include "CommandOptions.inc"
1846c5011aedSJim Ingham 
1847c5011aedSJim Ingham class CommandObjectCommandsContainerAdd : public CommandObjectParsed {
1848c5011aedSJim Ingham public:
1849c5011aedSJim Ingham   CommandObjectCommandsContainerAdd(CommandInterpreter &interpreter)
1850c5011aedSJim Ingham       : CommandObjectParsed(
1851c5011aedSJim Ingham             interpreter, "command container add",
1852c5011aedSJim Ingham             "Add a container command to lldb.  Adding to built-"
1853c5011aedSJim Ingham             "in container commands is not allowed.",
1854c5011aedSJim Ingham             "command container add [[path1]...] container-name") {
1855c5011aedSJim Ingham     CommandArgumentEntry arg1;
1856c5011aedSJim Ingham     CommandArgumentData cmd_arg;
1857c5011aedSJim Ingham 
1858c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
1859c5011aedSJim Ingham     // you want to add.
1860c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
1861c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
1862c5011aedSJim Ingham 
1863c5011aedSJim Ingham     // There is only one variant this argument could be; put it into the
1864c5011aedSJim Ingham     // argument entry.
1865c5011aedSJim Ingham     arg1.push_back(cmd_arg);
1866c5011aedSJim Ingham 
1867c5011aedSJim Ingham     // Push the data for the first argument into the m_arguments vector.
1868c5011aedSJim Ingham     m_arguments.push_back(arg1);
1869c5011aedSJim Ingham   }
1870c5011aedSJim Ingham 
1871c5011aedSJim Ingham   ~CommandObjectCommandsContainerAdd() override = default;
1872c5011aedSJim Ingham 
1873c5011aedSJim Ingham   Options *GetOptions() override { return &m_options; }
1874c5011aedSJim Ingham 
1875c5011aedSJim Ingham   void
1876c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
1877c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
1878c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
1879c5011aedSJim Ingham                                                       opt_element_vector);
1880c5011aedSJim Ingham   }
1881c5011aedSJim Ingham 
1882c5011aedSJim Ingham protected:
1883c5011aedSJim Ingham   class CommandOptions : public Options {
1884c5011aedSJim Ingham   public:
188524f9a2f5SShafik Yaghmour     CommandOptions() = default;
1886c5011aedSJim Ingham 
1887c5011aedSJim Ingham     ~CommandOptions() override = default;
1888c5011aedSJim Ingham 
1889c5011aedSJim Ingham     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1890c5011aedSJim Ingham                           ExecutionContext *execution_context) override {
1891c5011aedSJim Ingham       Status error;
1892c5011aedSJim Ingham       const int short_option = m_getopt_table[option_idx].val;
1893c5011aedSJim Ingham 
1894c5011aedSJim Ingham       switch (short_option) {
1895c5011aedSJim Ingham       case 'h':
1896c5011aedSJim Ingham         if (!option_arg.empty())
1897c5011aedSJim Ingham           m_short_help = std::string(option_arg);
1898c5011aedSJim Ingham         break;
1899c5011aedSJim Ingham       case 'o':
1900c5011aedSJim Ingham         m_overwrite = true;
1901c5011aedSJim Ingham         break;
1902c5011aedSJim Ingham       case 'H':
1903c5011aedSJim Ingham         if (!option_arg.empty())
1904c5011aedSJim Ingham           m_long_help = std::string(option_arg);
1905c5011aedSJim Ingham         break;
1906c5011aedSJim Ingham       default:
1907c5011aedSJim Ingham         llvm_unreachable("Unimplemented option");
1908c5011aedSJim Ingham       }
1909c5011aedSJim Ingham 
1910c5011aedSJim Ingham       return error;
1911c5011aedSJim Ingham     }
1912c5011aedSJim Ingham 
1913c5011aedSJim Ingham     void OptionParsingStarting(ExecutionContext *execution_context) override {
1914c5011aedSJim Ingham       m_short_help.clear();
1915c5011aedSJim Ingham       m_long_help.clear();
1916c5011aedSJim Ingham       m_overwrite = false;
1917c5011aedSJim Ingham     }
1918c5011aedSJim Ingham 
1919c5011aedSJim Ingham     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1920c5011aedSJim Ingham       return llvm::makeArrayRef(g_container_add_options);
1921c5011aedSJim Ingham     }
1922c5011aedSJim Ingham 
1923c5011aedSJim Ingham     // Instance variables to hold the values for command options.
1924c5011aedSJim Ingham 
1925c5011aedSJim Ingham     std::string m_short_help;
1926c5011aedSJim Ingham     std::string m_long_help;
1927c5011aedSJim Ingham     bool m_overwrite = false;
1928c5011aedSJim Ingham   };
1929c5011aedSJim Ingham   bool DoExecute(Args &command, CommandReturnObject &result) override {
1930c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
1931c5011aedSJim Ingham 
1932c5011aedSJim Ingham     if (num_args == 0) {
1933c5011aedSJim Ingham       result.AppendError("no command was specified");
1934c5011aedSJim Ingham       return false;
1935c5011aedSJim Ingham     }
1936c5011aedSJim Ingham 
1937c5011aedSJim Ingham     if (num_args == 1) {
1938c5011aedSJim Ingham       // We're adding this as a root command, so use the interpreter.
1939c5011aedSJim Ingham       const char *cmd_name = command.GetArgumentAtIndex(0);
1940c5011aedSJim Ingham       auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
1941c5011aedSJim Ingham           GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
1942c5011aedSJim Ingham           m_options.m_long_help.c_str()));
1943c5011aedSJim Ingham       cmd_sp->GetAsMultiwordCommand()->SetRemovable(true);
1944c5011aedSJim Ingham       Status add_error = GetCommandInterpreter().AddUserCommand(
1945c5011aedSJim Ingham           cmd_name, cmd_sp, m_options.m_overwrite);
1946c5011aedSJim Ingham       if (add_error.Fail()) {
1947c5011aedSJim Ingham         result.AppendErrorWithFormat("error adding command: %s",
1948c5011aedSJim Ingham                                      add_error.AsCString());
1949c5011aedSJim Ingham         return false;
1950c5011aedSJim Ingham       }
1951c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1952c5011aedSJim Ingham       return true;
1953c5011aedSJim Ingham     }
1954c5011aedSJim Ingham 
1955c5011aedSJim Ingham     // We're adding this to a subcommand, first find the subcommand:
1956c5011aedSJim Ingham     Status path_error;
1957c5011aedSJim Ingham     CommandObjectMultiword *add_to_me =
1958c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
1959c5011aedSJim Ingham                                                            path_error);
1960c5011aedSJim Ingham 
1961c5011aedSJim Ingham     if (!add_to_me) {
1962c5011aedSJim Ingham       result.AppendErrorWithFormat("error adding command: %s",
1963c5011aedSJim Ingham                                    path_error.AsCString());
1964c5011aedSJim Ingham       return false;
1965c5011aedSJim Ingham     }
1966c5011aedSJim Ingham 
1967c5011aedSJim Ingham     const char *cmd_name = command.GetArgumentAtIndex(num_args - 1);
1968c5011aedSJim Ingham     auto cmd_sp = CommandObjectSP(new CommandObjectMultiword(
1969c5011aedSJim Ingham         GetCommandInterpreter(), cmd_name, m_options.m_short_help.c_str(),
1970c5011aedSJim Ingham         m_options.m_long_help.c_str()));
1971c5011aedSJim Ingham     llvm::Error llvm_error =
1972c5011aedSJim Ingham         add_to_me->LoadUserSubcommand(cmd_name, cmd_sp, m_options.m_overwrite);
1973c5011aedSJim Ingham     if (llvm_error) {
1974c5011aedSJim Ingham       result.AppendErrorWithFormat("error adding subcommand: %s",
1975c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
1976c5011aedSJim Ingham       return false;
1977c5011aedSJim Ingham     }
1978c5011aedSJim Ingham 
1979c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1980c5011aedSJim Ingham     return true;
1981c5011aedSJim Ingham   }
1982c5011aedSJim Ingham 
1983c5011aedSJim Ingham private:
1984c5011aedSJim Ingham   CommandOptions m_options;
1985c5011aedSJim Ingham };
1986c5011aedSJim Ingham 
1987c5011aedSJim Ingham #define LLDB_OPTIONS_multiword_delete
1988c5011aedSJim Ingham #include "CommandOptions.inc"
1989c5011aedSJim Ingham class CommandObjectCommandsContainerDelete : public CommandObjectParsed {
1990c5011aedSJim Ingham public:
1991c5011aedSJim Ingham   CommandObjectCommandsContainerDelete(CommandInterpreter &interpreter)
1992c5011aedSJim Ingham       : CommandObjectParsed(
1993c5011aedSJim Ingham             interpreter, "command container delete",
1994c5011aedSJim Ingham             "Delete a container command previously added to "
1995c5011aedSJim Ingham             "lldb.",
1996c5011aedSJim Ingham             "command container delete [[path1] ...] container-cmd") {
1997c5011aedSJim Ingham     CommandArgumentEntry arg1;
1998c5011aedSJim Ingham     CommandArgumentData cmd_arg;
1999c5011aedSJim Ingham 
2000c5011aedSJim Ingham     // This is one or more command names, which form the path to the command
2001c5011aedSJim Ingham     // you want to add.
2002c5011aedSJim Ingham     cmd_arg.arg_type = eArgTypeCommand;
2003c5011aedSJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlus;
2004c5011aedSJim Ingham 
2005c5011aedSJim Ingham     // There is only one variant this argument could be; put it into the
2006c5011aedSJim Ingham     // argument entry.
2007c5011aedSJim Ingham     arg1.push_back(cmd_arg);
2008c5011aedSJim Ingham 
2009c5011aedSJim Ingham     // Push the data for the first argument into the m_arguments vector.
2010c5011aedSJim Ingham     m_arguments.push_back(arg1);
2011c5011aedSJim Ingham   }
2012c5011aedSJim Ingham 
2013c5011aedSJim Ingham   ~CommandObjectCommandsContainerDelete() override = default;
2014c5011aedSJim Ingham 
2015c5011aedSJim Ingham   void
2016c5011aedSJim Ingham   HandleArgumentCompletion(CompletionRequest &request,
2017c5011aedSJim Ingham                            OptionElementVector &opt_element_vector) override {
2018c5011aedSJim Ingham     CommandCompletions::CompleteModifiableCmdPathArgs(m_interpreter, request,
2019c5011aedSJim Ingham                                                       opt_element_vector);
2020c5011aedSJim Ingham   }
2021c5011aedSJim Ingham 
2022c5011aedSJim Ingham protected:
2023c5011aedSJim Ingham   bool DoExecute(Args &command, CommandReturnObject &result) override {
2024c5011aedSJim Ingham     size_t num_args = command.GetArgumentCount();
2025c5011aedSJim Ingham 
2026c5011aedSJim Ingham     if (num_args == 0) {
2027c5011aedSJim Ingham       result.AppendError("No command was specified.");
2028c5011aedSJim Ingham       return false;
2029c5011aedSJim Ingham     }
2030c5011aedSJim Ingham 
2031c5011aedSJim Ingham     if (num_args == 1) {
2032c5011aedSJim Ingham       // We're removing a root command, so we need to delete it from the
2033c5011aedSJim Ingham       // interpreter.
2034c5011aedSJim Ingham       const char *cmd_name = command.GetArgumentAtIndex(0);
2035c5011aedSJim Ingham       // Let's do a little more work here so we can do better error reporting.
2036c5011aedSJim Ingham       CommandInterpreter &interp = GetCommandInterpreter();
2037c5011aedSJim Ingham       CommandObjectSP cmd_sp = interp.GetCommandSPExact(cmd_name);
2038c5011aedSJim Ingham       if (!cmd_sp) {
2039c5011aedSJim Ingham         result.AppendErrorWithFormat("container command %s doesn't exist.",
2040c5011aedSJim Ingham                                      cmd_name);
2041c5011aedSJim Ingham         return false;
2042c5011aedSJim Ingham       }
2043c5011aedSJim Ingham       if (!cmd_sp->IsUserCommand()) {
2044c5011aedSJim Ingham         result.AppendErrorWithFormat(
2045c5011aedSJim Ingham             "container command %s is not a user command", cmd_name);
2046c5011aedSJim Ingham         return false;
2047c5011aedSJim Ingham       }
2048c5011aedSJim Ingham       if (!cmd_sp->GetAsMultiwordCommand()) {
2049c5011aedSJim Ingham         result.AppendErrorWithFormat("command %s is not a container command",
2050c5011aedSJim Ingham                                      cmd_name);
2051c5011aedSJim Ingham         return false;
2052c5011aedSJim Ingham       }
2053c5011aedSJim Ingham 
2054c5011aedSJim Ingham       bool did_remove = GetCommandInterpreter().RemoveUserMultiword(cmd_name);
2055c5011aedSJim Ingham       if (!did_remove) {
2056c5011aedSJim Ingham         result.AppendErrorWithFormat("error removing command %s.", cmd_name);
2057c5011aedSJim Ingham         return false;
2058c5011aedSJim Ingham       }
2059c5011aedSJim Ingham 
2060c5011aedSJim Ingham       result.SetStatus(eReturnStatusSuccessFinishNoResult);
2061c5011aedSJim Ingham       return true;
2062c5011aedSJim Ingham     }
2063c5011aedSJim Ingham 
2064c5011aedSJim Ingham     // We're removing a subcommand, first find the subcommand's owner:
2065c5011aedSJim Ingham     Status path_error;
2066c5011aedSJim Ingham     CommandObjectMultiword *container =
2067c5011aedSJim Ingham         GetCommandInterpreter().VerifyUserMultiwordCmdPath(command, true,
2068c5011aedSJim Ingham                                                            path_error);
2069c5011aedSJim Ingham 
2070c5011aedSJim Ingham     if (!container) {
2071c5011aedSJim Ingham       result.AppendErrorWithFormat("error removing container command: %s",
2072c5011aedSJim Ingham                                    path_error.AsCString());
2073c5011aedSJim Ingham       return false;
2074c5011aedSJim Ingham     }
2075c5011aedSJim Ingham     const char *leaf = command.GetArgumentAtIndex(num_args - 1);
2076c5011aedSJim Ingham     llvm::Error llvm_error =
2077c5011aedSJim Ingham         container->RemoveUserSubcommand(leaf, /* multiword okay */ true);
2078c5011aedSJim Ingham     if (llvm_error) {
2079c5011aedSJim Ingham       result.AppendErrorWithFormat("error removing container command: %s",
2080c5011aedSJim Ingham                                    llvm::toString(std::move(llvm_error)).c_str());
2081c5011aedSJim Ingham       return false;
2082c5011aedSJim Ingham     }
2083c5011aedSJim Ingham     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2084c5011aedSJim Ingham     return true;
2085c5011aedSJim Ingham   }
2086c5011aedSJim Ingham };
2087c5011aedSJim Ingham 
2088c5011aedSJim Ingham class CommandObjectCommandContainer : public CommandObjectMultiword {
2089c5011aedSJim Ingham public:
2090c5011aedSJim Ingham   CommandObjectCommandContainer(CommandInterpreter &interpreter)
2091c5011aedSJim Ingham       : CommandObjectMultiword(
2092c5011aedSJim Ingham             interpreter, "command container",
2093c5011aedSJim Ingham             "Commands for adding container commands to lldb.  "
2094c5011aedSJim Ingham             "Container commands are containers for other commands.  You can "
20958ba14214SLuboš Luňák             "add nested container commands by specifying a command path, "
2096c5011aedSJim Ingham             "but you can't add commands into the built-in command hierarchy.",
2097c5011aedSJim Ingham             "command container <subcommand> [<subcommand-options>]") {
2098c5011aedSJim Ingham     LoadSubCommand("add", CommandObjectSP(new CommandObjectCommandsContainerAdd(
2099c5011aedSJim Ingham                               interpreter)));
2100c5011aedSJim Ingham     LoadSubCommand(
2101c5011aedSJim Ingham         "delete",
2102c5011aedSJim Ingham         CommandObjectSP(new CommandObjectCommandsContainerDelete(interpreter)));
2103c5011aedSJim Ingham   }
2104c5011aedSJim Ingham 
2105c5011aedSJim Ingham   ~CommandObjectCommandContainer() override = default;
2106c5011aedSJim Ingham };
2107c5011aedSJim Ingham 
2108ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
2109ebc09c36SJim Ingham 
2110ebc09c36SJim Ingham // CommandObjectMultiwordCommands
2111ebc09c36SJim Ingham 
2112b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
2113b9c1b51eSKate Stone     CommandInterpreter &interpreter)
2114b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
2115b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
2116b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
2117b9c1b51eSKate Stone   LoadSubCommand("source",
2118b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
2119b9c1b51eSKate Stone   LoadSubCommand("alias",
2120b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
2121b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
2122b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
2123b9c1b51eSKate Stone   LoadSubCommand("delete",
2124b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
2125c5011aedSJim Ingham   LoadSubCommand("container", CommandObjectSP(new CommandObjectCommandContainer(
2126c5011aedSJim Ingham                                   interpreter)));
2127b9c1b51eSKate Stone   LoadSubCommand(
2128b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
2129b9c1b51eSKate Stone   LoadSubCommand(
2130b9c1b51eSKate Stone       "script",
2131b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
2132ebc09c36SJim Ingham }
2133ebc09c36SJim Ingham 
21346e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
2135