xref: /llvm-project/lldb/source/Commands/CommandObjectHelp.cpp (revision a925974bf166a83cfd45b0ca89c5c65d17f275cc)
1 //===-- CommandObjectHelp.cpp -----------------------------------*- C++ -*-===//
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 "CommandObjectHelp.h"
10 #include "lldb/Interpreter/CommandInterpreter.h"
11 #include "lldb/Interpreter/CommandObjectMultiword.h"
12 #include "lldb/Interpreter/CommandReturnObject.h"
13 #include "lldb/Interpreter/Options.h"
14 
15 using namespace lldb;
16 using namespace lldb_private;
17 
18 // CommandObjectHelp
19 
20 void CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
21     Stream *s, llvm::StringRef command, llvm::StringRef prefix,
22     llvm::StringRef subcommand, bool include_upropos,
23     bool include_type_lookup) {
24   if (!s || command.empty())
25     return;
26 
27   std::string command_str = command.str();
28   std::string prefix_str = prefix.str();
29   std::string subcommand_str = subcommand.str();
30   const std::string &lookup_str =
31       !subcommand_str.empty() ? subcommand_str : command_str;
32   s->Printf("'%s' is not a known command.\n", command_str.c_str());
33   s->Printf("Try '%shelp' to see a current list of commands.\n",
34             prefix.str().c_str());
35   if (include_upropos) {
36     s->Printf("Try '%sapropos %s' for a list of related commands.\n",
37               prefix_str.c_str(), lookup_str.c_str());
38   }
39   if (include_type_lookup) {
40     s->Printf("Try '%stype lookup %s' for information on types, methods, "
41               "functions, modules, etc.",
42               prefix_str.c_str(), lookup_str.c_str());
43   }
44 }
45 
46 CommandObjectHelp::CommandObjectHelp(CommandInterpreter &interpreter)
47     : CommandObjectParsed(interpreter, "help",
48                           "Show a list of all debugger "
49                           "commands, or give details "
50                           "about a specific command.",
51                           "help [<cmd-name>]"),
52       m_options() {
53   CommandArgumentEntry arg;
54   CommandArgumentData command_arg;
55 
56   // Define the first (and only) variant of this arg.
57   command_arg.arg_type = eArgTypeCommandName;
58   command_arg.arg_repetition = eArgRepeatStar;
59 
60   // There is only one variant this argument could be; put it into the argument
61   // entry.
62   arg.push_back(command_arg);
63 
64   // Push the data for the first argument into the m_arguments vector.
65   m_arguments.push_back(arg);
66 }
67 
68 CommandObjectHelp::~CommandObjectHelp() = default;
69 
70 #define LLDB_OPTIONS_help
71 #include "CommandOptions.inc"
72 
73 llvm::ArrayRef<OptionDefinition>
74 CommandObjectHelp::CommandOptions::GetDefinitions() {
75   return llvm::makeArrayRef(g_help_options);
76 }
77 
78 bool CommandObjectHelp::DoExecute(Args &command, CommandReturnObject &result) {
79   CommandObject::CommandMap::iterator pos;
80   CommandObject *cmd_obj;
81   const size_t argc = command.GetArgumentCount();
82 
83   // 'help' doesn't take any arguments, other than command names.  If argc is
84   // 0, we show the user all commands (aliases and user commands if asked for).
85   // Otherwise every argument must be the name of a command or a sub-command.
86   if (argc == 0) {
87     uint32_t cmd_types = CommandInterpreter::eCommandTypesBuiltin;
88     if (m_options.m_show_aliases)
89       cmd_types |= CommandInterpreter::eCommandTypesAliases;
90     if (m_options.m_show_user_defined)
91       cmd_types |= CommandInterpreter::eCommandTypesUserDef;
92     if (m_options.m_show_hidden)
93       cmd_types |= CommandInterpreter::eCommandTypesHidden;
94 
95     result.SetStatus(eReturnStatusSuccessFinishNoResult);
96     m_interpreter.GetHelp(result, cmd_types); // General help
97   } else {
98     // Get command object for the first command argument. Only search built-in
99     // command dictionary.
100     StringList matches;
101     auto command_name = command[0].ref();
102     cmd_obj = m_interpreter.GetCommandObject(command_name, &matches);
103 
104     if (cmd_obj != nullptr) {
105       StringList matches;
106       bool all_okay = true;
107       CommandObject *sub_cmd_obj = cmd_obj;
108       // Loop down through sub_command dictionaries until we find the command
109       // object that corresponds to the help command entered.
110       std::string sub_command;
111       for (auto &entry : command.entries().drop_front()) {
112         sub_command = entry.ref();
113         matches.Clear();
114         if (sub_cmd_obj->IsAlias())
115           sub_cmd_obj =
116               ((CommandAlias *)sub_cmd_obj)->GetUnderlyingCommand().get();
117         if (!sub_cmd_obj->IsMultiwordObject()) {
118           all_okay = false;
119           break;
120         } else {
121           CommandObject *found_cmd;
122           found_cmd =
123               sub_cmd_obj->GetSubcommandObject(sub_command.c_str(), &matches);
124           if (found_cmd == nullptr || matches.GetSize() > 1) {
125             all_okay = false;
126             break;
127           } else
128             sub_cmd_obj = found_cmd;
129         }
130       }
131 
132       if (!all_okay || (sub_cmd_obj == nullptr)) {
133         std::string cmd_string;
134         command.GetCommandString(cmd_string);
135         if (matches.GetSize() >= 2) {
136           StreamString s;
137           s.Printf("ambiguous command %s", cmd_string.c_str());
138           size_t num_matches = matches.GetSize();
139           for (size_t match_idx = 0; match_idx < num_matches; match_idx++) {
140             s.Printf("\n\t%s", matches.GetStringAtIndex(match_idx));
141           }
142           s.Printf("\n");
143           result.AppendError(s.GetString());
144           result.SetStatus(eReturnStatusFailed);
145           return false;
146         } else if (!sub_cmd_obj) {
147           StreamString error_msg_stream;
148           GenerateAdditionalHelpAvenuesMessage(
149               &error_msg_stream, cmd_string.c_str(),
150               m_interpreter.GetCommandPrefix(), sub_command.c_str());
151           result.AppendError(error_msg_stream.GetString());
152           result.SetStatus(eReturnStatusFailed);
153           return false;
154         } else {
155           GenerateAdditionalHelpAvenuesMessage(
156               &result.GetOutputStream(), cmd_string.c_str(),
157               m_interpreter.GetCommandPrefix(), sub_command.c_str());
158           result.GetOutputStream().Printf(
159               "\nThe closest match is '%s'. Help on it follows.\n\n",
160               sub_cmd_obj->GetCommandName().str().c_str());
161         }
162       }
163 
164       sub_cmd_obj->GenerateHelpText(result);
165       std::string alias_full_name;
166       // Don't use AliasExists here, that only checks exact name matches.  If
167       // the user typed a shorter unique alias name, we should still tell them
168       // it was an alias.
169       if (m_interpreter.GetAliasFullName(command_name, alias_full_name)) {
170         StreamString sstr;
171         m_interpreter.GetAlias(alias_full_name)->GetAliasExpansion(sstr);
172         result.GetOutputStream().Printf("\n'%s' is an abbreviation for %s\n",
173                                         command[0].c_str(), sstr.GetData());
174       }
175     } else if (matches.GetSize() > 0) {
176       Stream &output_strm = result.GetOutputStream();
177       output_strm.Printf("Help requested with ambiguous command name, possible "
178                          "completions:\n");
179       const size_t match_count = matches.GetSize();
180       for (size_t i = 0; i < match_count; i++) {
181         output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i));
182       }
183     } else {
184       // Maybe the user is asking for help about a command argument rather than
185       // a command.
186       const CommandArgumentType arg_type =
187           CommandObject::LookupArgumentName(command_name);
188       if (arg_type != eArgTypeLastArg) {
189         Stream &output_strm = result.GetOutputStream();
190         CommandObject::GetArgumentHelp(output_strm, arg_type, m_interpreter);
191         result.SetStatus(eReturnStatusSuccessFinishNoResult);
192       } else {
193         StreamString error_msg_stream;
194         GenerateAdditionalHelpAvenuesMessage(&error_msg_stream, command_name,
195                                              m_interpreter.GetCommandPrefix(),
196                                              "");
197         result.AppendError(error_msg_stream.GetString());
198         result.SetStatus(eReturnStatusFailed);
199       }
200     }
201   }
202 
203   return result.Succeeded();
204 }
205 
206 void CommandObjectHelp::HandleCompletion(CompletionRequest &request) {
207   // Return the completions of the commands in the help system:
208   if (request.GetCursorIndex() == 0) {
209     m_interpreter.HandleCompletionMatches(request);
210     return;
211   }
212   CommandObject *cmd_obj =
213       m_interpreter.GetCommandObject(request.GetParsedLine()[0].ref());
214 
215   // The command that they are getting help on might be ambiguous, in which
216   // case we should complete that, otherwise complete with the command the
217   // user is getting help on...
218 
219   if (cmd_obj) {
220     request.ShiftArguments();
221     cmd_obj->HandleCompletion(request);
222     return;
223   }
224   m_interpreter.HandleCompletionMatches(request);
225 }
226