xref: /llvm-project/lldb/source/Commands/CommandObjectExpression.cpp (revision ceff6644bba4d6c5e9c338afe92c453c7597609b)
1 //===-- CommandObjectExpression.cpp -----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/StringRef.h"
12 
13 #include "CommandObjectExpression.h"
14 #include "Plugins/ExpressionParser/Clang/ClangExpressionVariable.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Value.h"
17 #include "lldb/Core/ValueObjectVariable.h"
18 #include "lldb/DataFormatters/ValueObjectPrinter.h"
19 #include "lldb/Expression/DWARFExpression.h"
20 #include "lldb/Expression/REPL.h"
21 #include "lldb/Expression/UserExpression.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Host/OptionParser.h"
24 #include "lldb/Interpreter/CommandInterpreter.h"
25 #include "lldb/Interpreter/CommandReturnObject.h"
26 #include "lldb/Interpreter/OptionArgParser.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/Variable.h"
29 #include "lldb/Target/Language.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/StackFrame.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 CommandObjectExpression::CommandOptions::CommandOptions() : OptionGroup() {}
39 
40 CommandObjectExpression::CommandOptions::~CommandOptions() = default;
41 
42 static constexpr OptionEnumValueElement g_description_verbosity_type[] = {
43     {eLanguageRuntimeDescriptionDisplayVerbosityCompact, "compact",
44      "Only show the description string"},
45     {eLanguageRuntimeDescriptionDisplayVerbosityFull, "full",
46      "Show the full output, including persistent variable's name and type"} };
47 
48 static constexpr OptionEnumValues DescriptionVerbosityTypes() {
49   return OptionEnumValues(g_description_verbosity_type);
50 }
51 
52 static constexpr OptionDefinition g_expression_options[] = {
53     // clang-format off
54   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "all-threads",           'a', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeBoolean,              "Should we run all threads if the execution doesn't complete on one thread."},
55   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "ignore-breakpoints",    'i', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeBoolean,              "Ignore breakpoint hits while running expressions"},
56   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "timeout",               't', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeUnsignedInteger,      "Timeout value (in microseconds) for running the expression."},
57   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "unwind-on-error",       'u', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeBoolean,              "Clean up program state if the expression causes a crash, or raises a signal.  "
58                                                                                                                                                                                   "Note, unlike gdb hitting a breakpoint is controlled by another option (-i)."},
59   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "debug",                 'g', OptionParser::eNoArgument,       nullptr, {},                          0, eArgTypeNone,                 "When specified, debug the JIT code by setting a breakpoint on the first instruction "
60                                                                                                                                                                                   "and forcing breakpoints to not be ignored (-i0) and no unwinding to happen on error (-u0)."},
61   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "language",              'l', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeLanguage,             "Specifies the Language to use when parsing the expression.  If not set the target.language "
62                                                                                                                                                                                   "setting is used." },
63   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "apply-fixits",          'X', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeLanguage,             "If true, simple fix-it hints will be automatically applied to the expression." },
64   {LLDB_OPT_SET_1,                  false, "description-verbosity", 'v', OptionParser::eOptionalArgument, nullptr, DescriptionVerbosityTypes(), 0, eArgTypeDescriptionVerbosity, "How verbose should the output of this expression be, if the object description is asked for."},
65   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "top-level",             'p', OptionParser::eNoArgument,       nullptr, {},                          0, eArgTypeNone,                 "Interpret the expression as a complete translation unit, without injecting it into the local "
66                                                                                                                                                                                   "context.  Allows declaration of persistent, top-level entities without a $ prefix."},
67   {LLDB_OPT_SET_1 | LLDB_OPT_SET_2, false, "allow-jit",             'j', OptionParser::eRequiredArgument, nullptr, {},                          0, eArgTypeBoolean,              "Controls whether the expression can fall back to being JITted if it's not supported by "
68                                                                                                                                                                                   "the interpreter (defaults to true)."}
69     // clang-format on
70 };
71 
72 Status CommandObjectExpression::CommandOptions::SetOptionValue(
73     uint32_t option_idx, llvm::StringRef option_arg,
74     ExecutionContext *execution_context) {
75   Status error;
76 
77   const int short_option = GetDefinitions()[option_idx].short_option;
78 
79   switch (short_option) {
80   case 'l':
81     language = Language::GetLanguageTypeFromString(option_arg);
82     if (language == eLanguageTypeUnknown)
83       error.SetErrorStringWithFormat(
84           "unknown language type: '%s' for expression",
85           option_arg.str().c_str());
86     break;
87 
88   case 'a': {
89     bool success;
90     bool result;
91     result = OptionArgParser::ToBoolean(option_arg, true, &success);
92     if (!success)
93       error.SetErrorStringWithFormat(
94           "invalid all-threads value setting: \"%s\"",
95           option_arg.str().c_str());
96     else
97       try_all_threads = result;
98   } break;
99 
100   case 'i': {
101     bool success;
102     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
103     if (success)
104       ignore_breakpoints = tmp_value;
105     else
106       error.SetErrorStringWithFormat(
107           "could not convert \"%s\" to a boolean value.",
108           option_arg.str().c_str());
109     break;
110   }
111 
112   case 'j': {
113     bool success;
114     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
115     if (success)
116       allow_jit = tmp_value;
117     else
118       error.SetErrorStringWithFormat(
119           "could not convert \"%s\" to a boolean value.",
120           option_arg.str().c_str());
121     break;
122   }
123 
124   case 't':
125     if (option_arg.getAsInteger(0, timeout)) {
126       timeout = 0;
127       error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
128                                      option_arg.str().c_str());
129     }
130     break;
131 
132   case 'u': {
133     bool success;
134     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
135     if (success)
136       unwind_on_error = tmp_value;
137     else
138       error.SetErrorStringWithFormat(
139           "could not convert \"%s\" to a boolean value.",
140           option_arg.str().c_str());
141     break;
142   }
143 
144   case 'v':
145     if (option_arg.empty()) {
146       m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
147       break;
148     }
149     m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity)
150         OptionArgParser::ToOptionEnum(
151             option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
152     if (!error.Success())
153       error.SetErrorStringWithFormat(
154           "unrecognized value for description-verbosity '%s'",
155           option_arg.str().c_str());
156     break;
157 
158   case 'g':
159     debug = true;
160     unwind_on_error = false;
161     ignore_breakpoints = false;
162     break;
163 
164   case 'p':
165     top_level = true;
166     break;
167 
168   case 'X': {
169     bool success;
170     bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
171     if (success)
172       auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;
173     else
174       error.SetErrorStringWithFormat(
175           "could not convert \"%s\" to a boolean value.",
176           option_arg.str().c_str());
177     break;
178   }
179 
180   default:
181     error.SetErrorStringWithFormat("invalid short option character '%c'",
182                                    short_option);
183     break;
184   }
185 
186   return error;
187 }
188 
189 void CommandObjectExpression::CommandOptions::OptionParsingStarting(
190     ExecutionContext *execution_context) {
191   auto process_sp =
192       execution_context ? execution_context->GetProcessSP() : ProcessSP();
193   if (process_sp) {
194     ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();
195     unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();
196   } else {
197     ignore_breakpoints = true;
198     unwind_on_error = true;
199   }
200 
201   show_summary = true;
202   try_all_threads = true;
203   timeout = 0;
204   debug = false;
205   language = eLanguageTypeUnknown;
206   m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
207   auto_apply_fixits = eLazyBoolCalculate;
208   top_level = false;
209   allow_jit = true;
210 }
211 
212 llvm::ArrayRef<OptionDefinition>
213 CommandObjectExpression::CommandOptions::GetDefinitions() {
214   return llvm::makeArrayRef(g_expression_options);
215 }
216 
217 CommandObjectExpression::CommandObjectExpression(
218     CommandInterpreter &interpreter)
219     : CommandObjectRaw(
220           interpreter, "expression", "Evaluate an expression on the current "
221                                      "thread.  Displays any returned value "
222                                      "with LLDB's default formatting.",
223           "", eCommandProcessMustBePaused | eCommandTryTargetAPILock),
224       IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),
225       m_option_group(), m_format_options(eFormatDefault),
226       m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,
227                     true),
228       m_command_options(), m_expr_line_count(0), m_expr_lines() {
229   SetHelpLong(
230       R"(
231 Single and multi-line expressions:
232 
233 )"
234       "    The expression provided on the command line must be a complete expression \
235 with no newlines.  To evaluate a multi-line expression, \
236 hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
237 Hit return on an empty line to end the multi-line expression."
238 
239       R"(
240 
241 Timeouts:
242 
243 )"
244       "    If the expression can be evaluated statically (without running code) then it will be.  \
245 Otherwise, by default the expression will run on the current thread with a short timeout: \
246 currently .25 seconds.  If it doesn't return in that time, the evaluation will be interrupted \
247 and resumed with all threads running.  You can use the -a option to disable retrying on all \
248 threads.  You can use the -t option to set a shorter timeout."
249       R"(
250 
251 User defined variables:
252 
253 )"
254       "    You can define your own variables for convenience or to be used in subsequent expressions.  \
255 You define them the same way you would define variables in C.  If the first character of \
256 your user defined variable is a $, then the variable's value will be available in future \
257 expressions, otherwise it will just be available in the current expression."
258       R"(
259 
260 Continuing evaluation after a breakpoint:
261 
262 )"
263       "    If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
264 you are done with your investigation, you can either remove the expression execution frames \
265 from the stack with \"thread return -x\" or if you are still interested in the expression result \
266 you can issue the \"continue\" command and the expression evaluation will complete and the \
267 expression result will be available using the \"thread.completed-expression\" key in the thread \
268 format."
269 
270       R"(
271 
272 Examples:
273 
274     expr my_struct->a = my_array[3]
275     expr -f bin -- (index * 8) + 5
276     expr unsigned int $foo = 5
277     expr char c[] = \"foo\"; c[0])");
278 
279   CommandArgumentEntry arg;
280   CommandArgumentData expression_arg;
281 
282   // Define the first (and only) variant of this arg.
283   expression_arg.arg_type = eArgTypeExpression;
284   expression_arg.arg_repetition = eArgRepeatPlain;
285 
286   // There is only one variant this argument could be; put it into the argument
287   // entry.
288   arg.push_back(expression_arg);
289 
290   // Push the data for the first argument into the m_arguments vector.
291   m_arguments.push_back(arg);
292 
293   // Add the "--format" and "--gdb-format"
294   m_option_group.Append(&m_format_options,
295                         OptionGroupFormat::OPTION_GROUP_FORMAT |
296                             OptionGroupFormat::OPTION_GROUP_GDB_FMT,
297                         LLDB_OPT_SET_1);
298   m_option_group.Append(&m_command_options);
299   m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
300                         LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
301   m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
302   m_option_group.Finalize();
303 }
304 
305 CommandObjectExpression::~CommandObjectExpression() = default;
306 
307 Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
308 
309 int CommandObjectExpression::HandleCompletion(CompletionRequest &request) {
310   EvaluateExpressionOptions options;
311   options.SetCoerceToId(m_varobj_options.use_objc);
312   options.SetLanguage(m_command_options.language);
313   options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever);
314   options.SetAutoApplyFixIts(false);
315   options.SetGenerateDebugInfo(false);
316 
317   // We need a valid execution context with a frame pointer for this
318   // completion, so if we don't have one we should try to make a valid
319   // execution context.
320   if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr)
321     m_interpreter.UpdateExecutionContext(nullptr);
322 
323   // This didn't work, so let's get out before we start doing things that
324   // expect a valid frame pointer.
325   if (m_interpreter.GetExecutionContext().GetFramePtr() == nullptr)
326     return 0;
327 
328   ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
329 
330   Target *target = exe_ctx.GetTargetPtr();
331 
332   if (!target)
333     target = GetDummyTarget();
334 
335   if (!target)
336     return 0;
337 
338   unsigned cursor_pos = request.GetRawCursorPos();
339   llvm::StringRef code = request.GetRawLine();
340 
341   const std::size_t original_code_size = code.size();
342 
343   // Remove the first token which is 'expr' or some alias/abbreviation of that.
344   code = llvm::getToken(code).second.ltrim();
345   OptionsWithRaw args(code);
346   code = args.GetRawPart();
347 
348   // The position where the expression starts in the command line.
349   assert(original_code_size >= code.size());
350   std::size_t raw_start = original_code_size - code.size();
351 
352   // Check if the cursor is actually in the expression string, and if not, we
353   // exit.
354   // FIXME: We should complete the options here.
355   if (cursor_pos < raw_start)
356     return 0;
357 
358   // Make the cursor_pos again relative to the start of the code string.
359   assert(cursor_pos >= raw_start);
360   cursor_pos -= raw_start;
361 
362   auto language = exe_ctx.GetFrameRef().GetLanguage();
363 
364   Status error;
365   lldb::UserExpressionSP expr(target->GetUserExpressionForLanguage(
366       code, llvm::StringRef(), language, UserExpression::eResultTypeAny,
367       options, error));
368   if (error.Fail())
369     return 0;
370 
371   expr->Complete(exe_ctx, request, cursor_pos);
372   return request.GetNumberOfMatches();
373 }
374 
375 static lldb_private::Status
376 CanBeUsedForElementCountPrinting(ValueObject &valobj) {
377   CompilerType type(valobj.GetCompilerType());
378   CompilerType pointee;
379   if (!type.IsPointerType(&pointee))
380     return Status("as it does not refer to a pointer");
381   if (pointee.IsVoidType())
382     return Status("as it refers to a pointer to void");
383   return Status();
384 }
385 
386 bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
387                                                  Stream *output_stream,
388                                                  Stream *error_stream,
389                                                  CommandReturnObject *result) {
390   // Don't use m_exe_ctx as this might be called asynchronously after the
391   // command object DoExecute has finished when doing multi-line expression
392   // that use an input reader...
393   ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
394 
395   Target *target = exe_ctx.GetTargetPtr();
396 
397   if (!target)
398     target = GetDummyTarget();
399 
400   if (target) {
401     lldb::ValueObjectSP result_valobj_sp;
402     bool keep_in_memory = true;
403     StackFrame *frame = exe_ctx.GetFramePtr();
404 
405     EvaluateExpressionOptions options;
406     options.SetCoerceToId(m_varobj_options.use_objc);
407     options.SetUnwindOnError(m_command_options.unwind_on_error);
408     options.SetIgnoreBreakpoints(m_command_options.ignore_breakpoints);
409     options.SetKeepInMemory(keep_in_memory);
410     options.SetUseDynamic(m_varobj_options.use_dynamic);
411     options.SetTryAllThreads(m_command_options.try_all_threads);
412     options.SetDebug(m_command_options.debug);
413     options.SetLanguage(m_command_options.language);
414     options.SetExecutionPolicy(
415         m_command_options.allow_jit
416             ? EvaluateExpressionOptions::default_execution_policy
417             : lldb_private::eExecutionPolicyNever);
418 
419     bool auto_apply_fixits;
420     if (m_command_options.auto_apply_fixits == eLazyBoolCalculate)
421       auto_apply_fixits = target->GetEnableAutoApplyFixIts();
422     else
423       auto_apply_fixits =
424           m_command_options.auto_apply_fixits == eLazyBoolYes ? true : false;
425 
426     options.SetAutoApplyFixIts(auto_apply_fixits);
427 
428     if (m_command_options.top_level)
429       options.SetExecutionPolicy(eExecutionPolicyTopLevel);
430 
431     // If there is any chance we are going to stop and want to see what went
432     // wrong with our expression, we should generate debug info
433     if (!m_command_options.ignore_breakpoints ||
434         !m_command_options.unwind_on_error)
435       options.SetGenerateDebugInfo(true);
436 
437     if (m_command_options.timeout > 0)
438       options.SetTimeout(std::chrono::microseconds(m_command_options.timeout));
439     else
440       options.SetTimeout(llvm::None);
441 
442     ExpressionResults success = target->EvaluateExpression(
443         expr, frame, result_valobj_sp, options, &m_fixed_expression);
444 
445     // We only tell you about the FixIt if we applied it.  The compiler errors
446     // will suggest the FixIt if it parsed.
447     if (error_stream && !m_fixed_expression.empty() &&
448         target->GetEnableNotifyAboutFixIts()) {
449       if (success == eExpressionCompleted)
450         error_stream->Printf(
451             "  Fix-it applied, fixed expression was: \n    %s\n",
452             m_fixed_expression.c_str());
453     }
454 
455     if (result_valobj_sp) {
456       Format format = m_format_options.GetFormat();
457 
458       if (result_valobj_sp->GetError().Success()) {
459         if (format != eFormatVoid) {
460           if (format != eFormatDefault)
461             result_valobj_sp->SetFormat(format);
462 
463           if (m_varobj_options.elem_count > 0) {
464             Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
465             if (error.Fail()) {
466               result->AppendErrorWithFormat(
467                   "expression cannot be used with --element-count %s\n",
468                   error.AsCString(""));
469               result->SetStatus(eReturnStatusFailed);
470               return false;
471             }
472           }
473 
474           DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
475               m_command_options.m_verbosity, format));
476           options.SetVariableFormatDisplayLanguage(
477               result_valobj_sp->GetPreferredDisplayLanguage());
478 
479           result_valobj_sp->Dump(*output_stream, options);
480 
481           if (result)
482             result->SetStatus(eReturnStatusSuccessFinishResult);
483         }
484       } else {
485         if (result_valobj_sp->GetError().GetError() ==
486             UserExpression::kNoResult) {
487           if (format != eFormatVoid &&
488               m_interpreter.GetDebugger().GetNotifyVoid()) {
489             error_stream->PutCString("(void)\n");
490           }
491 
492           if (result)
493             result->SetStatus(eReturnStatusSuccessFinishResult);
494         } else {
495           const char *error_cstr = result_valobj_sp->GetError().AsCString();
496           if (error_cstr && error_cstr[0]) {
497             const size_t error_cstr_len = strlen(error_cstr);
498             const bool ends_with_newline =
499                 error_cstr[error_cstr_len - 1] == '\n';
500             if (strstr(error_cstr, "error:") != error_cstr)
501               error_stream->PutCString("error: ");
502             error_stream->Write(error_cstr, error_cstr_len);
503             if (!ends_with_newline)
504               error_stream->EOL();
505           } else {
506             error_stream->PutCString("error: unknown error\n");
507           }
508 
509           if (result)
510             result->SetStatus(eReturnStatusFailed);
511         }
512       }
513     }
514   } else {
515     error_stream->Printf("error: invalid execution context for expression\n");
516     return false;
517   }
518 
519   return true;
520 }
521 
522 void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
523                                                      std::string &line) {
524   io_handler.SetIsDone(true);
525   //    StreamSP output_stream =
526   //    io_handler.GetDebugger().GetAsyncOutputStream();
527   //    StreamSP error_stream = io_handler.GetDebugger().GetAsyncErrorStream();
528   StreamFileSP output_sp(io_handler.GetOutputStreamFile());
529   StreamFileSP error_sp(io_handler.GetErrorStreamFile());
530 
531   EvaluateExpression(line.c_str(), output_sp.get(), error_sp.get());
532   if (output_sp)
533     output_sp->Flush();
534   if (error_sp)
535     error_sp->Flush();
536 }
537 
538 bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
539                                                        StringList &lines) {
540   // An empty lines is used to indicate the end of input
541   const size_t num_lines = lines.GetSize();
542   if (num_lines > 0 && lines[num_lines - 1].empty()) {
543     // Remove the last empty line from "lines" so it doesn't appear in our
544     // resulting input and return true to indicate we are done getting lines
545     lines.PopBack();
546     return true;
547   }
548   return false;
549 }
550 
551 void CommandObjectExpression::GetMultilineExpression() {
552   m_expr_lines.clear();
553   m_expr_line_count = 0;
554 
555   Debugger &debugger = GetCommandInterpreter().GetDebugger();
556   bool color_prompt = debugger.GetUseColor();
557   const bool multiple_lines = true; // Get multiple lines
558   IOHandlerSP io_handler_sp(
559       new IOHandlerEditline(debugger, IOHandler::Type::Expression,
560                             "lldb-expr", // Name of input reader for history
561                             llvm::StringRef(), // No prompt
562                             llvm::StringRef(), // Continuation prompt
563                             multiple_lines, color_prompt,
564                             1, // Show line numbers starting at 1
565                             *this));
566 
567   StreamFileSP output_sp(io_handler_sp->GetOutputStreamFile());
568   if (output_sp) {
569     output_sp->PutCString(
570         "Enter expressions, then terminate with an empty line to evaluate:\n");
571     output_sp->Flush();
572   }
573   debugger.PushIOHandler(io_handler_sp);
574 }
575 
576 bool CommandObjectExpression::DoExecute(llvm::StringRef command,
577                                         CommandReturnObject &result) {
578   m_fixed_expression.clear();
579   auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
580   m_option_group.NotifyOptionParsingStarting(&exe_ctx);
581 
582   if (command.empty()) {
583     GetMultilineExpression();
584     return result.Succeeded();
585   }
586 
587   OptionsWithRaw args(command);
588   llvm::StringRef expr = args.GetRawPart();
589 
590   if (args.HasArgs()) {
591     if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))
592       return false;
593 
594     if (m_repl_option.GetOptionValue().GetCurrentValue()) {
595       Target *target = m_interpreter.GetExecutionContext().GetTargetPtr();
596       if (target) {
597         // Drop into REPL
598         m_expr_lines.clear();
599         m_expr_line_count = 0;
600 
601         Debugger &debugger = target->GetDebugger();
602 
603         // Check if the LLDB command interpreter is sitting on top of a REPL
604         // that launched it...
605         if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,
606                                             IOHandler::Type::REPL)) {
607           // the LLDB command interpreter is sitting on top of a REPL that
608           // launched it, so just say the command interpreter is done and
609           // fall back to the existing REPL
610           m_interpreter.GetIOHandler(false)->SetIsDone(true);
611         } else {
612           // We are launching the REPL on top of the current LLDB command
613           // interpreter, so just push one
614           bool initialize = false;
615           Status repl_error;
616           REPLSP repl_sp(target->GetREPL(repl_error, m_command_options.language,
617                                          nullptr, false));
618 
619           if (!repl_sp) {
620             initialize = true;
621             repl_sp = target->GetREPL(repl_error, m_command_options.language,
622                                       nullptr, true);
623             if (!repl_error.Success()) {
624               result.SetError(repl_error);
625               return result.Succeeded();
626             }
627           }
628 
629           if (repl_sp) {
630             if (initialize) {
631               repl_sp->SetCommandOptions(m_command_options);
632               repl_sp->SetFormatOptions(m_format_options);
633               repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
634             }
635 
636             IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
637 
638             io_handler_sp->SetIsDone(false);
639 
640             debugger.PushIOHandler(io_handler_sp);
641           } else {
642             repl_error.SetErrorStringWithFormat(
643                 "Couldn't create a REPL for %s",
644                 Language::GetNameForLanguageType(m_command_options.language));
645             result.SetError(repl_error);
646             return result.Succeeded();
647           }
648         }
649       }
650     }
651     // No expression following options
652     else if (expr.empty()) {
653       GetMultilineExpression();
654       return result.Succeeded();
655     }
656   }
657 
658   Target *target = GetSelectedOrDummyTarget();
659   if (EvaluateExpression(expr, &(result.GetOutputStream()),
660                          &(result.GetErrorStream()), &result)) {
661 
662     if (!m_fixed_expression.empty() && target->GetEnableNotifyAboutFixIts()) {
663       CommandHistory &history = m_interpreter.GetCommandHistory();
664       // FIXME: Can we figure out what the user actually typed (e.g. some alias
665       // for expr???)
666       // If we can it would be nice to show that.
667       std::string fixed_command("expression ");
668       if (args.HasArgs()) {
669         // Add in any options that might have been in the original command:
670         fixed_command.append(args.GetArgStringWithDelimiter());
671         fixed_command.append(m_fixed_expression);
672       } else
673         fixed_command.append(m_fixed_expression);
674       history.AppendString(fixed_command);
675     }
676     // Increment statistics to record this expression evaluation success.
677     target->IncrementStats(StatisticKind::ExpressionSuccessful);
678     return true;
679   }
680 
681   // Increment statistics to record this expression evaluation failure.
682   target->IncrementStats(StatisticKind::ExpressionFailure);
683   result.SetStatus(eReturnStatusFailed);
684   return false;
685 }
686