1ebc09c36SJim Ingham //===-- CommandObjectSource.cpp ---------------------------------*- C++ -*-===//
2ebc09c36SJim Ingham //
3ebc09c36SJim Ingham //                     The LLVM Compiler Infrastructure
4ebc09c36SJim Ingham //
5ebc09c36SJim Ingham // This file is distributed under the University of Illinois Open Source
6ebc09c36SJim Ingham // License. See LICENSE.TXT for details.
7ebc09c36SJim Ingham //
8ebc09c36SJim Ingham //===----------------------------------------------------------------------===//
9ebc09c36SJim Ingham 
10ebc09c36SJim Ingham // C Includes
11ebc09c36SJim Ingham // C++ Includes
12ebc09c36SJim Ingham // Other libraries and framework includes
130e5e5a79SGreg Clayton #include "llvm/ADT/StringRef.h"
140e5e5a79SGreg Clayton 
15ebc09c36SJim Ingham // Project includes
166e3d8e7fSEugene Zelenko #include "CommandObjectCommands.h"
1746d4aa21SEnrico Granata #include "CommandObjectHelp.h"
18ebc09c36SJim Ingham #include "lldb/Core/Debugger.h"
1944d93782SGreg Clayton #include "lldb/Core/IOHandler.h"
20be93a35aSEnrico Granata #include "lldb/Core/StringList.h"
21de164aaaSGreg Clayton #include "lldb/Interpreter/Args.h"
227594f14fSEnrico Granata #include "lldb/Interpreter/CommandHistory.h"
23ebc09c36SJim Ingham #include "lldb/Interpreter/CommandInterpreter.h"
24de164aaaSGreg Clayton #include "lldb/Interpreter/CommandObjectRegexCommand.h"
25ebc09c36SJim Ingham #include "lldb/Interpreter/CommandReturnObject.h"
26012d4fcaSEnrico Granata #include "lldb/Interpreter/OptionValueBoolean.h"
2745d0e238SEnrico Granata #include "lldb/Interpreter/OptionValueString.h"
287594f14fSEnrico Granata #include "lldb/Interpreter/OptionValueUInt64.h"
29ebc09c36SJim Ingham #include "lldb/Interpreter/Options.h"
3099f0b8f9SEnrico Granata #include "lldb/Interpreter/ScriptInterpreter.h"
31ebc09c36SJim Ingham 
32ebc09c36SJim Ingham using namespace lldb;
33ebc09c36SJim Ingham using namespace lldb_private;
34ebc09c36SJim Ingham 
35ebc09c36SJim Ingham //-------------------------------------------------------------------------
36ebc09c36SJim Ingham // CommandObjectCommandsSource
37ebc09c36SJim Ingham //-------------------------------------------------------------------------
38ebc09c36SJim Ingham 
391f0f5b5bSZachary Turner static OptionDefinition g_history_options[] = {
401f0f5b5bSZachary Turner     // clang-format off
411f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "count",       'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "How many history commands to print." },
421f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "start-index", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to start printing history commands (or end to mean tail mode)." },
431f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "end-index",   'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Index at which to stop printing history commands." },
441f0f5b5bSZachary Turner   { LLDB_OPT_SET_2, false, "clear",       'C', OptionParser::eNoArgument,       nullptr, nullptr, 0, eArgTypeBoolean,         "Clears the current command history." },
451f0f5b5bSZachary Turner     // clang-format on
461f0f5b5bSZachary Turner };
471f0f5b5bSZachary Turner 
48b9c1b51eSKate Stone class CommandObjectCommandsHistory : public CommandObjectParsed {
495a988416SJim Ingham public:
50b9c1b51eSKate Stone   CommandObjectCommandsHistory(CommandInterpreter &interpreter)
51b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command history",
525a988416SJim Ingham                             "Dump the history of commands in this session.",
536e3d8e7fSEugene Zelenko                             nullptr),
54b9c1b51eSKate Stone         m_options() {}
555a988416SJim Ingham 
566e3d8e7fSEugene Zelenko   ~CommandObjectCommandsHistory() override = default;
575a988416SJim Ingham 
58b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
595a988416SJim Ingham 
605a988416SJim Ingham protected:
61b9c1b51eSKate Stone   class CommandOptions : public Options {
62a5a97ebeSJim Ingham   public:
63b9c1b51eSKate Stone     CommandOptions()
64b9c1b51eSKate Stone         : Options(), m_start_idx(0), m_stop_idx(0), m_count(0), m_clear(false) {
65a5a97ebeSJim Ingham     }
66a5a97ebeSJim Ingham 
676e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
68a5a97ebeSJim Ingham 
69b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
70b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
71a5a97ebeSJim Ingham       Error error;
723bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
738cef4b0bSZachary Turner       llvm::StringRef option_strref =
748cef4b0bSZachary Turner           llvm::StringRef::withNullAsEmpty(option_arg);
75a5a97ebeSJim Ingham 
76b9c1b51eSKate Stone       switch (short_option) {
77a5a97ebeSJim Ingham       case 'c':
788cef4b0bSZachary Turner         error =
798cef4b0bSZachary Turner             m_count.SetValueFromString(option_strref, eVarSetOperationAssign);
80a5a97ebeSJim Ingham         break;
81a5a97ebeSJim Ingham       case 's':
82b9c1b51eSKate Stone         if (option_arg && strcmp("end", option_arg) == 0) {
837594f14fSEnrico Granata           m_start_idx.SetCurrentValue(UINT64_MAX);
847594f14fSEnrico Granata           m_start_idx.SetOptionWasSet();
85b9c1b51eSKate Stone         } else
868cef4b0bSZachary Turner           error = m_start_idx.SetValueFromString(option_strref,
87b9c1b51eSKate Stone                                                  eVarSetOperationAssign);
887594f14fSEnrico Granata         break;
897594f14fSEnrico Granata       case 'e':
908cef4b0bSZachary Turner         error = m_stop_idx.SetValueFromString(option_strref,
918cef4b0bSZachary Turner                                               eVarSetOperationAssign);
927594f14fSEnrico Granata         break;
9363123b64SEnrico Granata       case 'C':
9463123b64SEnrico Granata         m_clear.SetCurrentValue(true);
9563123b64SEnrico Granata         m_clear.SetOptionWasSet();
96a5a97ebeSJim Ingham         break;
97a5a97ebeSJim Ingham       default:
98b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
99b9c1b51eSKate Stone                                        short_option);
100a5a97ebeSJim Ingham         break;
101a5a97ebeSJim Ingham       }
102a5a97ebeSJim Ingham 
103a5a97ebeSJim Ingham       return error;
104a5a97ebeSJim Ingham     }
105a5a97ebeSJim Ingham 
106b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1077594f14fSEnrico Granata       m_start_idx.Clear();
1087594f14fSEnrico Granata       m_stop_idx.Clear();
1097594f14fSEnrico Granata       m_count.Clear();
11063123b64SEnrico Granata       m_clear.Clear();
111a5a97ebeSJim Ingham     }
112a5a97ebeSJim Ingham 
1131f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
11470602439SZachary Turner       return llvm::makeArrayRef(g_history_options);
1151f0f5b5bSZachary Turner     }
116a5a97ebeSJim Ingham 
117a5a97ebeSJim Ingham     // Instance variables to hold the values for command options.
118a5a97ebeSJim Ingham 
1197594f14fSEnrico Granata     OptionValueUInt64 m_start_idx;
1207594f14fSEnrico Granata     OptionValueUInt64 m_stop_idx;
1217594f14fSEnrico Granata     OptionValueUInt64 m_count;
12263123b64SEnrico Granata     OptionValueBoolean m_clear;
123a5a97ebeSJim Ingham   };
124a5a97ebeSJim Ingham 
125b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
126b9c1b51eSKate Stone     if (m_options.m_clear.GetCurrentValue() &&
127b9c1b51eSKate Stone         m_options.m_clear.OptionWasSet()) {
1287594f14fSEnrico Granata       m_interpreter.GetCommandHistory().Clear();
1297594f14fSEnrico Granata       result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
130b9c1b51eSKate Stone     } else {
131b9c1b51eSKate Stone       if (m_options.m_start_idx.OptionWasSet() &&
132b9c1b51eSKate Stone           m_options.m_stop_idx.OptionWasSet() &&
133b9c1b51eSKate Stone           m_options.m_count.OptionWasSet()) {
134b9c1b51eSKate Stone         result.AppendError("--count, --start-index and --end-index cannot be "
135b9c1b51eSKate Stone                            "all specified in the same invocation");
1367594f14fSEnrico Granata         result.SetStatus(lldb::eReturnStatusFailed);
137b9c1b51eSKate Stone       } else {
138b9c1b51eSKate Stone         std::pair<bool, uint64_t> start_idx(
139b9c1b51eSKate Stone             m_options.m_start_idx.OptionWasSet(),
140b9c1b51eSKate Stone             m_options.m_start_idx.GetCurrentValue());
141b9c1b51eSKate Stone         std::pair<bool, uint64_t> stop_idx(
142b9c1b51eSKate Stone             m_options.m_stop_idx.OptionWasSet(),
143b9c1b51eSKate Stone             m_options.m_stop_idx.GetCurrentValue());
144b9c1b51eSKate Stone         std::pair<bool, uint64_t> count(m_options.m_count.OptionWasSet(),
145b9c1b51eSKate Stone                                         m_options.m_count.GetCurrentValue());
146a5a97ebeSJim Ingham 
1477594f14fSEnrico Granata         const CommandHistory &history(m_interpreter.GetCommandHistory());
1487594f14fSEnrico Granata 
149b9c1b51eSKate Stone         if (start_idx.first && start_idx.second == UINT64_MAX) {
150b9c1b51eSKate Stone           if (count.first) {
1517594f14fSEnrico Granata             start_idx.second = history.GetSize() - count.second;
1527594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
153b9c1b51eSKate Stone           } else if (stop_idx.first) {
1547594f14fSEnrico Granata             start_idx.second = stop_idx.second;
1557594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
156b9c1b51eSKate Stone           } else {
1577594f14fSEnrico Granata             start_idx.second = 0;
1587594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
1597594f14fSEnrico Granata           }
160b9c1b51eSKate Stone         } else {
161b9c1b51eSKate Stone           if (!start_idx.first && !stop_idx.first && !count.first) {
1627594f14fSEnrico Granata             start_idx.second = 0;
1637594f14fSEnrico Granata             stop_idx.second = history.GetSize() - 1;
164b9c1b51eSKate Stone           } else if (start_idx.first) {
165b9c1b51eSKate Stone             if (count.first) {
1667594f14fSEnrico Granata               stop_idx.second = start_idx.second + count.second - 1;
167b9c1b51eSKate Stone             } else if (!stop_idx.first) {
1687594f14fSEnrico Granata               stop_idx.second = history.GetSize() - 1;
1697594f14fSEnrico Granata             }
170b9c1b51eSKate Stone           } else if (stop_idx.first) {
171b9c1b51eSKate Stone             if (count.first) {
1727594f14fSEnrico Granata               if (stop_idx.second >= count.second)
1737594f14fSEnrico Granata                 start_idx.second = stop_idx.second - count.second + 1;
1747594f14fSEnrico Granata               else
1757594f14fSEnrico Granata                 start_idx.second = 0;
1767594f14fSEnrico Granata             }
177b9c1b51eSKate Stone           } else /* if (count.first) */
1787594f14fSEnrico Granata           {
1797594f14fSEnrico Granata             start_idx.second = 0;
1807594f14fSEnrico Granata             stop_idx.second = count.second - 1;
1817594f14fSEnrico Granata           }
1827594f14fSEnrico Granata         }
183b9c1b51eSKate Stone         history.Dump(result.GetOutputStream(), start_idx.second,
184b9c1b51eSKate Stone                      stop_idx.second);
1857594f14fSEnrico Granata       }
1867594f14fSEnrico Granata     }
187a5a97ebeSJim Ingham     return result.Succeeded();
188a5a97ebeSJim Ingham   }
1895a988416SJim Ingham 
1905a988416SJim Ingham   CommandOptions m_options;
191a5a97ebeSJim Ingham };
192a5a97ebeSJim Ingham 
193a5a97ebeSJim Ingham //-------------------------------------------------------------------------
194a5a97ebeSJim Ingham // CommandObjectCommandsSource
195a5a97ebeSJim Ingham //-------------------------------------------------------------------------
196a5a97ebeSJim Ingham 
1971f0f5b5bSZachary Turner static OptionDefinition g_source_options[] = {
1981f0f5b5bSZachary Turner     // clang-format off
1991f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-error",    'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on error." },
2001f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "stop-on-continue", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true, stop executing commands on continue." },
2011f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "silent-run",       's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "If true don't echo commands while executing." },
2021f0f5b5bSZachary Turner     // clang-format on
2031f0f5b5bSZachary Turner };
2041f0f5b5bSZachary Turner 
205b9c1b51eSKate Stone class CommandObjectCommandsSource : public CommandObjectParsed {
2065a988416SJim Ingham public:
2077428a18cSKate Stone   CommandObjectCommandsSource(CommandInterpreter &interpreter)
208b9c1b51eSKate Stone       : CommandObjectParsed(
209b9c1b51eSKate Stone             interpreter, "command source",
210b9c1b51eSKate Stone             "Read and execute LLDB commands from the file <filename>.",
2116e3d8e7fSEugene Zelenko             nullptr),
212b9c1b51eSKate Stone         m_options() {
2135a988416SJim Ingham     CommandArgumentEntry arg;
2145a988416SJim Ingham     CommandArgumentData file_arg;
2155a988416SJim Ingham 
2165a988416SJim Ingham     // Define the first (and only) variant of this arg.
2175a988416SJim Ingham     file_arg.arg_type = eArgTypeFilename;
2185a988416SJim Ingham     file_arg.arg_repetition = eArgRepeatPlain;
2195a988416SJim Ingham 
220b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
221b9c1b51eSKate Stone     // argument entry.
2225a988416SJim Ingham     arg.push_back(file_arg);
2235a988416SJim Ingham 
2245a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
2255a988416SJim Ingham     m_arguments.push_back(arg);
2265a988416SJim Ingham   }
2275a988416SJim Ingham 
2286e3d8e7fSEugene Zelenko   ~CommandObjectCommandsSource() override = default;
2295a988416SJim Ingham 
230b9c1b51eSKate Stone   const char *GetRepeatCommand(Args &current_command_args,
231b9c1b51eSKate Stone                                uint32_t index) override {
2325a988416SJim Ingham     return "";
2335a988416SJim Ingham   }
2345a988416SJim Ingham 
235b9c1b51eSKate Stone   int HandleArgumentCompletion(Args &input, int &cursor_index,
2365a988416SJim Ingham                                int &cursor_char_position,
2375a988416SJim Ingham                                OptionElementVector &opt_element_vector,
238b9c1b51eSKate Stone                                int match_start_point, int max_return_elements,
2395a988416SJim Ingham                                bool &word_complete,
240b9c1b51eSKate Stone                                StringList &matches) override {
2415a988416SJim Ingham     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
2425a988416SJim Ingham     completion_str.erase(cursor_char_position);
2435a988416SJim Ingham 
244b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
245b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
246b9c1b51eSKate Stone         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
247b9c1b51eSKate Stone         word_complete, matches);
2485a988416SJim Ingham     return matches.GetSize();
2495a988416SJim Ingham   }
2505a988416SJim Ingham 
251b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
2525a988416SJim Ingham 
2535a988416SJim Ingham protected:
254b9c1b51eSKate Stone   class CommandOptions : public Options {
255e16c50a1SJim Ingham   public:
256b9c1b51eSKate Stone     CommandOptions()
257b9c1b51eSKate Stone         : Options(), m_stop_on_error(true), m_silent_run(false),
258b9c1b51eSKate Stone           m_stop_on_continue(true) {}
259e16c50a1SJim Ingham 
2606e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
261e16c50a1SJim Ingham 
262b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
263b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
264e16c50a1SJim Ingham       Error error;
2653bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
2668cef4b0bSZachary Turner       llvm::StringRef option_strref =
2678cef4b0bSZachary Turner           llvm::StringRef::withNullAsEmpty(option_arg);
268e16c50a1SJim Ingham 
269b9c1b51eSKate Stone       switch (short_option) {
270e16c50a1SJim Ingham       case 'e':
2718cef4b0bSZachary Turner         error = m_stop_on_error.SetValueFromString(option_strref);
272e16c50a1SJim Ingham         break;
273340b0309SGreg Clayton 
274e16c50a1SJim Ingham       case 'c':
2758cef4b0bSZachary Turner         error = m_stop_on_continue.SetValueFromString(option_strref);
276e16c50a1SJim Ingham         break;
277340b0309SGreg Clayton 
27860986174SMichael Sartain       case 's':
2798cef4b0bSZachary Turner         error = m_silent_run.SetValueFromString(option_strref);
28060986174SMichael Sartain         break;
281340b0309SGreg Clayton 
282e16c50a1SJim Ingham       default:
283b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
284b9c1b51eSKate Stone                                        short_option);
285e16c50a1SJim Ingham         break;
286e16c50a1SJim Ingham       }
287e16c50a1SJim Ingham 
288e16c50a1SJim Ingham       return error;
289e16c50a1SJim Ingham     }
290e16c50a1SJim Ingham 
291b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
292012d4fcaSEnrico Granata       m_stop_on_error.Clear();
293340b0309SGreg Clayton       m_silent_run.Clear();
294340b0309SGreg Clayton       m_stop_on_continue.Clear();
295e16c50a1SJim Ingham     }
296e16c50a1SJim Ingham 
2971f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
29870602439SZachary Turner       return llvm::makeArrayRef(g_source_options);
2991f0f5b5bSZachary Turner     }
300e16c50a1SJim Ingham 
301e16c50a1SJim Ingham     // Instance variables to hold the values for command options.
302e16c50a1SJim Ingham 
303012d4fcaSEnrico Granata     OptionValueBoolean m_stop_on_error;
304340b0309SGreg Clayton     OptionValueBoolean m_silent_run;
305340b0309SGreg Clayton     OptionValueBoolean m_stop_on_continue;
306e16c50a1SJim Ingham   };
307e16c50a1SJim Ingham 
308b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
30911eb9c64SZachary Turner     if (command.GetArgumentCount() == 1) {
31011eb9c64SZachary Turner       llvm::StringRef filename = command.GetArgumentAtIndex(0);
311ebc09c36SJim Ingham 
3121ee3853fSJohnny Chen       FileSpec cmd_file(filename, true);
3136e3d8e7fSEugene Zelenko       ExecutionContext *exe_ctx = nullptr; // Just use the default context.
314ebc09c36SJim Ingham 
315340b0309SGreg Clayton       // If any options were set, then use them
316340b0309SGreg Clayton       if (m_options.m_stop_on_error.OptionWasSet() ||
317340b0309SGreg Clayton           m_options.m_silent_run.OptionWasSet() ||
318b9c1b51eSKate Stone           m_options.m_stop_on_continue.OptionWasSet()) {
319340b0309SGreg Clayton         // Use user set settings
32026c7bf93SJim Ingham         CommandInterpreterRunOptions options;
321b9c1b51eSKate Stone         options.SetStopOnContinue(
322b9c1b51eSKate Stone             m_options.m_stop_on_continue.GetCurrentValue());
32326c7bf93SJim Ingham         options.SetStopOnError(m_options.m_stop_on_error.GetCurrentValue());
3247d8555c4SJim Ingham         options.SetEchoCommands(!m_options.m_silent_run.GetCurrentValue());
3257d8555c4SJim Ingham         options.SetPrintResults(!m_options.m_silent_run.GetCurrentValue());
32626c7bf93SJim Ingham 
327b9c1b51eSKate Stone         m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options,
328e16c50a1SJim Ingham                                              result);
329b9c1b51eSKate Stone       } else {
330b9c1b51eSKate Stone         // No options were set, inherit any settings from nested "command
331b9c1b51eSKate Stone         // source" commands,
332340b0309SGreg Clayton         // or set to sane default settings...
33326c7bf93SJim Ingham         CommandInterpreterRunOptions options;
334b9c1b51eSKate Stone         m_interpreter.HandleCommandsFromFile(cmd_file, exe_ctx, options,
335340b0309SGreg Clayton                                              result);
336340b0309SGreg Clayton       }
337b9c1b51eSKate Stone     } else {
338b9c1b51eSKate Stone       result.AppendErrorWithFormat(
339b9c1b51eSKate Stone           "'%s' takes exactly one executable filename argument.\n",
340a449698cSZachary Turner           GetCommandName().str().c_str());
341ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
342ebc09c36SJim Ingham     }
343ebc09c36SJim Ingham     return result.Succeeded();
344ebc09c36SJim Ingham   }
3456e3d8e7fSEugene Zelenko 
3465a988416SJim Ingham   CommandOptions m_options;
347ebc09c36SJim Ingham };
348ebc09c36SJim Ingham 
349ebc09c36SJim Ingham #pragma mark CommandObjectCommandsAlias
350ebc09c36SJim Ingham //-------------------------------------------------------------------------
351ebc09c36SJim Ingham // CommandObjectCommandsAlias
352ebc09c36SJim Ingham //-------------------------------------------------------------------------
353ebc09c36SJim Ingham 
3541f0f5b5bSZachary Turner static OptionDefinition g_alias_options[] = {
3551f0f5b5bSZachary Turner     // clang-format off
3561f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "help",      'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Help text for this command" },
3571f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "long-help", 'H', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeHelpText, "Long help text for this command" },
3581f0f5b5bSZachary Turner     // clang-format on
3591f0f5b5bSZachary Turner };
3601f0f5b5bSZachary Turner 
361b9c1b51eSKate Stone static const char *g_python_command_instructions =
362b9c1b51eSKate Stone     "Enter your Python command(s). Type 'DONE' to end.\n"
363be93a35aSEnrico Granata     "You must define a Python function with this signature:\n"
36444d93782SGreg Clayton     "def my_command_impl(debugger, args, result, internal_dict):\n";
365be93a35aSEnrico Granata 
366b9c1b51eSKate Stone class CommandObjectCommandsAlias : public CommandObjectRaw {
36745d0e238SEnrico Granata protected:
368b9c1b51eSKate Stone   class CommandOptions : public OptionGroup {
369ebc09c36SJim Ingham   public:
370b9c1b51eSKate Stone     CommandOptions() : OptionGroup(), m_help(), m_long_help() {}
37145d0e238SEnrico Granata 
37245d0e238SEnrico Granata     ~CommandOptions() override = default;
37345d0e238SEnrico Granata 
3741f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
37570602439SZachary Turner       return llvm::makeArrayRef(g_alias_options);
3761f0f5b5bSZachary Turner     }
37745d0e238SEnrico Granata 
3788cef4b0bSZachary Turner     Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
379b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
38045d0e238SEnrico Granata       Error error;
38145d0e238SEnrico Granata 
3821f0f5b5bSZachary Turner       const int short_option = GetDefinitions()[option_idx].short_option;
3838cef4b0bSZachary Turner       std::string option_str(option_value);
38445d0e238SEnrico Granata 
385b9c1b51eSKate Stone       switch (short_option) {
38645d0e238SEnrico Granata       case 'h':
3878cef4b0bSZachary Turner         m_help.SetCurrentValue(option_str);
38845d0e238SEnrico Granata         m_help.SetOptionWasSet();
38945d0e238SEnrico Granata         break;
39045d0e238SEnrico Granata 
39145d0e238SEnrico Granata       case 'H':
3928cef4b0bSZachary Turner         m_long_help.SetCurrentValue(option_str);
39345d0e238SEnrico Granata         m_long_help.SetOptionWasSet();
39445d0e238SEnrico Granata         break;
39545d0e238SEnrico Granata 
39645d0e238SEnrico Granata       default:
397b9c1b51eSKate Stone         error.SetErrorStringWithFormat("invalid short option character '%c'",
398b9c1b51eSKate Stone                                        short_option);
39945d0e238SEnrico Granata         break;
40045d0e238SEnrico Granata       }
40145d0e238SEnrico Granata 
40245d0e238SEnrico Granata       return error;
40345d0e238SEnrico Granata     }
4048cef4b0bSZachary Turner     Error SetOptionValue(uint32_t, const char *, ExecutionContext *) = delete;
40545d0e238SEnrico Granata 
406b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
40745d0e238SEnrico Granata       m_help.Clear();
40845d0e238SEnrico Granata       m_long_help.Clear();
40945d0e238SEnrico Granata     }
41045d0e238SEnrico Granata 
41145d0e238SEnrico Granata     OptionValueString m_help;
41245d0e238SEnrico Granata     OptionValueString m_long_help;
41345d0e238SEnrico Granata   };
41445d0e238SEnrico Granata 
41545d0e238SEnrico Granata   OptionGroupOptions m_option_group;
41645d0e238SEnrico Granata   CommandOptions m_command_options;
41745d0e238SEnrico Granata 
41845d0e238SEnrico Granata public:
419b9c1b51eSKate Stone   Options *GetOptions() override { return &m_option_group; }
42045d0e238SEnrico Granata 
4217428a18cSKate Stone   CommandObjectCommandsAlias(CommandInterpreter &interpreter)
422b9c1b51eSKate Stone       : CommandObjectRaw(
423b9c1b51eSKate Stone             interpreter, "command alias",
424a449698cSZachary Turner             "Define a custom command in terms of an existing command."),
425b9c1b51eSKate Stone         m_option_group(), m_command_options() {
42645d0e238SEnrico Granata     m_option_group.Append(&m_command_options);
42745d0e238SEnrico Granata     m_option_group.Finalize();
42845d0e238SEnrico Granata 
429ebc09c36SJim Ingham     SetHelpLong(
430ea671fbdSKate Stone         "'alias' allows the user to create a short-cut or abbreviation for long \
431ea671fbdSKate Stone commands, multi-word commands, and commands that take particular options.  \
432b9c1b51eSKate Stone Below are some simple examples of how one might use the 'alias' command:"
433b9c1b51eSKate Stone         R"(
434ea671fbdSKate Stone 
435ea671fbdSKate Stone (lldb) command alias sc script
436ea671fbdSKate Stone 
437ea671fbdSKate Stone     Creates the abbreviation 'sc' for the 'script' command.
438ea671fbdSKate Stone 
439ea671fbdSKate Stone (lldb) command alias bp breakpoint
440ea671fbdSKate Stone 
441b9c1b51eSKate Stone )"
442b9c1b51eSKate Stone         "    Creates the abbreviation 'bp' for the 'breakpoint' command.  Since \
443ea671fbdSKate Stone breakpoint commands are two-word commands, the user would still need to \
444b9c1b51eSKate Stone enter the second word after 'bp', e.g. 'bp enable' or 'bp delete'."
445b9c1b51eSKate Stone         R"(
446ea671fbdSKate Stone 
447ea671fbdSKate Stone (lldb) command alias bpl breakpoint list
448ea671fbdSKate Stone 
449ea671fbdSKate Stone     Creates the abbreviation 'bpl' for the two-word command 'breakpoint list'.
450ea671fbdSKate Stone 
451b9c1b51eSKate Stone )"
452b9c1b51eSKate Stone         "An alias can include some options for the command, with the values either \
453ea671fbdSKate Stone filled in at the time the alias is created, or specified as positional \
454ea671fbdSKate Stone arguments, to be filled in when the alias is invoked.  The following example \
455b9c1b51eSKate Stone shows how to create aliases with options:"
456b9c1b51eSKate Stone         R"(
457ea671fbdSKate Stone 
458ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
459ea671fbdSKate Stone 
460b9c1b51eSKate Stone )"
461b9c1b51eSKate Stone         "    Creates the abbreviation 'bfl' (for break-file-line), with the -f and -l \
462ea671fbdSKate Stone options already part of the alias.  So if the user wants to set a breakpoint \
463ea671fbdSKate Stone by file and line without explicitly having to use the -f and -l options, the \
464ea671fbdSKate Stone user can now use 'bfl' instead.  The '%1' and '%2' are positional placeholders \
465ea671fbdSKate Stone for the actual arguments that will be passed when the alias command is used.  \
466ea671fbdSKate Stone The number in the placeholder refers to the position/order the actual value \
467ea671fbdSKate Stone occupies when the alias is used.  All the occurrences of '%1' in the alias \
468ea671fbdSKate Stone will be replaced with the first argument, all the occurrences of '%2' in the \
469ea671fbdSKate Stone alias will be replaced with the second argument, and so on.  This also allows \
470ea671fbdSKate Stone actual arguments to be used multiple times within an alias (see 'process \
471b9c1b51eSKate Stone launch' example below)."
472b9c1b51eSKate Stone         R"(
473ea671fbdSKate Stone 
474b9c1b51eSKate Stone )"
475b9c1b51eSKate Stone         "Note: the positional arguments must substitute as whole words in the resultant \
476ea671fbdSKate Stone command, so you can't at present do something like this to append the file extension \
477b9c1b51eSKate Stone \".cpp\":"
478b9c1b51eSKate Stone         R"(
479ea671fbdSKate Stone 
480ea671fbdSKate Stone (lldb) command alias bcppfl breakpoint set -f %1.cpp -l %2
481ea671fbdSKate Stone 
482b9c1b51eSKate Stone )"
483b9c1b51eSKate Stone         "For more complex aliasing, use the \"command regex\" command instead.  In the \
484ea671fbdSKate Stone 'bfl' case above, the actual file value will be filled in with the first argument \
485ea671fbdSKate Stone following 'bfl' and the actual line number value will be filled in with the second \
486b9c1b51eSKate Stone argument.  The user would use this alias as follows:"
487b9c1b51eSKate Stone         R"(
488ea671fbdSKate Stone 
489ea671fbdSKate Stone (lldb) command alias bfl breakpoint set -f %1 -l %2
490ea671fbdSKate Stone (lldb) bfl my-file.c 137
491ea671fbdSKate Stone 
492ea671fbdSKate Stone This would be the same as if the user had entered 'breakpoint set -f my-file.c -l 137'.
493ea671fbdSKate Stone 
494ea671fbdSKate Stone Another example:
495ea671fbdSKate Stone 
496ea671fbdSKate Stone (lldb) command alias pltty process launch -s -o %1 -e %1
497ea671fbdSKate Stone (lldb) pltty /dev/tty0
498ea671fbdSKate Stone 
499ea671fbdSKate Stone     Interpreted as 'process launch -s -o /dev/tty0 -e /dev/tty0'
500ea671fbdSKate Stone 
501b9c1b51eSKate Stone )"
502b9c1b51eSKate Stone         "If the user always wanted to pass the same value to a particular option, the \
503ea671fbdSKate Stone alias could be defined with that value directly in the alias as a constant, \
504b9c1b51eSKate Stone rather than using a positional placeholder:"
505b9c1b51eSKate Stone         R"(
506ea671fbdSKate Stone 
507ea671fbdSKate Stone (lldb) command alias bl3 breakpoint set -f %1 -l 3
508ea671fbdSKate Stone 
509b9c1b51eSKate Stone     Always sets a breakpoint on line 3 of whatever file is indicated.)");
510ebc09c36SJim Ingham 
511405fe67fSCaroline Tice     CommandArgumentEntry arg1;
512405fe67fSCaroline Tice     CommandArgumentEntry arg2;
513405fe67fSCaroline Tice     CommandArgumentEntry arg3;
514405fe67fSCaroline Tice     CommandArgumentData alias_arg;
515405fe67fSCaroline Tice     CommandArgumentData cmd_arg;
516405fe67fSCaroline Tice     CommandArgumentData options_arg;
517405fe67fSCaroline Tice 
518405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
519405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
520405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
521405fe67fSCaroline Tice 
522b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
523b9c1b51eSKate Stone     // argument entry.
524405fe67fSCaroline Tice     arg1.push_back(alias_arg);
525405fe67fSCaroline Tice 
526405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
527405fe67fSCaroline Tice     cmd_arg.arg_type = eArgTypeCommandName;
528405fe67fSCaroline Tice     cmd_arg.arg_repetition = eArgRepeatPlain;
529405fe67fSCaroline Tice 
530b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
531b9c1b51eSKate Stone     // argument entry.
532405fe67fSCaroline Tice     arg2.push_back(cmd_arg);
533405fe67fSCaroline Tice 
534405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
535405fe67fSCaroline Tice     options_arg.arg_type = eArgTypeAliasOptions;
536405fe67fSCaroline Tice     options_arg.arg_repetition = eArgRepeatOptional;
537405fe67fSCaroline Tice 
538b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
539b9c1b51eSKate Stone     // argument entry.
540405fe67fSCaroline Tice     arg3.push_back(options_arg);
541405fe67fSCaroline Tice 
542405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
543405fe67fSCaroline Tice     m_arguments.push_back(arg1);
544405fe67fSCaroline Tice     m_arguments.push_back(arg2);
545405fe67fSCaroline Tice     m_arguments.push_back(arg3);
546ebc09c36SJim Ingham   }
547ebc09c36SJim Ingham 
5486e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAlias() override = default;
549ebc09c36SJim Ingham 
5505a988416SJim Ingham protected:
551b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
552b9c1b51eSKate Stone                  CommandReturnObject &result) override {
553b9c1b51eSKate Stone     if (!raw_command_line || !raw_command_line[0]) {
554d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
55545d0e238SEnrico Granata       return false;
55645d0e238SEnrico Granata     }
55745d0e238SEnrico Granata 
558e1cfbc79STodd Fiala     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
559e1cfbc79STodd Fiala     m_option_group.NotifyOptionParsingStarting(&exe_ctx);
56045d0e238SEnrico Granata 
56145d0e238SEnrico Granata     const char *remainder = nullptr;
56245d0e238SEnrico Granata 
563b9c1b51eSKate Stone     if (raw_command_line[0] == '-') {
56445d0e238SEnrico Granata       // We have some options and these options MUST end with --.
56545d0e238SEnrico Granata       const char *end_options = nullptr;
56645d0e238SEnrico Granata       const char *s = raw_command_line;
567b9c1b51eSKate Stone       while (s && s[0]) {
56845d0e238SEnrico Granata         end_options = ::strstr(s, "--");
569b9c1b51eSKate Stone         if (end_options) {
57045d0e238SEnrico Granata           end_options += 2; // Get past the "--"
571b9c1b51eSKate Stone           if (::isspace(end_options[0])) {
57245d0e238SEnrico Granata             remainder = end_options;
57345d0e238SEnrico Granata             while (::isspace(*remainder))
57445d0e238SEnrico Granata               ++remainder;
57545d0e238SEnrico Granata             break;
57645d0e238SEnrico Granata           }
57745d0e238SEnrico Granata         }
57845d0e238SEnrico Granata         s = end_options;
57945d0e238SEnrico Granata       }
58045d0e238SEnrico Granata 
581b9c1b51eSKate Stone       if (end_options) {
582b9c1b51eSKate Stone         Args args(
583b9c1b51eSKate Stone             llvm::StringRef(raw_command_line, end_options - raw_command_line));
58445d0e238SEnrico Granata         if (!ParseOptions(args, result))
58545d0e238SEnrico Granata           return false;
58645d0e238SEnrico Granata 
587e1cfbc79STodd Fiala         Error error(m_option_group.NotifyOptionParsingFinished(&exe_ctx));
588b9c1b51eSKate Stone         if (error.Fail()) {
58945d0e238SEnrico Granata           result.AppendError(error.AsCString());
59045d0e238SEnrico Granata           result.SetStatus(eReturnStatusFailed);
59145d0e238SEnrico Granata           return false;
59245d0e238SEnrico Granata         }
59345d0e238SEnrico Granata       }
59445d0e238SEnrico Granata     }
59545d0e238SEnrico Granata     if (nullptr == remainder)
59645d0e238SEnrico Granata       remainder = raw_command_line;
59745d0e238SEnrico Granata 
598a01bccdbSZachary Turner     llvm::StringRef raw_command_string(remainder);
599a01bccdbSZachary Turner     Args args(raw_command_string);
600844d2303SCaroline Tice 
60111eb9c64SZachary Turner     if (args.GetArgumentCount() < 2) {
602d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
603844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
604844d2303SCaroline Tice       return false;
605844d2303SCaroline Tice     }
606844d2303SCaroline Tice 
607844d2303SCaroline Tice     // Get the alias command.
608844d2303SCaroline Tice 
60911eb9c64SZachary Turner     // TODO: Convert this function to use StringRef.  Requires converting
61011eb9c64SZachary Turner     // GetCommandObjectForCommand.
611844d2303SCaroline Tice     const std::string alias_command = args.GetArgumentAtIndex(0);
612b9c1b51eSKate Stone     if (alias_command.size() > 1 && alias_command[0] == '-') {
613d72e412fSEnrico Granata       result.AppendError("aliases starting with a dash are not supported");
614b9c1b51eSKate Stone       if (alias_command == "--help" || alias_command == "--long-help") {
615b9c1b51eSKate Stone         result.AppendWarning("if trying to pass options to 'command alias' add "
616b9c1b51eSKate Stone                              "a -- at the end of the options");
617d72e412fSEnrico Granata       }
618d72e412fSEnrico Granata       result.SetStatus(eReturnStatusFailed);
619d72e412fSEnrico Granata       return false;
620d72e412fSEnrico Granata     }
621844d2303SCaroline Tice 
622b9c1b51eSKate Stone     // Strip the new alias name off 'raw_command_string'  (leave it on args,
623b9c1b51eSKate Stone     // which gets passed to 'Execute', which
624844d2303SCaroline Tice     // does the stripping itself.
625844d2303SCaroline Tice     size_t pos = raw_command_string.find(alias_command);
626b9c1b51eSKate Stone     if (pos == 0) {
627844d2303SCaroline Tice       raw_command_string = raw_command_string.substr(alias_command.size());
628844d2303SCaroline Tice       pos = raw_command_string.find_first_not_of(' ');
629844d2303SCaroline Tice       if ((pos != std::string::npos) && (pos > 0))
630844d2303SCaroline Tice         raw_command_string = raw_command_string.substr(pos);
631b9c1b51eSKate Stone     } else {
632844d2303SCaroline Tice       result.AppendError("Error parsing command string.  No alias created.");
633844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
634844d2303SCaroline Tice       return false;
635844d2303SCaroline Tice     }
636844d2303SCaroline Tice 
637844d2303SCaroline Tice     // Verify that the command is alias-able.
638b9c1b51eSKate Stone     if (m_interpreter.CommandExists(alias_command.c_str())) {
639b9c1b51eSKate Stone       result.AppendErrorWithFormat(
640b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
641844d2303SCaroline Tice           alias_command.c_str());
642844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
643844d2303SCaroline Tice       return false;
644844d2303SCaroline Tice     }
645844d2303SCaroline Tice 
646b9c1b51eSKate Stone     // Get CommandObject that is being aliased. The command name is read from
647a01bccdbSZachary Turner     // the front of raw_command_string. raw_command_string is returned with the
648a01bccdbSZachary Turner     // name of the command object stripped off the front.
649a01bccdbSZachary Turner     llvm::StringRef original_raw_command_string = raw_command_string;
650b9c1b51eSKate Stone     CommandObject *cmd_obj =
651b9c1b51eSKate Stone         m_interpreter.GetCommandObjectForCommand(raw_command_string);
652844d2303SCaroline Tice 
653b9c1b51eSKate Stone     if (!cmd_obj) {
654b9c1b51eSKate Stone       result.AppendErrorWithFormat("invalid command given to 'command alias'. "
655b9c1b51eSKate Stone                                    "'%s' does not begin with a valid command."
656b9c1b51eSKate Stone                                    "  No alias created.",
657a01bccdbSZachary Turner                                    original_raw_command_string.str().c_str());
658844d2303SCaroline Tice       result.SetStatus(eReturnStatusFailed);
659844d2303SCaroline Tice       return false;
660b9c1b51eSKate Stone     } else if (!cmd_obj->WantsRawCommandString()) {
661b9c1b51eSKate Stone       // Note that args was initialized with the original command, and has not
662b9c1b51eSKate Stone       // been updated to this point.
663b9c1b51eSKate Stone       // Therefore can we pass it to the version of Execute that does not
664b9c1b51eSKate Stone       // need/expect raw input in the alias.
6655a988416SJim Ingham       return HandleAliasingNormalCommand(args, result);
666b9c1b51eSKate Stone     } else {
667b9c1b51eSKate Stone       return HandleAliasingRawCommand(alias_command, raw_command_string,
668b9c1b51eSKate Stone                                       *cmd_obj, result);
6695a988416SJim Ingham     }
6705a988416SJim Ingham     return result.Succeeded();
6715a988416SJim Ingham   }
6725a988416SJim Ingham 
673a01bccdbSZachary Turner   bool HandleAliasingRawCommand(llvm::StringRef alias_command,
674a01bccdbSZachary Turner                                 llvm::StringRef raw_command_string,
675b9c1b51eSKate Stone                                 CommandObject &cmd_obj,
676b9c1b51eSKate Stone                                 CommandReturnObject &result) {
677844d2303SCaroline Tice     // Verify & handle any options/arguments passed to the alias command
678844d2303SCaroline Tice 
679b9c1b51eSKate Stone     OptionArgVectorSP option_arg_vector_sp =
680b9c1b51eSKate Stone         OptionArgVectorSP(new OptionArgVector);
681844d2303SCaroline Tice 
682b9c1b51eSKate Stone     if (CommandObjectSP cmd_obj_sp =
683b9c1b51eSKate Stone             m_interpreter.GetCommandSPExact(cmd_obj.GetCommandName(), false)) {
684a01bccdbSZachary Turner       if (m_interpreter.AliasExists(alias_command) ||
685a01bccdbSZachary Turner           m_interpreter.UserCommandExists(alias_command)) {
686b9c1b51eSKate Stone         result.AppendWarningWithFormat(
687b9c1b51eSKate Stone             "Overwriting existing definition for '%s'.\n",
688a01bccdbSZachary Turner             alias_command.str().c_str());
689844d2303SCaroline Tice       }
690b9c1b51eSKate Stone       if (CommandAlias *alias = m_interpreter.AddAlias(
691a01bccdbSZachary Turner               alias_command, cmd_obj_sp, raw_command_string)) {
69245d0e238SEnrico Granata         if (m_command_options.m_help.OptionWasSet())
69345d0e238SEnrico Granata           alias->SetHelp(m_command_options.m_help.GetCurrentValue());
69445d0e238SEnrico Granata         if (m_command_options.m_long_help.OptionWasSet())
69545d0e238SEnrico Granata           alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
696844d2303SCaroline Tice         result.SetStatus(eReturnStatusSuccessFinishNoResult);
697b9c1b51eSKate Stone       } else {
698472362e6SCaroline Tice         result.AppendError("Unable to create requested alias.\n");
699472362e6SCaroline Tice         result.SetStatus(eReturnStatusFailed);
700472362e6SCaroline Tice       }
701212130acSEnrico Granata 
702b9c1b51eSKate Stone     } else {
703212130acSEnrico Granata       result.AppendError("Unable to create requested alias.\n");
704212130acSEnrico Granata       result.SetStatus(eReturnStatusFailed);
705212130acSEnrico Granata     }
706212130acSEnrico Granata 
707844d2303SCaroline Tice     return result.Succeeded();
708844d2303SCaroline Tice   }
709ebc09c36SJim Ingham 
710b9c1b51eSKate Stone   bool HandleAliasingNormalCommand(Args &args, CommandReturnObject &result) {
711867b185dSCaroline Tice     size_t argc = args.GetArgumentCount();
712ebc09c36SJim Ingham 
713b9c1b51eSKate Stone     if (argc < 2) {
714d72e412fSEnrico Granata       result.AppendError("'command alias' requires at least two arguments");
715ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
716ebc09c36SJim Ingham       return false;
717ebc09c36SJim Ingham     }
718ebc09c36SJim Ingham 
71911eb9c64SZachary Turner     // TODO: Convert these to StringRefs.  Should convert other dependent
72011eb9c64SZachary Turner     // functions (CommandExists, UserCommandExists, AliasExists, AddAlias,
72111eb9c64SZachary Turner     // etc at the same time.
722ebc09c36SJim Ingham     const std::string alias_command = args.GetArgumentAtIndex(0);
723ebc09c36SJim Ingham     const std::string actual_command = args.GetArgumentAtIndex(1);
724ebc09c36SJim Ingham 
725ebc09c36SJim Ingham     args.Shift(); // Shift the alias command word off the argument vector.
726ebc09c36SJim Ingham     args.Shift(); // Shift the old command word off the argument vector.
727ebc09c36SJim Ingham 
728b9c1b51eSKate Stone     // Verify that the command is alias'able, and get the appropriate command
729b9c1b51eSKate Stone     // object.
730ebc09c36SJim Ingham 
731b9c1b51eSKate Stone     if (m_interpreter.CommandExists(alias_command.c_str())) {
732b9c1b51eSKate Stone       result.AppendErrorWithFormat(
733b9c1b51eSKate Stone           "'%s' is a permanent debugger command and cannot be redefined.\n",
734ebc09c36SJim Ingham           alias_command.c_str());
735ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
736b9c1b51eSKate Stone     } else {
737b9c1b51eSKate Stone       CommandObjectSP command_obj_sp(
738a449698cSZachary Turner           m_interpreter.GetCommandSPExact(actual_command, true));
739ebc09c36SJim Ingham       CommandObjectSP subcommand_obj_sp;
740ebc09c36SJim Ingham       bool use_subcommand = false;
741b9c1b51eSKate Stone       if (command_obj_sp) {
742ebc09c36SJim Ingham         CommandObject *cmd_obj = command_obj_sp.get();
7436e3d8e7fSEugene Zelenko         CommandObject *sub_cmd_obj = nullptr;
744b9c1b51eSKate Stone         OptionArgVectorSP option_arg_vector_sp =
745b9c1b51eSKate Stone             OptionArgVectorSP(new OptionArgVector);
746ebc09c36SJim Ingham 
74711eb9c64SZachary Turner         while (cmd_obj->IsMultiwordObject() && !args.empty()) {
748b9c1b51eSKate Stone           if (argc >= 3) {
749a449698cSZachary Turner             const std::string sub_command = args.GetArgumentAtIndex(0);
75011eb9c64SZachary Turner             assert(!sub_command.empty());
75111eb9c64SZachary Turner             subcommand_obj_sp = cmd_obj->GetSubcommandSP(sub_command.data());
752b9c1b51eSKate Stone             if (subcommand_obj_sp) {
753ebc09c36SJim Ingham               sub_cmd_obj = subcommand_obj_sp.get();
754ebc09c36SJim Ingham               use_subcommand = true;
755b9c1b51eSKate Stone               args.Shift(); // Shift the sub_command word off the argument
756b9c1b51eSKate Stone                             // vector.
757844d2303SCaroline Tice               cmd_obj = sub_cmd_obj;
758b9c1b51eSKate Stone             } else {
759b9c1b51eSKate Stone               result.AppendErrorWithFormat(
760b9c1b51eSKate Stone                   "'%s' is not a valid sub-command of '%s'.  "
761f415eeb4SCaroline Tice                   "Unable to create alias.\n",
762a449698cSZachary Turner                   sub_command.c_str(), actual_command.c_str());
763ebc09c36SJim Ingham               result.SetStatus(eReturnStatusFailed);
764ebc09c36SJim Ingham               return false;
765ebc09c36SJim Ingham             }
766ebc09c36SJim Ingham           }
767ebc09c36SJim Ingham         }
768ebc09c36SJim Ingham 
769ebc09c36SJim Ingham         // Verify & handle any options/arguments passed to the alias command
770ebc09c36SJim Ingham 
771212130acSEnrico Granata         std::string args_string;
772212130acSEnrico Granata 
77311eb9c64SZachary Turner         if (!args.empty()) {
774b9c1b51eSKate Stone           CommandObjectSP tmp_sp =
775b9c1b51eSKate Stone               m_interpreter.GetCommandSPExact(cmd_obj->GetCommandName(), false);
776ebc09c36SJim Ingham           if (use_subcommand)
777b9c1b51eSKate Stone             tmp_sp = m_interpreter.GetCommandSPExact(
778b9c1b51eSKate Stone                 sub_cmd_obj->GetCommandName(), false);
779ca90c47eSCaroline Tice 
780ca90c47eSCaroline Tice           args.GetCommandString(args_string);
781867b185dSCaroline Tice         }
782ebc09c36SJim Ingham 
783b9c1b51eSKate Stone         if (m_interpreter.AliasExists(alias_command.c_str()) ||
784b9c1b51eSKate Stone             m_interpreter.UserCommandExists(alias_command.c_str())) {
785b9c1b51eSKate Stone           result.AppendWarningWithFormat(
786b9c1b51eSKate Stone               "Overwriting existing definition for '%s'.\n",
787ebc09c36SJim Ingham               alias_command.c_str());
788ebc09c36SJim Ingham         }
789ebc09c36SJim Ingham 
790b9c1b51eSKate Stone         if (CommandAlias *alias = m_interpreter.AddAlias(
791b9c1b51eSKate Stone                 alias_command.c_str(),
792212130acSEnrico Granata                 use_subcommand ? subcommand_obj_sp : command_obj_sp,
793b9c1b51eSKate Stone                 args_string.c_str())) {
79445d0e238SEnrico Granata           if (m_command_options.m_help.OptionWasSet())
79545d0e238SEnrico Granata             alias->SetHelp(m_command_options.m_help.GetCurrentValue());
79645d0e238SEnrico Granata           if (m_command_options.m_long_help.OptionWasSet())
79745d0e238SEnrico Granata             alias->SetHelpLong(m_command_options.m_long_help.GetCurrentValue());
798ebc09c36SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishNoResult);
799b9c1b51eSKate Stone         } else {
800212130acSEnrico Granata           result.AppendError("Unable to create requested alias.\n");
801212130acSEnrico Granata           result.SetStatus(eReturnStatusFailed);
802212130acSEnrico Granata           return false;
803212130acSEnrico Granata         }
804b9c1b51eSKate Stone       } else {
805b9c1b51eSKate Stone         result.AppendErrorWithFormat("'%s' is not an existing command.\n",
806b9c1b51eSKate Stone                                      actual_command.c_str());
807ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
808e7941795SCaroline Tice         return false;
809ebc09c36SJim Ingham       }
810ebc09c36SJim Ingham     }
811ebc09c36SJim Ingham 
812ebc09c36SJim Ingham     return result.Succeeded();
813ebc09c36SJim Ingham   }
814ebc09c36SJim Ingham };
815ebc09c36SJim Ingham 
816ebc09c36SJim Ingham #pragma mark CommandObjectCommandsUnalias
817ebc09c36SJim Ingham //-------------------------------------------------------------------------
818ebc09c36SJim Ingham // CommandObjectCommandsUnalias
819ebc09c36SJim Ingham //-------------------------------------------------------------------------
820ebc09c36SJim Ingham 
821b9c1b51eSKate Stone class CommandObjectCommandsUnalias : public CommandObjectParsed {
822ebc09c36SJim Ingham public:
8237428a18cSKate Stone   CommandObjectCommandsUnalias(CommandInterpreter &interpreter)
824b9c1b51eSKate Stone       : CommandObjectParsed(
825b9c1b51eSKate Stone             interpreter, "command unalias",
826b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command alias'.",
827b9c1b51eSKate Stone             nullptr) {
828405fe67fSCaroline Tice     CommandArgumentEntry arg;
829405fe67fSCaroline Tice     CommandArgumentData alias_arg;
830405fe67fSCaroline Tice 
831405fe67fSCaroline Tice     // Define the first (and only) variant of this arg.
832405fe67fSCaroline Tice     alias_arg.arg_type = eArgTypeAliasName;
833405fe67fSCaroline Tice     alias_arg.arg_repetition = eArgRepeatPlain;
834405fe67fSCaroline Tice 
835b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
836b9c1b51eSKate Stone     // argument entry.
837405fe67fSCaroline Tice     arg.push_back(alias_arg);
838405fe67fSCaroline Tice 
839405fe67fSCaroline Tice     // Push the data for the first argument into the m_arguments vector.
840405fe67fSCaroline Tice     m_arguments.push_back(arg);
841ebc09c36SJim Ingham   }
842ebc09c36SJim Ingham 
8436e3d8e7fSEugene Zelenko   ~CommandObjectCommandsUnalias() override = default;
844ebc09c36SJim Ingham 
8455a988416SJim Ingham protected:
846b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
847ebc09c36SJim Ingham     CommandObject::CommandMap::iterator pos;
848ebc09c36SJim Ingham     CommandObject *cmd_obj;
849ebc09c36SJim Ingham 
85011eb9c64SZachary Turner     if (args.empty()) {
85111eb9c64SZachary Turner       result.AppendError("must call 'unalias' with a valid alias");
85211eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
85311eb9c64SZachary Turner       return false;
85411eb9c64SZachary Turner     }
85511eb9c64SZachary Turner 
85611eb9c64SZachary Turner     // TODO: Convert this function to return a StringRef.  Should also convert
85711eb9c64SZachary Turner     // dependent functions GetCommandObject, CommandExists, RemoveAlias,
85811eb9c64SZachary Turner     // AliasExists, etc.
859ebc09c36SJim Ingham     const char *command_name = args.GetArgumentAtIndex(0);
860a7015092SGreg Clayton     cmd_obj = m_interpreter.GetCommandObject(command_name);
861b9c1b51eSKate Stone     if (cmd_obj) {
862b9c1b51eSKate Stone       if (m_interpreter.CommandExists(command_name)) {
863b9c1b51eSKate Stone         if (cmd_obj->IsRemovable()) {
864b9c1b51eSKate Stone           result.AppendErrorWithFormat(
865b9c1b51eSKate Stone               "'%s' is not an alias, it is a debugger command which can be "
866b9c1b51eSKate Stone               "removed using the 'command delete' command.\n",
867b547278cSGreg Clayton               command_name);
868b9c1b51eSKate Stone         } else {
869b9c1b51eSKate Stone           result.AppendErrorWithFormat(
870b9c1b51eSKate Stone               "'%s' is a permanent debugger command and cannot be removed.\n",
871ebc09c36SJim Ingham               command_name);
872b547278cSGreg Clayton         }
873ebc09c36SJim Ingham         result.SetStatus(eReturnStatusFailed);
874b9c1b51eSKate Stone       } else {
875b9c1b51eSKate Stone         if (!m_interpreter.RemoveAlias(command_name)) {
876a7015092SGreg Clayton           if (m_interpreter.AliasExists(command_name))
877b9c1b51eSKate Stone             result.AppendErrorWithFormat(
878b9c1b51eSKate Stone                 "Error occurred while attempting to unalias '%s'.\n",
879ebc09c36SJim Ingham                 command_name);
880ebc09c36SJim Ingham           else
881b9c1b51eSKate Stone             result.AppendErrorWithFormat("'%s' is not an existing alias.\n",
882b9c1b51eSKate Stone                                          command_name);
883ebc09c36SJim Ingham           result.SetStatus(eReturnStatusFailed);
884b9c1b51eSKate Stone         } else
885ebc09c36SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishNoResult);
886ebc09c36SJim Ingham       }
887b9c1b51eSKate Stone     } else {
888b9c1b51eSKate Stone       result.AppendErrorWithFormat(
889b9c1b51eSKate Stone           "'%s' is not a known command.\nTry 'help' to see a "
890ebc09c36SJim Ingham           "current list of commands.\n",
891ebc09c36SJim Ingham           command_name);
892ebc09c36SJim Ingham       result.SetStatus(eReturnStatusFailed);
893ebc09c36SJim Ingham     }
894ebc09c36SJim Ingham 
895ebc09c36SJim Ingham     return result.Succeeded();
896ebc09c36SJim Ingham   }
897ebc09c36SJim Ingham };
898ebc09c36SJim Ingham 
899b547278cSGreg Clayton #pragma mark CommandObjectCommandsDelete
900b547278cSGreg Clayton //-------------------------------------------------------------------------
901b547278cSGreg Clayton // CommandObjectCommandsDelete
902b547278cSGreg Clayton //-------------------------------------------------------------------------
903b547278cSGreg Clayton 
904b9c1b51eSKate Stone class CommandObjectCommandsDelete : public CommandObjectParsed {
905b547278cSGreg Clayton public:
9067428a18cSKate Stone   CommandObjectCommandsDelete(CommandInterpreter &interpreter)
907b9c1b51eSKate Stone       : CommandObjectParsed(
908b9c1b51eSKate Stone             interpreter, "command delete",
909b9c1b51eSKate Stone             "Delete one or more custom commands defined by 'command regex'.",
910b9c1b51eSKate Stone             nullptr) {
911b547278cSGreg Clayton     CommandArgumentEntry arg;
912b547278cSGreg Clayton     CommandArgumentData alias_arg;
913b547278cSGreg Clayton 
914b547278cSGreg Clayton     // Define the first (and only) variant of this arg.
915b547278cSGreg Clayton     alias_arg.arg_type = eArgTypeCommandName;
916b547278cSGreg Clayton     alias_arg.arg_repetition = eArgRepeatPlain;
917b547278cSGreg Clayton 
918b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
919b9c1b51eSKate Stone     // argument entry.
920b547278cSGreg Clayton     arg.push_back(alias_arg);
921b547278cSGreg Clayton 
922b547278cSGreg Clayton     // Push the data for the first argument into the m_arguments vector.
923b547278cSGreg Clayton     m_arguments.push_back(arg);
924b547278cSGreg Clayton   }
925b547278cSGreg Clayton 
9266e3d8e7fSEugene Zelenko   ~CommandObjectCommandsDelete() override = default;
927b547278cSGreg Clayton 
928b547278cSGreg Clayton protected:
929b9c1b51eSKate Stone   bool DoExecute(Args &args, CommandReturnObject &result) override {
930b547278cSGreg Clayton     CommandObject::CommandMap::iterator pos;
931b547278cSGreg Clayton 
93211eb9c64SZachary Turner     if (args.empty()) {
93311eb9c64SZachary Turner       result.AppendErrorWithFormat("must call '%s' with one or more valid user "
93411eb9c64SZachary Turner                                    "defined regular expression command names",
935a449698cSZachary Turner                                    GetCommandName().str().c_str());
93611eb9c64SZachary Turner       result.SetStatus(eReturnStatusFailed);
93711eb9c64SZachary Turner     }
93811eb9c64SZachary Turner 
93911eb9c64SZachary Turner     // TODO: Convert this to accept a stringRef.
940b547278cSGreg Clayton     const char *command_name = args.GetArgumentAtIndex(0);
941b9c1b51eSKate Stone     if (m_interpreter.CommandExists(command_name)) {
942b9c1b51eSKate Stone       if (m_interpreter.RemoveCommand(command_name)) {
943b547278cSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
944b9c1b51eSKate Stone       } else {
945b9c1b51eSKate Stone         result.AppendErrorWithFormat(
946b9c1b51eSKate Stone             "'%s' is a permanent debugger command and cannot be removed.\n",
947b547278cSGreg Clayton             command_name);
948b547278cSGreg Clayton         result.SetStatus(eReturnStatusFailed);
949b547278cSGreg Clayton       }
950b9c1b51eSKate Stone     } else {
95146d4aa21SEnrico Granata       StreamString error_msg_stream;
95246d4aa21SEnrico Granata       const bool generate_apropos = true;
95346d4aa21SEnrico Granata       const bool generate_type_lookup = false;
954b9c1b51eSKate Stone       CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
955b9c1b51eSKate Stone           &error_msg_stream, command_name, nullptr, nullptr, generate_apropos,
95646d4aa21SEnrico Granata           generate_type_lookup);
95746d4aa21SEnrico Granata       result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
958b547278cSGreg Clayton       result.SetStatus(eReturnStatusFailed);
959b547278cSGreg Clayton     }
960b547278cSGreg Clayton 
961b547278cSGreg Clayton     return result.Succeeded();
962b547278cSGreg Clayton   }
963b547278cSGreg Clayton };
964b547278cSGreg Clayton 
965de164aaaSGreg Clayton //-------------------------------------------------------------------------
966de164aaaSGreg Clayton // CommandObjectCommandsAddRegex
967de164aaaSGreg Clayton //-------------------------------------------------------------------------
9681f0f5b5bSZachary Turner 
9691f0f5b5bSZachary Turner static OptionDefinition g_regex_options[] = {
9701f0f5b5bSZachary Turner     // clang-format off
9711f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "help"  , 'h', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The help text to display for this command." },
9721f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "syntax", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "A syntax string showing the typical usage syntax." },
9731f0f5b5bSZachary Turner     // clang-format on
9741f0f5b5bSZachary Turner };
9751f0f5b5bSZachary Turner 
9765a988416SJim Ingham #pragma mark CommandObjectCommandsAddRegex
977de164aaaSGreg Clayton 
978b9c1b51eSKate Stone class CommandObjectCommandsAddRegex : public CommandObjectParsed,
979b9c1b51eSKate Stone                                       public IOHandlerDelegateMultiline {
980de164aaaSGreg Clayton public:
9817428a18cSKate Stone   CommandObjectCommandsAddRegex(CommandInterpreter &interpreter)
982b9c1b51eSKate Stone       : CommandObjectParsed(
983b9c1b51eSKate Stone             interpreter, "command regex", "Define a custom command in terms of "
984b9c1b51eSKate Stone                                           "existing commands by matching "
985b9c1b51eSKate Stone                                           "regular expressions.",
9860e5e5a79SGreg Clayton             "command regex <cmd-name> [s/<regex>/<subst>/ ...]"),
987b9c1b51eSKate Stone         IOHandlerDelegateMultiline("",
988b9c1b51eSKate Stone                                    IOHandlerDelegate::Completion::LLDBCommand),
989b9c1b51eSKate Stone         m_options() {
990b9c1b51eSKate Stone     SetHelpLong(
991b9c1b51eSKate Stone         R"(
992b9c1b51eSKate Stone )"
993b9c1b51eSKate Stone         "This command allows the user to create powerful regular expression commands \
994ea671fbdSKate Stone with substitutions. The regular expressions and substitutions are specified \
995b9c1b51eSKate Stone using the regular expression substitution format of:"
996b9c1b51eSKate Stone         R"(
997ea671fbdSKate Stone 
998ea671fbdSKate Stone     s/<regex>/<subst>/
999ea671fbdSKate Stone 
1000b9c1b51eSKate Stone )"
1001b9c1b51eSKate Stone         "<regex> is a regular expression that can use parenthesis to capture regular \
1002ea671fbdSKate Stone expression input and substitute the captured matches in the output using %1 \
1003b9c1b51eSKate Stone for the first match, %2 for the second, and so on."
1004b9c1b51eSKate Stone         R"(
1005ea671fbdSKate Stone 
1006b9c1b51eSKate Stone )"
1007b9c1b51eSKate Stone         "The regular expressions can all be specified on the command line if more than \
1008ea671fbdSKate Stone one argument is provided. If just the command name is provided on the command \
1009ea671fbdSKate Stone line, then the regular expressions and substitutions can be entered on separate \
1010b9c1b51eSKate Stone lines, followed by an empty line to terminate the command definition."
1011b9c1b51eSKate Stone         R"(
1012ea671fbdSKate Stone 
1013ea671fbdSKate Stone EXAMPLES
1014ea671fbdSKate Stone 
1015b9c1b51eSKate Stone )"
1016b9c1b51eSKate Stone         "The following example will define a regular expression command named 'f' that \
1017ea671fbdSKate Stone will call 'finish' if there are no arguments, or 'frame select <frame-idx>' if \
1018b9c1b51eSKate Stone a number follows 'f':"
1019b9c1b51eSKate Stone         R"(
1020ea671fbdSKate Stone 
1021b9c1b51eSKate Stone     (lldb) command regex f s/^$/finish/ 's/([0-9]+)/frame select %1/')");
1022de164aaaSGreg Clayton   }
1023de164aaaSGreg Clayton 
10246e3d8e7fSEugene Zelenko   ~CommandObjectCommandsAddRegex() override = default;
1025de164aaaSGreg Clayton 
10265a988416SJim Ingham protected:
1027b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
102844d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1029b9c1b51eSKate Stone     if (output_sp) {
1030b9c1b51eSKate Stone       output_sp->PutCString("Enter one of more sed substitution commands in "
1031b9c1b51eSKate Stone                             "the form: 's/<regex>/<subst>/'.\nTerminate the "
1032b9c1b51eSKate Stone                             "substitution list with an empty line.\n");
103344d93782SGreg Clayton       output_sp->Flush();
103444d93782SGreg Clayton     }
103544d93782SGreg Clayton   }
103644d93782SGreg Clayton 
1037b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1038b9c1b51eSKate Stone                               std::string &data) override {
103944d93782SGreg Clayton     io_handler.SetIsDone(true);
1040b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
104144d93782SGreg Clayton       StringList lines;
1042b9c1b51eSKate Stone       if (lines.SplitIntoLines(data)) {
104344d93782SGreg Clayton         const size_t num_lines = lines.GetSize();
104444d93782SGreg Clayton         bool check_only = false;
1045b9c1b51eSKate Stone         for (size_t i = 0; i < num_lines; ++i) {
104644d93782SGreg Clayton           llvm::StringRef bytes_strref(lines[i]);
104744d93782SGreg Clayton           Error error = AppendRegexSubstitution(bytes_strref, check_only);
1048b9c1b51eSKate Stone           if (error.Fail()) {
1049b9c1b51eSKate Stone             if (!m_interpreter.GetDebugger()
1050b9c1b51eSKate Stone                      .GetCommandInterpreter()
1051b9c1b51eSKate Stone                      .GetBatchCommandMode()) {
1052b9c1b51eSKate Stone               StreamSP out_stream =
1053b9c1b51eSKate Stone                   m_interpreter.GetDebugger().GetAsyncOutputStream();
105444d93782SGreg Clayton               out_stream->Printf("error: %s\n", error.AsCString());
105544d93782SGreg Clayton             }
105644d93782SGreg Clayton           }
105744d93782SGreg Clayton         }
105844d93782SGreg Clayton       }
1059b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
106044d93782SGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
106144d93782SGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
106244d93782SGreg Clayton       }
106344d93782SGreg Clayton     }
106444d93782SGreg Clayton   }
106544d93782SGreg Clayton 
1066b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
10675a988416SJim Ingham     const size_t argc = command.GetArgumentCount();
1068b9c1b51eSKate Stone     if (argc == 0) {
1069b9c1b51eSKate Stone       result.AppendError("usage: 'command regex <command-name> "
1070b9c1b51eSKate Stone                          "[s/<regex1>/<subst1>/ s/<regex2>/<subst2>/ ...]'\n");
10710e5e5a79SGreg Clayton       result.SetStatus(eReturnStatusFailed);
107211eb9c64SZachary Turner       return false;
107311eb9c64SZachary Turner     }
107411eb9c64SZachary Turner 
10750e5e5a79SGreg Clayton     Error error;
10765a988416SJim Ingham     const char *name = command.GetArgumentAtIndex(0);
107711eb9c64SZachary Turner     m_regex_cmd_ap.reset(
107811eb9c64SZachary Turner         new CommandObjectRegexCommand(m_interpreter, name, m_options.GetHelp(),
107911eb9c64SZachary Turner                                       m_options.GetSyntax(), 10, 0, true));
10800e5e5a79SGreg Clayton 
1081b9c1b51eSKate Stone     if (argc == 1) {
108244d93782SGreg Clayton       Debugger &debugger = m_interpreter.GetDebugger();
1083e30f11d9SKate Stone       bool color_prompt = debugger.GetUseColor();
108444d93782SGreg Clayton       const bool multiple_lines = true; // Get multiple lines
1085b9c1b51eSKate Stone       IOHandlerSP io_handler_sp(new IOHandlerEditline(
1086b9c1b51eSKate Stone           debugger, IOHandler::Type::Other,
108773d80faaSGreg Clayton           "lldb-regex",          // Name of input reader for history
1088514d8cd8SZachary Turner           llvm::StringRef("> "), // Prompt
1089514d8cd8SZachary Turner           llvm::StringRef(),     // Continuation prompt
1090b9c1b51eSKate Stone           multiple_lines, color_prompt,
1091f6913cd7SGreg Clayton           0, // Don't show line numbers
109244d93782SGreg Clayton           *this));
109344d93782SGreg Clayton 
1094b9c1b51eSKate Stone       if (io_handler_sp) {
109544d93782SGreg Clayton         debugger.PushIOHandler(io_handler_sp);
1096de164aaaSGreg Clayton         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1097de164aaaSGreg Clayton       }
1098b9c1b51eSKate Stone     } else {
1099*97d2c401SZachary Turner       for (auto &entry : command.entries().drop_front()) {
110044d93782SGreg Clayton         bool check_only = false;
1101*97d2c401SZachary Turner         error = AppendRegexSubstitution(entry.ref, check_only);
11020e5e5a79SGreg Clayton         if (error.Fail())
11030e5e5a79SGreg Clayton           break;
11040e5e5a79SGreg Clayton       }
11050e5e5a79SGreg Clayton 
1106b9c1b51eSKate Stone       if (error.Success()) {
11070e5e5a79SGreg Clayton         AddRegexCommandToInterpreter();
11080e5e5a79SGreg Clayton       }
11090e5e5a79SGreg Clayton     }
1110b9c1b51eSKate Stone     if (error.Fail()) {
11110e5e5a79SGreg Clayton       result.AppendError(error.AsCString());
1112de164aaaSGreg Clayton       result.SetStatus(eReturnStatusFailed);
1113de164aaaSGreg Clayton     }
11140e5e5a79SGreg Clayton 
1115de164aaaSGreg Clayton     return result.Succeeded();
1116de164aaaSGreg Clayton   }
1117de164aaaSGreg Clayton 
1118b9c1b51eSKate Stone   Error AppendRegexSubstitution(const llvm::StringRef &regex_sed,
1119b9c1b51eSKate Stone                                 bool check_only) {
11200e5e5a79SGreg Clayton     Error error;
11210e5e5a79SGreg Clayton 
1122b9c1b51eSKate Stone     if (!m_regex_cmd_ap) {
1123b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1124b9c1b51eSKate Stone           "invalid regular expression command object for: '%.*s'",
1125b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11260e5e5a79SGreg Clayton       return error;
1127de164aaaSGreg Clayton     }
11280e5e5a79SGreg Clayton 
11290e5e5a79SGreg Clayton     size_t regex_sed_size = regex_sed.size();
11300e5e5a79SGreg Clayton 
1131b9c1b51eSKate Stone     if (regex_sed_size <= 1) {
1132b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1133b9c1b51eSKate Stone           "regular expression substitution string is too short: '%.*s'",
1134b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11350e5e5a79SGreg Clayton       return error;
11360e5e5a79SGreg Clayton     }
11370e5e5a79SGreg Clayton 
1138b9c1b51eSKate Stone     if (regex_sed[0] != 's') {
1139b9c1b51eSKate Stone       error.SetErrorStringWithFormat("regular expression substitution string "
1140b9c1b51eSKate Stone                                      "doesn't start with 's': '%.*s'",
1141b9c1b51eSKate Stone                                      (int)regex_sed.size(), regex_sed.data());
11420e5e5a79SGreg Clayton       return error;
11430e5e5a79SGreg Clayton     }
11440e5e5a79SGreg Clayton     const size_t first_separator_char_pos = 1;
11450e5e5a79SGreg Clayton     // use the char that follows 's' as the regex separator character
11460e5e5a79SGreg Clayton     // so we can have "s/<regex>/<subst>/" or "s|<regex>|<subst>|"
11470e5e5a79SGreg Clayton     const char separator_char = regex_sed[first_separator_char_pos];
1148b9c1b51eSKate Stone     const size_t second_separator_char_pos =
1149b9c1b51eSKate Stone         regex_sed.find(separator_char, first_separator_char_pos + 1);
11500e5e5a79SGreg Clayton 
1151b9c1b51eSKate Stone     if (second_separator_char_pos == std::string::npos) {
1152b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1153b9c1b51eSKate Stone           "missing second '%c' separator char after '%.*s' in '%.*s'",
11540e5e5a79SGreg Clayton           separator_char,
11550e5e5a79SGreg Clayton           (int)(regex_sed.size() - first_separator_char_pos - 1),
1156ea508635SGreg Clayton           regex_sed.data() + (first_separator_char_pos + 1),
1157b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11580e5e5a79SGreg Clayton       return error;
11590e5e5a79SGreg Clayton     }
11600e5e5a79SGreg Clayton 
1161b9c1b51eSKate Stone     const size_t third_separator_char_pos =
1162b9c1b51eSKate Stone         regex_sed.find(separator_char, second_separator_char_pos + 1);
11630e5e5a79SGreg Clayton 
1164b9c1b51eSKate Stone     if (third_separator_char_pos == std::string::npos) {
1165b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1166b9c1b51eSKate Stone           "missing third '%c' separator char after '%.*s' in '%.*s'",
11670e5e5a79SGreg Clayton           separator_char,
11680e5e5a79SGreg Clayton           (int)(regex_sed.size() - second_separator_char_pos - 1),
1169ea508635SGreg Clayton           regex_sed.data() + (second_separator_char_pos + 1),
1170b9c1b51eSKate Stone           (int)regex_sed.size(), regex_sed.data());
11710e5e5a79SGreg Clayton       return error;
11720e5e5a79SGreg Clayton     }
11730e5e5a79SGreg Clayton 
1174b9c1b51eSKate Stone     if (third_separator_char_pos != regex_sed_size - 1) {
11750e5e5a79SGreg Clayton       // Make sure that everything that follows the last regex
11760e5e5a79SGreg Clayton       // separator char
1177b9c1b51eSKate Stone       if (regex_sed.find_first_not_of("\t\n\v\f\r ",
1178b9c1b51eSKate Stone                                       third_separator_char_pos + 1) !=
1179b9c1b51eSKate Stone           std::string::npos) {
1180b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
1181b9c1b51eSKate Stone             "extra data found after the '%.*s' regular expression substitution "
1182b9c1b51eSKate Stone             "string: '%.*s'",
1183b9c1b51eSKate Stone             (int)third_separator_char_pos + 1, regex_sed.data(),
11840e5e5a79SGreg Clayton             (int)(regex_sed.size() - third_separator_char_pos - 1),
11850e5e5a79SGreg Clayton             regex_sed.data() + (third_separator_char_pos + 1));
11860e5e5a79SGreg Clayton         return error;
11870e5e5a79SGreg Clayton       }
1188b9c1b51eSKate Stone     } else if (first_separator_char_pos + 1 == second_separator_char_pos) {
1189b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1190b9c1b51eSKate Stone           "<regex> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1191b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11920e5e5a79SGreg Clayton           regex_sed.data());
11930e5e5a79SGreg Clayton       return error;
1194b9c1b51eSKate Stone     } else if (second_separator_char_pos + 1 == third_separator_char_pos) {
1195b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1196b9c1b51eSKate Stone           "<subst> can't be empty in 's%c<regex>%c<subst>%c' string: '%.*s'",
1197b9c1b51eSKate Stone           separator_char, separator_char, separator_char, (int)regex_sed.size(),
11980e5e5a79SGreg Clayton           regex_sed.data());
11990e5e5a79SGreg Clayton       return error;
12000e5e5a79SGreg Clayton     }
120144d93782SGreg Clayton 
1202b9c1b51eSKate Stone     if (!check_only) {
1203b9c1b51eSKate Stone       std::string regex(regex_sed.substr(first_separator_char_pos + 1,
1204b9c1b51eSKate Stone                                          second_separator_char_pos -
1205b9c1b51eSKate Stone                                              first_separator_char_pos - 1));
1206b9c1b51eSKate Stone       std::string subst(regex_sed.substr(second_separator_char_pos + 1,
1207b9c1b51eSKate Stone                                          third_separator_char_pos -
1208b9c1b51eSKate Stone                                              second_separator_char_pos - 1));
1209b9c1b51eSKate Stone       m_regex_cmd_ap->AddRegexCommand(regex.c_str(), subst.c_str());
121044d93782SGreg Clayton     }
12110e5e5a79SGreg Clayton     return error;
1212de164aaaSGreg Clayton   }
1213de164aaaSGreg Clayton 
1214b9c1b51eSKate Stone   void AddRegexCommandToInterpreter() {
1215b9c1b51eSKate Stone     if (m_regex_cmd_ap) {
1216b9c1b51eSKate Stone       if (m_regex_cmd_ap->HasRegexEntries()) {
1217de164aaaSGreg Clayton         CommandObjectSP cmd_sp(m_regex_cmd_ap.release());
1218de164aaaSGreg Clayton         m_interpreter.AddCommand(cmd_sp->GetCommandName(), cmd_sp, true);
1219de164aaaSGreg Clayton       }
1220de164aaaSGreg Clayton     }
1221de164aaaSGreg Clayton   }
1222de164aaaSGreg Clayton 
1223de164aaaSGreg Clayton private:
12247b0992d9SGreg Clayton   std::unique_ptr<CommandObjectRegexCommand> m_regex_cmd_ap;
1225de164aaaSGreg Clayton 
1226b9c1b51eSKate Stone   class CommandOptions : public Options {
1227de164aaaSGreg Clayton   public:
1228b9c1b51eSKate Stone     CommandOptions() : Options() {}
1229de164aaaSGreg Clayton 
12306e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1231de164aaaSGreg Clayton 
1232b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1233b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
1234de164aaaSGreg Clayton       Error error;
12353bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1236de164aaaSGreg Clayton 
1237b9c1b51eSKate Stone       switch (short_option) {
1238de164aaaSGreg Clayton       case 'h':
1239de164aaaSGreg Clayton         m_help.assign(option_arg);
1240de164aaaSGreg Clayton         break;
1241de164aaaSGreg Clayton       case 's':
1242de164aaaSGreg Clayton         m_syntax.assign(option_arg);
1243de164aaaSGreg Clayton         break;
1244de164aaaSGreg Clayton       default:
1245b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1246b9c1b51eSKate Stone                                        short_option);
1247de164aaaSGreg Clayton         break;
1248de164aaaSGreg Clayton       }
1249de164aaaSGreg Clayton 
1250de164aaaSGreg Clayton       return error;
1251de164aaaSGreg Clayton     }
1252de164aaaSGreg Clayton 
1253b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1254de164aaaSGreg Clayton       m_help.clear();
1255de164aaaSGreg Clayton       m_syntax.clear();
1256de164aaaSGreg Clayton     }
1257de164aaaSGreg Clayton 
12581f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
125970602439SZachary Turner       return llvm::makeArrayRef(g_regex_options);
12601f0f5b5bSZachary Turner     }
1261de164aaaSGreg Clayton 
126211eb9c64SZachary Turner     // TODO: Convert these functions to return StringRefs.
1263b9c1b51eSKate Stone     const char *GetHelp() {
12646e3d8e7fSEugene Zelenko       return (m_help.empty() ? nullptr : m_help.c_str());
1265de164aaaSGreg Clayton     }
12666e3d8e7fSEugene Zelenko 
1267b9c1b51eSKate Stone     const char *GetSyntax() {
12686e3d8e7fSEugene Zelenko       return (m_syntax.empty() ? nullptr : m_syntax.c_str());
1269de164aaaSGreg Clayton     }
12706e3d8e7fSEugene Zelenko 
1271de164aaaSGreg Clayton   protected:
12726e3d8e7fSEugene Zelenko     // Instance variables to hold the values for command options.
12736e3d8e7fSEugene Zelenko 
1274de164aaaSGreg Clayton     std::string m_help;
1275de164aaaSGreg Clayton     std::string m_syntax;
1276de164aaaSGreg Clayton   };
1277de164aaaSGreg Clayton 
1278b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
1279de164aaaSGreg Clayton 
12805a988416SJim Ingham   CommandOptions m_options;
1281de164aaaSGreg Clayton };
1282de164aaaSGreg Clayton 
1283b9c1b51eSKate Stone class CommandObjectPythonFunction : public CommandObjectRaw {
1284223383edSEnrico Granata public:
1285b9c1b51eSKate Stone   CommandObjectPythonFunction(CommandInterpreter &interpreter, std::string name,
1286b9c1b51eSKate Stone                               std::string funct, std::string help,
1287b9c1b51eSKate Stone                               ScriptedCommandSynchronicity synch)
1288a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1289b9c1b51eSKate Stone         m_function_name(funct), m_synchro(synch), m_fetched_help_long(false) {
1290735152e3SEnrico Granata     if (!help.empty())
1291735152e3SEnrico Granata       SetHelp(help.c_str());
1292b9c1b51eSKate Stone     else {
1293735152e3SEnrico Granata       StreamString stream;
1294735152e3SEnrico Granata       stream.Printf("For more information run 'help %s'", name.c_str());
1295735152e3SEnrico Granata       SetHelp(stream.GetData());
1296735152e3SEnrico Granata     }
1297223383edSEnrico Granata   }
1298223383edSEnrico Granata 
12996e3d8e7fSEugene Zelenko   ~CommandObjectPythonFunction() override = default;
1300223383edSEnrico Granata 
1301b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13025a988416SJim Ingham 
1303b9c1b51eSKate Stone   const std::string &GetFunctionName() { return m_function_name; }
13045a988416SJim Ingham 
1305b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13065a988416SJim Ingham 
1307b9c1b51eSKate Stone   const char *GetHelpLong() override {
1308b9c1b51eSKate Stone     if (!m_fetched_help_long) {
1309fac939e9SEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1310b9c1b51eSKate Stone       if (scripter) {
1311fac939e9SEnrico Granata         std::string docstring;
1312b9c1b51eSKate Stone         m_fetched_help_long = scripter->GetDocumentationForItem(
1313b9c1b51eSKate Stone             m_function_name.c_str(), docstring);
1314fac939e9SEnrico Granata         if (!docstring.empty())
1315bfb75e9bSEnrico Granata           SetHelpLong(docstring.c_str());
1316fac939e9SEnrico Granata       }
1317fac939e9SEnrico Granata     }
1318fac939e9SEnrico Granata     return CommandObjectRaw::GetHelpLong();
1319fac939e9SEnrico Granata   }
1320fac939e9SEnrico Granata 
13215a988416SJim Ingham protected:
1322b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
1323b9c1b51eSKate Stone                  CommandReturnObject &result) override {
1324223383edSEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1325223383edSEnrico Granata 
1326223383edSEnrico Granata     Error error;
1327223383edSEnrico Granata 
132870f11f88SJim Ingham     result.SetStatus(eReturnStatusInvalid);
132970f11f88SJim Ingham 
1330b9c1b51eSKate Stone     if (!scripter ||
1331b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_function_name.c_str(),
1332b9c1b51eSKate Stone                                          raw_command_line, m_synchro, result,
1333b9c1b51eSKate Stone                                          error, m_exe_ctx)) {
1334223383edSEnrico Granata       result.AppendError(error.AsCString());
1335223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1336b9c1b51eSKate Stone     } else {
133770f11f88SJim Ingham       // Don't change the status if the command already set it...
1338b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1339b9c1b51eSKate Stone         if (result.GetOutputData() == nullptr ||
1340b9c1b51eSKate Stone             result.GetOutputData()[0] == '\0')
1341223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
134270f11f88SJim Ingham         else
134370f11f88SJim Ingham           result.SetStatus(eReturnStatusSuccessFinishResult);
134470f11f88SJim Ingham       }
134570f11f88SJim Ingham     }
1346223383edSEnrico Granata 
1347223383edSEnrico Granata     return result.Succeeded();
1348223383edSEnrico Granata   }
1349223383edSEnrico Granata 
13506e3d8e7fSEugene Zelenko private:
13516e3d8e7fSEugene Zelenko   std::string m_function_name;
13526e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
13536e3d8e7fSEugene Zelenko   bool m_fetched_help_long;
1354223383edSEnrico Granata };
1355223383edSEnrico Granata 
1356b9c1b51eSKate Stone class CommandObjectScriptingObject : public CommandObjectRaw {
13579fe00e52SEnrico Granata public:
13589fe00e52SEnrico Granata   CommandObjectScriptingObject(CommandInterpreter &interpreter,
13599fe00e52SEnrico Granata                                std::string name,
13600641ca1aSZachary Turner                                StructuredData::GenericSP cmd_obj_sp,
1361b9c1b51eSKate Stone                                ScriptedCommandSynchronicity synch)
1362a449698cSZachary Turner       : CommandObjectRaw(interpreter, name),
1363b9c1b51eSKate Stone         m_cmd_obj_sp(cmd_obj_sp), m_synchro(synch), m_fetched_help_short(false),
1364b9c1b51eSKate Stone         m_fetched_help_long(false) {
13659fe00e52SEnrico Granata     StreamString stream;
13669fe00e52SEnrico Granata     stream.Printf("For more information run 'help %s'", name.c_str());
13679fe00e52SEnrico Granata     SetHelp(stream.GetData());
1368e87764f2SEnrico Granata     if (ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter())
1369e87764f2SEnrico Granata       GetFlags().Set(scripter->GetFlagsForCommandObject(cmd_obj_sp));
13709fe00e52SEnrico Granata   }
13719fe00e52SEnrico Granata 
13726e3d8e7fSEugene Zelenko   ~CommandObjectScriptingObject() override = default;
13739fe00e52SEnrico Granata 
1374b9c1b51eSKate Stone   bool IsRemovable() const override { return true; }
13759fe00e52SEnrico Granata 
1376b9c1b51eSKate Stone   StructuredData::GenericSP GetImplementingObject() { return m_cmd_obj_sp; }
13779fe00e52SEnrico Granata 
1378b9c1b51eSKate Stone   ScriptedCommandSynchronicity GetSynchronicity() { return m_synchro; }
13799fe00e52SEnrico Granata 
1380b9c1b51eSKate Stone   const char *GetHelp() override {
1381b9c1b51eSKate Stone     if (!m_fetched_help_short) {
13826f79bb2dSEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1383b9c1b51eSKate Stone       if (scripter) {
13846f79bb2dSEnrico Granata         std::string docstring;
1385b9c1b51eSKate Stone         m_fetched_help_short =
1386b9c1b51eSKate Stone             scripter->GetShortHelpForCommandObject(m_cmd_obj_sp, docstring);
13876f79bb2dSEnrico Granata         if (!docstring.empty())
1388bfb75e9bSEnrico Granata           SetHelp(docstring.c_str());
13896f79bb2dSEnrico Granata       }
13906f79bb2dSEnrico Granata     }
13916f79bb2dSEnrico Granata     return CommandObjectRaw::GetHelp();
13926f79bb2dSEnrico Granata   }
13936f79bb2dSEnrico Granata 
1394b9c1b51eSKate Stone   const char *GetHelpLong() override {
1395b9c1b51eSKate Stone     if (!m_fetched_help_long) {
13966f79bb2dSEnrico Granata       ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
1397b9c1b51eSKate Stone       if (scripter) {
13986f79bb2dSEnrico Granata         std::string docstring;
1399b9c1b51eSKate Stone         m_fetched_help_long =
1400b9c1b51eSKate Stone             scripter->GetLongHelpForCommandObject(m_cmd_obj_sp, docstring);
14016f79bb2dSEnrico Granata         if (!docstring.empty())
1402bfb75e9bSEnrico Granata           SetHelpLong(docstring.c_str());
14036f79bb2dSEnrico Granata       }
14046f79bb2dSEnrico Granata     }
14059fe00e52SEnrico Granata     return CommandObjectRaw::GetHelpLong();
14069fe00e52SEnrico Granata   }
14079fe00e52SEnrico Granata 
14089fe00e52SEnrico Granata protected:
1409b9c1b51eSKate Stone   bool DoExecute(const char *raw_command_line,
1410b9c1b51eSKate Stone                  CommandReturnObject &result) override {
14119fe00e52SEnrico Granata     ScriptInterpreter *scripter = m_interpreter.GetScriptInterpreter();
14129fe00e52SEnrico Granata 
14139fe00e52SEnrico Granata     Error error;
14149fe00e52SEnrico Granata 
14159fe00e52SEnrico Granata     result.SetStatus(eReturnStatusInvalid);
14169fe00e52SEnrico Granata 
1417b9c1b51eSKate Stone     if (!scripter ||
1418b9c1b51eSKate Stone         !scripter->RunScriptBasedCommand(m_cmd_obj_sp, raw_command_line,
1419b9c1b51eSKate Stone                                          m_synchro, result, error, m_exe_ctx)) {
14209fe00e52SEnrico Granata       result.AppendError(error.AsCString());
14219fe00e52SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1422b9c1b51eSKate Stone     } else {
14239fe00e52SEnrico Granata       // Don't change the status if the command already set it...
1424b9c1b51eSKate Stone       if (result.GetStatus() == eReturnStatusInvalid) {
1425b9c1b51eSKate Stone         if (result.GetOutputData() == nullptr ||
1426b9c1b51eSKate Stone             result.GetOutputData()[0] == '\0')
14279fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
14289fe00e52SEnrico Granata         else
14299fe00e52SEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishResult);
14309fe00e52SEnrico Granata       }
14319fe00e52SEnrico Granata     }
14329fe00e52SEnrico Granata 
14339fe00e52SEnrico Granata     return result.Succeeded();
14349fe00e52SEnrico Granata   }
14359fe00e52SEnrico Granata 
14366e3d8e7fSEugene Zelenko private:
14376e3d8e7fSEugene Zelenko   StructuredData::GenericSP m_cmd_obj_sp;
14386e3d8e7fSEugene Zelenko   ScriptedCommandSynchronicity m_synchro;
14396e3d8e7fSEugene Zelenko   bool m_fetched_help_short : 1;
14406e3d8e7fSEugene Zelenko   bool m_fetched_help_long : 1;
14419fe00e52SEnrico Granata };
14429fe00e52SEnrico Granata 
1443a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1444a9dbf432SEnrico Granata // CommandObjectCommandsScriptImport
1445a9dbf432SEnrico Granata //-------------------------------------------------------------------------
1446a9dbf432SEnrico Granata 
14471f0f5b5bSZachary Turner OptionDefinition g_script_import_options[] = {
14481f0f5b5bSZachary Turner     // clang-format off
14491f0f5b5bSZachary Turner   { LLDB_OPT_SET_1, false, "allow-reload", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow the script to be loaded even if it was already loaded before. This argument exists for backwards compatibility, but reloading is always allowed, whether you specify it or not." },
14501f0f5b5bSZachary Turner     // clang-format on
14511f0f5b5bSZachary Turner };
14521f0f5b5bSZachary Turner 
1453b9c1b51eSKate Stone class CommandObjectCommandsScriptImport : public CommandObjectParsed {
14545a988416SJim Ingham public:
1455b9c1b51eSKate Stone   CommandObjectCommandsScriptImport(CommandInterpreter &interpreter)
1456b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script import",
1457b9c1b51eSKate Stone                             "Import a scripting module in LLDB.", nullptr),
1458b9c1b51eSKate Stone         m_options() {
14595a988416SJim Ingham     CommandArgumentEntry arg1;
14605a988416SJim Ingham     CommandArgumentData cmd_arg;
14615a988416SJim Ingham 
14625a988416SJim Ingham     // Define the first (and only) variant of this arg.
14635a988416SJim Ingham     cmd_arg.arg_type = eArgTypeFilename;
14643b00e35bSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlus;
14655a988416SJim Ingham 
1466b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1467b9c1b51eSKate Stone     // argument entry.
14685a988416SJim Ingham     arg1.push_back(cmd_arg);
14695a988416SJim Ingham 
14705a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
14715a988416SJim Ingham     m_arguments.push_back(arg1);
14725a988416SJim Ingham   }
14735a988416SJim Ingham 
14746e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptImport() override = default;
14755a988416SJim Ingham 
1476b9c1b51eSKate Stone   int HandleArgumentCompletion(Args &input, int &cursor_index,
14775a988416SJim Ingham                                int &cursor_char_position,
14785a988416SJim Ingham                                OptionElementVector &opt_element_vector,
1479b9c1b51eSKate Stone                                int match_start_point, int max_return_elements,
14805a988416SJim Ingham                                bool &word_complete,
1481b9c1b51eSKate Stone                                StringList &matches) override {
14825a988416SJim Ingham     std::string completion_str(input.GetArgumentAtIndex(cursor_index));
14835a988416SJim Ingham     completion_str.erase(cursor_char_position);
14845a988416SJim Ingham 
1485b9c1b51eSKate Stone     CommandCompletions::InvokeCommonCompletionCallbacks(
1486b9c1b51eSKate Stone         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1487b9c1b51eSKate Stone         completion_str.c_str(), match_start_point, max_return_elements, nullptr,
1488b9c1b51eSKate Stone         word_complete, matches);
14895a988416SJim Ingham     return matches.GetSize();
14905a988416SJim Ingham   }
14915a988416SJim Ingham 
1492b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
14935a988416SJim Ingham 
14945a988416SJim Ingham protected:
1495b9c1b51eSKate Stone   class CommandOptions : public Options {
14960a305db7SEnrico Granata   public:
1497b9c1b51eSKate Stone     CommandOptions() : Options() {}
14980a305db7SEnrico Granata 
14996e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
15000a305db7SEnrico Granata 
1501b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1502b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
15030a305db7SEnrico Granata       Error error;
15043bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
15050a305db7SEnrico Granata 
1506b9c1b51eSKate Stone       switch (short_option) {
15070a305db7SEnrico Granata       case 'r':
15080a305db7SEnrico Granata         m_allow_reload = true;
15090a305db7SEnrico Granata         break;
15100a305db7SEnrico Granata       default:
1511b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1512b9c1b51eSKate Stone                                        short_option);
15130a305db7SEnrico Granata         break;
15140a305db7SEnrico Granata       }
15150a305db7SEnrico Granata 
15160a305db7SEnrico Granata       return error;
15170a305db7SEnrico Granata     }
15180a305db7SEnrico Granata 
1519b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
1520e0c70f1bSEnrico Granata       m_allow_reload = true;
15210a305db7SEnrico Granata     }
15220a305db7SEnrico Granata 
15231f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
152470602439SZachary Turner       return llvm::makeArrayRef(g_script_import_options);
15251f0f5b5bSZachary Turner     }
15260a305db7SEnrico Granata 
15270a305db7SEnrico Granata     // Instance variables to hold the values for command options.
15280a305db7SEnrico Granata 
15290a305db7SEnrico Granata     bool m_allow_reload;
15300a305db7SEnrico Granata   };
15310a305db7SEnrico Granata 
1532b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1533b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1534b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1535b9c1b51eSKate Stone       result.AppendError("only scripting language supported for module "
1536b9c1b51eSKate Stone                          "importing is currently Python");
1537a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1538a9dbf432SEnrico Granata       return false;
1539a9dbf432SEnrico Granata     }
1540a9dbf432SEnrico Granata 
154111eb9c64SZachary Turner     if (command.empty()) {
15423b00e35bSEnrico Granata       result.AppendError("command script import needs one or more arguments");
1543a9dbf432SEnrico Granata       result.SetStatus(eReturnStatusFailed);
1544a9dbf432SEnrico Granata       return false;
1545a9dbf432SEnrico Granata     }
1546a9dbf432SEnrico Granata 
154711eb9c64SZachary Turner     for (auto &entry : command.entries()) {
1548a9dbf432SEnrico Granata       Error error;
1549a9dbf432SEnrico Granata 
1550c9d645d3SGreg Clayton       const bool init_session = true;
1551b9c1b51eSKate Stone       // FIXME: this is necessary because CommandObject::CheckRequirements()
155211eb9c64SZachary Turner       // assumes that commands won't ever be recursively invoked, but it's
155311eb9c64SZachary Turner       // actually possible to craft a Python script that does other "command
155411eb9c64SZachary Turner       // script imports" in __lldb_init_module the real fix is to have recursive
155511eb9c64SZachary Turner       // commands possible with a CommandInvocation object separate from the
155611eb9c64SZachary Turner       // CommandObject itself, so that recursive command invocations won't stomp
155711eb9c64SZachary Turner       // on each other (wrt to execution contents, options, and more)
1558078551c7SEnrico Granata       m_exe_ctx.Clear();
1559b9c1b51eSKate Stone       if (m_interpreter.GetScriptInterpreter()->LoadScriptingModule(
156011eb9c64SZachary Turner               entry.c_str(), m_options.m_allow_reload, init_session, error)) {
1561a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1562b9c1b51eSKate Stone       } else {
1563b9c1b51eSKate Stone         result.AppendErrorWithFormat("module importing failed: %s",
1564b9c1b51eSKate Stone                                      error.AsCString());
1565a9dbf432SEnrico Granata         result.SetStatus(eReturnStatusFailed);
1566a9dbf432SEnrico Granata       }
15673b00e35bSEnrico Granata     }
1568a9dbf432SEnrico Granata 
1569a9dbf432SEnrico Granata     return result.Succeeded();
1570a9dbf432SEnrico Granata   }
15710a305db7SEnrico Granata 
15725a988416SJim Ingham   CommandOptions m_options;
1573a9dbf432SEnrico Granata };
1574223383edSEnrico Granata 
1575223383edSEnrico Granata //-------------------------------------------------------------------------
1576223383edSEnrico Granata // CommandObjectCommandsScriptAdd
1577223383edSEnrico Granata //-------------------------------------------------------------------------
1578223383edSEnrico Granata 
15791f0f5b5bSZachary Turner static OptionEnumValueElement g_script_synchro_type[] = {
15801f0f5b5bSZachary Turner     {eScriptedCommandSynchronicitySynchronous, "synchronous",
15811f0f5b5bSZachary Turner      "Run synchronous"},
15821f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityAsynchronous, "asynchronous",
15831f0f5b5bSZachary Turner      "Run asynchronous"},
15841f0f5b5bSZachary Turner     {eScriptedCommandSynchronicityCurrentValue, "current",
15851f0f5b5bSZachary Turner      "Do not alter current setting"},
15861f0f5b5bSZachary Turner     {0, nullptr, nullptr}};
15871f0f5b5bSZachary Turner 
15881f0f5b5bSZachary Turner static OptionDefinition g_script_add_options[] = {
15891f0f5b5bSZachary Turner     // clang-format off
15901f0f5b5bSZachary Turner   { LLDB_OPT_SET_1,   false, "function",      'f', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypePythonFunction,               "Name of the Python function to bind to this command name." },
15911f0f5b5bSZachary Turner   { LLDB_OPT_SET_2,   false, "class",         'c', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypePythonClass,                  "Name of the Python class to bind to this command name." },
15921f0f5b5bSZachary Turner   { LLDB_OPT_SET_1,   false, "help"  ,        'h', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeHelpText,                     "The help text to display for this command." },
15931f0f5b5bSZachary Turner   { LLDB_OPT_SET_ALL, false, "synchronicity", 's', OptionParser::eRequiredArgument, nullptr, g_script_synchro_type, 0, eArgTypeScriptedCommandSynchronicity, "Set the synchronicity of this command's executions with regard to LLDB event system." },
15941f0f5b5bSZachary Turner     // clang-format on
15951f0f5b5bSZachary Turner };
15961f0f5b5bSZachary Turner 
1597b9c1b51eSKate Stone class CommandObjectCommandsScriptAdd : public CommandObjectParsed,
1598b9c1b51eSKate Stone                                        public IOHandlerDelegateMultiline {
15995a988416SJim Ingham public:
1600b9c1b51eSKate Stone   CommandObjectCommandsScriptAdd(CommandInterpreter &interpreter)
1601b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script add",
16025a988416SJim Ingham                             "Add a scripted function as an LLDB command.",
16036e3d8e7fSEugene Zelenko                             nullptr),
1604b9c1b51eSKate Stone         IOHandlerDelegateMultiline("DONE"), m_options() {
16055a988416SJim Ingham     CommandArgumentEntry arg1;
16065a988416SJim Ingham     CommandArgumentData cmd_arg;
16075a988416SJim Ingham 
16085a988416SJim Ingham     // Define the first (and only) variant of this arg.
16095a988416SJim Ingham     cmd_arg.arg_type = eArgTypeCommandName;
16105a988416SJim Ingham     cmd_arg.arg_repetition = eArgRepeatPlain;
16115a988416SJim Ingham 
1612b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1613b9c1b51eSKate Stone     // argument entry.
16145a988416SJim Ingham     arg1.push_back(cmd_arg);
16155a988416SJim Ingham 
16165a988416SJim Ingham     // Push the data for the first argument into the m_arguments vector.
16175a988416SJim Ingham     m_arguments.push_back(arg1);
16185a988416SJim Ingham   }
16195a988416SJim Ingham 
16206e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptAdd() override = default;
16215a988416SJim Ingham 
1622b9c1b51eSKate Stone   Options *GetOptions() override { return &m_options; }
16235a988416SJim Ingham 
16245a988416SJim Ingham protected:
1625b9c1b51eSKate Stone   class CommandOptions : public Options {
1626223383edSEnrico Granata   public:
1627b9c1b51eSKate Stone     CommandOptions()
1628b9c1b51eSKate Stone         : Options(), m_class_name(), m_funct_name(), m_short_help(),
1629b9c1b51eSKate Stone           m_synchronicity(eScriptedCommandSynchronicitySynchronous) {}
1630223383edSEnrico Granata 
16316e3d8e7fSEugene Zelenko     ~CommandOptions() override = default;
1632223383edSEnrico Granata 
1633b9c1b51eSKate Stone     Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1634b9c1b51eSKate Stone                          ExecutionContext *execution_context) override {
1635223383edSEnrico Granata       Error error;
16363bcdfc0eSGreg Clayton       const int short_option = m_getopt_table[option_idx].val;
1637223383edSEnrico Granata 
1638b9c1b51eSKate Stone       switch (short_option) {
1639223383edSEnrico Granata       case 'f':
1640735152e3SEnrico Granata         if (option_arg)
1641735152e3SEnrico Granata           m_funct_name.assign(option_arg);
1642735152e3SEnrico Granata         break;
16439fe00e52SEnrico Granata       case 'c':
16449fe00e52SEnrico Granata         if (option_arg)
16459fe00e52SEnrico Granata           m_class_name.assign(option_arg);
16469fe00e52SEnrico Granata         break;
1647735152e3SEnrico Granata       case 'h':
1648735152e3SEnrico Granata         if (option_arg)
1649735152e3SEnrico Granata           m_short_help.assign(option_arg);
1650223383edSEnrico Granata         break;
16510a305db7SEnrico Granata       case 's':
1652b9c1b51eSKate Stone         m_synchronicity =
1653b9c1b51eSKate Stone             (ScriptedCommandSynchronicity)Args::StringToOptionEnum(
16548cef4b0bSZachary Turner                 llvm::StringRef::withNullAsEmpty(option_arg),
16558cef4b0bSZachary Turner                 GetDefinitions()[option_idx].enum_values, 0, error);
16560a305db7SEnrico Granata         if (!error.Success())
1657b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
1658b9c1b51eSKate Stone               "unrecognized value for synchronicity '%s'", option_arg);
16590a305db7SEnrico Granata         break;
1660223383edSEnrico Granata       default:
1661b9c1b51eSKate Stone         error.SetErrorStringWithFormat("unrecognized option '%c'",
1662b9c1b51eSKate Stone                                        short_option);
1663223383edSEnrico Granata         break;
1664223383edSEnrico Granata       }
1665223383edSEnrico Granata 
1666223383edSEnrico Granata       return error;
1667223383edSEnrico Granata     }
1668223383edSEnrico Granata 
1669b9c1b51eSKate Stone     void OptionParsingStarting(ExecutionContext *execution_context) override {
16709fe00e52SEnrico Granata       m_class_name.clear();
1671735152e3SEnrico Granata       m_funct_name.clear();
1672735152e3SEnrico Granata       m_short_help.clear();
167344d93782SGreg Clayton       m_synchronicity = eScriptedCommandSynchronicitySynchronous;
1674223383edSEnrico Granata     }
1675223383edSEnrico Granata 
16761f0f5b5bSZachary Turner     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
167770602439SZachary Turner       return llvm::makeArrayRef(g_script_add_options);
16781f0f5b5bSZachary Turner     }
1679223383edSEnrico Granata 
1680223383edSEnrico Granata     // Instance variables to hold the values for command options.
1681223383edSEnrico Granata 
16829fe00e52SEnrico Granata     std::string m_class_name;
1683223383edSEnrico Granata     std::string m_funct_name;
1684735152e3SEnrico Granata     std::string m_short_help;
168544d93782SGreg Clayton     ScriptedCommandSynchronicity m_synchronicity;
1686223383edSEnrico Granata   };
1687223383edSEnrico Granata 
1688b9c1b51eSKate Stone   void IOHandlerActivated(IOHandler &io_handler) override {
168944d93782SGreg Clayton     StreamFileSP output_sp(io_handler.GetOutputStreamFile());
1690b9c1b51eSKate Stone     if (output_sp) {
169144d93782SGreg Clayton       output_sp->PutCString(g_python_command_instructions);
169244d93782SGreg Clayton       output_sp->Flush();
1693223383edSEnrico Granata     }
1694223383edSEnrico Granata   }
1695223383edSEnrico Granata 
1696b9c1b51eSKate Stone   void IOHandlerInputComplete(IOHandler &io_handler,
1697b9c1b51eSKate Stone                               std::string &data) override {
169844d93782SGreg Clayton     StreamFileSP error_sp = io_handler.GetErrorStreamFile();
169944d93782SGreg Clayton 
170044d93782SGreg Clayton     ScriptInterpreter *interpreter = m_interpreter.GetScriptInterpreter();
1701b9c1b51eSKate Stone     if (interpreter) {
170244d93782SGreg Clayton 
170344d93782SGreg Clayton       StringList lines;
170444d93782SGreg Clayton       lines.SplitIntoLines(data);
1705b9c1b51eSKate Stone       if (lines.GetSize() > 0) {
1706a73b7df7SEnrico Granata         std::string funct_name_str;
1707b9c1b51eSKate Stone         if (interpreter->GenerateScriptAliasFunction(lines, funct_name_str)) {
1708b9c1b51eSKate Stone           if (funct_name_str.empty()) {
1709b9c1b51eSKate Stone             error_sp->Printf("error: unable to obtain a function name, didn't "
1710b9c1b51eSKate Stone                              "add python command.\n");
171144d93782SGreg Clayton             error_sp->Flush();
1712b9c1b51eSKate Stone           } else {
1713223383edSEnrico Granata             // everything should be fine now, let's add this alias
1714223383edSEnrico Granata 
1715b9c1b51eSKate Stone             CommandObjectSP command_obj_sp(new CommandObjectPythonFunction(
1716b9c1b51eSKate Stone                 m_interpreter, m_cmd_name, funct_name_str.c_str(), m_short_help,
171744d93782SGreg Clayton                 m_synchronicity));
1718223383edSEnrico Granata 
1719b9c1b51eSKate Stone             if (!m_interpreter.AddUserCommand(m_cmd_name, command_obj_sp,
1720b9c1b51eSKate Stone                                               true)) {
1721b9c1b51eSKate Stone               error_sp->Printf("error: unable to add selected command, didn't "
1722b9c1b51eSKate Stone                                "add python command.\n");
172344d93782SGreg Clayton               error_sp->Flush();
1724223383edSEnrico Granata             }
1725223383edSEnrico Granata           }
1726b9c1b51eSKate Stone         } else {
1727b9c1b51eSKate Stone           error_sp->Printf(
1728b9c1b51eSKate Stone               "error: unable to create function, didn't add python command.\n");
172944d93782SGreg Clayton           error_sp->Flush();
173044d93782SGreg Clayton         }
1731b9c1b51eSKate Stone       } else {
173244d93782SGreg Clayton         error_sp->Printf("error: empty function, didn't add python command.\n");
173344d93782SGreg Clayton         error_sp->Flush();
173444d93782SGreg Clayton       }
1735b9c1b51eSKate Stone     } else {
1736b9c1b51eSKate Stone       error_sp->Printf(
1737b9c1b51eSKate Stone           "error: script interpreter missing, didn't add python command.\n");
173844d93782SGreg Clayton       error_sp->Flush();
173944d93782SGreg Clayton     }
174044d93782SGreg Clayton 
174144d93782SGreg Clayton     io_handler.SetIsDone(true);
174244d93782SGreg Clayton   }
1743223383edSEnrico Granata 
17445a988416SJim Ingham protected:
1745b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1746b9c1b51eSKate Stone     if (m_interpreter.GetDebugger().GetScriptLanguage() !=
1747b9c1b51eSKate Stone         lldb::eScriptLanguagePython) {
1748b9c1b51eSKate Stone       result.AppendError("only scripting language supported for scripted "
1749b9c1b51eSKate Stone                          "commands is currently Python");
175099f0b8f9SEnrico Granata       result.SetStatus(eReturnStatusFailed);
175199f0b8f9SEnrico Granata       return false;
175299f0b8f9SEnrico Granata     }
175399f0b8f9SEnrico Granata 
175411eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1755223383edSEnrico Granata       result.AppendError("'command script add' requires one argument");
1756223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1757223383edSEnrico Granata       return false;
1758223383edSEnrico Granata     }
1759223383edSEnrico Granata 
1760735152e3SEnrico Granata     // Store the options in case we get multi-line input
176144d93782SGreg Clayton     m_cmd_name = command.GetArgumentAtIndex(0);
1762735152e3SEnrico Granata     m_short_help.assign(m_options.m_short_help);
176344d93782SGreg Clayton     m_synchronicity = m_options.m_synchronicity;
1764223383edSEnrico Granata 
1765b9c1b51eSKate Stone     if (m_options.m_class_name.empty()) {
1766b9c1b51eSKate Stone       if (m_options.m_funct_name.empty()) {
1767b9c1b51eSKate Stone         m_interpreter.GetPythonCommandsFromIOHandler(
1768b9c1b51eSKate Stone             "     ",  // Prompt
176944d93782SGreg Clayton             *this,    // IOHandlerDelegate
177044d93782SGreg Clayton             true,     // Run IOHandler in async mode
1771b9c1b51eSKate Stone             nullptr); // Baton for the "io_handler" that will be passed back
1772b9c1b51eSKate Stone                       // into our IOHandlerDelegate functions
1773b9c1b51eSKate Stone       } else {
1774b9c1b51eSKate Stone         CommandObjectSP new_cmd(new CommandObjectPythonFunction(
1775b9c1b51eSKate Stone             m_interpreter, m_cmd_name, m_options.m_funct_name,
1776b9c1b51eSKate Stone             m_options.m_short_help, m_synchronicity));
1777b9c1b51eSKate Stone         if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
1778223383edSEnrico Granata           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1779b9c1b51eSKate Stone         } else {
1780223383edSEnrico Granata           result.AppendError("cannot add command");
1781223383edSEnrico Granata           result.SetStatus(eReturnStatusFailed);
1782223383edSEnrico Granata         }
1783223383edSEnrico Granata       }
1784b9c1b51eSKate Stone     } else {
1785b9c1b51eSKate Stone       ScriptInterpreter *interpreter =
1786b9c1b51eSKate Stone           GetCommandInterpreter().GetScriptInterpreter();
1787b9c1b51eSKate Stone       if (!interpreter) {
17889fe00e52SEnrico Granata         result.AppendError("cannot find ScriptInterpreter");
17899fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17909fe00e52SEnrico Granata         return false;
17919fe00e52SEnrico Granata       }
17929fe00e52SEnrico Granata 
1793b9c1b51eSKate Stone       auto cmd_obj_sp = interpreter->CreateScriptCommandObject(
1794b9c1b51eSKate Stone           m_options.m_class_name.c_str());
1795b9c1b51eSKate Stone       if (!cmd_obj_sp) {
17969fe00e52SEnrico Granata         result.AppendError("cannot create helper object");
17979fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
17989fe00e52SEnrico Granata         return false;
17999fe00e52SEnrico Granata       }
18009fe00e52SEnrico Granata 
1801b9c1b51eSKate Stone       CommandObjectSP new_cmd(new CommandObjectScriptingObject(
1802b9c1b51eSKate Stone           m_interpreter, m_cmd_name, cmd_obj_sp, m_synchronicity));
1803b9c1b51eSKate Stone       if (m_interpreter.AddUserCommand(m_cmd_name, new_cmd, true)) {
18049fe00e52SEnrico Granata         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1805b9c1b51eSKate Stone       } else {
18069fe00e52SEnrico Granata         result.AppendError("cannot add command");
18079fe00e52SEnrico Granata         result.SetStatus(eReturnStatusFailed);
18089fe00e52SEnrico Granata       }
18099fe00e52SEnrico Granata     }
1810223383edSEnrico Granata 
1811223383edSEnrico Granata     return result.Succeeded();
1812223383edSEnrico Granata   }
18135a988416SJim Ingham 
18145a988416SJim Ingham   CommandOptions m_options;
181544d93782SGreg Clayton   std::string m_cmd_name;
1816735152e3SEnrico Granata   std::string m_short_help;
181744d93782SGreg Clayton   ScriptedCommandSynchronicity m_synchronicity;
1818223383edSEnrico Granata };
1819223383edSEnrico Granata 
1820223383edSEnrico Granata //-------------------------------------------------------------------------
1821223383edSEnrico Granata // CommandObjectCommandsScriptList
1822223383edSEnrico Granata //-------------------------------------------------------------------------
1823223383edSEnrico Granata 
1824b9c1b51eSKate Stone class CommandObjectCommandsScriptList : public CommandObjectParsed {
1825223383edSEnrico Granata public:
1826b9c1b51eSKate Stone   CommandObjectCommandsScriptList(CommandInterpreter &interpreter)
1827b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script list",
1828b9c1b51eSKate Stone                             "List defined scripted commands.", nullptr) {}
1829223383edSEnrico Granata 
18306e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptList() override = default;
1831223383edSEnrico Granata 
1832b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1833b9c1b51eSKate Stone     m_interpreter.GetHelp(result, CommandInterpreter::eCommandTypesUserDef);
1834223383edSEnrico Granata 
1835223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1836223383edSEnrico Granata 
1837223383edSEnrico Granata     return true;
1838223383edSEnrico Granata   }
1839223383edSEnrico Granata };
1840223383edSEnrico Granata 
1841223383edSEnrico Granata //-------------------------------------------------------------------------
1842223383edSEnrico Granata // CommandObjectCommandsScriptClear
1843223383edSEnrico Granata //-------------------------------------------------------------------------
1844223383edSEnrico Granata 
1845b9c1b51eSKate Stone class CommandObjectCommandsScriptClear : public CommandObjectParsed {
1846223383edSEnrico Granata public:
1847b9c1b51eSKate Stone   CommandObjectCommandsScriptClear(CommandInterpreter &interpreter)
1848b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script clear",
1849b9c1b51eSKate Stone                             "Delete all scripted commands.", nullptr) {}
1850223383edSEnrico Granata 
18516e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptClear() override = default;
1852223383edSEnrico Granata 
18535a988416SJim Ingham protected:
1854b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1855223383edSEnrico Granata     m_interpreter.RemoveAllUser();
1856223383edSEnrico Granata 
1857223383edSEnrico Granata     result.SetStatus(eReturnStatusSuccessFinishResult);
1858223383edSEnrico Granata 
1859223383edSEnrico Granata     return true;
1860223383edSEnrico Granata   }
1861223383edSEnrico Granata };
1862223383edSEnrico Granata 
1863223383edSEnrico Granata //-------------------------------------------------------------------------
1864223383edSEnrico Granata // CommandObjectCommandsScriptDelete
1865223383edSEnrico Granata //-------------------------------------------------------------------------
1866223383edSEnrico Granata 
1867b9c1b51eSKate Stone class CommandObjectCommandsScriptDelete : public CommandObjectParsed {
1868223383edSEnrico Granata public:
1869b9c1b51eSKate Stone   CommandObjectCommandsScriptDelete(CommandInterpreter &interpreter)
1870b9c1b51eSKate Stone       : CommandObjectParsed(interpreter, "command script delete",
1871b9c1b51eSKate Stone                             "Delete a scripted command.", nullptr) {
1872223383edSEnrico Granata     CommandArgumentEntry arg1;
1873223383edSEnrico Granata     CommandArgumentData cmd_arg;
1874223383edSEnrico Granata 
1875223383edSEnrico Granata     // Define the first (and only) variant of this arg.
1876223383edSEnrico Granata     cmd_arg.arg_type = eArgTypeCommandName;
1877223383edSEnrico Granata     cmd_arg.arg_repetition = eArgRepeatPlain;
1878223383edSEnrico Granata 
1879b9c1b51eSKate Stone     // There is only one variant this argument could be; put it into the
1880b9c1b51eSKate Stone     // argument entry.
1881223383edSEnrico Granata     arg1.push_back(cmd_arg);
1882223383edSEnrico Granata 
1883223383edSEnrico Granata     // Push the data for the first argument into the m_arguments vector.
1884223383edSEnrico Granata     m_arguments.push_back(arg1);
1885223383edSEnrico Granata   }
1886223383edSEnrico Granata 
18876e3d8e7fSEugene Zelenko   ~CommandObjectCommandsScriptDelete() override = default;
1888223383edSEnrico Granata 
18895a988416SJim Ingham protected:
1890b9c1b51eSKate Stone   bool DoExecute(Args &command, CommandReturnObject &result) override {
1891223383edSEnrico Granata 
189211eb9c64SZachary Turner     if (command.GetArgumentCount() != 1) {
1893223383edSEnrico Granata       result.AppendError("'command script delete' requires one argument");
1894223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1895223383edSEnrico Granata       return false;
1896223383edSEnrico Granata     }
1897223383edSEnrico Granata 
18985a988416SJim Ingham     const char *cmd_name = command.GetArgumentAtIndex(0);
1899223383edSEnrico Granata 
1900b9c1b51eSKate Stone     if (cmd_name && *cmd_name && m_interpreter.HasUserCommands() &&
1901b9c1b51eSKate Stone         m_interpreter.UserCommandExists(cmd_name)) {
1902223383edSEnrico Granata       m_interpreter.RemoveUser(cmd_name);
1903223383edSEnrico Granata       result.SetStatus(eReturnStatusSuccessFinishResult);
1904b9c1b51eSKate Stone     } else {
1905223383edSEnrico Granata       result.AppendErrorWithFormat("command %s not found", cmd_name);
1906223383edSEnrico Granata       result.SetStatus(eReturnStatusFailed);
1907223383edSEnrico Granata     }
1908223383edSEnrico Granata 
1909223383edSEnrico Granata     return result.Succeeded();
1910223383edSEnrico Granata   }
1911223383edSEnrico Granata };
1912223383edSEnrico Granata 
1913223383edSEnrico Granata #pragma mark CommandObjectMultiwordCommandsScript
1914223383edSEnrico Granata 
1915223383edSEnrico Granata //-------------------------------------------------------------------------
1916223383edSEnrico Granata // CommandObjectMultiwordCommandsScript
1917223383edSEnrico Granata //-------------------------------------------------------------------------
1918223383edSEnrico Granata 
1919b9c1b51eSKate Stone class CommandObjectMultiwordCommandsScript : public CommandObjectMultiword {
1920223383edSEnrico Granata public:
19217428a18cSKate Stone   CommandObjectMultiwordCommandsScript(CommandInterpreter &interpreter)
1922b9c1b51eSKate Stone       : CommandObjectMultiword(
1923b9c1b51eSKate Stone             interpreter, "command script", "Commands for managing custom "
1924b9c1b51eSKate Stone                                            "commands implemented by "
1925b9c1b51eSKate Stone                                            "interpreter scripts.",
1926b9c1b51eSKate Stone             "command script <subcommand> [<subcommand-options>]") {
1927b9c1b51eSKate Stone     LoadSubCommand("add", CommandObjectSP(
1928b9c1b51eSKate Stone                               new CommandObjectCommandsScriptAdd(interpreter)));
1929b9c1b51eSKate Stone     LoadSubCommand(
1930b9c1b51eSKate Stone         "delete",
1931b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptDelete(interpreter)));
1932b9c1b51eSKate Stone     LoadSubCommand(
1933b9c1b51eSKate Stone         "clear",
1934b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptClear(interpreter)));
1935b9c1b51eSKate Stone     LoadSubCommand("list", CommandObjectSP(new CommandObjectCommandsScriptList(
1936b9c1b51eSKate Stone                                interpreter)));
1937b9c1b51eSKate Stone     LoadSubCommand(
1938b9c1b51eSKate Stone         "import",
1939b9c1b51eSKate Stone         CommandObjectSP(new CommandObjectCommandsScriptImport(interpreter)));
1940223383edSEnrico Granata   }
1941223383edSEnrico Granata 
19426e3d8e7fSEugene Zelenko   ~CommandObjectMultiwordCommandsScript() override = default;
1943223383edSEnrico Granata };
1944223383edSEnrico Granata 
1945ebc09c36SJim Ingham #pragma mark CommandObjectMultiwordCommands
1946ebc09c36SJim Ingham 
1947ebc09c36SJim Ingham //-------------------------------------------------------------------------
1948ebc09c36SJim Ingham // CommandObjectMultiwordCommands
1949ebc09c36SJim Ingham //-------------------------------------------------------------------------
1950ebc09c36SJim Ingham 
1951b9c1b51eSKate Stone CommandObjectMultiwordCommands::CommandObjectMultiwordCommands(
1952b9c1b51eSKate Stone     CommandInterpreter &interpreter)
1953b9c1b51eSKate Stone     : CommandObjectMultiword(interpreter, "command",
1954b9c1b51eSKate Stone                              "Commands for managing custom LLDB commands.",
1955b9c1b51eSKate Stone                              "command <subcommand> [<subcommand-options>]") {
1956b9c1b51eSKate Stone   LoadSubCommand("source",
1957b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsSource(interpreter)));
1958b9c1b51eSKate Stone   LoadSubCommand("alias",
1959b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsAlias(interpreter)));
1960b9c1b51eSKate Stone   LoadSubCommand("unalias", CommandObjectSP(
1961b9c1b51eSKate Stone                                 new CommandObjectCommandsUnalias(interpreter)));
1962b9c1b51eSKate Stone   LoadSubCommand("delete",
1963b9c1b51eSKate Stone                  CommandObjectSP(new CommandObjectCommandsDelete(interpreter)));
1964b9c1b51eSKate Stone   LoadSubCommand(
1965b9c1b51eSKate Stone       "regex", CommandObjectSP(new CommandObjectCommandsAddRegex(interpreter)));
1966b9c1b51eSKate Stone   LoadSubCommand("history", CommandObjectSP(
1967b9c1b51eSKate Stone                                 new CommandObjectCommandsHistory(interpreter)));
1968b9c1b51eSKate Stone   LoadSubCommand(
1969b9c1b51eSKate Stone       "script",
1970b9c1b51eSKate Stone       CommandObjectSP(new CommandObjectMultiwordCommandsScript(interpreter)));
1971ebc09c36SJim Ingham }
1972ebc09c36SJim Ingham 
19736e3d8e7fSEugene Zelenko CommandObjectMultiwordCommands::~CommandObjectMultiwordCommands() = default;
1974