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