Files
llvm/lldb/source/Interpreter/CommandAlias.cpp

246 lines
7.7 KiB
C++
Raw Normal View History

//===-- CommandAlias.cpp -----------------------------------------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Interpreter/CommandAlias.h"
#include "llvm/Support/ErrorHandling.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandObject.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Interpreter/Options.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb;
using namespace lldb_private;
static bool ProcessAliasOptionsArgs(lldb::CommandObjectSP &cmd_obj_sp,
llvm::StringRef options_args,
OptionArgVectorSP &option_arg_vector_sp) {
bool success = true;
OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
if (options_args.size() < 1)
return true;
Args args(options_args);
std::string options_string(options_args);
CommandReturnObject result;
// Check to see if the command being aliased can take any command options.
Options *options = cmd_obj_sp->GetOptions();
if (options) {
// See if any options were specified as part of the alias; if so, handle
// them appropriately.
ExecutionContext exe_ctx =
cmd_obj_sp->GetCommandInterpreter().GetExecutionContext();
options->NotifyOptionParsingStarting(&exe_ctx);
Move option parsing out of the Args class Summary: The args class is used in plenty of places (a lot of them in the lower lldb layers) for representing a list of arguments, and most of these places don't care about option parsing. Moving the option parsing out of the class removes the largest external dependency (there are a couple more, but these are in static functions), and brings us closer to being able to move it to the Utility module). The new home for these functions is the Options class, which was already used as an argument to the parse calls, so this just inverts the dependency between the two. The functions are themselves are mainly just copied -- the biggest functional change I've made to them is to avoid modifying the input Args argument (getopt likes to permute the argument vector), as it was weird to have another class reorder the entries in Args class. So now the functions don't modify the input arguments, and (for those where it makes sense) return a new Args vector instead. I've also made the addition of a "fake arg0" (required for getopt compatibility) an implementation detail rather than a part of interface. While doing that I noticed that ParseForCompletion function was recording the option indexes in the shuffled vector, but then the consumer was looking up the entries in the unshuffled one. This manifested itself as us not being able to complete "watchpoint set variable foo --" (because getopt would move "foo" to the end). Surprisingly all other completions (e.g. "watchpoint set variable foo --w") were not affected by this. However, I couldn't find a comprehensive test for command argument completion, so I consolidated the existing tests and added a bunch of new ones. Reviewers: davide, jingham, zturner Subscribers: lldb-commits Differential Revision: https://reviews.llvm.org/D43837 llvm-svn: 327110
2018-03-09 10:39:40 +00:00
llvm::Expected<Args> args_or =
options->ParseAlias(args, option_arg_vector, options_string);
if (!args_or) {
result.AppendError(toString(args_or.takeError()));
result.AppendError("Unable to create requested alias.\n");
result.SetStatus(eReturnStatusFailed);
return false;
}
args = std::move(*args_or);
options->VerifyPartialOptions(result);
if (!result.Succeeded() &&
result.GetStatus() != lldb::eReturnStatusStarted) {
result.AppendError("Unable to create requested alias.\n");
return false;
}
}
if (!options_string.empty()) {
if (cmd_obj_sp->WantsRawCommandString())
option_arg_vector->emplace_back("<argument>", -1, options_string);
else {
for (auto &entry : args.entries()) {
if (!entry.ref.empty())
option_arg_vector->emplace_back("<argument>", -1, entry.ref);
}
}
}
return success;
}
CommandAlias::CommandAlias(CommandInterpreter &interpreter,
lldb::CommandObjectSP cmd_sp,
llvm::StringRef options_args, llvm::StringRef name,
llvm::StringRef help, llvm::StringRef syntax,
uint32_t flags)
: CommandObject(interpreter, name, help, syntax, flags),
m_underlying_command_sp(), m_option_string(options_args),
m_option_args_sp(new OptionArgVector),
m_is_dashdash_alias(eLazyBoolCalculate), m_did_set_help(false),
m_did_set_help_long(false) {
if (ProcessAliasOptionsArgs(cmd_sp, options_args, m_option_args_sp)) {
m_underlying_command_sp = cmd_sp;
for (int i = 0;
auto cmd_entry = m_underlying_command_sp->GetArgumentEntryAtIndex(i);
i++) {
m_arguments.push_back(*cmd_entry);
}
if (!help.empty()) {
StreamString sstr;
StreamString translation_and_help;
GetAliasExpansion(sstr);
translation_and_help.Printf(
"(%s) %s", sstr.GetData(),
GetUnderlyingCommand()->GetHelp().str().c_str());
SetHelp(translation_and_help.GetString());
}
}
}
bool CommandAlias::WantsRawCommandString() {
if (IsValid())
return m_underlying_command_sp->WantsRawCommandString();
return false;
}
bool CommandAlias::WantsCompletion() {
if (IsValid())
return m_underlying_command_sp->WantsCompletion();
return false;
}
Refactoring for for the internal command line completion API (NFC) Summary: This patch refactors the internal completion API. It now takes (as far as possible) a single CompletionRequest object instead o half a dozen in/out/in-out parameters. The CompletionRequest contains a common superset of the different parameters as far as it makes sense. This includes the raw command line string and raw cursor position, which should make the `expr` command possible to implement (at least without hacks that reconstruct the command line from the args). This patch is not intended to change the observable behavior of lldb in any way. It's also as minimal as possible and doesn't attempt to fix all the problems the API has. Some Q&A: Q: Why is this not fixing all the problems in the completion API? A: Because is a blocker for the expr command completion which I want to get in ASAP. This is the smallest patch that unblocks the expr completion patch and which allows trivial refactoring in the future. The patch also doesn't really change the internal information flow in the API, so that hopefully saves us from ever having to revert and resubmit this humongous patch. Q: Can we merge all the copy-pasted code in the completion methods (like computing the current incomplete arg) into CompletionRequest class? A: Yes, but it's out of scope for this patch. Q: Why the `word_complete = request.GetWordComplete(); ... ` pattern? A: I don't want to add a getter that returns a reference to the internal integer. So we have to use a temporary variable and the Getter/Setter instead. We don't throw exceptions from what I can tell, so the behavior doesn't change. Q: Why are we not owning the list of matches? A: Because that's how the previous API works. But that should be fixed too (in another patch). Q: Can we make the constructor simpler and compute some of the values from the plain command? A: I think this works, but I rather want to have this in a follow up commit. Especially when making nested request it's a bit awkward that the parsed arguments behave as both input/output (as we should in theory propagate the changes on the nested request back to the parent request if we don't want to change the behavior too much). Q: Can't we pass one const request object and then just return another result object instead of mixing them together in one in/out parameter? A: It's hard to get keep the same behavior with that pattern, but I think we can also get a nice API with just a single request object. If we make all input parameters read-only, we have a clear separation between what is actually an input and what an output parameter (and hopefully we get rid of the in-out parameters). Q: Can we throw out the 'match' variables that are not implemented according to the comment? A: We currently just forward them as in the old code to the different methods, even though I think they are really not used. We can easily remove and readd them once every single completion method just takes a CompletionRequest, but for now I prefer NFC behavior from the perspective of the API user. Reviewers: davide, jingham, labath Reviewed By: jingham Subscribers: mgorny, friss, lldb-commits Differential Revision: https://reviews.llvm.org/D48796 llvm-svn: 336146
2018-07-02 21:29:56 +00:00
int CommandAlias::HandleCompletion(CompletionRequest &request) {
if (IsValid())
Refactoring for for the internal command line completion API (NFC) Summary: This patch refactors the internal completion API. It now takes (as far as possible) a single CompletionRequest object instead o half a dozen in/out/in-out parameters. The CompletionRequest contains a common superset of the different parameters as far as it makes sense. This includes the raw command line string and raw cursor position, which should make the `expr` command possible to implement (at least without hacks that reconstruct the command line from the args). This patch is not intended to change the observable behavior of lldb in any way. It's also as minimal as possible and doesn't attempt to fix all the problems the API has. Some Q&A: Q: Why is this not fixing all the problems in the completion API? A: Because is a blocker for the expr command completion which I want to get in ASAP. This is the smallest patch that unblocks the expr completion patch and which allows trivial refactoring in the future. The patch also doesn't really change the internal information flow in the API, so that hopefully saves us from ever having to revert and resubmit this humongous patch. Q: Can we merge all the copy-pasted code in the completion methods (like computing the current incomplete arg) into CompletionRequest class? A: Yes, but it's out of scope for this patch. Q: Why the `word_complete = request.GetWordComplete(); ... ` pattern? A: I don't want to add a getter that returns a reference to the internal integer. So we have to use a temporary variable and the Getter/Setter instead. We don't throw exceptions from what I can tell, so the behavior doesn't change. Q: Why are we not owning the list of matches? A: Because that's how the previous API works. But that should be fixed too (in another patch). Q: Can we make the constructor simpler and compute some of the values from the plain command? A: I think this works, but I rather want to have this in a follow up commit. Especially when making nested request it's a bit awkward that the parsed arguments behave as both input/output (as we should in theory propagate the changes on the nested request back to the parent request if we don't want to change the behavior too much). Q: Can't we pass one const request object and then just return another result object instead of mixing them together in one in/out parameter? A: It's hard to get keep the same behavior with that pattern, but I think we can also get a nice API with just a single request object. If we make all input parameters read-only, we have a clear separation between what is actually an input and what an output parameter (and hopefully we get rid of the in-out parameters). Q: Can we throw out the 'match' variables that are not implemented according to the comment? A: We currently just forward them as in the old code to the different methods, even though I think they are really not used. We can easily remove and readd them once every single completion method just takes a CompletionRequest, but for now I prefer NFC behavior from the perspective of the API user. Reviewers: davide, jingham, labath Reviewed By: jingham Subscribers: mgorny, friss, lldb-commits Differential Revision: https://reviews.llvm.org/D48796 llvm-svn: 336146
2018-07-02 21:29:56 +00:00
return m_underlying_command_sp->HandleCompletion(request);
return -1;
}
int CommandAlias::HandleArgumentCompletion(
Refactoring for for the internal command line completion API (NFC) Summary: This patch refactors the internal completion API. It now takes (as far as possible) a single CompletionRequest object instead o half a dozen in/out/in-out parameters. The CompletionRequest contains a common superset of the different parameters as far as it makes sense. This includes the raw command line string and raw cursor position, which should make the `expr` command possible to implement (at least without hacks that reconstruct the command line from the args). This patch is not intended to change the observable behavior of lldb in any way. It's also as minimal as possible and doesn't attempt to fix all the problems the API has. Some Q&A: Q: Why is this not fixing all the problems in the completion API? A: Because is a blocker for the expr command completion which I want to get in ASAP. This is the smallest patch that unblocks the expr completion patch and which allows trivial refactoring in the future. The patch also doesn't really change the internal information flow in the API, so that hopefully saves us from ever having to revert and resubmit this humongous patch. Q: Can we merge all the copy-pasted code in the completion methods (like computing the current incomplete arg) into CompletionRequest class? A: Yes, but it's out of scope for this patch. Q: Why the `word_complete = request.GetWordComplete(); ... ` pattern? A: I don't want to add a getter that returns a reference to the internal integer. So we have to use a temporary variable and the Getter/Setter instead. We don't throw exceptions from what I can tell, so the behavior doesn't change. Q: Why are we not owning the list of matches? A: Because that's how the previous API works. But that should be fixed too (in another patch). Q: Can we make the constructor simpler and compute some of the values from the plain command? A: I think this works, but I rather want to have this in a follow up commit. Especially when making nested request it's a bit awkward that the parsed arguments behave as both input/output (as we should in theory propagate the changes on the nested request back to the parent request if we don't want to change the behavior too much). Q: Can't we pass one const request object and then just return another result object instead of mixing them together in one in/out parameter? A: It's hard to get keep the same behavior with that pattern, but I think we can also get a nice API with just a single request object. If we make all input parameters read-only, we have a clear separation between what is actually an input and what an output parameter (and hopefully we get rid of the in-out parameters). Q: Can we throw out the 'match' variables that are not implemented according to the comment? A: We currently just forward them as in the old code to the different methods, even though I think they are really not used. We can easily remove and readd them once every single completion method just takes a CompletionRequest, but for now I prefer NFC behavior from the perspective of the API user. Reviewers: davide, jingham, labath Reviewed By: jingham Subscribers: mgorny, friss, lldb-commits Differential Revision: https://reviews.llvm.org/D48796 llvm-svn: 336146
2018-07-02 21:29:56 +00:00
CompletionRequest &request, OptionElementVector &opt_element_vector) {
if (IsValid())
return m_underlying_command_sp->HandleArgumentCompletion(
Refactoring for for the internal command line completion API (NFC) Summary: This patch refactors the internal completion API. It now takes (as far as possible) a single CompletionRequest object instead o half a dozen in/out/in-out parameters. The CompletionRequest contains a common superset of the different parameters as far as it makes sense. This includes the raw command line string and raw cursor position, which should make the `expr` command possible to implement (at least without hacks that reconstruct the command line from the args). This patch is not intended to change the observable behavior of lldb in any way. It's also as minimal as possible and doesn't attempt to fix all the problems the API has. Some Q&A: Q: Why is this not fixing all the problems in the completion API? A: Because is a blocker for the expr command completion which I want to get in ASAP. This is the smallest patch that unblocks the expr completion patch and which allows trivial refactoring in the future. The patch also doesn't really change the internal information flow in the API, so that hopefully saves us from ever having to revert and resubmit this humongous patch. Q: Can we merge all the copy-pasted code in the completion methods (like computing the current incomplete arg) into CompletionRequest class? A: Yes, but it's out of scope for this patch. Q: Why the `word_complete = request.GetWordComplete(); ... ` pattern? A: I don't want to add a getter that returns a reference to the internal integer. So we have to use a temporary variable and the Getter/Setter instead. We don't throw exceptions from what I can tell, so the behavior doesn't change. Q: Why are we not owning the list of matches? A: Because that's how the previous API works. But that should be fixed too (in another patch). Q: Can we make the constructor simpler and compute some of the values from the plain command? A: I think this works, but I rather want to have this in a follow up commit. Especially when making nested request it's a bit awkward that the parsed arguments behave as both input/output (as we should in theory propagate the changes on the nested request back to the parent request if we don't want to change the behavior too much). Q: Can't we pass one const request object and then just return another result object instead of mixing them together in one in/out parameter? A: It's hard to get keep the same behavior with that pattern, but I think we can also get a nice API with just a single request object. If we make all input parameters read-only, we have a clear separation between what is actually an input and what an output parameter (and hopefully we get rid of the in-out parameters). Q: Can we throw out the 'match' variables that are not implemented according to the comment? A: We currently just forward them as in the old code to the different methods, even though I think they are really not used. We can easily remove and readd them once every single completion method just takes a CompletionRequest, but for now I prefer NFC behavior from the perspective of the API user. Reviewers: davide, jingham, labath Reviewed By: jingham Subscribers: mgorny, friss, lldb-commits Differential Revision: https://reviews.llvm.org/D48796 llvm-svn: 336146
2018-07-02 21:29:56 +00:00
request, opt_element_vector);
return -1;
}
Options *CommandAlias::GetOptions() {
if (IsValid())
return m_underlying_command_sp->GetOptions();
return nullptr;
}
bool CommandAlias::Execute(const char *args_string,
CommandReturnObject &result) {
llvm_unreachable("CommandAlias::Execute is not to be called");
}
void CommandAlias::GetAliasExpansion(StreamString &help_string) const {
llvm::StringRef command_name = m_underlying_command_sp->GetCommandName();
help_string.Printf("'%*s", (int)command_name.size(), command_name.data());
if (!m_option_args_sp) {
help_string.Printf("'");
return;
}
OptionArgVector *options = m_option_args_sp.get();
std::string opt;
std::string value;
for (const auto &opt_entry : *options) {
std::tie(opt, std::ignore, value) = opt_entry;
if (opt == "<argument>") {
help_string.Printf(" %s", value.c_str());
} else {
help_string.Printf(" %s", opt.c_str());
if ((value != "<no-argument>") && (value != "<need-argument")) {
help_string.Printf(" %s", value.c_str());
}
}
}
help_string.Printf("'");
}
bool CommandAlias::IsDashDashCommand() {
if (m_is_dashdash_alias != eLazyBoolCalculate)
return (m_is_dashdash_alias == eLazyBoolYes);
m_is_dashdash_alias = eLazyBoolNo;
if (!IsValid())
return false;
std::string opt;
std::string value;
for (const auto &opt_entry : *GetOptionArguments()) {
std::tie(opt, std::ignore, value) = opt_entry;
if (opt == "<argument>" && !value.empty() &&
llvm::StringRef(value).endswith("--")) {
m_is_dashdash_alias = eLazyBoolYes;
break;
}
}
// if this is a nested alias, it may be adding arguments on top of an already
// dash-dash alias
if ((m_is_dashdash_alias == eLazyBoolNo) && IsNestedAlias())
m_is_dashdash_alias =
(GetUnderlyingCommand()->IsDashDashCommand() ? eLazyBoolYes
: eLazyBoolNo);
return (m_is_dashdash_alias == eLazyBoolYes);
}
bool CommandAlias::IsNestedAlias() {
if (GetUnderlyingCommand())
return GetUnderlyingCommand()->IsAlias();
return false;
}
std::pair<lldb::CommandObjectSP, OptionArgVectorSP> CommandAlias::Desugar() {
auto underlying = GetUnderlyingCommand();
if (!underlying)
return {nullptr, nullptr};
if (underlying->IsAlias()) {
auto desugared = ((CommandAlias *)underlying.get())->Desugar();
auto options = GetOptionArguments();
options->insert(options->begin(), desugared.second->begin(),
desugared.second->end());
return {desugared.first, options};
}
return {underlying, GetOptionArguments()};
}
// allow CommandAlias objects to provide their own help, but fallback to the
// info for the underlying command if no customization has been provided
void CommandAlias::SetHelp(llvm::StringRef str) {
this->CommandObject::SetHelp(str);
m_did_set_help = true;
}
void CommandAlias::SetHelpLong(llvm::StringRef str) {
this->CommandObject::SetHelpLong(str);
m_did_set_help_long = true;
}
llvm::StringRef CommandAlias::GetHelp() {
if (!m_cmd_help_short.empty() || m_did_set_help)
return m_cmd_help_short;
if (IsValid())
return m_underlying_command_sp->GetHelp();
return llvm::StringRef();
}
llvm::StringRef CommandAlias::GetHelpLong() {
if (!m_cmd_help_long.empty() || m_did_set_help_long)
return m_cmd_help_long;
if (IsValid())
return m_underlying_command_sp->GetHelpLong();
return llvm::StringRef();
}