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 static OptionDefinition g_help_options[] = {
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     // clang-format on
75 };
76 
77 llvm::ArrayRef<OptionDefinition>
78 CommandObjectHelp::CommandOptions::GetDefinitions() {
79   return llvm::makeArrayRef(g_help_options);
80 }
81 
82 bool CommandObjectHelp::DoExecute(Args &command, CommandReturnObject &result) {
83   CommandObject::CommandMap::iterator pos;
84   CommandObject *cmd_obj;
85   const size_t argc = command.GetArgumentCount();
86 
87   // 'help' doesn't take any arguments, other than command names.  If argc is 0,
88   // we show the user
89   // all commands (aliases and user commands if asked for).  Otherwise every
90   // argument must be the name of a command or a sub-command.
91   if (argc == 0) {
92     uint32_t cmd_types = CommandInterpreter::eCommandTypesBuiltin;
93     if (m_options.m_show_aliases)
94       cmd_types |= CommandInterpreter::eCommandTypesAliases;
95     if (m_options.m_show_user_defined)
96       cmd_types |= CommandInterpreter::eCommandTypesUserDef;
97     if (m_options.m_show_hidden)
98       cmd_types |= CommandInterpreter::eCommandTypesHidden;
99 
100     result.SetStatus(eReturnStatusSuccessFinishNoResult);
101     m_interpreter.GetHelp(result, cmd_types); // General help
102   } else {
103     // Get command object for the first command argument. Only search built-in
104     // command dictionary.
105     StringList matches;
106     cmd_obj =
107         m_interpreter.GetCommandObject(command.GetArgumentAtIndex(0), &matches);
108     bool is_alias_command =
109         m_interpreter.AliasExists(command.GetArgumentAtIndex(0));
110     std::string alias_name = command.GetArgumentAtIndex(0);
111 
112     if (cmd_obj != nullptr) {
113       StringList matches;
114       bool all_okay = true;
115       CommandObject *sub_cmd_obj = cmd_obj;
116       // Loop down through sub_command dictionaries until we find the command
117       // object that corresponds
118       // to the help command entered.
119       std::string sub_command;
120       for (size_t i = 1; i < argc && all_okay; ++i) {
121         sub_command = command.GetArgumentAtIndex(i);
122         matches.Clear();
123         if (sub_cmd_obj->IsAlias())
124           sub_cmd_obj =
125               ((CommandAlias *)sub_cmd_obj)->GetUnderlyingCommand().get();
126         if (!sub_cmd_obj->IsMultiwordObject()) {
127           all_okay = false;
128         } else {
129           CommandObject *found_cmd;
130           found_cmd =
131               sub_cmd_obj->GetSubcommandObject(sub_command.c_str(), &matches);
132           if (found_cmd == nullptr)
133             all_okay = false;
134           else if (matches.GetSize() > 1)
135             all_okay = false;
136           else
137             sub_cmd_obj = found_cmd;
138         }
139       }
140 
141       if (!all_okay || (sub_cmd_obj == nullptr)) {
142         std::string cmd_string;
143         command.GetCommandString(cmd_string);
144         if (matches.GetSize() >= 2) {
145           StreamString s;
146           s.Printf("ambiguous command %s", cmd_string.c_str());
147           size_t num_matches = matches.GetSize();
148           for (size_t match_idx = 0; match_idx < num_matches; match_idx++) {
149             s.Printf("\n\t%s", matches.GetStringAtIndex(match_idx));
150           }
151           s.Printf("\n");
152           result.AppendError(s.GetData());
153           result.SetStatus(eReturnStatusFailed);
154           return false;
155         } else if (!sub_cmd_obj) {
156           StreamString error_msg_stream;
157           GenerateAdditionalHelpAvenuesMessage(
158               &error_msg_stream, cmd_string.c_str(),
159               m_interpreter.GetCommandPrefix(), sub_command.c_str());
160           result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
161           result.SetStatus(eReturnStatusFailed);
162           return false;
163         } else {
164           GenerateAdditionalHelpAvenuesMessage(
165               &result.GetOutputStream(), cmd_string.c_str(),
166               m_interpreter.GetCommandPrefix(), sub_command.c_str());
167           result.GetOutputStream().Printf(
168               "\nThe closest match is '%s'. Help on it follows.\n\n",
169               sub_cmd_obj->GetCommandName());
170         }
171       }
172 
173       sub_cmd_obj->GenerateHelpText(result);
174 
175       if (is_alias_command) {
176         StreamString sstr;
177         m_interpreter.GetAlias(alias_name.c_str())->GetAliasExpansion(sstr);
178         result.GetOutputStream().Printf("\n'%s' is an abbreviation for %s\n",
179                                         alias_name.c_str(), sstr.GetData());
180       }
181     } else if (matches.GetSize() > 0) {
182       Stream &output_strm = result.GetOutputStream();
183       output_strm.Printf("Help requested with ambiguous command name, possible "
184                          "completions:\n");
185       const size_t match_count = matches.GetSize();
186       for (size_t i = 0; i < match_count; i++) {
187         output_strm.Printf("\t%s\n", matches.GetStringAtIndex(i));
188       }
189     } else {
190       // Maybe the user is asking for help about a command argument rather than
191       // a command.
192       const CommandArgumentType arg_type =
193           CommandObject::LookupArgumentName(command.GetArgumentAtIndex(0));
194       if (arg_type != eArgTypeLastArg) {
195         Stream &output_strm = result.GetOutputStream();
196         CommandObject::GetArgumentHelp(output_strm, arg_type, m_interpreter);
197         result.SetStatus(eReturnStatusSuccessFinishNoResult);
198       } else {
199         StreamString error_msg_stream;
200         GenerateAdditionalHelpAvenuesMessage(&error_msg_stream,
201                                              command.GetArgumentAtIndex(0),
202                                              m_interpreter.GetCommandPrefix());
203         result.AppendErrorWithFormat("%s", error_msg_stream.GetData());
204         result.SetStatus(eReturnStatusFailed);
205       }
206     }
207   }
208 
209   return result.Succeeded();
210 }
211 
212 int CommandObjectHelp::HandleCompletion(Args &input, int &cursor_index,
213                                         int &cursor_char_position,
214                                         int match_start_point,
215                                         int max_return_elements,
216                                         bool &word_complete,
217                                         StringList &matches) {
218   // Return the completions of the commands in the help system:
219   if (cursor_index == 0) {
220     return m_interpreter.HandleCompletionMatches(
221         input, cursor_index, cursor_char_position, match_start_point,
222         max_return_elements, word_complete, matches);
223   } else {
224     CommandObject *cmd_obj =
225         m_interpreter.GetCommandObject(input.GetArgumentAtIndex(0));
226 
227     // The command that they are getting help on might be ambiguous, in which
228     // case we should complete that,
229     // otherwise complete with the command the user is getting help on...
230 
231     if (cmd_obj) {
232       input.Shift();
233       cursor_index--;
234       return cmd_obj->HandleCompletion(
235           input, cursor_index, cursor_char_position, match_start_point,
236           max_return_elements, word_complete, matches);
237     } else {
238       return m_interpreter.HandleCompletionMatches(
239           input, cursor_index, cursor_char_position, match_start_point,
240           max_return_elements, word_complete, matches);
241     }
242   }
243 }
244