1 //===-- CommandObjectHelp.cpp -----------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "CommandObjectHelp.h"
15 #include "lldb/Interpreter/CommandInterpreter.h"
16 #include "lldb/Interpreter/CommandObjectMultiword.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/Options.h"
19 
20 using namespace lldb;
21 using namespace lldb_private;
22 
23 //-------------------------------------------------------------------------
24 // CommandObjectHelp
25 //-------------------------------------------------------------------------
26 
27 void CommandObjectHelp::GenerateAdditionalHelpAvenuesMessage(
28     Stream *s, const char *command, const char *prefix, const char *subcommand,
29     bool include_apropos, bool include_type_lookup) {
30   if (s && command && *command) {
31     s->Printf("'%s' is not a known command.\n", command);
32     s->Printf("Try '%shelp' to see a current list of commands.\n",
33               prefix ? prefix : "");
34     if (include_apropos) {
35       s->Printf("Try '%sapropos %s' for a list of related commands.\n",
36                 prefix ? prefix : "", subcommand ? subcommand : command);
37     }
38     if (include_type_lookup) {
39       s->Printf("Try '%stype lookup %s' for information on types, methods, "
40                 "functions, modules, etc.",
41                 prefix ? prefix : "", subcommand ? subcommand : command);
42     }
43   }
44 }
45 
46 CommandObjectHelp::CommandObjectHelp(CommandInterpreter &interpreter)
47     : CommandObjectParsed(interpreter, "help", "Show a list of all debugger "
48                                                "commands, or give details "
49                                                "about a specific command.",
50                           "help [<cmd-name>]"),
51       m_options() {
52   CommandArgumentEntry arg;
53   CommandArgumentData command_arg;
54 
55   // Define the first (and only) variant of this arg.
56   command_arg.arg_type = eArgTypeCommandName;
57   command_arg.arg_repetition = eArgRepeatStar;
58 
59   // There is only one variant this argument could be; put it into the argument
60   // entry.
61   arg.push_back(command_arg);
62 
63   // Push the data for the first argument into the m_arguments vector.
64   m_arguments.push_back(arg);
65 }
66 
67 CommandObjectHelp::~CommandObjectHelp() = default;
68 
69 OptionDefinition CommandObjectHelp::CommandOptions::g_option_table[] = {
70     // clang-format off
71   {LLDB_OPT_SET_ALL, false, "hide-aliases",         'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Hide aliases in the command list."},
72   {LLDB_OPT_SET_ALL, false, "hide-user-commands",   'u', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Hide user-defined commands from the list."},
73   {LLDB_OPT_SET_ALL, false, "show-hidden-commands", 'h', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Include commands prefixed with an underscore."},
74   {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}
75     // clang-format on
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 0,
84   // we show the user
85   // all commands (aliases and user commands if asked for).  Otherwise every
86   // argument must be the name of a command or a sub-command.
87   if (argc == 0) {
88     uint32_t cmd_types = CommandInterpreter::eCommandTypesBuiltin;
89     if (m_options.m_show_aliases)
90       cmd_types |= CommandInterpreter::eCommandTypesAliases;
91     if (m_options.m_show_user_defined)
92       cmd_types |= CommandInterpreter::eCommandTypesUserDef;
93     if (m_options.m_show_hidden)
94       cmd_types |= CommandInterpreter::eCommandTypesHidden;
95 
96     result.SetStatus(eReturnStatusSuccessFinishNoResult);
97     m_interpreter.GetHelp(result, cmd_types); // General help
98   } else {
99     // Get command object for the first command argument. Only search built-in
100     // command dictionary.
101     StringList matches;
102     cmd_obj =
103         m_interpreter.GetCommandObject(command.GetArgumentAtIndex(0), &matches);
104     bool is_alias_command =
105         m_interpreter.AliasExists(command.GetArgumentAtIndex(0));
106     std::string alias_name = command.GetArgumentAtIndex(0);
107 
108     if (cmd_obj != nullptr) {
109       StringList matches;
110       bool all_okay = true;
111       CommandObject *sub_cmd_obj = cmd_obj;
112       // Loop down through sub_command dictionaries until we find the command
113       // object that corresponds
114       // to the help command entered.
115       std::string sub_command;
116       for (size_t i = 1; i < argc && all_okay; ++i) {
117         sub_command = command.GetArgumentAtIndex(i);
118         matches.Clear();
119         if (sub_cmd_obj->IsAlias())
120           sub_cmd_obj =
121               ((CommandAlias *)sub_cmd_obj)->GetUnderlyingCommand().get();
122         if (!sub_cmd_obj->IsMultiwordObject()) {
123           all_okay = false;
124         } else {
125           CommandObject *found_cmd;
126           found_cmd =
127               sub_cmd_obj->GetSubcommandObject(sub_command.c_str(), &matches);
128           if (found_cmd == nullptr)
129             all_okay = false;
130           else if (matches.GetSize() > 1)
131             all_okay = false;
132           else
133             sub_cmd_obj = found_cmd;
134         }
135       }
136 
137       if (!all_okay || (sub_cmd_obj == nullptr)) {
138         std::string cmd_string;
139         command.GetCommandString(cmd_string);
140         if (matches.GetSize() >= 2) {
141           StreamString s;
142           s.Printf("ambiguous command %s", cmd_string.c_str());
143           size_t num_matches = matches.GetSize();
144           for (size_t match_idx = 0; match_idx < num_matches; match_idx++) {
145             s.Printf("\n\t%s", matches.GetStringAtIndex(match_idx));
146           }
147           s.Printf("\n");
148           result.AppendError(s.GetData());
149           result.SetStatus(eReturnStatusFailed);
150           return false;
151         } else if (!sub_cmd_obj) {
152           StreamString error_msg_stream;
153           GenerateAdditionalHelpAvenuesMessage(
154               &error_msg_stream, cmd_string.c_str(),
155               m_interpreter.GetCommandPrefix(), sub_command.c_str());
156           result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
157           result.SetStatus(eReturnStatusFailed);
158           return false;
159         } else {
160           GenerateAdditionalHelpAvenuesMessage(
161               &result.GetOutputStream(), cmd_string.c_str(),
162               m_interpreter.GetCommandPrefix(), sub_command.c_str());
163           result.GetOutputStream().Printf(
164               "\nThe closest match is '%s'. Help on it follows.\n\n",
165               sub_cmd_obj->GetCommandName());
166         }
167       }
168 
169       sub_cmd_obj->GenerateHelpText(result);
170 
171       if (is_alias_command) {
172         StreamString sstr;
173         m_interpreter.GetAlias(alias_name.c_str())->GetAliasExpansion(sstr);
174         result.GetOutputStream().Printf("\n'%s' is an abbreviation for %s\n",
175                                         alias_name.c_str(), sstr.GetData());
176       }
177     } else if (matches.GetSize() > 0) {
178       Stream &output_strm = result.GetOutputStream();
179       output_strm.Printf("Help requested with ambiguous command name, possible "
180                          "completions:\n");
181       const size_t match_count = matches.GetSize();
182       for (size_t i = 0; i < match_count; i++) {
183         output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i));
184       }
185     } else {
186       // Maybe the user is asking for help about a command argument rather than
187       // a command.
188       const CommandArgumentType arg_type =
189           CommandObject::LookupArgumentName(command.GetArgumentAtIndex(0));
190       if (arg_type != eArgTypeLastArg) {
191         Stream &output_strm = result.GetOutputStream();
192         CommandObject::GetArgumentHelp(output_strm, arg_type, m_interpreter);
193         result.SetStatus(eReturnStatusSuccessFinishNoResult);
194       } else {
195         StreamString error_msg_stream;
196         GenerateAdditionalHelpAvenuesMessage(&error_msg_stream,
197                                              command.GetArgumentAtIndex(0),
198                                              m_interpreter.GetCommandPrefix());
199         result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
200         result.SetStatus(eReturnStatusFailed);
201       }
202     }
203   }
204 
205   return result.Succeeded();
206 }
207 
208 int CommandObjectHelp::HandleCompletion(Args &input, int &cursor_index,
209                                         int &cursor_char_position,
210                                         int match_start_point,
211                                         int max_return_elements,
212                                         bool &word_complete,
213                                         StringList &matches) {
214   // Return the completions of the commands in the help system:
215   if (cursor_index == 0) {
216     return m_interpreter.HandleCompletionMatches(
217         input, cursor_index, cursor_char_position, match_start_point,
218         max_return_elements, word_complete, matches);
219   } else {
220     CommandObject *cmd_obj =
221         m_interpreter.GetCommandObject(input.GetArgumentAtIndex(0));
222 
223     // The command that they are getting help on might be ambiguous, in which
224     // case we should complete that,
225     // otherwise complete with the command the user is getting help on...
226 
227     if (cmd_obj) {
228       input.Shift();
229       cursor_index--;
230       return cmd_obj->HandleCompletion(
231           input, cursor_index, cursor_char_position, match_start_point,
232           max_return_elements, word_complete, matches);
233     } else {
234       return m_interpreter.HandleCompletionMatches(
235           input, cursor_index, cursor_char_position, match_start_point,
236           max_return_elements, word_complete, matches);
237     }
238   }
239 }
240