1 //===-- ClangUserExpression.cpp ---------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <stdio.h>
10 #if HAVE_SYS_TYPES_H
11 #include <sys/types.h>
12 #endif
13 
14 #include <cstdlib>
15 #include <map>
16 #include <string>
17 
18 #include "ClangUserExpression.h"
19 
20 #include "ASTResultSynthesizer.h"
21 #include "ClangDiagnostic.h"
22 #include "ClangExpressionDeclMap.h"
23 #include "ClangExpressionParser.h"
24 #include "ClangExpressionSourceCode.h"
25 #include "ClangModulesDeclVendor.h"
26 #include "ClangPersistentVariables.h"
27 
28 #include "lldb/Core/Debugger.h"
29 #include "lldb/Core/Module.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Core/ValueObjectConstResult.h"
32 #include "lldb/Expression/ExpressionSourceCode.h"
33 #include "lldb/Expression/IRExecutionUnit.h"
34 #include "lldb/Expression/IRInterpreter.h"
35 #include "lldb/Expression/Materializer.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Symbol/Block.h"
38 #include "lldb/Symbol/ClangASTContext.h"
39 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
40 #include "lldb/Symbol/Function.h"
41 #include "lldb/Symbol/ObjectFile.h"
42 #include "lldb/Symbol/SymbolVendor.h"
43 #include "lldb/Symbol/Type.h"
44 #include "lldb/Symbol/VariableList.h"
45 #include "lldb/Target/ExecutionContext.h"
46 #include "lldb/Target/Process.h"
47 #include "lldb/Target/StackFrame.h"
48 #include "lldb/Target/Target.h"
49 #include "lldb/Target/ThreadPlan.h"
50 #include "lldb/Target/ThreadPlanCallUserExpression.h"
51 #include "lldb/Utility/ConstString.h"
52 #include "lldb/Utility/Log.h"
53 #include "lldb/Utility/StreamString.h"
54 
55 #include "clang/AST/DeclCXX.h"
56 #include "clang/AST/DeclObjC.h"
57 
58 using namespace lldb_private;
59 
60 ClangUserExpression::ClangUserExpression(
61     ExecutionContextScope &exe_scope, llvm::StringRef expr,
62     llvm::StringRef prefix, lldb::LanguageType language,
63     ResultType desired_type, const EvaluateExpressionOptions &options,
64     ValueObject *ctx_obj)
65     : LLVMUserExpression(exe_scope, expr, prefix, language, desired_type,
66                          options),
67       m_type_system_helper(*m_target_wp.lock(), options.GetExecutionPolicy() ==
68                                                     eExecutionPolicyTopLevel),
69       m_result_delegate(exe_scope.CalculateTarget()), m_ctx_obj(ctx_obj) {
70   switch (m_language) {
71   case lldb::eLanguageTypeC_plus_plus:
72     m_allow_cxx = true;
73     break;
74   case lldb::eLanguageTypeObjC:
75     m_allow_objc = true;
76     break;
77   case lldb::eLanguageTypeObjC_plus_plus:
78   default:
79     m_allow_cxx = true;
80     m_allow_objc = true;
81     break;
82   }
83 }
84 
85 ClangUserExpression::~ClangUserExpression() {}
86 
87 void ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Status &err) {
88   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
89 
90   if (log)
91     log->Printf("ClangUserExpression::ScanContext()");
92 
93   m_target = exe_ctx.GetTargetPtr();
94 
95   if (!(m_allow_cxx || m_allow_objc)) {
96     if (log)
97       log->Printf("  [CUE::SC] Settings inhibit C++ and Objective-C");
98     return;
99   }
100 
101   StackFrame *frame = exe_ctx.GetFramePtr();
102   if (frame == NULL) {
103     if (log)
104       log->Printf("  [CUE::SC] Null stack frame");
105     return;
106   }
107 
108   SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
109                                                   lldb::eSymbolContextBlock);
110 
111   if (!sym_ctx.function) {
112     if (log)
113       log->Printf("  [CUE::SC] Null function");
114     return;
115   }
116 
117   // Find the block that defines the function represented by "sym_ctx"
118   Block *function_block = sym_ctx.GetFunctionBlock();
119 
120   if (!function_block) {
121     if (log)
122       log->Printf("  [CUE::SC] Null function block");
123     return;
124   }
125 
126   CompilerDeclContext decl_context = function_block->GetDeclContext();
127 
128   if (!decl_context) {
129     if (log)
130       log->Printf("  [CUE::SC] Null decl context");
131     return;
132   }
133 
134   if (m_ctx_obj) {
135     switch (m_ctx_obj->GetObjectRuntimeLanguage()) {
136     case lldb::eLanguageTypeC:
137     case lldb::eLanguageTypeC89:
138     case lldb::eLanguageTypeC99:
139     case lldb::eLanguageTypeC11:
140     case lldb::eLanguageTypeC_plus_plus:
141     case lldb::eLanguageTypeC_plus_plus_03:
142     case lldb::eLanguageTypeC_plus_plus_11:
143     case lldb::eLanguageTypeC_plus_plus_14:
144       m_in_cplusplus_method = true;
145       break;
146     case lldb::eLanguageTypeObjC:
147     case lldb::eLanguageTypeObjC_plus_plus:
148       m_in_objectivec_method = true;
149       break;
150     default:
151       break;
152     }
153     m_needs_object_ptr = true;
154   } else if (clang::CXXMethodDecl *method_decl =
155           ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context)) {
156     if (m_allow_cxx && method_decl->isInstance()) {
157       if (m_enforce_valid_object) {
158         lldb::VariableListSP variable_list_sp(
159             function_block->GetBlockVariableList(true));
160 
161         const char *thisErrorString = "Stopped in a C++ method, but 'this' "
162                                       "isn't available; pretending we are in a "
163                                       "generic context";
164 
165         if (!variable_list_sp) {
166           err.SetErrorString(thisErrorString);
167           return;
168         }
169 
170         lldb::VariableSP this_var_sp(
171             variable_list_sp->FindVariable(ConstString("this")));
172 
173         if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
174             !this_var_sp->LocationIsValidForFrame(frame)) {
175           err.SetErrorString(thisErrorString);
176           return;
177         }
178       }
179 
180       m_in_cplusplus_method = true;
181       m_needs_object_ptr = true;
182     }
183   } else if (clang::ObjCMethodDecl *method_decl =
184                  ClangASTContext::DeclContextGetAsObjCMethodDecl(
185                      decl_context)) {
186     if (m_allow_objc) {
187       if (m_enforce_valid_object) {
188         lldb::VariableListSP variable_list_sp(
189             function_block->GetBlockVariableList(true));
190 
191         const char *selfErrorString = "Stopped in an Objective-C method, but "
192                                       "'self' isn't available; pretending we "
193                                       "are in a generic context";
194 
195         if (!variable_list_sp) {
196           err.SetErrorString(selfErrorString);
197           return;
198         }
199 
200         lldb::VariableSP self_variable_sp =
201             variable_list_sp->FindVariable(ConstString("self"));
202 
203         if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
204             !self_variable_sp->LocationIsValidForFrame(frame)) {
205           err.SetErrorString(selfErrorString);
206           return;
207         }
208       }
209 
210       m_in_objectivec_method = true;
211       m_needs_object_ptr = true;
212 
213       if (!method_decl->isInstanceMethod())
214         m_in_static_method = true;
215     }
216   } else if (clang::FunctionDecl *function_decl =
217                  ClangASTContext::DeclContextGetAsFunctionDecl(decl_context)) {
218     // We might also have a function that said in the debug information that it
219     // captured an object pointer.  The best way to deal with getting to the
220     // ivars at present is by pretending that this is a method of a class in
221     // whatever runtime the debug info says the object pointer belongs to.  Do
222     // that here.
223 
224     ClangASTMetadata *metadata =
225         ClangASTContext::DeclContextGetMetaData(decl_context, function_decl);
226     if (metadata && metadata->HasObjectPtr()) {
227       lldb::LanguageType language = metadata->GetObjectPtrLanguage();
228       if (language == lldb::eLanguageTypeC_plus_plus) {
229         if (m_enforce_valid_object) {
230           lldb::VariableListSP variable_list_sp(
231               function_block->GetBlockVariableList(true));
232 
233           const char *thisErrorString = "Stopped in a context claiming to "
234                                         "capture a C++ object pointer, but "
235                                         "'this' isn't available; pretending we "
236                                         "are in a generic context";
237 
238           if (!variable_list_sp) {
239             err.SetErrorString(thisErrorString);
240             return;
241           }
242 
243           lldb::VariableSP this_var_sp(
244               variable_list_sp->FindVariable(ConstString("this")));
245 
246           if (!this_var_sp || !this_var_sp->IsInScope(frame) ||
247               !this_var_sp->LocationIsValidForFrame(frame)) {
248             err.SetErrorString(thisErrorString);
249             return;
250           }
251         }
252 
253         m_in_cplusplus_method = true;
254         m_needs_object_ptr = true;
255       } else if (language == lldb::eLanguageTypeObjC) {
256         if (m_enforce_valid_object) {
257           lldb::VariableListSP variable_list_sp(
258               function_block->GetBlockVariableList(true));
259 
260           const char *selfErrorString =
261               "Stopped in a context claiming to capture an Objective-C object "
262               "pointer, but 'self' isn't available; pretending we are in a "
263               "generic context";
264 
265           if (!variable_list_sp) {
266             err.SetErrorString(selfErrorString);
267             return;
268           }
269 
270           lldb::VariableSP self_variable_sp =
271               variable_list_sp->FindVariable(ConstString("self"));
272 
273           if (!self_variable_sp || !self_variable_sp->IsInScope(frame) ||
274               !self_variable_sp->LocationIsValidForFrame(frame)) {
275             err.SetErrorString(selfErrorString);
276             return;
277           }
278 
279           Type *self_type = self_variable_sp->GetType();
280 
281           if (!self_type) {
282             err.SetErrorString(selfErrorString);
283             return;
284           }
285 
286           CompilerType self_clang_type = self_type->GetForwardCompilerType();
287 
288           if (!self_clang_type) {
289             err.SetErrorString(selfErrorString);
290             return;
291           }
292 
293           if (ClangASTContext::IsObjCClassType(self_clang_type)) {
294             return;
295           } else if (ClangASTContext::IsObjCObjectPointerType(
296                          self_clang_type)) {
297             m_in_objectivec_method = true;
298             m_needs_object_ptr = true;
299           } else {
300             err.SetErrorString(selfErrorString);
301             return;
302           }
303         } else {
304           m_in_objectivec_method = true;
305           m_needs_object_ptr = true;
306         }
307       }
308     }
309   }
310 }
311 
312 // This is a really nasty hack, meant to fix Objective-C expressions of the
313 // form (int)[myArray count].  Right now, because the type information for
314 // count is not available, [myArray count] returns id, which can't be directly
315 // cast to int without causing a clang error.
316 static void ApplyObjcCastHack(std::string &expr) {
317 #define OBJC_CAST_HACK_FROM "(int)["
318 #define OBJC_CAST_HACK_TO "(int)(long long)["
319 
320   size_t from_offset;
321 
322   while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
323     expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1,
324                  OBJC_CAST_HACK_TO);
325 
326 #undef OBJC_CAST_HACK_TO
327 #undef OBJC_CAST_HACK_FROM
328 }
329 
330 namespace {
331 // Utility guard that calls a callback when going out of scope.
332 class OnExit {
333 public:
334   typedef std::function<void(void)> Callback;
335 
336   OnExit(Callback const &callback) : m_callback(callback) {}
337 
338   ~OnExit() { m_callback(); }
339 
340 private:
341   Callback m_callback;
342 };
343 } // namespace
344 
345 bool ClangUserExpression::SetupPersistentState(DiagnosticManager &diagnostic_manager,
346                                  ExecutionContext &exe_ctx) {
347   if (Target *target = exe_ctx.GetTargetPtr()) {
348     if (PersistentExpressionState *persistent_state =
349             target->GetPersistentExpressionStateForLanguage(
350                 lldb::eLanguageTypeC)) {
351       m_result_delegate.RegisterPersistentState(persistent_state);
352     } else {
353       diagnostic_manager.PutString(
354           eDiagnosticSeverityError,
355           "couldn't start parsing (no persistent data)");
356       return false;
357     }
358   } else {
359     diagnostic_manager.PutString(eDiagnosticSeverityError,
360                                  "error: couldn't start parsing (no target)");
361     return false;
362   }
363   return true;
364 }
365 
366 static void SetupDeclVendor(ExecutionContext &exe_ctx, Target *target) {
367   if (ClangModulesDeclVendor *decl_vendor =
368           target->GetClangModulesDeclVendor()) {
369     const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
370         llvm::cast<ClangPersistentVariables>(
371             target->GetPersistentExpressionStateForLanguage(
372                 lldb::eLanguageTypeC))
373             ->GetHandLoadedClangModules();
374     ClangModulesDeclVendor::ModuleVector modules_for_macros;
375 
376     for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
377       modules_for_macros.push_back(module);
378     }
379 
380     if (target->GetEnableAutoImportClangModules()) {
381       if (StackFrame *frame = exe_ctx.GetFramePtr()) {
382         if (Block *block = frame->GetFrameBlock()) {
383           SymbolContext sc;
384 
385           block->CalculateSymbolContext(&sc);
386 
387           if (sc.comp_unit) {
388             StreamString error_stream;
389 
390             decl_vendor->AddModulesForCompileUnit(
391                 *sc.comp_unit, modules_for_macros, error_stream);
392           }
393         }
394       }
395     }
396   }
397 }
398 
399 void ClangUserExpression::UpdateLanguageForExpr(
400     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
401   m_expr_lang = lldb::LanguageType::eLanguageTypeUnknown;
402 
403   std::string prefix = m_expr_prefix;
404 
405   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
406     m_transformed_text = m_expr_text;
407   } else {
408     std::unique_ptr<ClangExpressionSourceCode> source_code(
409         ClangExpressionSourceCode::CreateWrapped(prefix.c_str(),
410                                             m_expr_text.c_str()));
411 
412     if (m_in_cplusplus_method)
413       m_expr_lang = lldb::eLanguageTypeC_plus_plus;
414     else if (m_in_objectivec_method)
415       m_expr_lang = lldb::eLanguageTypeObjC;
416     else
417       m_expr_lang = lldb::eLanguageTypeC;
418 
419     if (!source_code->GetText(m_transformed_text, m_expr_lang,
420                               m_in_static_method, exe_ctx,
421                               !m_ctx_obj)) {
422       diagnostic_manager.PutString(eDiagnosticSeverityError,
423                                    "couldn't construct expression body");
424       return;
425     }
426 
427     // Find and store the start position of the original code inside the
428     // transformed code. We need this later for the code completion.
429     std::size_t original_start;
430     std::size_t original_end;
431     bool found_bounds = source_code->GetOriginalBodyBounds(
432         m_transformed_text, m_expr_lang, original_start, original_end);
433     if (found_bounds) {
434       m_user_expression_start_pos = original_start;
435     }
436   }
437 }
438 
439 bool ClangUserExpression::PrepareForParsing(
440     DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) {
441   InstallContext(exe_ctx);
442 
443   if (!SetupPersistentState(diagnostic_manager, exe_ctx))
444     return false;
445 
446   Status err;
447   ScanContext(exe_ctx, err);
448 
449   if (!err.Success()) {
450     diagnostic_manager.PutString(eDiagnosticSeverityWarning, err.AsCString());
451   }
452 
453   ////////////////////////////////////
454   // Generate the expression
455   //
456 
457   ApplyObjcCastHack(m_expr_text);
458 
459   SetupDeclVendor(exe_ctx, m_target);
460 
461   UpdateLanguageForExpr(diagnostic_manager, exe_ctx);
462   return true;
463 }
464 
465 bool ClangUserExpression::Parse(DiagnosticManager &diagnostic_manager,
466                                 ExecutionContext &exe_ctx,
467                                 lldb_private::ExecutionPolicy execution_policy,
468                                 bool keep_result_in_memory,
469                                 bool generate_debug_info) {
470   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
471 
472   if (!PrepareForParsing(diagnostic_manager, exe_ctx))
473     return false;
474 
475   if (log)
476     log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
477 
478   ////////////////////////////////////
479   // Set up the target and compiler
480   //
481 
482   Target *target = exe_ctx.GetTargetPtr();
483 
484   if (!target) {
485     diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
486     return false;
487   }
488 
489   //////////////////////////
490   // Parse the expression
491   //
492 
493   m_materializer_up.reset(new Materializer());
494 
495   ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
496 
497   OnExit on_exit([this]() { ResetDeclMap(); });
498 
499   if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) {
500     diagnostic_manager.PutString(
501         eDiagnosticSeverityError,
502         "current process state is unsuitable for expression parsing");
503     return false;
504   }
505 
506   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
507     DeclMap()->SetLookupsEnabled(true);
508   }
509 
510   Process *process = exe_ctx.GetProcessPtr();
511   ExecutionContextScope *exe_scope = process;
512 
513   if (!exe_scope)
514     exe_scope = exe_ctx.GetTargetPtr();
515 
516   // We use a shared pointer here so we can use the original parser - if it
517   // succeeds or the rewrite parser we might make if it fails.  But the
518   // parser_sp will never be empty.
519 
520   ClangExpressionParser parser(exe_scope, *this, generate_debug_info);
521 
522   unsigned num_errors = parser.Parse(diagnostic_manager);
523 
524   // Check here for FixItHints.  If there are any try to apply the fixits and
525   // set the fixed text in m_fixed_text before returning an error.
526   if (num_errors) {
527     if (diagnostic_manager.HasFixIts()) {
528       if (parser.RewriteExpression(diagnostic_manager)) {
529         size_t fixed_start;
530         size_t fixed_end;
531         const std::string &fixed_expression =
532             diagnostic_manager.GetFixedExpression();
533         if (ClangExpressionSourceCode::GetOriginalBodyBounds(
534                 fixed_expression, m_expr_lang, fixed_start, fixed_end))
535           m_fixed_text =
536               fixed_expression.substr(fixed_start, fixed_end - fixed_start);
537       }
538     }
539     return false;
540   }
541 
542   //////////////////////////////////////////////////////////////////////////////////////////
543   // Prepare the output of the parser for execution, evaluating it statically
544   // if possible
545   //
546 
547   {
548     Status jit_error = parser.PrepareForExecution(
549         m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
550         m_can_interpret, execution_policy);
551 
552     if (!jit_error.Success()) {
553       const char *error_cstr = jit_error.AsCString();
554       if (error_cstr && error_cstr[0])
555         diagnostic_manager.PutString(eDiagnosticSeverityError, error_cstr);
556       else
557         diagnostic_manager.PutString(eDiagnosticSeverityError,
558                                      "expression can't be interpreted or run");
559       return false;
560     }
561   }
562 
563   if (exe_ctx.GetProcessPtr() && execution_policy == eExecutionPolicyTopLevel) {
564     Status static_init_error =
565         parser.RunStaticInitializers(m_execution_unit_sp, exe_ctx);
566 
567     if (!static_init_error.Success()) {
568       const char *error_cstr = static_init_error.AsCString();
569       if (error_cstr && error_cstr[0])
570         diagnostic_manager.Printf(eDiagnosticSeverityError,
571                                   "couldn't run static initializers: %s\n",
572                                   error_cstr);
573       else
574         diagnostic_manager.PutString(eDiagnosticSeverityError,
575                                      "couldn't run static initializers\n");
576       return false;
577     }
578   }
579 
580   if (m_execution_unit_sp) {
581     bool register_execution_unit = false;
582 
583     if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
584       register_execution_unit = true;
585     }
586 
587     // If there is more than one external function in the execution unit, it
588     // needs to keep living even if it's not top level, because the result
589     // could refer to that function.
590 
591     if (m_execution_unit_sp->GetJittedFunctions().size() > 1) {
592       register_execution_unit = true;
593     }
594 
595     if (register_execution_unit) {
596       llvm::cast<PersistentExpressionState>(
597           exe_ctx.GetTargetPtr()->GetPersistentExpressionStateForLanguage(
598               m_language))
599           ->RegisterExecutionUnit(m_execution_unit_sp);
600     }
601   }
602 
603   if (generate_debug_info) {
604     lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
605 
606     if (jit_module_sp) {
607       ConstString const_func_name(FunctionName());
608       FileSpec jit_file;
609       jit_file.GetFilename() = const_func_name;
610       jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
611       m_jit_module_wp = jit_module_sp;
612       target->GetImages().Append(jit_module_sp);
613     }
614   }
615 
616   if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
617     m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
618   return true;
619 }
620 
621 //------------------------------------------------------------------
622 /// Converts an absolute position inside a given code string into
623 /// a column/line pair.
624 ///
625 /// \param[in] abs_pos
626 ///     A absolute position in the code string that we want to convert
627 ///     to a column/line pair.
628 ///
629 /// \param[in] code
630 ///     A multi-line string usually representing source code.
631 ///
632 /// \param[out] line
633 ///     The line in the code that contains the given absolute position.
634 ///     The first line in the string is indexed as 1.
635 ///
636 /// \param[out] column
637 ///     The column in the line that contains the absolute position.
638 ///     The first character in a line is indexed as 0.
639 //------------------------------------------------------------------
640 static void AbsPosToLineColumnPos(size_t abs_pos, llvm::StringRef code,
641                                   unsigned &line, unsigned &column) {
642   // Reset to code position to beginning of the file.
643   line = 0;
644   column = 0;
645 
646   assert(abs_pos <= code.size() && "Absolute position outside code string?");
647 
648   // We have to walk up to the position and count lines/columns.
649   for (std::size_t i = 0; i < abs_pos; ++i) {
650     // If we hit a line break, we go back to column 0 and enter a new line.
651     // We only handle \n because that's what we internally use to make new
652     // lines for our temporary code strings.
653     if (code[i] == '\n') {
654       ++line;
655       column = 0;
656       continue;
657     }
658     ++column;
659   }
660 }
661 
662 bool ClangUserExpression::Complete(ExecutionContext &exe_ctx,
663                                    CompletionRequest &request,
664                                    unsigned complete_pos) {
665   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
666 
667   // We don't want any visible feedback when completing an expression. Mostly
668   // because the results we get from an incomplete invocation are probably not
669   // correct.
670   DiagnosticManager diagnostic_manager;
671 
672   if (!PrepareForParsing(diagnostic_manager, exe_ctx))
673     return false;
674 
675   if (log)
676     log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
677 
678   //////////////////////////
679   // Parse the expression
680   //
681 
682   m_materializer_up.reset(new Materializer());
683 
684   ResetDeclMap(exe_ctx, m_result_delegate, /*keep result in memory*/ true);
685 
686   OnExit on_exit([this]() { ResetDeclMap(); });
687 
688   if (!DeclMap()->WillParse(exe_ctx, m_materializer_up.get())) {
689     diagnostic_manager.PutString(
690         eDiagnosticSeverityError,
691         "current process state is unsuitable for expression parsing");
692 
693     return false;
694   }
695 
696   if (m_options.GetExecutionPolicy() == eExecutionPolicyTopLevel) {
697     DeclMap()->SetLookupsEnabled(true);
698   }
699 
700   Process *process = exe_ctx.GetProcessPtr();
701   ExecutionContextScope *exe_scope = process;
702 
703   if (!exe_scope)
704     exe_scope = exe_ctx.GetTargetPtr();
705 
706   ClangExpressionParser parser(exe_scope, *this, false);
707 
708   // We have to find the source code location where the user text is inside
709   // the transformed expression code. When creating the transformed text, we
710   // already stored the absolute position in the m_transformed_text string. The
711   // only thing left to do is to transform it into the line:column format that
712   // Clang expects.
713 
714   // The line and column of the user expression inside the transformed source
715   // code.
716   unsigned user_expr_line, user_expr_column;
717   if (m_user_expression_start_pos.hasValue())
718     AbsPosToLineColumnPos(*m_user_expression_start_pos, m_transformed_text,
719                           user_expr_line, user_expr_column);
720   else
721     return false;
722 
723   // The actual column where we have to complete is the start column of the
724   // user expression + the offset inside the user code that we were given.
725   const unsigned completion_column = user_expr_column + complete_pos;
726   parser.Complete(request, user_expr_line, completion_column, complete_pos);
727 
728   return true;
729 }
730 
731 bool ClangUserExpression::AddArguments(ExecutionContext &exe_ctx,
732                                        std::vector<lldb::addr_t> &args,
733                                        lldb::addr_t struct_address,
734                                        DiagnosticManager &diagnostic_manager) {
735   lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
736   lldb::addr_t cmd_ptr = LLDB_INVALID_ADDRESS;
737 
738   if (m_needs_object_ptr) {
739     lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
740     if (!frame_sp)
741       return true;
742 
743     ConstString object_name;
744 
745     if (m_in_cplusplus_method) {
746       object_name.SetCString("this");
747     } else if (m_in_objectivec_method) {
748       object_name.SetCString("self");
749     } else {
750       diagnostic_manager.PutString(
751           eDiagnosticSeverityError,
752           "need object pointer but don't know the language");
753       return false;
754     }
755 
756     Status object_ptr_error;
757 
758     if (m_ctx_obj) {
759       AddressType address_type;
760       object_ptr = m_ctx_obj->GetAddressOf(false, &address_type);
761       if (object_ptr == LLDB_INVALID_ADDRESS ||
762           address_type != eAddressTypeLoad)
763         object_ptr_error.SetErrorString("Can't get context object's "
764                                         "debuggee address");
765     } else
766       object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
767 
768     if (!object_ptr_error.Success()) {
769       exe_ctx.GetTargetRef().GetDebugger().GetAsyncOutputStream()->Printf(
770           "warning: `%s' is not accessible (substituting 0)\n",
771           object_name.AsCString());
772       object_ptr = 0;
773     }
774 
775     if (m_in_objectivec_method) {
776       ConstString cmd_name("_cmd");
777 
778       cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
779 
780       if (!object_ptr_error.Success()) {
781         diagnostic_manager.Printf(
782             eDiagnosticSeverityWarning,
783             "couldn't get cmd pointer (substituting NULL): %s",
784             object_ptr_error.AsCString());
785         cmd_ptr = 0;
786       }
787     }
788 
789     args.push_back(object_ptr);
790 
791     if (m_in_objectivec_method)
792       args.push_back(cmd_ptr);
793 
794     args.push_back(struct_address);
795   } else {
796     args.push_back(struct_address);
797   }
798   return true;
799 }
800 
801 lldb::ExpressionVariableSP ClangUserExpression::GetResultAfterDematerialization(
802     ExecutionContextScope *exe_scope) {
803   return m_result_delegate.GetVariable();
804 }
805 
806 void ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(
807     ExecutionContext &exe_ctx,
808     Materializer::PersistentVariableDelegate &delegate,
809     bool keep_result_in_memory,
810     ValueObject *ctx_obj) {
811   m_expr_decl_map_up.reset(
812       new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx,
813                                  ctx_obj));
814 }
815 
816 clang::ASTConsumer *
817 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer(
818     clang::ASTConsumer *passthrough) {
819   m_result_synthesizer_up.reset(
820       new ASTResultSynthesizer(passthrough, m_top_level, m_target));
821 
822   return m_result_synthesizer_up.get();
823 }
824 
825 void ClangUserExpression::ClangUserExpressionHelper::CommitPersistentDecls() {
826   if (m_result_synthesizer_up) {
827     m_result_synthesizer_up->CommitPersistentDecls();
828   }
829 }
830 
831 ConstString ClangUserExpression::ResultDelegate::GetName() {
832   auto prefix = m_persistent_state->GetPersistentVariablePrefix();
833   return m_persistent_state->GetNextPersistentVariableName(*m_target_sp,
834                                                            prefix);
835 }
836 
837 void ClangUserExpression::ResultDelegate::DidDematerialize(
838     lldb::ExpressionVariableSP &variable) {
839   m_variable = variable;
840 }
841 
842 void ClangUserExpression::ResultDelegate::RegisterPersistentState(
843     PersistentExpressionState *persistent_state) {
844   m_persistent_state = persistent_state;
845 }
846 
847 lldb::ExpressionVariableSP &ClangUserExpression::ResultDelegate::GetVariable() {
848   return m_variable;
849 }
850