xref: /llvm-project/lldb/source/Commands/CommandObjectDWIMPrint.cpp (revision d1bc75c0bce141b94f9afadfde4e784760735ec0)
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 
9 #include "CommandObjectDWIMPrint.h"
10 
11 #include "lldb/Core/ValueObject.h"
12 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
13 #include "lldb/Expression/ExpressionVariable.h"
14 #include "lldb/Expression/UserExpression.h"
15 #include "lldb/Interpreter/CommandInterpreter.h"
16 #include "lldb/Interpreter/CommandObject.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/OptionGroupFormat.h"
19 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
20 #include "lldb/Target/StackFrame.h"
21 #include "lldb/Utility/ConstString.h"
22 #include "lldb/lldb-defines.h"
23 #include "lldb/lldb-enumerations.h"
24 #include "lldb/lldb-forward.h"
25 #include "llvm/ADT/StringRef.h"
26 
27 #include <regex>
28 
29 using namespace llvm;
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 CommandObjectDWIMPrint::CommandObjectDWIMPrint(CommandInterpreter &interpreter)
34     : CommandObjectRaw(interpreter, "dwim-print",
35                        "Print a variable or expression.",
36                        "dwim-print [<variable-name> | <expression>]",
37                        eCommandProcessMustBePaused | eCommandTryTargetAPILock) {
38 
39   AddSimpleArgumentList(eArgTypeVarName);
40 
41   m_option_group.Append(&m_format_options,
42                         OptionGroupFormat::OPTION_GROUP_FORMAT |
43                             OptionGroupFormat::OPTION_GROUP_GDB_FMT,
44                         LLDB_OPT_SET_1);
45   StringRef exclude_expr_options[] = {"debug", "top-level"};
46   m_option_group.Append(&m_expr_options, exclude_expr_options);
47   m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
48   m_option_group.Finalize();
49 }
50 
51 Options *CommandObjectDWIMPrint::GetOptions() { return &m_option_group; }
52 
53 void CommandObjectDWIMPrint::DoExecute(StringRef command,
54                                        CommandReturnObject &result) {
55   m_option_group.NotifyOptionParsingStarting(&m_exe_ctx);
56   OptionsWithRaw args{command};
57   StringRef expr = args.GetRawPart();
58 
59   if (expr.empty()) {
60     result.AppendErrorWithFormatv("'{0}' takes a variable or expression",
61                                   m_cmd_name);
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.
72   if (m_expr_options.suppress_persistent_result == eLazyBoolCalculate)
73     m_expr_options.suppress_persistent_result = eLazyBoolYes;
74   bool suppress_result = m_expr_options.ShouldSuppressResult(m_varobj_options);
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 =
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 
92   bool is_po = m_varobj_options.use_objc;
93 
94   StackFrame *frame = m_exe_ctx.GetFramePtr();
95 
96   // Either the language was explicitly specified, or we check the frame.
97   lldb::LanguageType language = m_expr_options.language;
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.GetOutputStream()
125           << "note: 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       if (llvm::Error error =
145               valobj.Dump(result.GetOutputStream(), dump_options))
146         result.AppendError(toString(std::move(error)));
147     }
148   };
149 
150   // First, try `expr` as the name of a frame variable.
151   if (frame) {
152     auto valobj_sp = frame->FindVariable(ConstString(expr));
153     if (valobj_sp && valobj_sp->GetError().Success()) {
154       if (!suppress_result) {
155         if (auto persisted_valobj = valobj_sp->Persist())
156           valobj_sp = persisted_valobj;
157       }
158 
159       if (verbosity == eDWIMPrintVerbosityFull) {
160         StringRef flags;
161         if (args.HasArgs())
162           flags = args.GetArgString();
163         result.AppendMessageWithFormatv("note: ran `frame variable {0}{1}`",
164                                         flags, expr);
165       }
166 
167       dump_val_object(*valobj_sp);
168       result.SetStatus(eReturnStatusSuccessFinishResult);
169       return;
170     }
171   }
172 
173   // Second, try `expr` as a persistent variable.
174   if (expr.starts_with("$"))
175     if (auto *state = target.GetPersistentExpressionStateForLanguage(language))
176       if (auto var_sp = state->GetVariable(expr))
177         if (auto valobj_sp = var_sp->GetValueObject()) {
178           dump_val_object(*valobj_sp);
179           result.SetStatus(eReturnStatusSuccessFinishResult);
180           return;
181         }
182 
183   // Third, and lastly, try `expr` as a source expression to evaluate.
184   {
185     auto *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
186     ValueObjectSP valobj_sp;
187     std::string fixed_expression;
188 
189     ExpressionResults expr_result = target.EvaluateExpression(
190         expr, exe_scope, valobj_sp, eval_options, &fixed_expression);
191 
192     // Only mention Fix-Its if the expression evaluator applied them.
193     // Compiler errors refer to the final expression after applying Fix-It(s).
194     if (!fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
195       Stream &error_stream = result.GetErrorStream();
196       error_stream << "  Evaluated this expression after applying Fix-It(s):\n";
197       error_stream << "    " << fixed_expression << "\n";
198     }
199 
200     if (expr_result == eExpressionCompleted) {
201       if (verbosity != eDWIMPrintVerbosityNone) {
202         StringRef flags;
203         if (args.HasArgs())
204           flags = args.GetArgStringWithDelimiter();
205         result.AppendMessageWithFormatv("note: ran `expression {0}{1}`", flags,
206                                         expr);
207       }
208 
209       if (valobj_sp->GetError().GetError() != UserExpression::kNoResult)
210         dump_val_object(*valobj_sp);
211 
212       if (suppress_result)
213         if (auto result_var_sp =
214                 target.GetPersistentVariable(valobj_sp->GetName())) {
215           auto language = valobj_sp->GetPreferredDisplayLanguage();
216           if (auto *persistent_state =
217                   target.GetPersistentExpressionStateForLanguage(language))
218             persistent_state->RemovePersistentVariable(result_var_sp);
219         }
220 
221       result.SetStatus(eReturnStatusSuccessFinishResult);
222     } else {
223       if (valobj_sp)
224         result.SetError(valobj_sp->GetError());
225       else
226         result.AppendErrorWithFormatv(
227             "unknown error evaluating expression `{0}`", expr);
228     }
229   }
230 }
231