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