LLDB mainline
CommandObjectDWIMPrint.cpp
Go to the documentation of this file.
1//===-- CommandObjectDWIMPrint.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
10
22#include "lldb/lldb-defines.h"
24#include "lldb/lldb-forward.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Support/FormatVariadic.h"
27
28#include <regex>
29
30using namespace llvm;
31using namespace lldb;
32using namespace lldb_private;
33
35 : CommandObjectRaw(interpreter, "dwim-print",
36 "Print a variable or expression.",
37 "dwim-print [<variable-name> | <expression>]",
38 eCommandProcessMustBePaused | eCommandTryTargetAPILock) {
39
41 m_arguments.push_back({var_name_arg});
42
47 StringRef exclude_expr_options[] = {"debug", "top-level"};
48 m_option_group.Append(&m_expr_options, exclude_expr_options);
51}
52
54
56 CompletionRequest &request, OptionElementVector &opt_element_vector) {
59}
60
61bool CommandObjectDWIMPrint::DoExecute(StringRef command,
62 CommandReturnObject &result) {
64 OptionsWithRaw args{command};
65 StringRef expr = args.GetRawPart();
66
67 if (expr.empty()) {
68 result.AppendErrorWithFormatv("'{0}' takes a variable or expression",
70 return false;
71 }
72
73 if (args.HasArgs()) {
74 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
75 m_exe_ctx))
76 return false;
77 }
78
79 // If the user has not specified, default to disabling persistent results.
83
84 auto verbosity = GetDebugger().GetDWIMPrintVerbosity();
85
86 Target *target_ptr = m_exe_ctx.GetTargetPtr();
87 // Fallback to the dummy target, which can allow for expression evaluation.
88 Target &target = target_ptr ? *target_ptr : GetDummyTarget();
89
90 EvaluateExpressionOptions eval_options =
92 // This command manually removes the result variable, make sure expression
93 // evaluation doesn't do it first.
94 eval_options.SetSuppressPersistentResult(false);
95
98 dump_options.SetHideRootName(suppress_result);
99
100 bool is_po = m_varobj_options.use_objc;
101
103
104 // Either Swift was explicitly specified, or the frame is Swift.
106 if (language == lldb::eLanguageTypeUnknown && frame)
107 language = frame->GuessLanguage();
108
109 // Add a hint if object description was requested, but no description
110 // function was implemented.
111 auto maybe_add_hint = [&](llvm::StringRef output) {
112 // Identify the default output of object description for Swift and
113 // Objective-C
114 // "<Name: 0x...>. The regex is:
115 // - Start with "<".
116 // - Followed by 1 or more non-whitespace characters.
117 // - Followed by ": 0x".
118 // - Followed by 5 or more hex digits.
119 // - Followed by ">".
120 // - End with zero or more whitespace characters.
121 const std::regex swift_class_regex("^<\\S+: 0x[[:xdigit:]]{5,}>\\s*$");
122
123 if (GetDebugger().GetShowDontUsePoHint() && target_ptr &&
124 (language == lldb::eLanguageTypeSwift ||
125 language == lldb::eLanguageTypeObjC) &&
126 std::regex_match(output.data(), swift_class_regex)) {
127
128 static bool note_shown = false;
129 if (note_shown)
130 return;
131
132 result.GetOutputStream()
133 << "note: object description requested, but type doesn't implement "
134 "a custom object description. Consider using \"p\" instead of "
135 "\"po\" (this note will only be shown once per debug session).\n";
136 note_shown = true;
137 }
138 };
139
140 // First, try `expr` as the name of a frame variable.
141 if (frame) {
142 auto valobj_sp = frame->FindVariable(ConstString(expr));
143 if (valobj_sp && valobj_sp->GetError().Success()) {
144 if (!suppress_result) {
145 if (auto persisted_valobj = valobj_sp->Persist())
146 valobj_sp = persisted_valobj;
147 }
148
149 if (verbosity == eDWIMPrintVerbosityFull) {
150 StringRef flags;
151 if (args.HasArgs())
152 flags = args.GetArgString();
153 result.AppendMessageWithFormatv("note: ran `frame variable {0}{1}`",
154 flags, expr);
155 }
156
157 if (is_po) {
158 StreamString temp_result_stream;
159 valobj_sp->Dump(temp_result_stream, dump_options);
160 llvm::StringRef output = temp_result_stream.GetString();
161 maybe_add_hint(output);
162 result.GetOutputStream() << output;
163 } else {
164 valobj_sp->Dump(result.GetOutputStream(), dump_options);
165 }
167 return true;
168 }
169 }
170
171 // Second, also lastly, try `expr` as a source expression to evaluate.
172 {
173 auto *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
174 ValueObjectSP valobj_sp;
175 ExpressionResults expr_result =
176 target.EvaluateExpression(expr, exe_scope, valobj_sp, eval_options);
177 if (expr_result == eExpressionCompleted) {
178 if (verbosity != eDWIMPrintVerbosityNone) {
179 StringRef flags;
180 if (args.HasArgs())
181 flags = args.GetArgStringWithDelimiter();
182 result.AppendMessageWithFormatv("note: ran `expression {0}{1}`", flags,
183 expr);
184 }
185
186 if (valobj_sp->GetError().GetError() != UserExpression::kNoResult) {
187 if (is_po) {
188 StreamString temp_result_stream;
189 valobj_sp->Dump(temp_result_stream, dump_options);
190 llvm::StringRef output = temp_result_stream.GetString();
191 maybe_add_hint(output);
192 result.GetOutputStream() << output;
193 } else {
194 valobj_sp->Dump(result.GetOutputStream(), dump_options);
195 }
196 }
197
198 if (suppress_result)
199 if (auto result_var_sp =
200 target.GetPersistentVariable(valobj_sp->GetName())) {
201 auto language = valobj_sp->GetPreferredDisplayLanguage();
202 if (auto *persistent_state =
204 persistent_state->RemovePersistentVariable(result_var_sp);
205 }
206
208 return true;
209 } else {
210 if (valobj_sp)
211 result.SetError(valobj_sp->GetError());
212 else
214 "unknown error evaluating expression `{0}`", expr);
215 return false;
216 }
217 }
218}
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
bool DoExecute(llvm::StringRef command, CommandReturnObject &result) override
CommandObjectExpression::CommandOptions m_expr_options
CommandObjectDWIMPrint(CommandInterpreter &interpreter)
OptionGroupValueObjectDisplay m_varobj_options
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The input array contains a parsed version of the line.
bool ShouldSuppressResult(const OptionGroupValueObjectDisplay &display_opts) const
LanguageRuntimeDescriptionDisplayVerbosity m_verbosity
EvaluateExpressionOptions GetEvaluateExpressionOptions(const Target &target, const OptionGroupValueObjectDisplay &display_opts)
Return the appropriate expression options used for evaluating the expression in the given target.
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
ExecutionContext m_exe_ctx
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
void AppendErrorWithFormatv(const char *format, Args &&... args)
void SetStatus(lldb::ReturnStatus status)
void void AppendMessageWithFormatv(const char *format, Args &&... args)
void SetError(const Status &error, const char *fallback_error_cstr=nullptr)
"lldb/Utility/ArgCompletionRequest.h"
A uniqued constant string class.
Definition: ConstString.h:40
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition: Debugger.cpp:578
DumpValueObjectOptions & SetHideRootName(bool hide_root_name)
ExecutionContextScope * GetBestExecutionContextScope() const
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
static const uint32_t OPTION_GROUP_GDB_FMT
static const uint32_t OPTION_GROUP_FORMAT
void Append(OptionGroup *group)
Append options from a OptionGroup class.
Definition: Options.cpp:755
DumpValueObjectOptions GetAsDumpOptions(LanguageRuntimeDescriptionDisplayVerbosity lang_descr_verbosity=eLanguageRuntimeDescriptionDisplayVerbosityFull, lldb::Format format=lldb::eFormatDefault, lldb::TypeSummaryImplSP summary_sp=lldb::TypeSummaryImplSP())
A pair of an option list with a 'raw' string as a suffix.
Definition: Args.h:315
const std::string & GetRawPart() const
Returns the raw suffix part of the parsed string.
Definition: Args.h:364
A command line option parsing protocol class.
Definition: Options.h:58
void NotifyOptionParsingStarting(ExecutionContext *execution_context)
Definition: Options.cpp:33
This base class provides an interface to stack frames.
Definition: StackFrame.h:41
lldb::LanguageType GuessLanguage()
lldb::ValueObjectSP FindVariable(ConstString name)
Attempt to reconstruct the ValueObject for a variable with a given name from within the current Stack...
llvm::StringRef GetString() const
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2442
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition: Target.cpp:2684
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Definition: Target.cpp:2611
static const Status::ValueType kNoResult
ValueObject::GetError() returns this if there is no result from the expression.
#define LLDB_OPT_SET_1
Definition: lldb-defines.h:107
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:106
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
std::vector< OptionArgElement > OptionElementVector
Definition: Options.h:43
Definition: SBAddress.h:15
@ eVariablePathCompletion
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:458
@ eDWIMPrintVerbosityFull
Always print a message indicating how dwim-print is evaluating its expression.
@ eDWIMPrintVerbosityNone
Run dwim-print with no verbosity.
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeSwift
Swift.
@ eLanguageTypeObjC
Objective-C.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eReturnStatusSuccessFinishResult
Definition: Debugger.h:53
Used to build individual command argument lists.
Definition: CommandObject.h:93