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