1 //===-- CommandObjectMultiword.cpp ----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Interpreter/CommandObjectMultiword.h"
10 #include "lldb/Interpreter/CommandInterpreter.h"
11 #include "lldb/Interpreter/CommandReturnObject.h"
12 #include "lldb/Interpreter/Options.h"
13 
14 using namespace lldb;
15 using namespace lldb_private;
16 
17 // CommandObjectMultiword
18 
CommandObjectMultiword(CommandInterpreter & interpreter,const char * name,const char * help,const char * syntax,uint32_t flags)19 CommandObjectMultiword::CommandObjectMultiword(CommandInterpreter &interpreter,
20                                                const char *name,
21                                                const char *help,
22                                                const char *syntax,
23                                                uint32_t flags)
24     : CommandObject(interpreter, name, help, syntax, flags),
25       m_can_be_removed(false) {}
26 
27 CommandObjectMultiword::~CommandObjectMultiword() = default;
28 
GetSubcommandSP(llvm::StringRef sub_cmd,StringList * matches)29 CommandObjectSP CommandObjectMultiword::GetSubcommandSP(llvm::StringRef sub_cmd,
30                                                         StringList *matches) {
31   CommandObjectSP return_cmd_sp;
32   CommandObject::CommandMap::iterator pos;
33 
34   if (!m_subcommand_dict.empty()) {
35     pos = m_subcommand_dict.find(std::string(sub_cmd));
36     if (pos != m_subcommand_dict.end()) {
37       // An exact match; append the sub_cmd to the 'matches' string list.
38       if (matches)
39         matches->AppendString(sub_cmd);
40       return_cmd_sp = pos->second;
41     } else {
42       StringList local_matches;
43       if (matches == nullptr)
44         matches = &local_matches;
45       int num_matches =
46           AddNamesMatchingPartialString(m_subcommand_dict, sub_cmd, *matches);
47 
48       if (num_matches == 1) {
49         // Cleaner, but slightly less efficient would be to call back into this
50         // function, since I now know I have an exact match...
51 
52         sub_cmd = matches->GetStringAtIndex(0);
53         pos = m_subcommand_dict.find(std::string(sub_cmd));
54         if (pos != m_subcommand_dict.end())
55           return_cmd_sp = pos->second;
56       }
57     }
58   }
59   return return_cmd_sp;
60 }
61 
62 CommandObject *
GetSubcommandObject(llvm::StringRef sub_cmd,StringList * matches)63 CommandObjectMultiword::GetSubcommandObject(llvm::StringRef sub_cmd,
64                                             StringList *matches) {
65   return GetSubcommandSP(sub_cmd, matches).get();
66 }
67 
LoadSubCommand(llvm::StringRef name,const CommandObjectSP & cmd_obj)68 bool CommandObjectMultiword::LoadSubCommand(llvm::StringRef name,
69                                             const CommandObjectSP &cmd_obj) {
70   if (cmd_obj)
71     assert((&GetCommandInterpreter() == &cmd_obj->GetCommandInterpreter()) &&
72            "tried to add a CommandObject from a different interpreter");
73 
74   CommandMap::iterator pos;
75   bool success = true;
76 
77   pos = m_subcommand_dict.find(std::string(name));
78   if (pos == m_subcommand_dict.end()) {
79     m_subcommand_dict[std::string(name)] = cmd_obj;
80   } else
81     success = false;
82 
83   return success;
84 }
85 
Execute(const char * args_string,CommandReturnObject & result)86 bool CommandObjectMultiword::Execute(const char *args_string,
87                                      CommandReturnObject &result) {
88   Args args(args_string);
89   const size_t argc = args.GetArgumentCount();
90   if (argc == 0) {
91     this->CommandObject::GenerateHelpText(result);
92     return result.Succeeded();
93   }
94 
95   auto sub_command = args[0].ref();
96   if (sub_command.empty()) {
97     result.AppendError("Need to specify a non-empty subcommand.");
98     return result.Succeeded();
99   }
100 
101   if (sub_command.equals_lower("help")) {
102     this->CommandObject::GenerateHelpText(result);
103     return result.Succeeded();
104   }
105 
106   if (m_subcommand_dict.empty()) {
107     result.AppendErrorWithFormat("'%s' does not have any subcommands.\n",
108                                  GetCommandName().str().c_str());
109     result.SetStatus(eReturnStatusFailed);
110     return false;
111   }
112 
113   StringList matches;
114   CommandObject *sub_cmd_obj = GetSubcommandObject(sub_command, &matches);
115   if (sub_cmd_obj != nullptr) {
116     // Now call CommandObject::Execute to process options in `rest_of_line`.
117     // From there the command-specific version of Execute will be called, with
118     // the processed arguments.
119 
120     args.Shift();
121     sub_cmd_obj->Execute(args_string, result);
122     return result.Succeeded();
123   }
124 
125   std::string error_msg;
126   const size_t num_subcmd_matches = matches.GetSize();
127   if (num_subcmd_matches > 0)
128     error_msg.assign("ambiguous command ");
129   else
130     error_msg.assign("invalid command ");
131 
132   error_msg.append("'");
133   error_msg.append(std::string(GetCommandName()));
134   error_msg.append(" ");
135   error_msg.append(std::string(sub_command));
136   error_msg.append("'.");
137 
138   if (num_subcmd_matches > 0) {
139     error_msg.append(" Possible completions:");
140     for (const std::string &match : matches) {
141       error_msg.append("\n\t");
142       error_msg.append(match);
143     }
144   }
145   error_msg.append("\n");
146   result.AppendRawError(error_msg.c_str());
147   result.SetStatus(eReturnStatusFailed);
148   return false;
149 }
150 
GenerateHelpText(Stream & output_stream)151 void CommandObjectMultiword::GenerateHelpText(Stream &output_stream) {
152   // First time through here, generate the help text for the object and push it
153   // to the return result object as well
154 
155   CommandObject::GenerateHelpText(output_stream);
156   output_stream.PutCString("\nThe following subcommands are supported:\n\n");
157 
158   CommandMap::iterator pos;
159   uint32_t max_len = FindLongestCommandWord(m_subcommand_dict);
160 
161   if (max_len)
162     max_len += 4; // Indent the output by 4 spaces.
163 
164   for (pos = m_subcommand_dict.begin(); pos != m_subcommand_dict.end(); ++pos) {
165     std::string indented_command("    ");
166     indented_command.append(pos->first);
167     if (pos->second->WantsRawCommandString()) {
168       std::string help_text(std::string(pos->second->GetHelp()));
169       help_text.append("  Expects 'raw' input (see 'help raw-input'.)");
170       m_interpreter.OutputFormattedHelpText(output_stream, indented_command,
171                                             "--", help_text, max_len);
172     } else
173       m_interpreter.OutputFormattedHelpText(output_stream, indented_command,
174                                             "--", pos->second->GetHelp(),
175                                             max_len);
176   }
177 
178   output_stream.PutCString("\nFor more help on any particular subcommand, type "
179                            "'help <command> <subcommand>'.\n");
180 }
181 
HandleCompletion(CompletionRequest & request)182 void CommandObjectMultiword::HandleCompletion(CompletionRequest &request) {
183   auto arg0 = request.GetParsedLine()[0].ref();
184   if (request.GetCursorIndex() == 0) {
185     StringList new_matches, descriptions;
186     AddNamesMatchingPartialString(m_subcommand_dict, arg0, new_matches,
187                                   &descriptions);
188     request.AddCompletions(new_matches, descriptions);
189 
190     if (new_matches.GetSize() == 1 &&
191         new_matches.GetStringAtIndex(0) != nullptr &&
192         (arg0 == new_matches.GetStringAtIndex(0))) {
193       StringList temp_matches;
194       CommandObject *cmd_obj = GetSubcommandObject(arg0, &temp_matches);
195       if (cmd_obj != nullptr) {
196         if (request.GetParsedLine().GetArgumentCount() != 1) {
197           request.GetParsedLine().Shift();
198           request.AppendEmptyArgument();
199           cmd_obj->HandleCompletion(request);
200         }
201       }
202     }
203     return;
204   }
205 
206   StringList new_matches;
207   CommandObject *sub_command_object = GetSubcommandObject(arg0, &new_matches);
208   if (sub_command_object == nullptr) {
209     request.AddCompletions(new_matches);
210     return;
211   }
212 
213   // Remove the one match that we got from calling GetSubcommandObject.
214   new_matches.DeleteStringAtIndex(0);
215   request.AddCompletions(new_matches);
216   request.ShiftArguments();
217   sub_command_object->HandleCompletion(request);
218 }
219 
GetRepeatCommand(Args & current_command_args,uint32_t index)220 const char *CommandObjectMultiword::GetRepeatCommand(Args &current_command_args,
221                                                      uint32_t index) {
222   index++;
223   if (current_command_args.GetArgumentCount() <= index)
224     return nullptr;
225   CommandObject *sub_command_object =
226       GetSubcommandObject(current_command_args[index].ref());
227   if (sub_command_object == nullptr)
228     return nullptr;
229   return sub_command_object->GetRepeatCommand(current_command_args, index);
230 }
231 
AproposAllSubCommands(llvm::StringRef prefix,llvm::StringRef search_word,StringList & commands_found,StringList & commands_help)232 void CommandObjectMultiword::AproposAllSubCommands(llvm::StringRef prefix,
233                                                    llvm::StringRef search_word,
234                                                    StringList &commands_found,
235                                                    StringList &commands_help) {
236   CommandObject::CommandMap::const_iterator pos;
237 
238   for (pos = m_subcommand_dict.begin(); pos != m_subcommand_dict.end(); ++pos) {
239     const char *command_name = pos->first.c_str();
240     CommandObject *sub_cmd_obj = pos->second.get();
241     StreamString complete_command_name;
242 
243     complete_command_name << prefix << " " << command_name;
244 
245     if (sub_cmd_obj->HelpTextContainsWord(search_word)) {
246       commands_found.AppendString(complete_command_name.GetString());
247       commands_help.AppendString(sub_cmd_obj->GetHelp());
248     }
249 
250     if (sub_cmd_obj->IsMultiwordObject())
251       sub_cmd_obj->AproposAllSubCommands(complete_command_name.GetString(),
252                                          search_word, commands_found,
253                                          commands_help);
254   }
255 }
256 
CommandObjectProxy(CommandInterpreter & interpreter,const char * name,const char * help,const char * syntax,uint32_t flags)257 CommandObjectProxy::CommandObjectProxy(CommandInterpreter &interpreter,
258                                        const char *name, const char *help,
259                                        const char *syntax, uint32_t flags)
260     : CommandObject(interpreter, name, help, syntax, flags) {}
261 
262 CommandObjectProxy::~CommandObjectProxy() = default;
263 
GetHelpLong()264 llvm::StringRef CommandObjectProxy::GetHelpLong() {
265   CommandObject *proxy_command = GetProxyCommandObject();
266   if (proxy_command)
267     return proxy_command->GetHelpLong();
268   return llvm::StringRef();
269 }
270 
IsRemovable() const271 bool CommandObjectProxy::IsRemovable() const {
272   const CommandObject *proxy_command =
273       const_cast<CommandObjectProxy *>(this)->GetProxyCommandObject();
274   if (proxy_command)
275     return proxy_command->IsRemovable();
276   return false;
277 }
278 
IsMultiwordObject()279 bool CommandObjectProxy::IsMultiwordObject() {
280   CommandObject *proxy_command = GetProxyCommandObject();
281   if (proxy_command)
282     return proxy_command->IsMultiwordObject();
283   return false;
284 }
285 
GetAsMultiwordCommand()286 CommandObjectMultiword *CommandObjectProxy::GetAsMultiwordCommand() {
287   CommandObject *proxy_command = GetProxyCommandObject();
288   if (proxy_command)
289     return proxy_command->GetAsMultiwordCommand();
290   return nullptr;
291 }
292 
GenerateHelpText(Stream & result)293 void CommandObjectProxy::GenerateHelpText(Stream &result) {
294   CommandObject *proxy_command = GetProxyCommandObject();
295   if (proxy_command)
296     return proxy_command->GenerateHelpText(result);
297 }
298 
299 lldb::CommandObjectSP
GetSubcommandSP(llvm::StringRef sub_cmd,StringList * matches)300 CommandObjectProxy::GetSubcommandSP(llvm::StringRef sub_cmd,
301                                     StringList *matches) {
302   CommandObject *proxy_command = GetProxyCommandObject();
303   if (proxy_command)
304     return proxy_command->GetSubcommandSP(sub_cmd, matches);
305   return lldb::CommandObjectSP();
306 }
307 
GetSubcommandObject(llvm::StringRef sub_cmd,StringList * matches)308 CommandObject *CommandObjectProxy::GetSubcommandObject(llvm::StringRef sub_cmd,
309                                                        StringList *matches) {
310   CommandObject *proxy_command = GetProxyCommandObject();
311   if (proxy_command)
312     return proxy_command->GetSubcommandObject(sub_cmd, matches);
313   return nullptr;
314 }
315 
AproposAllSubCommands(llvm::StringRef prefix,llvm::StringRef search_word,StringList & commands_found,StringList & commands_help)316 void CommandObjectProxy::AproposAllSubCommands(llvm::StringRef prefix,
317                                                llvm::StringRef search_word,
318                                                StringList &commands_found,
319                                                StringList &commands_help) {
320   CommandObject *proxy_command = GetProxyCommandObject();
321   if (proxy_command)
322     return proxy_command->AproposAllSubCommands(prefix, search_word,
323                                                 commands_found, commands_help);
324 }
325 
LoadSubCommand(llvm::StringRef cmd_name,const lldb::CommandObjectSP & command_sp)326 bool CommandObjectProxy::LoadSubCommand(
327     llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_sp) {
328   CommandObject *proxy_command = GetProxyCommandObject();
329   if (proxy_command)
330     return proxy_command->LoadSubCommand(cmd_name, command_sp);
331   return false;
332 }
333 
WantsRawCommandString()334 bool CommandObjectProxy::WantsRawCommandString() {
335   CommandObject *proxy_command = GetProxyCommandObject();
336   if (proxy_command)
337     return proxy_command->WantsRawCommandString();
338   return false;
339 }
340 
WantsCompletion()341 bool CommandObjectProxy::WantsCompletion() {
342   CommandObject *proxy_command = GetProxyCommandObject();
343   if (proxy_command)
344     return proxy_command->WantsCompletion();
345   return false;
346 }
347 
GetOptions()348 Options *CommandObjectProxy::GetOptions() {
349   CommandObject *proxy_command = GetProxyCommandObject();
350   if (proxy_command)
351     return proxy_command->GetOptions();
352   return nullptr;
353 }
354 
HandleCompletion(CompletionRequest & request)355 void CommandObjectProxy::HandleCompletion(CompletionRequest &request) {
356   CommandObject *proxy_command = GetProxyCommandObject();
357   if (proxy_command)
358     proxy_command->HandleCompletion(request);
359 }
360 
HandleArgumentCompletion(CompletionRequest & request,OptionElementVector & opt_element_vector)361 void CommandObjectProxy::HandleArgumentCompletion(
362     CompletionRequest &request, OptionElementVector &opt_element_vector) {
363   CommandObject *proxy_command = GetProxyCommandObject();
364   if (proxy_command)
365     proxy_command->HandleArgumentCompletion(request, opt_element_vector);
366 }
367 
GetRepeatCommand(Args & current_command_args,uint32_t index)368 const char *CommandObjectProxy::GetRepeatCommand(Args &current_command_args,
369                                                  uint32_t index) {
370   CommandObject *proxy_command = GetProxyCommandObject();
371   if (proxy_command)
372     return proxy_command->GetRepeatCommand(current_command_args, index);
373   return nullptr;
374 }
375 
Execute(const char * args_string,CommandReturnObject & result)376 bool CommandObjectProxy::Execute(const char *args_string,
377                                  CommandReturnObject &result) {
378   CommandObject *proxy_command = GetProxyCommandObject();
379   if (proxy_command)
380     return proxy_command->Execute(args_string, result);
381   result.AppendError("command is not implemented");
382   result.SetStatus(eReturnStatusFailed);
383   return false;
384 }
385