xref: /src/contrib/llvm-project/lldb/source/Commands/CommandObjectDWIMPrint.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e3b55780SDimitry Andric //===-- CommandObjectDWIMPrint.cpp ------------------------------*- C++ -*-===//
2e3b55780SDimitry Andric //
3e3b55780SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e3b55780SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e3b55780SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e3b55780SDimitry Andric //
7e3b55780SDimitry Andric //===----------------------------------------------------------------------===//
8e3b55780SDimitry Andric 
9e3b55780SDimitry Andric #include "CommandObjectDWIMPrint.h"
10e3b55780SDimitry Andric 
11e3b55780SDimitry Andric #include "lldb/Core/ValueObject.h"
127fa27ce4SDimitry Andric #include "lldb/DataFormatters/DumpValueObjectOptions.h"
137fa27ce4SDimitry Andric #include "lldb/Expression/ExpressionVariable.h"
147fa27ce4SDimitry Andric #include "lldb/Expression/UserExpression.h"
15e3b55780SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
16e3b55780SDimitry Andric #include "lldb/Interpreter/CommandObject.h"
17e3b55780SDimitry Andric #include "lldb/Interpreter/CommandReturnObject.h"
187fa27ce4SDimitry Andric #include "lldb/Interpreter/OptionGroupFormat.h"
197fa27ce4SDimitry Andric #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
20e3b55780SDimitry Andric #include "lldb/Target/StackFrame.h"
21e3b55780SDimitry Andric #include "lldb/Utility/ConstString.h"
227fa27ce4SDimitry Andric #include "lldb/lldb-defines.h"
23e3b55780SDimitry Andric #include "lldb/lldb-enumerations.h"
24e3b55780SDimitry Andric #include "lldb/lldb-forward.h"
257fa27ce4SDimitry Andric #include "llvm/ADT/StringRef.h"
26e3b55780SDimitry Andric 
27b1c73532SDimitry Andric #include <regex>
28b1c73532SDimitry Andric 
29e3b55780SDimitry Andric using namespace llvm;
30e3b55780SDimitry Andric using namespace lldb;
31e3b55780SDimitry Andric using namespace lldb_private;
32e3b55780SDimitry Andric 
CommandObjectDWIMPrint(CommandInterpreter & interpreter)33e3b55780SDimitry Andric CommandObjectDWIMPrint::CommandObjectDWIMPrint(CommandInterpreter &interpreter)
34e3b55780SDimitry Andric     : CommandObjectRaw(interpreter, "dwim-print",
35e3b55780SDimitry Andric                        "Print a variable or expression.",
36e3b55780SDimitry Andric                        "dwim-print [<variable-name> | <expression>]",
37e3b55780SDimitry Andric                        eCommandProcessMustBePaused | eCommandTryTargetAPILock) {
387fa27ce4SDimitry Andric 
39ac9a064cSDimitry Andric   AddSimpleArgumentList(eArgTypeVarName);
407fa27ce4SDimitry Andric 
417fa27ce4SDimitry Andric   m_option_group.Append(&m_format_options,
427fa27ce4SDimitry Andric                         OptionGroupFormat::OPTION_GROUP_FORMAT |
437fa27ce4SDimitry Andric                             OptionGroupFormat::OPTION_GROUP_GDB_FMT,
447fa27ce4SDimitry Andric                         LLDB_OPT_SET_1);
457fa27ce4SDimitry Andric   StringRef exclude_expr_options[] = {"debug", "top-level"};
467fa27ce4SDimitry Andric   m_option_group.Append(&m_expr_options, exclude_expr_options);
477fa27ce4SDimitry Andric   m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
487fa27ce4SDimitry Andric   m_option_group.Finalize();
49e3b55780SDimitry Andric }
50e3b55780SDimitry Andric 
GetOptions()517fa27ce4SDimitry Andric Options *CommandObjectDWIMPrint::GetOptions() { return &m_option_group; }
527fa27ce4SDimitry Andric 
DoExecute(StringRef command,CommandReturnObject & result)53b1c73532SDimitry Andric void CommandObjectDWIMPrint::DoExecute(StringRef command,
54e3b55780SDimitry Andric                                        CommandReturnObject &result) {
557fa27ce4SDimitry Andric   m_option_group.NotifyOptionParsingStarting(&m_exe_ctx);
567fa27ce4SDimitry Andric   OptionsWithRaw args{command};
577fa27ce4SDimitry Andric   StringRef expr = args.GetRawPart();
58e3b55780SDimitry Andric 
59e3b55780SDimitry Andric   if (expr.empty()) {
60e3b55780SDimitry Andric     result.AppendErrorWithFormatv("'{0}' takes a variable or expression",
61e3b55780SDimitry Andric                                   m_cmd_name);
62b1c73532SDimitry Andric     return;
63e3b55780SDimitry Andric   }
64e3b55780SDimitry Andric 
657fa27ce4SDimitry Andric   if (args.HasArgs()) {
667fa27ce4SDimitry Andric     if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group,
677fa27ce4SDimitry Andric                                m_exe_ctx))
68b1c73532SDimitry Andric       return;
697fa27ce4SDimitry Andric   }
707fa27ce4SDimitry Andric 
717fa27ce4SDimitry Andric   // If the user has not specified, default to disabling persistent results.
727fa27ce4SDimitry Andric   if (m_expr_options.suppress_persistent_result == eLazyBoolCalculate)
737fa27ce4SDimitry Andric     m_expr_options.suppress_persistent_result = eLazyBoolYes;
747fa27ce4SDimitry Andric   bool suppress_result = m_expr_options.ShouldSuppressResult(m_varobj_options);
757fa27ce4SDimitry Andric 
76e3b55780SDimitry Andric   auto verbosity = GetDebugger().GetDWIMPrintVerbosity();
77e3b55780SDimitry Andric 
787fa27ce4SDimitry Andric   Target *target_ptr = m_exe_ctx.GetTargetPtr();
797fa27ce4SDimitry Andric   // Fallback to the dummy target, which can allow for expression evaluation.
807fa27ce4SDimitry Andric   Target &target = target_ptr ? *target_ptr : GetDummyTarget();
817fa27ce4SDimitry Andric 
827fa27ce4SDimitry Andric   EvaluateExpressionOptions eval_options =
837fa27ce4SDimitry Andric       m_expr_options.GetEvaluateExpressionOptions(target, m_varobj_options);
847fa27ce4SDimitry Andric   // This command manually removes the result variable, make sure expression
857fa27ce4SDimitry Andric   // evaluation doesn't do it first.
867fa27ce4SDimitry Andric   eval_options.SetSuppressPersistentResult(false);
877fa27ce4SDimitry Andric 
887fa27ce4SDimitry Andric   DumpValueObjectOptions dump_options = m_varobj_options.GetAsDumpOptions(
897fa27ce4SDimitry Andric       m_expr_options.m_verbosity, m_format_options.GetFormat());
907fa27ce4SDimitry Andric   dump_options.SetHideRootName(suppress_result);
917fa27ce4SDimitry Andric 
92b1c73532SDimitry Andric   bool is_po = m_varobj_options.use_objc;
93b1c73532SDimitry Andric 
947fa27ce4SDimitry Andric   StackFrame *frame = m_exe_ctx.GetFramePtr();
957fa27ce4SDimitry Andric 
96ac9a064cSDimitry Andric   // Either the language was explicitly specified, or we check the frame.
97b1c73532SDimitry Andric   lldb::LanguageType language = m_expr_options.language;
98b1c73532SDimitry Andric   if (language == lldb::eLanguageTypeUnknown && frame)
99ac9a064cSDimitry Andric     language = frame->GuessLanguage().AsLanguageType();
100b1c73532SDimitry Andric 
101b1c73532SDimitry Andric   // Add a hint if object description was requested, but no description
102b1c73532SDimitry Andric   // function was implemented.
103b1c73532SDimitry Andric   auto maybe_add_hint = [&](llvm::StringRef output) {
104b1c73532SDimitry Andric     // Identify the default output of object description for Swift and
105b1c73532SDimitry Andric     // Objective-C
106b1c73532SDimitry Andric     // "<Name: 0x...>. The regex is:
107b1c73532SDimitry Andric     // - Start with "<".
108b1c73532SDimitry Andric     // - Followed by 1 or more non-whitespace characters.
109b1c73532SDimitry Andric     // - Followed by ": 0x".
110b1c73532SDimitry Andric     // - Followed by 5 or more hex digits.
111b1c73532SDimitry Andric     // - Followed by ">".
112b1c73532SDimitry Andric     // - End with zero or more whitespace characters.
113b1c73532SDimitry Andric     const std::regex swift_class_regex("^<\\S+: 0x[[:xdigit:]]{5,}>\\s*$");
114b1c73532SDimitry Andric 
115b1c73532SDimitry Andric     if (GetDebugger().GetShowDontUsePoHint() && target_ptr &&
116b1c73532SDimitry Andric         (language == lldb::eLanguageTypeSwift ||
117b1c73532SDimitry Andric          language == lldb::eLanguageTypeObjC) &&
118b1c73532SDimitry Andric         std::regex_match(output.data(), swift_class_regex)) {
119b1c73532SDimitry Andric 
120b1c73532SDimitry Andric       static bool note_shown = false;
121b1c73532SDimitry Andric       if (note_shown)
122b1c73532SDimitry Andric         return;
123b1c73532SDimitry Andric 
124b1c73532SDimitry Andric       result.GetOutputStream()
125b1c73532SDimitry Andric           << "note: object description requested, but type doesn't implement "
126b1c73532SDimitry Andric              "a custom object description. Consider using \"p\" instead of "
127b1c73532SDimitry Andric              "\"po\" (this note will only be shown once per debug session).\n";
128b1c73532SDimitry Andric       note_shown = true;
129b1c73532SDimitry Andric     }
130b1c73532SDimitry Andric   };
131b1c73532SDimitry Andric 
132ac9a064cSDimitry Andric   // Dump `valobj` according to whether `po` was requested or not.
133ac9a064cSDimitry Andric   auto dump_val_object = [&](ValueObject &valobj) {
134ac9a064cSDimitry Andric     if (is_po) {
135ac9a064cSDimitry Andric       StreamString temp_result_stream;
136ac9a064cSDimitry Andric       if (llvm::Error error = valobj.Dump(temp_result_stream, dump_options)) {
137ac9a064cSDimitry Andric         result.AppendError(toString(std::move(error)));
138ac9a064cSDimitry Andric         return;
139ac9a064cSDimitry Andric       }
140ac9a064cSDimitry Andric       llvm::StringRef output = temp_result_stream.GetString();
141ac9a064cSDimitry Andric       maybe_add_hint(output);
142ac9a064cSDimitry Andric       result.GetOutputStream() << output;
143ac9a064cSDimitry Andric     } else {
144ac9a064cSDimitry Andric       llvm::Error error =
145ac9a064cSDimitry Andric         valobj.Dump(result.GetOutputStream(), dump_options);
146ac9a064cSDimitry Andric       if (error) {
147ac9a064cSDimitry Andric         result.AppendError(toString(std::move(error)));
148ac9a064cSDimitry Andric         return;
149ac9a064cSDimitry Andric       }
150ac9a064cSDimitry Andric     }
151ac9a064cSDimitry Andric     result.SetStatus(eReturnStatusSuccessFinishResult);
152ac9a064cSDimitry Andric   };
153ac9a064cSDimitry Andric 
154e3b55780SDimitry Andric   // First, try `expr` as the name of a frame variable.
1557fa27ce4SDimitry Andric   if (frame) {
156e3b55780SDimitry Andric     auto valobj_sp = frame->FindVariable(ConstString(expr));
157e3b55780SDimitry Andric     if (valobj_sp && valobj_sp->GetError().Success()) {
1587fa27ce4SDimitry Andric       if (!suppress_result) {
1597fa27ce4SDimitry Andric         if (auto persisted_valobj = valobj_sp->Persist())
1607fa27ce4SDimitry Andric           valobj_sp = persisted_valobj;
1617fa27ce4SDimitry Andric       }
1627fa27ce4SDimitry Andric 
1637fa27ce4SDimitry Andric       if (verbosity == eDWIMPrintVerbosityFull) {
1647fa27ce4SDimitry Andric         StringRef flags;
1657fa27ce4SDimitry Andric         if (args.HasArgs())
1667fa27ce4SDimitry Andric           flags = args.GetArgString();
1677fa27ce4SDimitry Andric         result.AppendMessageWithFormatv("note: ran `frame variable {0}{1}`",
1687fa27ce4SDimitry Andric                                         flags, expr);
1697fa27ce4SDimitry Andric       }
1707fa27ce4SDimitry Andric 
171ac9a064cSDimitry Andric       dump_val_object(*valobj_sp);
172b1c73532SDimitry Andric       return;
173e3b55780SDimitry Andric     }
174e3b55780SDimitry Andric   }
175e3b55780SDimitry Andric 
176ac9a064cSDimitry Andric   // Second, try `expr` as a persistent variable.
177ac9a064cSDimitry Andric   if (expr.starts_with("$"))
178ac9a064cSDimitry Andric     if (auto *state = target.GetPersistentExpressionStateForLanguage(language))
179ac9a064cSDimitry Andric       if (auto var_sp = state->GetVariable(expr))
180ac9a064cSDimitry Andric         if (auto valobj_sp = var_sp->GetValueObject()) {
181ac9a064cSDimitry Andric           dump_val_object(*valobj_sp);
182ac9a064cSDimitry Andric           return;
183ac9a064cSDimitry Andric         }
184ac9a064cSDimitry Andric 
185ac9a064cSDimitry Andric   // Third, and lastly, try `expr` as a source expression to evaluate.
186e3b55780SDimitry Andric   {
187e3b55780SDimitry Andric     auto *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
188e3b55780SDimitry Andric     ValueObjectSP valobj_sp;
189b1c73532SDimitry Andric     std::string fixed_expression;
190b1c73532SDimitry Andric 
191b1c73532SDimitry Andric     ExpressionResults expr_result = target.EvaluateExpression(
192b1c73532SDimitry Andric         expr, exe_scope, valobj_sp, eval_options, &fixed_expression);
193b1c73532SDimitry Andric 
194b1c73532SDimitry Andric     // Only mention Fix-Its if the expression evaluator applied them.
195b1c73532SDimitry Andric     // Compiler errors refer to the final expression after applying Fix-It(s).
196b1c73532SDimitry Andric     if (!fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
197b1c73532SDimitry Andric       Stream &error_stream = result.GetErrorStream();
198b1c73532SDimitry Andric       error_stream << "  Evaluated this expression after applying Fix-It(s):\n";
199b1c73532SDimitry Andric       error_stream << "    " << fixed_expression << "\n";
200b1c73532SDimitry Andric     }
201b1c73532SDimitry Andric 
202ac9a064cSDimitry Andric     // If the expression failed, return an error.
203ac9a064cSDimitry Andric     if (expr_result != eExpressionCompleted) {
204ac9a064cSDimitry Andric       if (valobj_sp)
205ac9a064cSDimitry Andric         result.SetError(valobj_sp->GetError());
206ac9a064cSDimitry Andric       else
207ac9a064cSDimitry Andric         result.AppendErrorWithFormatv(
208ac9a064cSDimitry Andric             "unknown error evaluating expression `{0}`", expr);
209ac9a064cSDimitry Andric       return;
210ac9a064cSDimitry Andric     }
211ac9a064cSDimitry Andric 
2127fa27ce4SDimitry Andric     if (verbosity != eDWIMPrintVerbosityNone) {
2137fa27ce4SDimitry Andric       StringRef flags;
2147fa27ce4SDimitry Andric       if (args.HasArgs())
2157fa27ce4SDimitry Andric         flags = args.GetArgStringWithDelimiter();
2167fa27ce4SDimitry Andric       result.AppendMessageWithFormatv("note: ran `expression {0}{1}`", flags,
2177fa27ce4SDimitry Andric                                       expr);
2187fa27ce4SDimitry Andric     }
2197fa27ce4SDimitry Andric 
220ac9a064cSDimitry Andric     if (valobj_sp->GetError().GetError() != UserExpression::kNoResult)
221ac9a064cSDimitry Andric       dump_val_object(*valobj_sp);
222ac9a064cSDimitry Andric     else
223ac9a064cSDimitry Andric       result.SetStatus(eReturnStatusSuccessFinishResult);
2247fa27ce4SDimitry Andric 
2257fa27ce4SDimitry Andric     if (suppress_result)
2267fa27ce4SDimitry Andric       if (auto result_var_sp =
2277fa27ce4SDimitry Andric               target.GetPersistentVariable(valobj_sp->GetName())) {
2287fa27ce4SDimitry Andric         auto language = valobj_sp->GetPreferredDisplayLanguage();
2297fa27ce4SDimitry Andric         if (auto *persistent_state =
2307fa27ce4SDimitry Andric                 target.GetPersistentExpressionStateForLanguage(language))
2317fa27ce4SDimitry Andric           persistent_state->RemovePersistentVariable(result_var_sp);
2327fa27ce4SDimitry Andric       }
233e3b55780SDimitry Andric   }
234e3b55780SDimitry Andric }
235