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