130fdc8d8SChris Lattner //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
230fdc8d8SChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
630fdc8d8SChris Lattner //
730fdc8d8SChris Lattner //===----------------------------------------------------------------------===//
830fdc8d8SChris Lattner 
9c8ecc2a9SEugene Zelenko #include "llvm/ADT/StringRef.h"
10c8ecc2a9SEugene Zelenko 
11c8ecc2a9SEugene Zelenko #include "CommandObjectExpression.h"
12b9c1b51eSKate Stone #include "lldb/Core/Debugger.h"
13f2bd5c3eSSean Callanan #include "lldb/Expression/REPL.h"
14b9c1b51eSKate Stone #include "lldb/Expression/UserExpression.h"
153eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
166611103cSGreg Clayton #include "lldb/Interpreter/CommandInterpreter.h"
1730fdc8d8SChris Lattner #include "lldb/Interpreter/CommandReturnObject.h"
1847cbf4a0SPavel Labath #include "lldb/Interpreter/OptionArgParser.h"
19b9c1b51eSKate Stone #include "lldb/Target/Language.h"
2030fdc8d8SChris Lattner #include "lldb/Target/Process.h"
21b57e4a1bSJason Molenda #include "lldb/Target/StackFrame.h"
2230fdc8d8SChris Lattner #include "lldb/Target/Target.h"
2330fdc8d8SChris Lattner 
2430fdc8d8SChris Lattner using namespace lldb;
2530fdc8d8SChris Lattner using namespace lldb_private;
2630fdc8d8SChris Lattner 
27b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {}
2830fdc8d8SChris Lattner 
29c8ecc2a9SEugene Zelenko CommandObjectExpression::CommandOptions::~CommandOptions() = default;
3030fdc8d8SChris Lattner 
318fe53c49STatyana Krasnukha static constexpr OptionEnumValueElement g_description_verbosity_type[] = {
32e063ecccSJonas Devlieghere     {
33e063ecccSJonas Devlieghere         eLanguageRuntimeDescriptionDisplayVerbosityCompact,
34e063ecccSJonas Devlieghere         "compact",
35e063ecccSJonas Devlieghere         "Only show the description string",
36e063ecccSJonas Devlieghere     },
37e063ecccSJonas Devlieghere     {
38e063ecccSJonas Devlieghere         eLanguageRuntimeDescriptionDisplayVerbosityFull,
39e063ecccSJonas Devlieghere         "full",
40e063ecccSJonas Devlieghere         "Show the full output, including persistent variable's name and type",
41e063ecccSJonas Devlieghere     },
42e063ecccSJonas Devlieghere };
434d93b8cdSEnrico Granata 
448fe53c49STatyana Krasnukha static constexpr OptionEnumValues DescriptionVerbosityTypes() {
458fe53c49STatyana Krasnukha   return OptionEnumValues(g_description_verbosity_type);
468fe53c49STatyana Krasnukha }
478fe53c49STatyana Krasnukha 
48ec67e734SRaphael Isemann #define LLDB_OPTIONS_expression
49ec67e734SRaphael Isemann #include "CommandOptions.inc"
501deb7962SGreg Clayton 
5197206d57SZachary Turner Status CommandObjectExpression::CommandOptions::SetOptionValue(
528cef4b0bSZachary Turner     uint32_t option_idx, llvm::StringRef option_arg,
53b9c1b51eSKate Stone     ExecutionContext *execution_context) {
5497206d57SZachary Turner   Status error;
5530fdc8d8SChris Lattner 
561f0f5b5bSZachary Turner   const int short_option = GetDefinitions()[option_idx].short_option;
5730fdc8d8SChris Lattner 
58b9c1b51eSKate Stone   switch (short_option) {
5915663c53SDawn Perchik   case 'l':
600e0984eeSJim Ingham     language = Language::GetLanguageTypeFromString(option_arg);
6115663c53SDawn Perchik     if (language == eLanguageTypeUnknown)
62b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
638cef4b0bSZachary Turner           "unknown language type: '%s' for expression",
648cef4b0bSZachary Turner           option_arg.str().c_str());
6515663c53SDawn Perchik     break;
6630fdc8d8SChris Lattner 
67b9c1b51eSKate Stone   case 'a': {
6835e1bda6SJim Ingham     bool success;
6935e1bda6SJim Ingham     bool result;
7047cbf4a0SPavel Labath     result = OptionArgParser::ToBoolean(option_arg, true, &success);
7135e1bda6SJim Ingham     if (!success)
72b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
738cef4b0bSZachary Turner           "invalid all-threads value setting: \"%s\"",
748cef4b0bSZachary Turner           option_arg.str().c_str());
7535e1bda6SJim Ingham     else
7635e1bda6SJim Ingham       try_all_threads = result;
77b9c1b51eSKate Stone   } break;
786c68fb45SJim Ingham 
79b9c1b51eSKate Stone   case 'i': {
80184e9811SJim Ingham     bool success;
8147cbf4a0SPavel Labath     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
82184e9811SJim Ingham     if (success)
83184e9811SJim Ingham       ignore_breakpoints = tmp_value;
84184e9811SJim Ingham     else
85b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
868cef4b0bSZachary Turner           "could not convert \"%s\" to a boolean value.",
878cef4b0bSZachary Turner           option_arg.str().c_str());
88184e9811SJim Ingham     break;
89184e9811SJim Ingham   }
903fe71581SMarianne Mailhot-Sarrasin 
91b9c1b51eSKate Stone   case 'j': {
923fe71581SMarianne Mailhot-Sarrasin     bool success;
9347cbf4a0SPavel Labath     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
943fe71581SMarianne Mailhot-Sarrasin     if (success)
953fe71581SMarianne Mailhot-Sarrasin       allow_jit = tmp_value;
963fe71581SMarianne Mailhot-Sarrasin     else
97b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
988cef4b0bSZachary Turner           "could not convert \"%s\" to a boolean value.",
998cef4b0bSZachary Turner           option_arg.str().c_str());
1003fe71581SMarianne Mailhot-Sarrasin     break;
1013fe71581SMarianne Mailhot-Sarrasin   }
1023fe71581SMarianne Mailhot-Sarrasin 
1038cef4b0bSZachary Turner   case 't':
1048cef4b0bSZachary Turner     if (option_arg.getAsInteger(0, timeout)) {
1058cef4b0bSZachary Turner       timeout = 0;
106b9c1b51eSKate Stone       error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
1078cef4b0bSZachary Turner                                      option_arg.str().c_str());
1088cef4b0bSZachary Turner     }
1098cef4b0bSZachary Turner     break;
11035e1bda6SJim Ingham 
111b9c1b51eSKate Stone   case 'u': {
112399f1cafSJim Ingham     bool success;
11347cbf4a0SPavel Labath     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
114184e9811SJim Ingham     if (success)
115184e9811SJim Ingham       unwind_on_error = tmp_value;
116184e9811SJim Ingham     else
117b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1188cef4b0bSZachary Turner           "could not convert \"%s\" to a boolean value.",
1198cef4b0bSZachary Turner           option_arg.str().c_str());
120399f1cafSJim Ingham     break;
1213bfdaa2aSSean Callanan   }
1224d93b8cdSEnrico Granata 
1234d93b8cdSEnrico Granata   case 'v':
124543a26e9SEnrico Granata     if (option_arg.empty()) {
1254d93b8cdSEnrico Granata       m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
1264d93b8cdSEnrico Granata       break;
1274d93b8cdSEnrico Granata     }
12847cbf4a0SPavel Labath     m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity)
12947cbf4a0SPavel Labath         OptionArgParser::ToOptionEnum(
1301f0f5b5bSZachary Turner             option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
1314d93b8cdSEnrico Granata     if (!error.Success())
132b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1338cef4b0bSZachary Turner           "unrecognized value for description-verbosity '%s'",
1348cef4b0bSZachary Turner           option_arg.str().c_str());
1354d93b8cdSEnrico Granata     break;
1364d93b8cdSEnrico Granata 
13762afb9f6SGreg Clayton   case 'g':
13862afb9f6SGreg Clayton     debug = true;
13962afb9f6SGreg Clayton     unwind_on_error = false;
14062afb9f6SGreg Clayton     ignore_breakpoints = false;
14162afb9f6SGreg Clayton     break;
14262afb9f6SGreg Clayton 
143863fab69SSean Callanan   case 'p':
144863fab69SSean Callanan     top_level = true;
145863fab69SSean Callanan     break;
146863fab69SSean Callanan 
147b9c1b51eSKate Stone   case 'X': {
148a1e541bfSJim Ingham     bool success;
14947cbf4a0SPavel Labath     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
150a1e541bfSJim Ingham     if (success)
151a1e541bfSJim Ingham       auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;
152a1e541bfSJim Ingham     else
153b9c1b51eSKate Stone       error.SetErrorStringWithFormat(
1548cef4b0bSZachary Turner           "could not convert \"%s\" to a boolean value.",
1558cef4b0bSZachary Turner           option_arg.str().c_str());
156a1e541bfSJim Ingham     break;
157a1e541bfSJim Ingham   }
158a1e541bfSJim Ingham 
15930fdc8d8SChris Lattner   default:
16036162014SRaphael Isemann     llvm_unreachable("Unimplemented option");
16130fdc8d8SChris Lattner   }
16230fdc8d8SChris Lattner 
16330fdc8d8SChris Lattner   return error;
16430fdc8d8SChris Lattner }
16530fdc8d8SChris Lattner 
166b9c1b51eSKate Stone void CommandObjectExpression::CommandOptions::OptionParsingStarting(
167b9c1b51eSKate Stone     ExecutionContext *execution_context) {
168e1cfbc79STodd Fiala   auto process_sp =
169e1cfbc79STodd Fiala       execution_context ? execution_context->GetProcessSP() : ProcessSP();
170b9c1b51eSKate Stone   if (process_sp) {
171e1cfbc79STodd Fiala     ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();
172e1cfbc79STodd Fiala     unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();
173b9c1b51eSKate Stone   } else {
174fc03f8fcSGreg Clayton     ignore_breakpoints = true;
175399f1cafSJim Ingham     unwind_on_error = true;
176184e9811SJim Ingham   }
177184e9811SJim Ingham 
17830fdc8d8SChris Lattner   show_summary = true;
17935e1bda6SJim Ingham   try_all_threads = true;
18035e1bda6SJim Ingham   timeout = 0;
18162afb9f6SGreg Clayton   debug = false;
18215663c53SDawn Perchik   language = eLanguageTypeUnknown;
1834d93b8cdSEnrico Granata   m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
184a1e541bfSJim Ingham   auto_apply_fixits = eLazyBoolCalculate;
185863fab69SSean Callanan   top_level = false;
1863fe71581SMarianne Mailhot-Sarrasin   allow_jit = true;
18730fdc8d8SChris Lattner }
18830fdc8d8SChris Lattner 
1891f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition>
190b9c1b51eSKate Stone CommandObjectExpression::CommandOptions::GetDefinitions() {
19170602439SZachary Turner   return llvm::makeArrayRef(g_expression_options);
19230fdc8d8SChris Lattner }
19330fdc8d8SChris Lattner 
194b9c1b51eSKate Stone CommandObjectExpression::CommandObjectExpression(
195b9c1b51eSKate Stone     CommandInterpreter &interpreter)
196a925974bSAdrian Prantl     : CommandObjectRaw(interpreter, "expression",
197a925974bSAdrian Prantl                        "Evaluate an expression on the current "
198b9c1b51eSKate Stone                        "thread.  Displays any returned value "
199b9c1b51eSKate Stone                        "with LLDB's default formatting.",
200a925974bSAdrian Prantl                        "",
201a925974bSAdrian Prantl                        eCommandProcessMustBePaused | eCommandTryTargetAPILock),
20244d93782SGreg Clayton       IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),
203b9c1b51eSKate Stone       m_option_group(), m_format_options(eFormatDefault),
204b9c1b51eSKate Stone       m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,
205b9c1b51eSKate Stone                     true),
206b9c1b51eSKate Stone       m_command_options(), m_expr_line_count(0), m_expr_lines() {
20730fdc8d8SChris Lattner   SetHelpLong(
208ea671fbdSKate Stone       R"(
209d0309916SJim Ingham Single and multi-line expressions:
210d0309916SJim Ingham 
211d0309916SJim Ingham )"
212d0309916SJim Ingham       "    The expression provided on the command line must be a complete expression \
213d0309916SJim Ingham with no newlines.  To evaluate a multi-line expression, \
214d0309916SJim Ingham hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
215d0309916SJim Ingham Hit return on an empty line to end the multi-line expression."
216d0309916SJim Ingham 
217d0309916SJim Ingham       R"(
218d0309916SJim Ingham 
219ea671fbdSKate Stone Timeouts:
220ea671fbdSKate Stone 
221b9c1b51eSKate Stone )"
222b9c1b51eSKate Stone       "    If the expression can be evaluated statically (without running code) then it will be.  \
223ea671fbdSKate Stone Otherwise, by default the expression will run on the current thread with a short timeout: \
224ea671fbdSKate Stone currently .25 seconds.  If it doesn't return in that time, the evaluation will be interrupted \
225ea671fbdSKate Stone and resumed with all threads running.  You can use the -a option to disable retrying on all \
226b9c1b51eSKate Stone threads.  You can use the -t option to set a shorter timeout."
227b9c1b51eSKate Stone       R"(
228ea671fbdSKate Stone 
229ea671fbdSKate Stone User defined variables:
230ea671fbdSKate Stone 
231b9c1b51eSKate Stone )"
232b9c1b51eSKate Stone       "    You can define your own variables for convenience or to be used in subsequent expressions.  \
233ea671fbdSKate Stone You define them the same way you would define variables in C.  If the first character of \
234ea671fbdSKate Stone your user defined variable is a $, then the variable's value will be available in future \
235b9c1b51eSKate Stone expressions, otherwise it will just be available in the current expression."
236b9c1b51eSKate Stone       R"(
237ea671fbdSKate Stone 
238ea671fbdSKate Stone Continuing evaluation after a breakpoint:
239ea671fbdSKate Stone 
240b9c1b51eSKate Stone )"
241b9c1b51eSKate Stone       "    If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
242ea671fbdSKate Stone you are done with your investigation, you can either remove the expression execution frames \
243ea671fbdSKate Stone from the stack with \"thread return -x\" or if you are still interested in the expression result \
244ea671fbdSKate Stone you can issue the \"continue\" command and the expression evaluation will complete and the \
245ea671fbdSKate Stone expression result will be available using the \"thread.completed-expression\" key in the thread \
246b9c1b51eSKate Stone format."
247d0309916SJim Ingham 
248b9c1b51eSKate Stone       R"(
249ea671fbdSKate Stone 
250ea671fbdSKate Stone Examples:
251ea671fbdSKate Stone 
252ea671fbdSKate Stone     expr my_struct->a = my_array[3]
253ea671fbdSKate Stone     expr -f bin -- (index * 8) + 5
254ea671fbdSKate Stone     expr unsigned int $foo = 5
255b9c1b51eSKate Stone     expr char c[] = \"foo\"; c[0])");
256405fe67fSCaroline Tice 
257405fe67fSCaroline Tice   CommandArgumentEntry arg;
258405fe67fSCaroline Tice   CommandArgumentData expression_arg;
259405fe67fSCaroline Tice 
260405fe67fSCaroline Tice   // Define the first (and only) variant of this arg.
261405fe67fSCaroline Tice   expression_arg.arg_type = eArgTypeExpression;
262405fe67fSCaroline Tice   expression_arg.arg_repetition = eArgRepeatPlain;
263405fe67fSCaroline Tice 
264b9c1b51eSKate Stone   // There is only one variant this argument could be; put it into the argument
265b9c1b51eSKate Stone   // entry.
266405fe67fSCaroline Tice   arg.push_back(expression_arg);
267405fe67fSCaroline Tice 
268405fe67fSCaroline Tice   // Push the data for the first argument into the m_arguments vector.
269405fe67fSCaroline Tice   m_arguments.push_back(arg);
2701deb7962SGreg Clayton 
2715009f9d5SGreg Clayton   // Add the "--format" and "--gdb-format"
272b9c1b51eSKate Stone   m_option_group.Append(&m_format_options,
273b9c1b51eSKate Stone                         OptionGroupFormat::OPTION_GROUP_FORMAT |
274b9c1b51eSKate Stone                             OptionGroupFormat::OPTION_GROUP_GDB_FMT,
275b9c1b51eSKate Stone                         LLDB_OPT_SET_1);
2761deb7962SGreg Clayton   m_option_group.Append(&m_command_options);
277b9c1b51eSKate Stone   m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
278b9c1b51eSKate Stone                         LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
279f2bd5c3eSSean Callanan   m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
2801deb7962SGreg Clayton   m_option_group.Finalize();
28130fdc8d8SChris Lattner }
28230fdc8d8SChris Lattner 
283c8ecc2a9SEugene Zelenko CommandObjectExpression::~CommandObjectExpression() = default;
28430fdc8d8SChris Lattner 
285b9c1b51eSKate Stone Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
28630fdc8d8SChris Lattner 
287ae34ed2cSRaphael Isemann void CommandObjectExpression::HandleCompletion(CompletionRequest &request) {
28874829734SRaphael Isemann   EvaluateExpressionOptions options;
28974829734SRaphael Isemann   options.SetCoerceToId(m_varobj_options.use_objc);
29074829734SRaphael Isemann   options.SetLanguage(m_command_options.language);
29174829734SRaphael Isemann   options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever);
29274829734SRaphael Isemann   options.SetAutoApplyFixIts(false);
29374829734SRaphael Isemann   options.SetGenerateDebugInfo(false);
29474829734SRaphael Isemann 
29574829734SRaphael Isemann   // We need a valid execution context with a frame pointer for this
29674829734SRaphael Isemann   // completion, so if we don't have one we should try to make a valid
29774829734SRaphael Isemann   // execution context.
29874829734SRaphael Isemann   if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr)
29974829734SRaphael Isemann     m_interpreter.UpdateExecutionContext(nullptr);
30074829734SRaphael Isemann 
30174829734SRaphael Isemann   // This didn't work, so let's get out before we start doing things that
30274829734SRaphael Isemann   // expect a valid frame pointer.
30374829734SRaphael Isemann   if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr)
304ae34ed2cSRaphael Isemann     return;
30574829734SRaphael Isemann 
30674829734SRaphael Isemann   ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
30774829734SRaphael Isemann 
30874829734SRaphael Isemann   Target *target = exe_ctx.GetTargetPtr();
30974829734SRaphael Isemann 
31074829734SRaphael Isemann   if (!target)
311cb2380c9SRaphael Isemann     target = &GetDummyTarget();
31274829734SRaphael Isemann 
31374829734SRaphael Isemann   unsigned cursor_pos = request.GetRawCursorPos();
31474829734SRaphael Isemann   llvm::StringRef code = request.GetRawLine();
31574829734SRaphael Isemann 
31674829734SRaphael Isemann   const std::size_t original_code_size = code.size();
31774829734SRaphael Isemann 
31874829734SRaphael Isemann   // Remove the first token which is 'expr' or some alias/abbreviation of that.
31974829734SRaphael Isemann   code = llvm::getToken(code).second.ltrim();
32074829734SRaphael Isemann   OptionsWithRaw args(code);
32174829734SRaphael Isemann   code = args.GetRawPart();
32274829734SRaphael Isemann 
32374829734SRaphael Isemann   // The position where the expression starts in the command line.
32474829734SRaphael Isemann   assert(original_code_size >= code.size());
32574829734SRaphael Isemann   std::size_t raw_start = original_code_size - code.size();
32674829734SRaphael Isemann 
32774829734SRaphael Isemann   // Check if the cursor is actually in the expression string, and if not, we
32874829734SRaphael Isemann   // exit.
32974829734SRaphael Isemann   // FIXME: We should complete the options here.
33074829734SRaphael Isemann   if (cursor_pos < raw_start)
331ae34ed2cSRaphael Isemann     return;
33274829734SRaphael Isemann 
33374829734SRaphael Isemann   // Make the cursor_pos again relative to the start of the code string.
33474829734SRaphael Isemann   assert(cursor_pos >= raw_start);
33574829734SRaphael Isemann   cursor_pos -= raw_start;
33674829734SRaphael Isemann 
33774829734SRaphael Isemann   auto language = exe_ctx.GetFrameRef().GetLanguage();
33874829734SRaphael Isemann 
33974829734SRaphael Isemann   Status error;
34074829734SRaphael Isemann   lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage(
34174829734SRaphael Isemann       code, llvm::StringRef(), language, UserExpression::eResultTypeAny,
34240624a08SAleksandr Urakov       options, nullptr, error));
34374829734SRaphael Isemann   if (error.Fail())
344ae34ed2cSRaphael Isemann     return;
34574829734SRaphael Isemann 
346c11a780eSRaphael Isemann   expr->Complete(exe_ctx, request, cursor_pos);
34774829734SRaphael Isemann }
34874829734SRaphael Isemann 
34997206d57SZachary Turner static lldb_private::Status
350b9c1b51eSKate Stone CanBeUsedForElementCountPrinting(ValueObject &valobj) {
351520a422bSEnrico Granata   CompilerType type(valobj.GetCompilerType());
352520a422bSEnrico Granata   CompilerType pointee;
353520a422bSEnrico Granata   if (!type.IsPointerType(&pointee))
35497206d57SZachary Turner     return Status("as it does not refer to a pointer");
355520a422bSEnrico Granata   if (pointee.IsVoidType())
35697206d57SZachary Turner     return Status("as it refers to a pointer to void");
35797206d57SZachary Turner   return Status();
358520a422bSEnrico Granata }
359520a422bSEnrico Granata 
3604d51a902SRaphael Isemann bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
3616e8dc334SCaroline Tice                                                  Stream *output_stream,
3626e8dc334SCaroline Tice                                                  Stream *error_stream,
363b9c1b51eSKate Stone                                                  CommandReturnObject *result) {
36405097246SAdrian Prantl   // Don't use m_exe_ctx as this might be called asynchronously after the
36505097246SAdrian Prantl   // command object DoExecute has finished when doing multi-line expression
36605097246SAdrian Prantl   // that use an input reader...
367ba7b8e2cSGreg Clayton   ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
368ba7b8e2cSGreg Clayton 
369ba7b8e2cSGreg Clayton   Target *target = exe_ctx.GetTargetPtr();
370c0a6e061SSean Callanan 
371c0a6e061SSean Callanan   if (!target)
372cb2380c9SRaphael Isemann     target = &GetDummyTarget();
373c0a6e061SSean Callanan 
3748b2fe6dcSGreg Clayton   lldb::ValueObjectSP result_valobj_sp;
37592adcac9SSean Callanan   bool keep_in_memory = true;
376009d110dSDawn Perchik   StackFrame *frame = exe_ctx.GetFramePtr();
37792adcac9SSean Callanan 
37835e1bda6SJim Ingham   EvaluateExpressionOptions options;
3796fbc48bcSJim Ingham   options.SetCoerceToId(m_varobj_options.use_objc);
3806fbc48bcSJim Ingham   options.SetUnwindOnError(m_command_options.unwind_on_error);
3816fbc48bcSJim Ingham   options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
3826fbc48bcSJim Ingham   options.SetKeepInMemory(keep_in_memory);
3836fbc48bcSJim Ingham   options.SetUseDynamic(m_varobj_options.use_dynamic);
3846fbc48bcSJim Ingham   options.SetTryAllThreads(m_command_options.try_all_threads);
3856fbc48bcSJim Ingham   options.SetDebug(m_command_options.debug);
38615663c53SDawn Perchik   options.SetLanguage(m_command_options.language);
387b9c1b51eSKate Stone   options.SetExecutionPolicy(
388b9c1b51eSKate Stone       m_command_options.allow_jit
389b9c1b51eSKate Stone           ? EvaluateExpressionOptions::default_execution_policy
390b9c1b51eSKate Stone           : lldb_private::eExecutionPolicyNever);
39115663c53SDawn Perchik 
392a1e541bfSJim Ingham   bool auto_apply_fixits;
393a1e541bfSJim Ingham   if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
394a1e541bfSJim Ingham     auto_apply_fixits = target->GetEnableAutoApplyFixIts();
395a1e541bfSJim Ingham   else
396a6682a41SJonas Devlieghere     auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes;
397a1e541bfSJim Ingham 
398a1e541bfSJim Ingham   options.SetAutoApplyFixIts(auto_apply_fixits);
399a1e541bfSJim Ingham 
400863fab69SSean Callanan   if (m_command_options.top_level)
401863fab69SSean Callanan     options.SetExecutionPolicy(eExecutionPolicyTopLevel);
402863fab69SSean Callanan 
40305097246SAdrian Prantl   // If there is any chance we are going to stop and want to see what went
40405097246SAdrian Prantl   // wrong with our expression, we should generate debug info
40523f8c95aSGreg Clayton   if (!m_command_options.ignore_breakpoints ||
40623f8c95aSGreg Clayton       !m_command_options.unwind_on_error)
40723f8c95aSGreg Clayton     options.SetGenerateDebugInfo(true);
40823f8c95aSGreg Clayton 
40962afb9f6SGreg Clayton   if (m_command_options.timeout > 0)
41043d35418SPavel Labath     options.SetTimeout(std::chrono::microseconds(m_command_options.timeout));
4116f78f386SJim Ingham   else
41243d35418SPavel Labath     options.SetTimeout(llvm::None);
413d4439aa9SEnrico Granata 
414b9c1b51eSKate Stone   ExpressionResults success = target->EvaluateExpression(
415b9c1b51eSKate Stone       expr, frame, result_valobj_sp, options, &m_fixed_expression);
416e5ee6f04SJim Ingham 
417b9c1b51eSKate Stone   // We only tell you about the FixIt if we applied it.  The compiler errors
418b9c1b51eSKate Stone   // will suggest the FixIt if it parsed.
419b9c1b51eSKate Stone   if (error_stream && !m_fixed_expression.empty() &&
420b9c1b51eSKate Stone       target->GetEnableNotifyAboutFixIts()) {
421e5ee6f04SJim Ingham     if (success == eExpressionCompleted)
422365b30a3SPavel Labath       error_stream->Printf("  Fix-it applied, fixed expression was: \n    %s\n",
423b9c1b51eSKate Stone                            m_fixed_expression.c_str());
424e5ee6f04SJim Ingham   }
4258b2fe6dcSGreg Clayton 
426b9c1b51eSKate Stone   if (result_valobj_sp) {
427bf154daeSSean Callanan     Format format = m_format_options.GetFormat();
428bf154daeSSean Callanan 
429b9c1b51eSKate Stone     if (result_valobj_sp->GetError().Success()) {
430b9c1b51eSKate Stone       if (format != eFormatVoid) {
4311deb7962SGreg Clayton         if (format != eFormatDefault)
4321deb7962SGreg Clayton           result_valobj_sp->SetFormat(format);
43332c4085bSGreg Clayton 
434b9c1b51eSKate Stone         if (m_varobj_options.elem_count > 0) {
43597206d57SZachary Turner           Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
436b9c1b51eSKate Stone           if (error.Fail()) {
437b9c1b51eSKate Stone             result->AppendErrorWithFormat(
438b9c1b51eSKate Stone                 "expression cannot be used with --element-count %s\n",
439b9c1b51eSKate Stone                 error.AsCString(""));
440520a422bSEnrico Granata             result->SetStatus(eReturnStatusFailed);
441520a422bSEnrico Granata             return false;
442520a422bSEnrico Granata           }
443520a422bSEnrico Granata         }
444520a422bSEnrico Granata 
445b9c1b51eSKate Stone         DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
446b9c1b51eSKate Stone             m_command_options.m_verbosity, format));
447b9c1b51eSKate Stone         options.SetVariableFormatDisplayLanguage(
448b9c1b51eSKate Stone             result_valobj_sp->GetPreferredDisplayLanguage());
449770eb05aSEnrico Granata 
4504d93b8cdSEnrico Granata         result_valobj_sp->Dump(*output_stream, options);
4514d93b8cdSEnrico Granata 
452fcd43b71SJohnny Chen         if (result)
453fcd43b71SJohnny Chen           result->SetStatus(eReturnStatusSuccessFinishResult);
45430fdc8d8SChris Lattner       }
455b9c1b51eSKate Stone     } else {
456b9c1b51eSKate Stone       if (result_valobj_sp->GetError().GetError() ==
457a35912daSKrasimir Georgiev           UserExpression::kNoResult) {
45857179860SJonas Devlieghere         if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) {
459bcf897faSSean Callanan           error_stream->PutCString("(void)\n");
460bcf897faSSean Callanan         }
461bccce813SSean Callanan 
462bccce813SSean Callanan         if (result)
463bccce813SSean Callanan           result->SetStatus(eReturnStatusSuccessFinishResult);
464b9c1b51eSKate Stone       } else {
4655fd05903SGreg Clayton         const char *error_cstr = result_valobj_sp->GetError().AsCString();
466b9c1b51eSKate Stone         if (error_cstr && error_cstr[0]) {
467c7bece56SGreg Clayton           const size_t error_cstr_len = strlen(error_cstr);
468365b30a3SPavel Labath           const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
4695fd05903SGreg Clayton           if (strstr(error_cstr, "error:") != error_cstr)
4705fd05903SGreg Clayton             error_stream->PutCString("error: ");
4715fd05903SGreg Clayton           error_stream->Write(error_cstr, error_cstr_len);
4725fd05903SGreg Clayton           if (!ends_with_newline)
4735fd05903SGreg Clayton             error_stream->EOL();
474b9c1b51eSKate Stone         } else {
4755fd05903SGreg Clayton           error_stream->PutCString("error: unknown error\n");
4765fd05903SGreg Clayton         }
4775fd05903SGreg Clayton 
478fcd43b71SJohnny Chen         if (result)
479b71f3844SGreg Clayton           result->SetStatus(eReturnStatusFailed);
48030fdc8d8SChris Lattner       }
4818b2fe6dcSGreg Clayton     }
4828b2fe6dcSGreg Clayton   }
48330fdc8d8SChris Lattner 
48416ad5faeSSean Callanan   return true;
48530fdc8d8SChris Lattner }
48630fdc8d8SChris Lattner 
487b9c1b51eSKate Stone void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
488b9c1b51eSKate Stone                                                      std::string &line) {
48944d93782SGreg Clayton   io_handler.SetIsDone(true);
490b9c1b51eSKate Stone   //    StreamSP output_stream =
491b9c1b51eSKate Stone   //    io_handler.GetDebugger().GetAsyncOutputStream();
49244d93782SGreg Clayton   //    StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
4937ca15ba7SLawrence D'Anna   StreamFileSP output_sp = io_handler.GetOutputStreamFileSP();
4947ca15ba7SLawrence D'Anna   StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
49544d93782SGreg Clayton 
496b9c1b51eSKate Stone   EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get());
49744d93782SGreg Clayton   if (output_sp)
49844d93782SGreg Clayton     output_sp->Flush();
49944d93782SGreg Clayton   if (error_sp)
50044d93782SGreg Clayton     error_sp->Flush();
50144d93782SGreg Clayton }
50244d93782SGreg Clayton 
503b9c1b51eSKate Stone bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
504b9c1b51eSKate Stone                                                        StringList &lines) {
505f52c40c5SSean Callanan   // An empty lines is used to indicate the end of input
506f52c40c5SSean Callanan   const size_t num_lines = lines.GetSize();
507b9c1b51eSKate Stone   if (num_lines > 0 && lines[num_lines - 1].empty()) {
50805097246SAdrian Prantl     // Remove the last empty line from "lines" so it doesn't appear in our
50905097246SAdrian Prantl     // resulting input and return true to indicate we are done getting lines
51044d93782SGreg Clayton     lines.PopBack();
511f52c40c5SSean Callanan     return true;
51244d93782SGreg Clayton   }
513f52c40c5SSean Callanan   return false;
51444d93782SGreg Clayton }
51544d93782SGreg Clayton 
516b9c1b51eSKate Stone void CommandObjectExpression::GetMultilineExpression() {
51730fdc8d8SChris Lattner   m_expr_lines.clear();
51830fdc8d8SChris Lattner   m_expr_line_count = 0;
51930fdc8d8SChris Lattner 
52044d93782SGreg Clayton   Debugger &debugger = GetCommandInterpreter().GetDebugger();
521e30f11d9SKate Stone   bool color_prompt = debugger.GetUseColor();
52244d93782SGreg Clayton   const bool multiple_lines = true; // Get multiple lines
523b9c1b51eSKate Stone   IOHandlerSP io_handler_sp(
524b9c1b51eSKate Stone       new IOHandlerEditline(debugger, IOHandler::Type::Expression,
52544d93782SGreg Clayton                             "lldb-expr", // Name of input reader for history
526514d8cd8SZachary Turner                             llvm::StringRef(), // No prompt
527514d8cd8SZachary Turner                             llvm::StringRef(), // Continuation prompt
528b9c1b51eSKate Stone                             multiple_lines, color_prompt,
529f6913cd7SGreg Clayton                             1, // Show line numbers starting at 1
530d77c2e09SJonas Devlieghere                             *this, nullptr));
531b6892508SGreg Clayton 
5327ca15ba7SLawrence D'Anna   StreamFileSP output_sp = io_handler_sp->GetOutputStreamFileSP();
533b9c1b51eSKate Stone   if (output_sp) {
534b9c1b51eSKate Stone     output_sp->PutCString(
535b9c1b51eSKate Stone         "Enter expressions, then terminate with an empty line to evaluate:\n");
536b6892508SGreg Clayton     output_sp->Flush();
537b6892508SGreg Clayton   }
538*7ce2de2cSJonas Devlieghere   debugger.RunIOHandlerAsync(io_handler_sp);
539cf28a8b7SGreg Clayton }
540cf28a8b7SGreg Clayton 
541c5bfa3daSJonas Devlieghere static EvaluateExpressionOptions
542c5bfa3daSJonas Devlieghere GetExprOptions(ExecutionContext &ctx,
543c5bfa3daSJonas Devlieghere                CommandObjectExpression::CommandOptions command_options) {
544c5bfa3daSJonas Devlieghere   command_options.OptionParsingStarting(&ctx);
545c5bfa3daSJonas Devlieghere 
546c5bfa3daSJonas Devlieghere   // Default certain settings for REPL regardless of the global settings.
547c5bfa3daSJonas Devlieghere   command_options.unwind_on_error = false;
548c5bfa3daSJonas Devlieghere   command_options.ignore_breakpoints = false;
549c5bfa3daSJonas Devlieghere   command_options.debug = false;
550c5bfa3daSJonas Devlieghere 
551c5bfa3daSJonas Devlieghere   EvaluateExpressionOptions expr_options;
552c5bfa3daSJonas Devlieghere   expr_options.SetUnwindOnError(command_options.unwind_on_error);
553c5bfa3daSJonas Devlieghere   expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints);
554c5bfa3daSJonas Devlieghere   expr_options.SetTryAllThreads(command_options.try_all_threads);
555c5bfa3daSJonas Devlieghere 
556c5bfa3daSJonas Devlieghere   if (command_options.timeout > 0)
557c5bfa3daSJonas Devlieghere     expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout));
558c5bfa3daSJonas Devlieghere   else
559c5bfa3daSJonas Devlieghere     expr_options.SetTimeout(llvm::None);
560c5bfa3daSJonas Devlieghere 
561c5bfa3daSJonas Devlieghere   return expr_options;
562c5bfa3daSJonas Devlieghere }
563c5bfa3daSJonas Devlieghere 
5644d51a902SRaphael Isemann bool CommandObjectExpression::DoExecute(llvm::StringRef command,
565b9c1b51eSKate Stone                                         CommandReturnObject &result) {
566e5ee6f04SJim Ingham   m_fixed_expression.clear();
567e1cfbc79STodd Fiala   auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
568e1cfbc79STodd Fiala   m_option_group.NotifyOptionParsingStarting(&exe_ctx);
569cf28a8b7SGreg Clayton 
5704d51a902SRaphael Isemann   if (command.empty()) {
571cf28a8b7SGreg Clayton     GetMultilineExpression();
57230fdc8d8SChris Lattner     return result.Succeeded();
57330fdc8d8SChris Lattner   }
57430fdc8d8SChris Lattner 
5753a0e1270SRaphael Isemann   OptionsWithRaw args(command);
5764d51a902SRaphael Isemann   llvm::StringRef expr = args.GetRawPart();
57730fdc8d8SChris Lattner 
5783a0e1270SRaphael Isemann   if (args.HasArgs()) {
5793a0e1270SRaphael Isemann     if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))
58030fdc8d8SChris Lattner       return false;
581f6b8b581SGreg Clayton 
582b9c1b51eSKate Stone     if (m_repl_option.GetOptionValue().GetCurrentValue()) {
5835a1bac4dSRaphael Isemann       Target &target = GetSelectedOrDummyTarget();
584f2bd5c3eSSean Callanan       // Drop into REPL
585f2bd5c3eSSean Callanan       m_expr_lines.clear();
586f2bd5c3eSSean Callanan       m_expr_line_count = 0;
587f2bd5c3eSSean Callanan 
5885a1bac4dSRaphael Isemann       Debugger &debugger = target.GetDebugger();
589f2bd5c3eSSean Callanan 
590b9c1b51eSKate Stone       // Check if the LLDB command interpreter is sitting on top of a REPL
59105097246SAdrian Prantl       // that launched it...
5923a0e1270SRaphael Isemann       if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,
5933a0e1270SRaphael Isemann                                           IOHandler::Type::REPL)) {
594b9c1b51eSKate Stone         // the LLDB command interpreter is sitting on top of a REPL that
59505097246SAdrian Prantl         // launched it, so just say the command interpreter is done and
59605097246SAdrian Prantl         // fall back to the existing REPL
597f2bd5c3eSSean Callanan         m_interpreter.GetIOHandler(false)->SetIsDone(true);
598b9c1b51eSKate Stone       } else {
599b9c1b51eSKate Stone         // We are launching the REPL on top of the current LLDB command
60005097246SAdrian Prantl         // interpreter, so just push one
601f2bd5c3eSSean Callanan         bool initialize = false;
60297206d57SZachary Turner         Status repl_error;
6035a1bac4dSRaphael Isemann         REPLSP repl_sp(target.GetREPL(repl_error, m_command_options.language,
6043a0e1270SRaphael Isemann                                        nullptr, false));
605f2bd5c3eSSean Callanan 
606b9c1b51eSKate Stone         if (!repl_sp) {
607f2bd5c3eSSean Callanan           initialize = true;
6085a1bac4dSRaphael Isemann           repl_sp = target.GetREPL(repl_error, m_command_options.language,
609b9c1b51eSKate Stone                                     nullptr, true);
610b9c1b51eSKate Stone           if (!repl_error.Success()) {
611f2bd5c3eSSean Callanan             result.SetError(repl_error);
612f2bd5c3eSSean Callanan             return result.Succeeded();
613f2bd5c3eSSean Callanan           }
614f2bd5c3eSSean Callanan         }
615f2bd5c3eSSean Callanan 
616b9c1b51eSKate Stone         if (repl_sp) {
617b9c1b51eSKate Stone           if (initialize) {
618c5bfa3daSJonas Devlieghere             repl_sp->SetEvaluateOptions(
619c5bfa3daSJonas Devlieghere                 GetExprOptions(exe_ctx, m_command_options));
620f2bd5c3eSSean Callanan             repl_sp->SetFormatOptions(m_format_options);
621f2bd5c3eSSean Callanan             repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
622f2bd5c3eSSean Callanan           }
623f2bd5c3eSSean Callanan 
624f2bd5c3eSSean Callanan           IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
625f2bd5c3eSSean Callanan           io_handler_sp->SetIsDone(false);
626*7ce2de2cSJonas Devlieghere           debugger.RunIOHandlerAsync(io_handler_sp);
627b9c1b51eSKate Stone         } else {
628b9c1b51eSKate Stone           repl_error.SetErrorStringWithFormat(
629b9c1b51eSKate Stone               "Couldn't create a REPL for %s",
630b9c1b51eSKate Stone               Language::GetNameForLanguageType(m_command_options.language));
631f2bd5c3eSSean Callanan           result.SetError(repl_error);
632f2bd5c3eSSean Callanan           return result.Succeeded();
633f2bd5c3eSSean Callanan         }
634f2bd5c3eSSean Callanan       }
635f2bd5c3eSSean Callanan     }
636cf28a8b7SGreg Clayton     // No expression following options
6374d51a902SRaphael Isemann     else if (expr.empty()) {
638cf28a8b7SGreg Clayton       GetMultilineExpression();
639cf28a8b7SGreg Clayton       return result.Succeeded();
640cf28a8b7SGreg Clayton     }
64130fdc8d8SChris Lattner   }
64230fdc8d8SChris Lattner 
643cb2380c9SRaphael Isemann   Target &target = GetSelectedOrDummyTarget();
64424fff242SDavide Italiano   if (EvaluateExpression(expr, &(result.GetOutputStream()),
64524fff242SDavide Italiano                          &(result.GetErrorStream()), &result)) {
64624fff242SDavide Italiano 
647cb2380c9SRaphael Isemann     if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
648e5ee6f04SJim Ingham       CommandHistory &history = m_interpreter.GetCommandHistory();
649b9c1b51eSKate Stone       // FIXME: Can we figure out what the user actually typed (e.g. some alias
650b9c1b51eSKate Stone       // for expr???)
651e5ee6f04SJim Ingham       // If we can it would be nice to show that.
652e5ee6f04SJim Ingham       std::string fixed_command("expression ");
6533a0e1270SRaphael Isemann       if (args.HasArgs()) {
654e5ee6f04SJim Ingham         // Add in any options that might have been in the original command:
6553a0e1270SRaphael Isemann         fixed_command.append(args.GetArgStringWithDelimiter());
656e5ee6f04SJim Ingham         fixed_command.append(m_fixed_expression);
6573a0e1270SRaphael Isemann       } else
6583a0e1270SRaphael Isemann         fixed_command.append(m_fixed_expression);
659e5ee6f04SJim Ingham       history.AppendString(fixed_command);
660e5ee6f04SJim Ingham     }
66105097246SAdrian Prantl     // Increment statistics to record this expression evaluation success.
662cb2380c9SRaphael Isemann     target.IncrementStats(StatisticKind::ExpressionSuccessful);
663fcd43b71SJohnny Chen     return true;
664e5ee6f04SJim Ingham   }
665fcd43b71SJohnny Chen 
66605097246SAdrian Prantl   // Increment statistics to record this expression evaluation failure.
667cb2380c9SRaphael Isemann   target.IncrementStats(StatisticKind::ExpressionFailure);
668fcd43b71SJohnny Chen   result.SetStatus(eReturnStatusFailed);
669fcd43b71SJohnny Chen   return false;
67030fdc8d8SChris Lattner }
671