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
27#include <regex>
28
29using namespace llvm;
30using namespace lldb;
31using namespace lldb_private;
32
34 : CommandObjectRaw(interpreter, "dwim-print",
35 "Print a variable or expression.",
36 "dwim-print [<variable-name> | <expression>]",
37 eCommandProcessMustBePaused | eCommandTryTargetAPILock) {
38
40
45 StringRef exclude_expr_options[] = {"debug", "top-level"};
46 m_option_group.Append(&m_expr_options, exclude_expr_options);
49}
50
52
53void CommandObjectDWIMPrint::DoExecute(StringRef command,
54 CommandReturnObject &result) {
56 OptionsWithRaw args{command};
57 StringRef expr = args.GetRawPart();
58
59 if (expr.empty()) {
60 result.AppendErrorWithFormatv("'{0}' takes a variable or expression",
62 return;
63 }
64
65 if (args.HasArgs()) {
66 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
67 m_exe_ctx))
68 return;
69 }
70
71 // If the user has not specified, default to disabling persistent results.
75
76 auto verbosity = GetDebugger().GetDWIMPrintVerbosity();
77
78 Target *target_ptr = m_exe_ctx.GetTargetPtr();
79 // Fallback to the dummy target, which can allow for expression evaluation.
80 Target &target = target_ptr ? *target_ptr : GetDummyTarget();
81
82 EvaluateExpressionOptions eval_options =
84 // This command manually removes the result variable, make sure expression
85 // evaluation doesn't do it first.
86 eval_options.SetSuppressPersistentResult(false);
87
90 dump_options.SetHideRootName(suppress_result);
91
92 bool is_po = m_varobj_options.use_objc;
93
95
96 // Either the language was explicitly specified, or we check the frame.
98 if (language == lldb::eLanguageTypeUnknown && frame)
99 language = frame->GuessLanguage().AsLanguageType();
100
101 // Add a hint if object description was requested, but no description
102 // function was implemented.
103 auto maybe_add_hint = [&](llvm::StringRef output) {
104 // Identify the default output of object description for Swift and
105 // Objective-C
106 // "<Name: 0x...>. The regex is:
107 // - Start with "<".
108 // - Followed by 1 or more non-whitespace characters.
109 // - Followed by ": 0x".
110 // - Followed by 5 or more hex digits.
111 // - Followed by ">".
112 // - End with zero or more whitespace characters.
113 const std::regex swift_class_regex("^<\\S+: 0x[[:xdigit:]]{5,}>\\s*$");
114
115 if (GetDebugger().GetShowDontUsePoHint() && target_ptr &&
116 (language == lldb::eLanguageTypeSwift ||
117 language == lldb::eLanguageTypeObjC) &&
118 std::regex_match(output.data(), swift_class_regex)) {
119
120 static bool note_shown = false;
121 if (note_shown)
122 return;
123
124 result.AppendNote(
125 "object description requested, but type doesn't implement "
126 "a custom object description. Consider using \"p\" instead of "
127 "\"po\" (this note will only be shown once per debug session).\n");
128 note_shown = true;
129 }
130 };
131
132 // Dump `valobj` according to whether `po` was requested or not.
133 auto dump_val_object = [&](ValueObject &valobj) {
134 if (is_po) {
135 StreamString temp_result_stream;
136 if (llvm::Error error = valobj.Dump(temp_result_stream, dump_options)) {
137 result.AppendError(toString(std::move(error)));
138 return;
139 }
140 llvm::StringRef output = temp_result_stream.GetString();
141 maybe_add_hint(output);
142 result.GetOutputStream() << output;
143 } else {
144 llvm::Error error =
145 valobj.Dump(result.GetOutputStream(), dump_options);
146 if (error) {
147 result.AppendError(toString(std::move(error)));
148 return;
149 }
150 }
152 };
153
154 // First, try `expr` as a _limited_ frame variable expression path: only the
155 // dot operator (`.`) is permitted for this case.
156 //
157 // This is limited to support only unambiguous expression paths. Of note,
158 // expression paths are not attempted if the expression contain either the
159 // arrow operator (`->`) or the subscript operator (`[]`). This is because
160 // both operators can be overloaded in C++, and could result in ambiguity in
161 // how the expression is handled. Additionally, `*` and `&` are not supported.
162 const bool try_variable_path =
163 expr.find_first_of("*&->[]") == StringRef::npos;
164 if (frame && try_variable_path) {
165 VariableSP var_sp;
166 Status status;
167 auto valobj_sp = frame->GetValueForVariableExpressionPath(
168 expr, eval_options.GetUseDynamic(),
170 status);
171 if (valobj_sp && status.Success() && valobj_sp->GetError().Success()) {
172 if (!suppress_result) {
173 if (auto persisted_valobj = valobj_sp->Persist())
174 valobj_sp = persisted_valobj;
175 }
176
177 if (verbosity == eDWIMPrintVerbosityFull) {
178 StringRef flags;
179 if (args.HasArgs())
180 flags = args.GetArgString();
181 result.AppendNoteWithFormatv("ran `frame variable {0}{1}`", flags,
182 expr);
183 }
184
185 dump_val_object(*valobj_sp);
186 return;
187 }
188 }
189
190 // Second, try `expr` as a persistent variable.
191 if (expr.starts_with("$"))
192 if (auto *state = target.GetPersistentExpressionStateForLanguage(language))
193 if (auto var_sp = state->GetVariable(expr))
194 if (auto valobj_sp = var_sp->GetValueObject()) {
195 dump_val_object(*valobj_sp);
196 return;
197 }
198
199 // Third, and lastly, try `expr` as a source expression to evaluate.
200 {
201 auto *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
202 ValueObjectSP valobj_sp;
203 std::string fixed_expression;
204
205 ExpressionResults expr_result = target.EvaluateExpression(
206 expr, exe_scope, valobj_sp, eval_options, &fixed_expression);
207
208 // Record the position of the expression in the command.
209 std::optional<uint16_t> indent;
210 if (fixed_expression.empty()) {
211 size_t pos = m_original_command.rfind(expr);
212 if (pos != llvm::StringRef::npos)
213 indent = pos;
214 }
215 // Previously the indent was set up for diagnosing command line
216 // parsing errors. Now point it to the expression.
217 result.SetDiagnosticIndent(indent);
218
219 // Only mention Fix-Its if the expression evaluator applied them.
220 // Compiler errors refer to the final expression after applying Fix-It(s).
221 if (!fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
222 Stream &error_stream = result.GetErrorStream();
223 error_stream << " Evaluated this expression after applying Fix-It(s):\n";
224 error_stream << " " << fixed_expression << "\n";
225 }
226
227 // If the expression failed, return an error.
228 if (expr_result != eExpressionCompleted) {
229 if (valobj_sp)
230 result.SetError(valobj_sp->GetError().Clone());
231 else
233 "unknown error evaluating expression `{0}`", expr);
234 return;
235 }
236
237 if (verbosity != eDWIMPrintVerbosityNone) {
238 StringRef flags;
239 if (args.HasArgs())
240 flags = args.GetArgStringWithDelimiter();
241 result.AppendNoteWithFormatv("ran `expression {0}{1}`", flags, expr);
242 }
243
244 if (valobj_sp->GetError().GetError() != UserExpression::kNoResult)
245 dump_val_object(*valobj_sp);
246 else
248
249 if (suppress_result)
250 if (auto result_var_sp =
251 target.GetPersistentVariable(valobj_sp->GetName())) {
252 auto language = valobj_sp->GetPreferredDisplayLanguage();
253 if (auto *persistent_state =
255 persistent_state->RemovePersistentVariable(result_var_sp);
256 }
257 }
258}
static llvm::raw_ostream & error(Stream &strm)
CommandObjectExpression::CommandOptions m_expr_options
CommandObjectDWIMPrint(CommandInterpreter &interpreter)
OptionGroupValueObjectDisplay m_varobj_options
void DoExecute(llvm::StringRef command, CommandReturnObject &result) override
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.
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
ExecutionContext m_exe_ctx
void AppendErrorWithFormatv(const char *format, Args &&... args)
void void AppendError(llvm::StringRef in_string)
void void AppendNote(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void SetDiagnosticIndent(std::optional< uint16_t > indent)
void AppendNoteWithFormatv(const char *format, Args &&...args)
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition: Debugger.cpp:609
DumpValueObjectOptions & SetHideRootName(bool hide_root_name)
lldb::DynamicValueType GetUseDynamic() const
Definition: Target.h:371
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:788
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:319
const std::string & GetRawPart() const
Returns the raw suffix part of the parsed string.
Definition: Args.h:368
A command line option parsing protocol class.
Definition: Options.h:58
void NotifyOptionParsingStarting(ExecutionContext *execution_context)
Definition: Options.cpp:68
This base class provides an interface to stack frames.
Definition: StackFrame.h:44
@ eExpressionPathOptionsAllowDirectIVarAccess
Definition: StackFrame.h:51
lldb::ValueObjectSP GetValueForVariableExpressionPath(llvm::StringRef var_expr, lldb::DynamicValueType use_dynamic, uint32_t options, lldb::VariableSP &var_sp, Status &error)
Create a ValueObject for a variable name / pathname, possibly including simple dereference/child sele...
Definition: StackFrame.cpp:509
SourceLanguage GuessLanguage()
Similar to GetLanguage(), but is allowed to take a potentially incorrect guess if exact information i...
An error handling class.
Definition: Status.h:115
bool Success() const
Test for success condition.
Definition: Status.cpp:280
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
bool GetEnableNotifyAboutFixIts() const
Definition: Target.cpp:4721
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2623
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition: Target.cpp:2858
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:2790
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:111
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:110
A class that represents a running process on the host machine.
const char * toString(AppleArm64ExceptionClass EC)
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:484
@ 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
@ eReturnStatusSuccessFinishNoResult
std::shared_ptr< lldb_private::Variable > VariableSP
Definition: lldb-forward.h:486
Definition: Debugger.h:54
lldb::LanguageType AsLanguageType() const
Definition: Language.cpp:554