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 eCommandAllowsDummyTarget) {
39
41
46 StringRef exclude_expr_options[] = {"debug", "top-level"};
47 m_option_group.Append(&m_expr_options, exclude_expr_options);
49 m_option_group.Finalize();
50}
51
53
54void CommandObjectDWIMPrint::DoExecute(StringRef command,
55 CommandReturnObject &result) {
56 m_option_group.NotifyOptionParsingStarting(&m_exe_ctx);
57 OptionsWithRaw args{command};
58 StringRef expr = args.GetRawPart();
59
60 if (expr.empty()) {
61 result.AppendErrorWithFormatv("'{0}' takes a variable or expression",
63 return;
64 }
65
66 if (args.HasArgs()) {
67 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
68 m_exe_ctx))
69 return;
70 }
71
72 // If the user has not specified, default to disabling persistent results.
73 if (m_expr_options.suppress_persistent_result == eLazyBoolCalculate)
74 m_expr_options.suppress_persistent_result = eLazyBoolYes;
75 bool suppress_result = m_expr_options.ShouldSuppressResult(m_varobj_options);
76
77 auto verbosity = GetDebugger().GetDWIMPrintVerbosity();
78
79 Target &target = m_exe_ctx.GetTargetRef();
80
81 EvaluateExpressionOptions eval_options =
82 m_expr_options.GetEvaluateExpressionOptions(target, m_varobj_options);
83 // This command manually removes the result variable, make sure expression
84 // evaluation doesn't do it first.
85 eval_options.SetSuppressPersistentResult(false);
86
87 DumpValueObjectOptions dump_options = m_varobj_options.GetAsDumpOptions(
88 m_expr_options.m_verbosity, m_format_options.GetFormat());
89 dump_options.SetHideRootName(suppress_result)
90 .SetExpandPointerTypeFlags(lldb::eTypeIsObjC);
91
92 bool is_po = m_varobj_options.use_object_desc;
93
94 StackFrame *frame = m_exe_ctx.GetFramePtr();
95
96 // Either the language was explicitly specified, or we check the frame.
97 SourceLanguage language{m_expr_options.language};
98 if (!language && frame)
99 language = frame->GuessLanguage();
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 static bool note_shown = false;
105 if (note_shown)
106 return;
107
108 // Identify the default output of object description for Swift and
109 // Objective-C
110 // "<Name: 0x...>. The regex is:
111 // - Start with "<".
112 // - Capture 1 or more non-whitespace characters (the class name).
113 // - Followed by ": 0x".
114 // - Followed by 5 or more hex digits.
115 // - Followed by ">".
116 // - End with zero or more whitespace characters.
117 static const std::regex swift_class_regex(
118 "^<(\\S+): 0x[[:xdigit:]]{5,}>\\s*$");
119
120 std::cmatch match;
121 if (GetDebugger().GetShowDontUsePoHint() && !target.IsDummyTarget() &&
123 language.IsObjC()) &&
124 std::regex_match(output.data(), match, swift_class_regex)) {
125
127 "{0} has no custom object description, use \"p\" to see its children",
128 match[1].str());
129 note_shown = true;
130 }
131 };
132
133 // Dump `valobj` according to whether `po` was requested or not.
134 auto dump_val_object = [&](ValueObject &valobj) {
135 if (is_po) {
136 StreamString temp_result_stream;
137 if (llvm::Error error = valobj.Dump(temp_result_stream, dump_options)) {
138 result.AppendError(toString(std::move(error)));
139 return;
140 }
141 llvm::StringRef output = temp_result_stream.GetString();
142 maybe_add_hint(output);
143 result.GetOutputStream() << output;
144 } else {
145 llvm::Error error =
146 valobj.Dump(result.GetOutputStream(), dump_options);
147 if (error) {
148 result.AppendError(toString(std::move(error)));
149 return;
150 }
151 }
152 m_interpreter.PrintWarningsIfNecessary(result.GetOutputStream(),
153 m_cmd_name);
155 };
156
157 // First, try `expr` as a _limited_ frame variable expression path: only the
158 // dot operator (`.`) is permitted for this case.
159 //
160 // This is limited to support only unambiguous expression paths. Of note,
161 // expression paths are not attempted if the expression contain either the
162 // arrow operator (`->`) or the subscript operator (`[]`). This is because
163 // both operators can be overloaded in C++, and could result in ambiguity in
164 // how the expression is handled. Additionally, `*` and `&` are not supported.
165 const bool try_variable_path =
166 expr.find_first_of("*&->[]") == StringRef::npos;
167 if (frame && try_variable_path) {
168 VariableSP var_sp;
169 Status status;
170 auto valobj_sp = frame->GetValueForVariableExpressionPath(
171 expr, eval_options.GetUseDynamic(),
174 var_sp, status, lldb::eDILModeSimple);
175 if (valobj_sp && status.Success() && valobj_sp->GetError().Success()) {
176 if (!suppress_result) {
177 if (auto persisted_valobj = valobj_sp->Persist())
178 valobj_sp = persisted_valobj;
179 }
180
181 if (verbosity == eDWIMPrintVerbosityFull) {
182 StringRef flags;
183 if (args.HasArgs())
184 flags = args.GetArgString();
185 result.AppendNoteWithFormatv("ran `frame variable {0}{1}`", flags,
186 expr);
187 }
188
189 dump_val_object(*valobj_sp);
190 return;
191 }
192 }
193
194 // Second, try `expr` as a persistent variable.
195 if (expr.starts_with("$"))
196 if (auto *state = target.GetPersistentExpressionStateForLanguage(
197 language.AsLanguageType()))
198 if (auto var_sp = state->GetVariable(expr))
199 if (auto valobj_sp = var_sp->GetValueObject()) {
200 dump_val_object(*valobj_sp);
201 return;
202 }
203
204 // Third, and lastly, try `expr` as a source expression to evaluate.
205 {
206 auto *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
207 ValueObjectSP valobj_sp;
208 std::string fixed_expression;
209
210 ExpressionResults expr_result = target.EvaluateExpression(
211 expr, exe_scope, valobj_sp, eval_options, &fixed_expression);
212
213 if (valobj_sp)
214 result.GetValueObjectList().Append(valobj_sp);
215
216 // Record the position of the expression in the command.
217 std::optional<uint16_t> indent;
218 if (fixed_expression.empty()) {
219 size_t pos = m_original_command.rfind(expr);
220 if (pos != llvm::StringRef::npos)
221 indent = pos;
222 }
223 // Previously the indent was set up for diagnosing command line
224 // parsing errors. Now point it to the expression.
225 result.SetDiagnosticIndent(indent);
226
227 // Only mention Fix-Its if the expression evaluator applied them.
228 // Compiler errors refer to the final expression after applying Fix-It(s).
229 if (!fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
230 Stream &error_stream = result.GetErrorStream();
231 error_stream << " Evaluated this expression after applying Fix-It(s):\n";
232 error_stream << " " << fixed_expression << "\n";
233 }
234
235 // If the expression failed, return an error.
236 if (expr_result != eExpressionCompleted) {
237 if (valobj_sp)
238 result.SetError(valobj_sp->GetError().Clone());
239 else
241 "unknown error evaluating expression `{0}`", expr);
242 return;
243 }
244
245 if (verbosity != eDWIMPrintVerbosityNone) {
246 StringRef flags;
247 if (args.HasArgs())
248 flags = args.GetArgStringWithDelimiter();
249 result.AppendNoteWithFormatv("ran `expression {0}{1}`", flags, expr);
250 }
251
252 if (valobj_sp->GetError().GetError() != UserExpression::kNoResult)
253 dump_val_object(*valobj_sp);
254 else
256
257 if (suppress_result)
258 if (auto result_var_sp =
259 target.GetPersistentVariable(valobj_sp->GetName())) {
260 auto language = valobj_sp->GetPreferredDisplayLanguage();
261 if (auto *persistent_state =
263 persistent_state->RemovePersistentVariable(result_var_sp);
264 }
265 }
266}
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
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
CommandInterpreter & m_interpreter
void AppendError(llvm::StringRef in_string)
const ValueObjectList & GetValueObjectList() const
void SetStatus(lldb::ReturnStatus status)
void SetDiagnosticIndent(std::optional< uint16_t > indent)
void AppendNoteWithFormatv(const char *format, Args &&...args)
void AppendErrorWithFormatv(const char *format, Args &&...args)
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition Debugger.cpp:765
DumpValueObjectOptions & SetHideRootName(bool hide_root_name)
DumpValueObjectOptions & SetExpandPointerTypeFlags(unsigned flags)
lldb::DynamicValueType GetUseDynamic() const
Definition Target.h:408
static const uint32_t OPTION_GROUP_GDB_FMT
static const uint32_t OPTION_GROUP_FORMAT
A pair of an option list with a 'raw' string as a suffix.
Definition Args.h:319
bool HasArgs() const
Returns true if there are any arguments before the raw suffix.
Definition Args.h:330
Args & GetArgs()
Returns the list of arguments.
Definition Args.h:335
llvm::StringRef GetArgString() const
Returns the part of the input string that was used for parsing the argument list.
Definition Args.h:362
const std::string & GetRawPart() const
Returns the raw suffix part of the parsed string.
Definition Args.h:368
llvm::StringRef GetArgStringWithDelimiter() const
Returns the part of the input string that was used for parsing the argument list.
Definition Args.h:353
A command line option parsing protocol class.
Definition Options.h:58
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual lldb::ValueObjectSP GetValueForVariableExpressionPath(llvm::StringRef var_expr, lldb::DynamicValueType use_dynamic, uint32_t options, lldb::VariableSP &var_sp, Status &error, lldb::DILMode mode=lldb::eDILModeFull)
Create a ValueObject for a variable name / pathname, possibly including simple dereference/child sele...
@ eExpressionPathOptionsAllowDirectIVarAccess
Definition StackFrame.h:56
virtual 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:118
bool Success() const
Test for success condition.
Definition Status.cpp:303
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:5486
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2743
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition Target.cpp:2985
bool IsDummyTarget() const
Definition Target.h:671
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:2907
static const Status::ValueType kNoResult
ValueObject::GetError() returns this if there is no result from the expression.
void Append(const lldb::ValueObjectSP &val_obj_sp)
#define LLDB_OPT_SET_1
#define LLDB_OPT_SET_ALL
A class that represents a running process on the host machine.
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
@ eDWIMPrintVerbosityFull
Always print a message indicating how dwim-print is evaluating its expression.
@ eDWIMPrintVerbosityNone
Run dwim-print with no verbosity.
@ eLanguageTypeSwift
Swift.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
std::shared_ptr< lldb_private::Variable > VariableSP
@ eDILModeSimple
Allowed: identifiers, operators: '.'.
A type-erased pair of llvm::dwarf::SourceLanguageName and version.
lldb::LanguageType AsLanguageType() const
Definition Language.cpp:614