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);
48 m_expr_options.AppendLanguageOptions(m_option_group);
50 m_option_group.Finalize();
51}
52
54
55void CommandObjectDWIMPrint::DoExecute(StringRef command,
56 CommandReturnObject &result) {
57 m_option_group.NotifyOptionParsingStarting(&m_exe_ctx);
58 OptionsWithRaw args{command};
59 StringRef expr = args.GetRawPart();
60
61 if (expr.empty()) {
62 result.AppendErrorWithFormatv("'{0}' takes a variable or expression",
64 return;
65 }
66
67 if (args.HasArgs()) {
68 if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
69 m_exe_ctx))
70 return;
71 }
72
73 // If the user has not specified, default to disabling persistent results.
74 if (m_expr_options.suppress_persistent_result == eLazyBoolCalculate)
75 m_expr_options.suppress_persistent_result = eLazyBoolYes;
76 bool suppress_result = m_expr_options.ShouldSuppressResult(m_varobj_options);
77
78 auto verbosity = GetDebugger().GetDWIMPrintVerbosity();
79
80 Target &target = m_exe_ctx.GetTargetRef();
81
82 EvaluateExpressionOptions eval_options =
83 m_expr_options.GetEvaluateExpressionOptions(target, m_varobj_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
88 DumpValueObjectOptions dump_options = m_varobj_options.GetAsDumpOptions(
89 m_expr_options.m_verbosity, m_format_options.GetFormat());
90 dump_options.SetHideRootName(suppress_result)
91 .SetExpandPointerTypeFlags(lldb::eTypeIsObjC);
92
93 bool is_po = m_varobj_options.use_object_desc;
94
95 StackFrame *frame = m_exe_ctx.GetFramePtr();
96
97 // Either the language was explicitly specified, or we check the frame.
98 SourceLanguage language{m_expr_options.language};
99 if (!language && frame)
100 language = frame->GuessLanguage();
101
102 // Add a hint if object description was requested, but no description
103 // function was implemented.
104 auto maybe_add_hint = [&](llvm::StringRef output) {
105 static bool note_shown = false;
106 if (note_shown)
107 return;
108
109 // Identify the default output of object description for Swift and
110 // Objective-C
111 // "<Name: 0x...>. The regex is:
112 // - Start with "<".
113 // - Capture 1 or more non-whitespace characters (the class name).
114 // - Followed by ": 0x".
115 // - Followed by 5 or more hex digits.
116 // - Followed by ">".
117 // - End with zero or more whitespace characters.
118 static const std::regex swift_class_regex(
119 "^<(\\S+): 0x[[:xdigit:]]{5,}>\\s*$");
120
121 std::cmatch match;
122 if (GetDebugger().GetShowDontUsePoHint() && !target.IsDummyTarget() &&
124 language.IsObjC()) &&
125 std::regex_match(output.data(), match, swift_class_regex)) {
126
128 "{0} has no custom object description, use \"p\" to see its children",
129 match[1].str());
130 note_shown = true;
131 }
132 };
133
134 // Dump `valobj` according to whether `po` was requested or not.
135 auto dump_val_object = [&](ValueObject &valobj) {
136 if (is_po) {
137 StreamString temp_result_stream;
138 if (llvm::Error error = valobj.Dump(temp_result_stream, dump_options)) {
139 result.AppendError(toString(std::move(error)));
140 return;
141 }
142 llvm::StringRef output = temp_result_stream.GetString();
143 maybe_add_hint(output);
144 result.GetOutputStream() << output;
145 } else {
146 llvm::Error error =
147 valobj.Dump(result.GetOutputStream(), dump_options);
148 if (error) {
149 result.AppendError(toString(std::move(error)));
150 return;
151 }
152 }
153 m_interpreter.PrintWarningsIfNecessary(result.GetOutputStream(),
154 m_cmd_name);
156 };
157
158 // First, try `expr` as a _limited_ frame variable expression path: only the
159 // dot operator (`.`) is permitted for this case.
160 if (frame) {
161 VariableSP var_sp;
162 Status status;
163 auto valobj_sp = frame->GetValueForVariableExpressionPath(
164 expr, eval_options.GetUseDynamic(),
167 var_sp, status, lldb::eDILModeSimple);
168 if (valobj_sp && status.Success() && valobj_sp->GetError().Success()) {
169 if (!suppress_result) {
170 if (auto persisted_valobj = valobj_sp->Persist())
171 valobj_sp = persisted_valobj;
172 }
173
174 if (verbosity == eDWIMPrintVerbosityFull) {
175 StringRef flags;
176 if (args.HasArgs())
177 flags = args.GetArgString();
178 result.AppendNoteWithFormatv("ran `frame variable {0}{1}`", flags,
179 expr);
180 }
181
182 dump_val_object(*valobj_sp);
183 return;
184 }
185 }
186
187 // Second, try `expr` as a persistent variable.
188 if (expr.starts_with("$"))
189 if (auto *state = target.GetPersistentExpressionStateForLanguage(
190 language.AsLanguageType()))
191 if (auto var_sp = state->GetVariable(expr))
192 if (auto valobj_sp = var_sp->GetValueObject()) {
193 dump_val_object(*valobj_sp);
194 return;
195 }
196
197 // Third, and lastly, try `expr` as a source expression to evaluate.
198 {
199 auto *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
200 ValueObjectSP valobj_sp;
201 std::string fixed_expression;
202
203 ExpressionResults expr_result = target.EvaluateExpression(
204 expr, exe_scope, valobj_sp, eval_options, &fixed_expression);
205
206 if (valobj_sp)
207 result.GetValueObjectList().Append(valobj_sp);
208
209 // Record the position of the expression in the command.
210 std::optional<uint16_t> indent;
211 if (fixed_expression.empty()) {
212 size_t pos = m_original_command.rfind(expr);
213 if (pos != llvm::StringRef::npos)
214 indent = pos;
215 }
216 // Previously the indent was set up for diagnosing command line
217 // parsing errors. Now point it to the expression.
218 result.SetDiagnosticIndent(indent);
219
220 // Only mention Fix-Its if the expression evaluator applied them.
221 // Compiler errors refer to the final expression after applying Fix-It(s).
222 if (!fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
223 Stream &error_stream = result.GetErrorStream();
224 error_stream << " Evaluated this expression after applying Fix-It(s):\n";
225 error_stream << " " << fixed_expression << "\n";
226 }
227
228 // If the expression failed, return an error.
229 if (expr_result != eExpressionCompleted) {
230 if (valobj_sp)
231 result.SetError(valobj_sp->GetError().Clone());
232 else
234 "unknown error evaluating expression `{0}`", expr);
235 // A setup or parse error can be a bug in the evaluator. Any other failure
236 // happens once the expression runs.
237 if (expr_result == eExpressionSetupError ||
238 expr_result == eExpressionParseError)
240 return;
241 }
242
243 if (verbosity != eDWIMPrintVerbosityNone) {
244 StringRef flags;
245 if (args.HasArgs())
246 flags = args.GetArgStringWithDelimiter();
247 result.AppendNoteWithFormatv("ran `expression {0}{1}`", flags, expr);
248 }
249
250 if (valobj_sp->GetError().GetError() != UserExpression::kNoResult)
251 dump_val_object(*valobj_sp);
252 else
254
255 if (suppress_result)
256 if (auto result_var_sp =
257 target.GetPersistentVariable(valobj_sp->GetName())) {
258 auto language = valobj_sp->GetPreferredDisplayLanguage();
259 if (auto *persistent_state =
261 persistent_state->RemovePersistentVariable(result_var_sp);
262 }
263 }
264}
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)
void SuggestBugReport(llvm::StringRef failure, Stream &strm)
Writes the 'bugreport' note to strm if ShouldSuggestBugReport.
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition Debugger.cpp:821
DumpValueObjectOptions & SetHideRootName(bool hide_root_name)
DumpValueObjectOptions & SetExpandPointerTypeFlags(unsigned flags)
lldb::DynamicValueType GetUseDynamic() const
Definition Target.h:424
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)
Evaluate the Data Inspection Language (DIL) expression var_expr in this frame.
@ 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:5738
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2865
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition Target.cpp:3097
bool IsDummyTarget() const
Definition Target.h:696
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:3029
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
@ eExpressionParseError
@ eExpressionSetupError
@ 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:619