180814287SRaphael Isemann //===-- CommandObjectExpression.cpp ---------------------------------------===//
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());
307*b2fa3b92SJonas Devlieghere   Target *exe_target = exe_ctx.GetTargetPtr();
308*b2fa3b92SJonas Devlieghere   Target &target = exe_target ? *exe_target : GetDummyTarget();
30974829734SRaphael Isemann 
31074829734SRaphael Isemann   unsigned cursor_pos = request.GetRawCursorPos();
311243f52b5SRaphael Isemann   // Get the full user input including the suffix. The suffix is necessary
312243f52b5SRaphael Isemann   // as OptionsWithRaw will use it to detect if the cursor is cursor is in the
313243f52b5SRaphael Isemann   // argument part of in the raw input part of the arguments. If we cut of
314243f52b5SRaphael Isemann   // of the suffix then "expr -arg[cursor] --" would interpret the "-arg" as
315243f52b5SRaphael Isemann   // the raw input (as the "--" is hidden in the suffix).
316243f52b5SRaphael Isemann   llvm::StringRef code = request.GetRawLineWithUnusedSuffix();
31774829734SRaphael Isemann 
31874829734SRaphael Isemann   const std::size_t original_code_size = code.size();
31974829734SRaphael Isemann 
32074829734SRaphael Isemann   // Remove the first token which is 'expr' or some alias/abbreviation of that.
32174829734SRaphael Isemann   code = llvm::getToken(code).second.ltrim();
32274829734SRaphael Isemann   OptionsWithRaw args(code);
32374829734SRaphael Isemann   code = args.GetRawPart();
32474829734SRaphael Isemann 
32574829734SRaphael Isemann   // The position where the expression starts in the command line.
32674829734SRaphael Isemann   assert(original_code_size >= code.size());
32774829734SRaphael Isemann   std::size_t raw_start = original_code_size - code.size();
32874829734SRaphael Isemann 
32974829734SRaphael Isemann   // Check if the cursor is actually in the expression string, and if not, we
33074829734SRaphael Isemann   // exit.
33174829734SRaphael Isemann   // FIXME: We should complete the options here.
33274829734SRaphael Isemann   if (cursor_pos < raw_start)
333ae34ed2cSRaphael Isemann     return;
33474829734SRaphael Isemann 
33574829734SRaphael Isemann   // Make the cursor_pos again relative to the start of the code string.
33674829734SRaphael Isemann   assert(cursor_pos >= raw_start);
33774829734SRaphael Isemann   cursor_pos -= raw_start;
33874829734SRaphael Isemann 
33974829734SRaphael Isemann   auto language = exe_ctx.GetFrameRef().GetLanguage();
34074829734SRaphael Isemann 
34174829734SRaphael Isemann   Status error;
342*b2fa3b92SJonas Devlieghere   lldb::UserExpressionSP expr(target.GetUserExpressionForLanguage(
34374829734SRaphael Isemann       code, llvm::StringRef(), language, UserExpression::eResultTypeAny,
34440624a08SAleksandr Urakov       options, nullptr, error));
34574829734SRaphael Isemann   if (error.Fail())
346ae34ed2cSRaphael Isemann     return;
34774829734SRaphael Isemann 
348c11a780eSRaphael Isemann   expr->Complete(exe_ctx, request, cursor_pos);
34974829734SRaphael Isemann }
35074829734SRaphael Isemann 
35197206d57SZachary Turner static lldb_private::Status
352b9c1b51eSKate Stone CanBeUsedForElementCountPrinting(ValueObject &valobj) {
353520a422bSEnrico Granata   CompilerType type(valobj.GetCompilerType());
354520a422bSEnrico Granata   CompilerType pointee;
355520a422bSEnrico Granata   if (!type.IsPointerType(&pointee))
35697206d57SZachary Turner     return Status("as it does not refer to a pointer");
357520a422bSEnrico Granata   if (pointee.IsVoidType())
35897206d57SZachary Turner     return Status("as it refers to a pointer to void");
35997206d57SZachary Turner   return Status();
360520a422bSEnrico Granata }
361520a422bSEnrico Granata 
3628f7c911bSRaphael Isemann EvaluateExpressionOptions
3638f7c911bSRaphael Isemann CommandObjectExpression::GetEvalOptions(const Target &target) {
36435e1bda6SJim Ingham   EvaluateExpressionOptions options;
3656fbc48bcSJim Ingham   options.SetCoerceToId(m_varobj_options.use_objc);
3666fbc48bcSJim Ingham   options.SetUnwindOnError(m_command_options.unwind_on_error);
3676fbc48bcSJim Ingham   options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
3688f7c911bSRaphael Isemann   options.SetKeepInMemory(true);
3696fbc48bcSJim Ingham   options.SetUseDynamic(m_varobj_options.use_dynamic);
3706fbc48bcSJim Ingham   options.SetTryAllThreads(m_command_options.try_all_threads);
3716fbc48bcSJim Ingham   options.SetDebug(m_command_options.debug);
37215663c53SDawn Perchik   options.SetLanguage(m_command_options.language);
373b9c1b51eSKate Stone   options.SetExecutionPolicy(
374b9c1b51eSKate Stone       m_command_options.allow_jit
375b9c1b51eSKate Stone           ? EvaluateExpressionOptions::default_execution_policy
376b9c1b51eSKate Stone           : lldb_private::eExecutionPolicyNever);
37715663c53SDawn Perchik 
378a1e541bfSJim Ingham   bool auto_apply_fixits;
379a1e541bfSJim Ingham   if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
3808f7c911bSRaphael Isemann     auto_apply_fixits = target.GetEnableAutoApplyFixIts();
381a1e541bfSJim Ingham   else
382a6682a41SJonas Devlieghere     auto_apply_fixits = m_command_options.auto_apply_fixits == eLazyBoolYes;
383a1e541bfSJim Ingham 
384a1e541bfSJim Ingham   options.SetAutoApplyFixIts(auto_apply_fixits);
385203a8adbSRaphael Isemann   options.SetRetriesWithFixIts(target.GetNumberOfRetriesWithFixits());
386a1e541bfSJim Ingham 
387863fab69SSean Callanan   if (m_command_options.top_level)
388863fab69SSean Callanan     options.SetExecutionPolicy(eExecutionPolicyTopLevel);
389863fab69SSean Callanan 
39005097246SAdrian Prantl   // If there is any chance we are going to stop and want to see what went
39105097246SAdrian Prantl   // wrong with our expression, we should generate debug info
39223f8c95aSGreg Clayton   if (!m_command_options.ignore_breakpoints ||
39323f8c95aSGreg Clayton       !m_command_options.unwind_on_error)
39423f8c95aSGreg Clayton     options.SetGenerateDebugInfo(true);
39523f8c95aSGreg Clayton 
39662afb9f6SGreg Clayton   if (m_command_options.timeout > 0)
39743d35418SPavel Labath     options.SetTimeout(std::chrono::microseconds(m_command_options.timeout));
3986f78f386SJim Ingham   else
39943d35418SPavel Labath     options.SetTimeout(llvm::None);
4008f7c911bSRaphael Isemann   return options;
4018f7c911bSRaphael Isemann }
402d4439aa9SEnrico Granata 
4038f7c911bSRaphael Isemann bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
4047c6e52acSRaphael Isemann                                                  Stream &output_stream,
4057c6e52acSRaphael Isemann                                                  Stream &error_stream,
4067c6e52acSRaphael Isemann                                                  CommandReturnObject &result) {
4078f7c911bSRaphael Isemann   // Don't use m_exe_ctx as this might be called asynchronously after the
4088f7c911bSRaphael Isemann   // command object DoExecute has finished when doing multi-line expression
4098f7c911bSRaphael Isemann   // that use an input reader...
4108f7c911bSRaphael Isemann   ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
411*b2fa3b92SJonas Devlieghere   Target *exe_target = exe_ctx.GetTargetPtr();
412*b2fa3b92SJonas Devlieghere   Target &target = exe_target ? *exe_target : GetDummyTarget();
4138f7c911bSRaphael Isemann 
4148f7c911bSRaphael Isemann   lldb::ValueObjectSP result_valobj_sp;
4158f7c911bSRaphael Isemann   StackFrame *frame = exe_ctx.GetFramePtr();
4168f7c911bSRaphael Isemann 
417*b2fa3b92SJonas Devlieghere   const EvaluateExpressionOptions options = GetEvalOptions(target);
418*b2fa3b92SJonas Devlieghere   ExpressionResults success = target.EvaluateExpression(
419b9c1b51eSKate Stone       expr, frame, result_valobj_sp, options, &m_fixed_expression);
420e5ee6f04SJim Ingham 
421b9c1b51eSKate Stone   // We only tell you about the FixIt if we applied it.  The compiler errors
422b9c1b51eSKate Stone   // will suggest the FixIt if it parsed.
423*b2fa3b92SJonas Devlieghere   if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
424e5ee6f04SJim Ingham     if (success == eExpressionCompleted)
4257c6e52acSRaphael Isemann       error_stream.Printf("  Fix-it applied, fixed expression was: \n    %s\n",
426b9c1b51eSKate Stone                           m_fixed_expression.c_str());
427e5ee6f04SJim Ingham   }
4288b2fe6dcSGreg Clayton 
429b9c1b51eSKate Stone   if (result_valobj_sp) {
430bf154daeSSean Callanan     Format format = m_format_options.GetFormat();
431bf154daeSSean Callanan 
432b9c1b51eSKate Stone     if (result_valobj_sp->GetError().Success()) {
433b9c1b51eSKate Stone       if (format != eFormatVoid) {
4341deb7962SGreg Clayton         if (format != eFormatDefault)
4351deb7962SGreg Clayton           result_valobj_sp->SetFormat(format);
43632c4085bSGreg Clayton 
437b9c1b51eSKate Stone         if (m_varobj_options.elem_count > 0) {
43897206d57SZachary Turner           Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
439b9c1b51eSKate Stone           if (error.Fail()) {
4407c6e52acSRaphael Isemann             result.AppendErrorWithFormat(
441b9c1b51eSKate Stone                 "expression cannot be used with --element-count %s\n",
442b9c1b51eSKate Stone                 error.AsCString(""));
4437c6e52acSRaphael Isemann             result.SetStatus(eReturnStatusFailed);
444520a422bSEnrico Granata             return false;
445520a422bSEnrico Granata           }
446520a422bSEnrico Granata         }
447520a422bSEnrico Granata 
448b9c1b51eSKate Stone         DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
449b9c1b51eSKate Stone             m_command_options.m_verbosity, format));
450b9c1b51eSKate Stone         options.SetVariableFormatDisplayLanguage(
451b9c1b51eSKate Stone             result_valobj_sp->GetPreferredDisplayLanguage());
452770eb05aSEnrico Granata 
4537c6e52acSRaphael Isemann         result_valobj_sp->Dump(output_stream, options);
4544d93b8cdSEnrico Granata 
4557c6e52acSRaphael Isemann         result.SetStatus(eReturnStatusSuccessFinishResult);
45630fdc8d8SChris Lattner       }
457b9c1b51eSKate Stone     } else {
458b9c1b51eSKate Stone       if (result_valobj_sp->GetError().GetError() ==
459a35912daSKrasimir Georgiev           UserExpression::kNoResult) {
46057179860SJonas Devlieghere         if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) {
4617c6e52acSRaphael Isemann           error_stream.PutCString("(void)\n");
462bcf897faSSean Callanan         }
463bccce813SSean Callanan 
4647c6e52acSRaphael Isemann         result.SetStatus(eReturnStatusSuccessFinishResult);
465b9c1b51eSKate Stone       } else {
4665fd05903SGreg Clayton         const char *error_cstr = result_valobj_sp->GetError().AsCString();
467b9c1b51eSKate Stone         if (error_cstr && error_cstr[0]) {
468c7bece56SGreg Clayton           const size_t error_cstr_len = strlen(error_cstr);
469365b30a3SPavel Labath           const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
4705fd05903SGreg Clayton           if (strstr(error_cstr, "error:") != error_cstr)
4717c6e52acSRaphael Isemann             error_stream.PutCString("error: ");
4727c6e52acSRaphael Isemann           error_stream.Write(error_cstr, error_cstr_len);
4735fd05903SGreg Clayton           if (!ends_with_newline)
4747c6e52acSRaphael Isemann             error_stream.EOL();
475b9c1b51eSKate Stone         } else {
4767c6e52acSRaphael Isemann           error_stream.PutCString("error: unknown error\n");
4775fd05903SGreg Clayton         }
4785fd05903SGreg Clayton 
4797c6e52acSRaphael Isemann         result.SetStatus(eReturnStatusFailed);
48030fdc8d8SChris Lattner       }
4818b2fe6dcSGreg Clayton     }
4828b2fe6dcSGreg Clayton   }
48330fdc8d8SChris Lattner 
4846a4905aeSRaphael Isemann   return (success != eExpressionSetupError &&
4856a4905aeSRaphael Isemann           success != eExpressionParseError);
48630fdc8d8SChris Lattner }
48730fdc8d8SChris Lattner 
488b9c1b51eSKate Stone void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
489b9c1b51eSKate Stone                                                      std::string &line) {
49044d93782SGreg Clayton   io_handler.SetIsDone(true);
491b9c1b51eSKate Stone   //    StreamSP output_stream =
492b9c1b51eSKate Stone   //    io_handler.GetDebugger().GetAsyncOutputStream();
49344d93782SGreg Clayton   //    StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
4947ca15ba7SLawrence D'Anna   StreamFileSP output_sp = io_handler.GetOutputStreamFileSP();
4957ca15ba7SLawrence D'Anna   StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
49644d93782SGreg Clayton 
497de019b88SJonas Devlieghere   CommandReturnObject return_obj(
498de019b88SJonas Devlieghere       GetCommandInterpreter().GetDebugger().GetUseColor());
4997c6e52acSRaphael Isemann   EvaluateExpression(line.c_str(), *output_sp, *error_sp, return_obj);
50044d93782SGreg Clayton   if (output_sp)
50144d93782SGreg Clayton     output_sp->Flush();
50244d93782SGreg Clayton   if (error_sp)
50344d93782SGreg Clayton     error_sp->Flush();
50444d93782SGreg Clayton }
50544d93782SGreg Clayton 
506b9c1b51eSKate Stone bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
507b9c1b51eSKate Stone                                                        StringList &lines) {
508f52c40c5SSean Callanan   // An empty lines is used to indicate the end of input
509f52c40c5SSean Callanan   const size_t num_lines = lines.GetSize();
510b9c1b51eSKate Stone   if (num_lines > 0 && lines[num_lines - 1].empty()) {
51105097246SAdrian Prantl     // Remove the last empty line from "lines" so it doesn't appear in our
51205097246SAdrian Prantl     // resulting input and return true to indicate we are done getting lines
51344d93782SGreg Clayton     lines.PopBack();
514f52c40c5SSean Callanan     return true;
51544d93782SGreg Clayton   }
516f52c40c5SSean Callanan   return false;
51744d93782SGreg Clayton }
51844d93782SGreg Clayton 
519b9c1b51eSKate Stone void CommandObjectExpression::GetMultilineExpression() {
52030fdc8d8SChris Lattner   m_expr_lines.clear();
52130fdc8d8SChris Lattner   m_expr_line_count = 0;
52230fdc8d8SChris Lattner 
52344d93782SGreg Clayton   Debugger &debugger = GetCommandInterpreter().GetDebugger();
524e30f11d9SKate Stone   bool color_prompt = debugger.GetUseColor();
52544d93782SGreg Clayton   const bool multiple_lines = true; // Get multiple lines
526b9c1b51eSKate Stone   IOHandlerSP io_handler_sp(
527b9c1b51eSKate Stone       new IOHandlerEditline(debugger, IOHandler::Type::Expression,
52844d93782SGreg Clayton                             "lldb-expr", // Name of input reader for history
529514d8cd8SZachary Turner                             llvm::StringRef(), // No prompt
530514d8cd8SZachary Turner                             llvm::StringRef(), // Continuation prompt
531b9c1b51eSKate Stone                             multiple_lines, color_prompt,
532f6913cd7SGreg Clayton                             1, // Show line numbers starting at 1
533d77c2e09SJonas Devlieghere                             *this, nullptr));
534b6892508SGreg Clayton 
5357ca15ba7SLawrence D'Anna   StreamFileSP output_sp = io_handler_sp->GetOutputStreamFileSP();
536b9c1b51eSKate Stone   if (output_sp) {
537b9c1b51eSKate Stone     output_sp->PutCString(
538b9c1b51eSKate Stone         "Enter expressions, then terminate with an empty line to evaluate:\n");
539b6892508SGreg Clayton     output_sp->Flush();
540b6892508SGreg Clayton   }
5417ce2de2cSJonas Devlieghere   debugger.RunIOHandlerAsync(io_handler_sp);
542cf28a8b7SGreg Clayton }
543cf28a8b7SGreg Clayton 
544c5bfa3daSJonas Devlieghere static EvaluateExpressionOptions
545c5bfa3daSJonas Devlieghere GetExprOptions(ExecutionContext &ctx,
546c5bfa3daSJonas Devlieghere                CommandObjectExpression::CommandOptions command_options) {
547c5bfa3daSJonas Devlieghere   command_options.OptionParsingStarting(&ctx);
548c5bfa3daSJonas Devlieghere 
549c5bfa3daSJonas Devlieghere   // Default certain settings for REPL regardless of the global settings.
550c5bfa3daSJonas Devlieghere   command_options.unwind_on_error = false;
551c5bfa3daSJonas Devlieghere   command_options.ignore_breakpoints = false;
552c5bfa3daSJonas Devlieghere   command_options.debug = false;
553c5bfa3daSJonas Devlieghere 
554c5bfa3daSJonas Devlieghere   EvaluateExpressionOptions expr_options;
555c5bfa3daSJonas Devlieghere   expr_options.SetUnwindOnError(command_options.unwind_on_error);
556c5bfa3daSJonas Devlieghere   expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints);
557c5bfa3daSJonas Devlieghere   expr_options.SetTryAllThreads(command_options.try_all_threads);
558c5bfa3daSJonas Devlieghere 
559c5bfa3daSJonas Devlieghere   if (command_options.timeout > 0)
560c5bfa3daSJonas Devlieghere     expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout));
561c5bfa3daSJonas Devlieghere   else
562c5bfa3daSJonas Devlieghere     expr_options.SetTimeout(llvm::None);
563c5bfa3daSJonas Devlieghere 
564c5bfa3daSJonas Devlieghere   return expr_options;
565c5bfa3daSJonas Devlieghere }
566c5bfa3daSJonas Devlieghere 
5674d51a902SRaphael Isemann bool CommandObjectExpression::DoExecute(llvm::StringRef command,
568b9c1b51eSKate Stone                                         CommandReturnObject &result) {
569e5ee6f04SJim Ingham   m_fixed_expression.clear();
570e1cfbc79STodd Fiala   auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
571e1cfbc79STodd Fiala   m_option_group.NotifyOptionParsingStarting(&exe_ctx);
572cf28a8b7SGreg Clayton 
5734d51a902SRaphael Isemann   if (command.empty()) {
574cf28a8b7SGreg Clayton     GetMultilineExpression();
57530fdc8d8SChris Lattner     return result.Succeeded();
57630fdc8d8SChris Lattner   }
57730fdc8d8SChris Lattner 
5783a0e1270SRaphael Isemann   OptionsWithRaw args(command);
5794d51a902SRaphael Isemann   llvm::StringRef expr = args.GetRawPart();
58030fdc8d8SChris Lattner 
5813a0e1270SRaphael Isemann   if (args.HasArgs()) {
5823a0e1270SRaphael Isemann     if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))
58330fdc8d8SChris Lattner       return false;
584f6b8b581SGreg Clayton 
585b9c1b51eSKate Stone     if (m_repl_option.GetOptionValue().GetCurrentValue()) {
5865a1bac4dSRaphael Isemann       Target &target = GetSelectedOrDummyTarget();
587f2bd5c3eSSean Callanan       // Drop into REPL
588f2bd5c3eSSean Callanan       m_expr_lines.clear();
589f2bd5c3eSSean Callanan       m_expr_line_count = 0;
590f2bd5c3eSSean Callanan 
5915a1bac4dSRaphael Isemann       Debugger &debugger = target.GetDebugger();
592f2bd5c3eSSean Callanan 
593b9c1b51eSKate Stone       // Check if the LLDB command interpreter is sitting on top of a REPL
59405097246SAdrian Prantl       // that launched it...
5953a0e1270SRaphael Isemann       if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,
5963a0e1270SRaphael Isemann                                           IOHandler::Type::REPL)) {
597b9c1b51eSKate Stone         // the LLDB command interpreter is sitting on top of a REPL that
59805097246SAdrian Prantl         // launched it, so just say the command interpreter is done and
59905097246SAdrian Prantl         // fall back to the existing REPL
600f2bd5c3eSSean Callanan         m_interpreter.GetIOHandler(false)->SetIsDone(true);
601b9c1b51eSKate Stone       } else {
602b9c1b51eSKate Stone         // We are launching the REPL on top of the current LLDB command
60305097246SAdrian Prantl         // interpreter, so just push one
604f2bd5c3eSSean Callanan         bool initialize = false;
60597206d57SZachary Turner         Status repl_error;
6065a1bac4dSRaphael Isemann         REPLSP repl_sp(target.GetREPL(repl_error, m_command_options.language,
6073a0e1270SRaphael Isemann                                        nullptr, false));
608f2bd5c3eSSean Callanan 
609b9c1b51eSKate Stone         if (!repl_sp) {
610f2bd5c3eSSean Callanan           initialize = true;
6115a1bac4dSRaphael Isemann           repl_sp = target.GetREPL(repl_error, m_command_options.language,
612b9c1b51eSKate Stone                                     nullptr, true);
613b9c1b51eSKate Stone           if (!repl_error.Success()) {
614f2bd5c3eSSean Callanan             result.SetError(repl_error);
615f2bd5c3eSSean Callanan             return result.Succeeded();
616f2bd5c3eSSean Callanan           }
617f2bd5c3eSSean Callanan         }
618f2bd5c3eSSean Callanan 
619b9c1b51eSKate Stone         if (repl_sp) {
620b9c1b51eSKate Stone           if (initialize) {
621c5bfa3daSJonas Devlieghere             repl_sp->SetEvaluateOptions(
622c5bfa3daSJonas Devlieghere                 GetExprOptions(exe_ctx, m_command_options));
623f2bd5c3eSSean Callanan             repl_sp->SetFormatOptions(m_format_options);
624f2bd5c3eSSean Callanan             repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
625f2bd5c3eSSean Callanan           }
626f2bd5c3eSSean Callanan 
627f2bd5c3eSSean Callanan           IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
628f2bd5c3eSSean Callanan           io_handler_sp->SetIsDone(false);
6297ce2de2cSJonas Devlieghere           debugger.RunIOHandlerAsync(io_handler_sp);
630b9c1b51eSKate Stone         } else {
631b9c1b51eSKate Stone           repl_error.SetErrorStringWithFormat(
632b9c1b51eSKate Stone               "Couldn't create a REPL for %s",
633b9c1b51eSKate Stone               Language::GetNameForLanguageType(m_command_options.language));
634f2bd5c3eSSean Callanan           result.SetError(repl_error);
635f2bd5c3eSSean Callanan           return result.Succeeded();
636f2bd5c3eSSean Callanan         }
637f2bd5c3eSSean Callanan       }
638f2bd5c3eSSean Callanan     }
639cf28a8b7SGreg Clayton     // No expression following options
6404d51a902SRaphael Isemann     else if (expr.empty()) {
641cf28a8b7SGreg Clayton       GetMultilineExpression();
642cf28a8b7SGreg Clayton       return result.Succeeded();
643cf28a8b7SGreg Clayton     }
64430fdc8d8SChris Lattner   }
64530fdc8d8SChris Lattner 
646cb2380c9SRaphael Isemann   Target &target = GetSelectedOrDummyTarget();
6477c6e52acSRaphael Isemann   if (EvaluateExpression(expr, result.GetOutputStream(),
6487c6e52acSRaphael Isemann                          result.GetErrorStream(), result)) {
64924fff242SDavide Italiano 
650cb2380c9SRaphael Isemann     if (!m_fixed_expression.empty() && target.GetEnableNotifyAboutFixIts()) {
651e5ee6f04SJim Ingham       CommandHistory &history = m_interpreter.GetCommandHistory();
652b9c1b51eSKate Stone       // FIXME: Can we figure out what the user actually typed (e.g. some alias
653b9c1b51eSKate Stone       // for expr???)
654e5ee6f04SJim Ingham       // If we can it would be nice to show that.
655e5ee6f04SJim Ingham       std::string fixed_command("expression ");
6563a0e1270SRaphael Isemann       if (args.HasArgs()) {
657e5ee6f04SJim Ingham         // Add in any options that might have been in the original command:
658adcd0268SBenjamin Kramer         fixed_command.append(std::string(args.GetArgStringWithDelimiter()));
659e5ee6f04SJim Ingham         fixed_command.append(m_fixed_expression);
6603a0e1270SRaphael Isemann       } else
6613a0e1270SRaphael Isemann         fixed_command.append(m_fixed_expression);
662e5ee6f04SJim Ingham       history.AppendString(fixed_command);
663e5ee6f04SJim Ingham     }
66405097246SAdrian Prantl     // Increment statistics to record this expression evaluation success.
665cb2380c9SRaphael Isemann     target.IncrementStats(StatisticKind::ExpressionSuccessful);
666fcd43b71SJohnny Chen     return true;
667e5ee6f04SJim Ingham   }
668fcd43b71SJohnny Chen 
66905097246SAdrian Prantl   // Increment statistics to record this expression evaluation failure.
670cb2380c9SRaphael Isemann   target.IncrementStats(StatisticKind::ExpressionFailure);
671fcd43b71SJohnny Chen   result.SetStatus(eReturnStatusFailed);
672fcd43b71SJohnny Chen   return false;
67330fdc8d8SChris Lattner }
674