xref: /src/contrib/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1cfca06d7SDimitry Andric //===-- ClangExpressionSourceCode.cpp -------------------------------------===//
2f034231aSEd Maste //
35f29bb8aSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45f29bb8aSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55f29bb8aSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f034231aSEd Maste //
7f034231aSEd Maste //===----------------------------------------------------------------------===//
8f034231aSEd Maste 
95f29bb8aSDimitry Andric #include "ClangExpressionSourceCode.h"
105f29bb8aSDimitry Andric 
114b4fe385SDimitry Andric #include "ClangExpressionUtil.h"
124b4fe385SDimitry Andric 
135f29bb8aSDimitry Andric #include "clang/Basic/CharInfo.h"
14cfca06d7SDimitry Andric #include "clang/Basic/FileManager.h"
155f29bb8aSDimitry Andric #include "clang/Basic/SourceManager.h"
165f29bb8aSDimitry Andric #include "clang/Lex/Lexer.h"
177fa27ce4SDimitry Andric #include "llvm/ADT/ScopeExit.h"
185f29bb8aSDimitry Andric #include "llvm/ADT/StringRef.h"
19f034231aSEd Maste 
20e81d9d49SDimitry Andric #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
21e81d9d49SDimitry Andric #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
2214f1b3e8SDimitry Andric #include "lldb/Symbol/Block.h"
23e81d9d49SDimitry Andric #include "lldb/Symbol/CompileUnit.h"
24e81d9d49SDimitry Andric #include "lldb/Symbol/DebugMacros.h"
25e81d9d49SDimitry Andric #include "lldb/Symbol/TypeSystem.h"
26f3fbd1c0SDimitry Andric #include "lldb/Symbol/VariableList.h"
270cac4ca3SEd Maste #include "lldb/Target/ExecutionContext.h"
28f3fbd1c0SDimitry Andric #include "lldb/Target/Language.h"
290cac4ca3SEd Maste #include "lldb/Target/Platform.h"
305e95aa85SEd Maste #include "lldb/Target/StackFrame.h"
310cac4ca3SEd Maste #include "lldb/Target/Target.h"
3274a628f7SDimitry Andric #include "lldb/Utility/StreamString.h"
334b4fe385SDimitry Andric #include "lldb/lldb-forward.h"
34f034231aSEd Maste 
35f034231aSEd Maste using namespace lldb_private;
36f034231aSEd Maste 
37ead24645SDimitry Andric #define PREFIX_NAME "<lldb wrapper prefix>"
38344a3780SDimitry Andric #define SUFFIX_NAME "<lldb wrapper suffix>"
39ead24645SDimitry Andric 
40ead24645SDimitry Andric const llvm::StringRef ClangExpressionSourceCode::g_prefix_file_name = PREFIX_NAME;
41ead24645SDimitry Andric 
42ead24645SDimitry Andric const char *ClangExpressionSourceCode::g_expression_prefix =
43ead24645SDimitry Andric "#line 1 \"" PREFIX_NAME R"("
44ead24645SDimitry Andric #ifndef offsetof
45ead24645SDimitry Andric #define offsetof(t, d) __builtin_offsetof(t, d)
46ead24645SDimitry Andric #endif
475e95aa85SEd Maste #ifndef NULL
48f034231aSEd Maste #define NULL (__null)
495e95aa85SEd Maste #endif
505e95aa85SEd Maste #ifndef Nil
51f034231aSEd Maste #define Nil (__null)
525e95aa85SEd Maste #endif
535e95aa85SEd Maste #ifndef nil
54f034231aSEd Maste #define nil (__null)
555e95aa85SEd Maste #endif
565e95aa85SEd Maste #ifndef YES
57f034231aSEd Maste #define YES ((BOOL)1)
585e95aa85SEd Maste #endif
595e95aa85SEd Maste #ifndef NO
60f034231aSEd Maste #define NO ((BOOL)0)
615e95aa85SEd Maste #endif
620cac4ca3SEd Maste typedef __INT8_TYPE__ int8_t;
630cac4ca3SEd Maste typedef __UINT8_TYPE__ uint8_t;
640cac4ca3SEd Maste typedef __INT16_TYPE__ int16_t;
650cac4ca3SEd Maste typedef __UINT16_TYPE__ uint16_t;
660cac4ca3SEd Maste typedef __INT32_TYPE__ int32_t;
670cac4ca3SEd Maste typedef __UINT32_TYPE__ uint32_t;
680cac4ca3SEd Maste typedef __INT64_TYPE__ int64_t;
690cac4ca3SEd Maste typedef __UINT64_TYPE__ uint64_t;
700cac4ca3SEd Maste typedef __INTPTR_TYPE__ intptr_t;
710cac4ca3SEd Maste typedef __UINTPTR_TYPE__ uintptr_t;
72f034231aSEd Maste typedef __SIZE_TYPE__ size_t;
73f034231aSEd Maste typedef __PTRDIFF_TYPE__ ptrdiff_t;
74f034231aSEd Maste typedef unsigned short unichar;
7512bd4897SEd Maste extern "C"
7612bd4897SEd Maste {
7712bd4897SEd Maste     int printf(const char * __restrict, ...);
7812bd4897SEd Maste }
79f034231aSEd Maste )";
80f034231aSEd Maste 
81344a3780SDimitry Andric const char *ClangExpressionSourceCode::g_expression_suffix =
82344a3780SDimitry Andric     "\n;\n#line 1 \"" SUFFIX_NAME "\"\n";
83344a3780SDimitry Andric 
84e81d9d49SDimitry Andric namespace {
85e81d9d49SDimitry Andric 
8614f1b3e8SDimitry Andric class AddMacroState {
8714f1b3e8SDimitry Andric   enum State {
88e81d9d49SDimitry Andric     CURRENT_FILE_NOT_YET_PUSHED,
89e81d9d49SDimitry Andric     CURRENT_FILE_PUSHED,
90e81d9d49SDimitry Andric     CURRENT_FILE_POPPED
91e81d9d49SDimitry Andric   };
92e81d9d49SDimitry Andric 
93e81d9d49SDimitry Andric public:
AddMacroState(const FileSpec & current_file,const uint32_t current_file_line)94e81d9d49SDimitry Andric   AddMacroState(const FileSpec &current_file, const uint32_t current_file_line)
95145449b1SDimitry Andric       : m_current_file(current_file), m_current_file_line(current_file_line) {}
96e81d9d49SDimitry Andric 
StartFile(const FileSpec & file)9714f1b3e8SDimitry Andric   void StartFile(const FileSpec &file) {
98e81d9d49SDimitry Andric     m_file_stack.push_back(file);
99e81d9d49SDimitry Andric     if (file == m_current_file)
100e81d9d49SDimitry Andric       m_state = CURRENT_FILE_PUSHED;
101e81d9d49SDimitry Andric   }
102e81d9d49SDimitry Andric 
EndFile()10314f1b3e8SDimitry Andric   void EndFile() {
104e81d9d49SDimitry Andric     if (m_file_stack.size() == 0)
105e81d9d49SDimitry Andric       return;
106e81d9d49SDimitry Andric 
107e81d9d49SDimitry Andric     FileSpec old_top = m_file_stack.back();
108e81d9d49SDimitry Andric     m_file_stack.pop_back();
109e81d9d49SDimitry Andric     if (old_top == m_current_file)
110e81d9d49SDimitry Andric       m_state = CURRENT_FILE_POPPED;
111e81d9d49SDimitry Andric   }
112e81d9d49SDimitry Andric 
113f73363f1SDimitry Andric   // An entry is valid if it occurs before the current line in the current
114f73363f1SDimitry Andric   // file.
IsValidEntry(uint32_t line)11514f1b3e8SDimitry Andric   bool IsValidEntry(uint32_t line) {
11614f1b3e8SDimitry Andric     switch (m_state) {
117e81d9d49SDimitry Andric     case CURRENT_FILE_NOT_YET_PUSHED:
118e81d9d49SDimitry Andric       return true;
119e81d9d49SDimitry Andric     case CURRENT_FILE_PUSHED:
120f73363f1SDimitry Andric       // If we are in file included in the current file, the entry should be
121f73363f1SDimitry Andric       // added.
122e81d9d49SDimitry Andric       if (m_file_stack.back() != m_current_file)
123e81d9d49SDimitry Andric         return true;
124e81d9d49SDimitry Andric 
12594994d37SDimitry Andric       return line < m_current_file_line;
126f3fbd1c0SDimitry Andric     default:
127f3fbd1c0SDimitry Andric       return false;
128e81d9d49SDimitry Andric     }
129e81d9d49SDimitry Andric   }
130e81d9d49SDimitry Andric 
131e81d9d49SDimitry Andric private:
132e81d9d49SDimitry Andric   std::vector<FileSpec> m_file_stack;
133145449b1SDimitry Andric   State m_state = CURRENT_FILE_NOT_YET_PUSHED;
134e81d9d49SDimitry Andric   FileSpec m_current_file;
135e81d9d49SDimitry Andric   uint32_t m_current_file_line;
136e81d9d49SDimitry Andric };
137e81d9d49SDimitry Andric 
138e81d9d49SDimitry Andric } // anonymous namespace
139e81d9d49SDimitry Andric 
AddMacros(const DebugMacros * dm,CompileUnit * comp_unit,AddMacroState & state,StreamString & stream)14014f1b3e8SDimitry Andric static void AddMacros(const DebugMacros *dm, CompileUnit *comp_unit,
14114f1b3e8SDimitry Andric                       AddMacroState &state, StreamString &stream) {
142e81d9d49SDimitry Andric   if (dm == nullptr)
143e81d9d49SDimitry Andric     return;
144e81d9d49SDimitry Andric 
1457fa27ce4SDimitry Andric   // The macros directives below can potentially redefine builtin macros of the
1467fa27ce4SDimitry Andric   // Clang instance which parses the user expression. The Clang diagnostics
1477fa27ce4SDimitry Andric   // caused by this are not useful for the user as the source code here is
1487fa27ce4SDimitry Andric   // generated by LLDB.
1497fa27ce4SDimitry Andric   stream << "#pragma clang diagnostic push\n";
1507fa27ce4SDimitry Andric   stream << "#pragma clang diagnostic ignored \"-Wmacro-redefined\"\n";
1517fa27ce4SDimitry Andric   stream << "#pragma clang diagnostic ignored \"-Wbuiltin-macro-redefined\"\n";
1527fa27ce4SDimitry Andric   auto pop_warning = llvm::make_scope_exit([&stream](){
1537fa27ce4SDimitry Andric     stream << "#pragma clang diagnostic pop\n";
1547fa27ce4SDimitry Andric   });
1557fa27ce4SDimitry Andric 
15614f1b3e8SDimitry Andric   for (size_t i = 0; i < dm->GetNumMacroEntries(); i++) {
157e81d9d49SDimitry Andric     const DebugMacroEntry &entry = dm->GetMacroEntryAtIndex(i);
158e81d9d49SDimitry Andric     uint32_t line;
159e81d9d49SDimitry Andric 
16014f1b3e8SDimitry Andric     switch (entry.GetType()) {
161e81d9d49SDimitry Andric     case DebugMacroEntry::DEFINE:
162e81d9d49SDimitry Andric       if (state.IsValidEntry(entry.GetLineNumber()))
163e81d9d49SDimitry Andric         stream.Printf("#define %s\n", entry.GetMacroString().AsCString());
164e81d9d49SDimitry Andric       else
165e81d9d49SDimitry Andric         return;
166e81d9d49SDimitry Andric       break;
167e81d9d49SDimitry Andric     case DebugMacroEntry::UNDEF:
168e81d9d49SDimitry Andric       if (state.IsValidEntry(entry.GetLineNumber()))
169e81d9d49SDimitry Andric         stream.Printf("#undef %s\n", entry.GetMacroString().AsCString());
170e81d9d49SDimitry Andric       else
171e81d9d49SDimitry Andric         return;
172e81d9d49SDimitry Andric       break;
173e81d9d49SDimitry Andric     case DebugMacroEntry::START_FILE:
174e81d9d49SDimitry Andric       line = entry.GetLineNumber();
175e81d9d49SDimitry Andric       if (state.IsValidEntry(line))
176e81d9d49SDimitry Andric         state.StartFile(entry.GetFileSpec(comp_unit));
177e81d9d49SDimitry Andric       else
178e81d9d49SDimitry Andric         return;
179e81d9d49SDimitry Andric       break;
180e81d9d49SDimitry Andric     case DebugMacroEntry::END_FILE:
181e81d9d49SDimitry Andric       state.EndFile();
182e81d9d49SDimitry Andric       break;
183e81d9d49SDimitry Andric     case DebugMacroEntry::INDIRECT:
184e81d9d49SDimitry Andric       AddMacros(entry.GetIndirectDebugMacros(), comp_unit, state, stream);
185e81d9d49SDimitry Andric       break;
186e81d9d49SDimitry Andric     default:
187e81d9d49SDimitry Andric       // This is an unknown/invalid entry. Ignore.
188e81d9d49SDimitry Andric       break;
189e81d9d49SDimitry Andric     }
190e81d9d49SDimitry Andric   }
191e81d9d49SDimitry Andric }
192f034231aSEd Maste 
ClangExpressionSourceCode(llvm::StringRef filename,llvm::StringRef name,llvm::StringRef prefix,llvm::StringRef body,Wrapping wrap,WrapKind wrap_kind)193ead24645SDimitry Andric lldb_private::ClangExpressionSourceCode::ClangExpressionSourceCode(
194ead24645SDimitry Andric     llvm::StringRef filename, llvm::StringRef name, llvm::StringRef prefix,
195cfca06d7SDimitry Andric     llvm::StringRef body, Wrapping wrap, WrapKind wrap_kind)
196cfca06d7SDimitry Andric     : ExpressionSourceCode(name, prefix, body, wrap), m_wrap_kind(wrap_kind) {
197ead24645SDimitry Andric   // Use #line markers to pretend that we have a single-line source file
198ead24645SDimitry Andric   // containing only the user expression. This will hide our wrapper code
199ead24645SDimitry Andric   // from the user when we render diagnostics with Clang.
200ead24645SDimitry Andric   m_start_marker = "#line 1 \"" + filename.str() + "\"\n";
201344a3780SDimitry Andric   m_end_marker = g_expression_suffix;
202ead24645SDimitry Andric }
203ead24645SDimitry Andric 
2045f29bb8aSDimitry Andric namespace {
2055f29bb8aSDimitry Andric /// Allows checking if a token is contained in a given expression.
2065f29bb8aSDimitry Andric class TokenVerifier {
2075f29bb8aSDimitry Andric   /// The tokens we found in the expression.
2085f29bb8aSDimitry Andric   llvm::StringSet<> m_tokens;
2095f29bb8aSDimitry Andric 
2105f29bb8aSDimitry Andric public:
2115f29bb8aSDimitry Andric   TokenVerifier(std::string body);
2125f29bb8aSDimitry Andric   /// Returns true iff the given expression body contained a token with the
2135f29bb8aSDimitry Andric   /// given content.
hasToken(llvm::StringRef token) const2145f29bb8aSDimitry Andric   bool hasToken(llvm::StringRef token) const {
2157fa27ce4SDimitry Andric     return m_tokens.contains(token);
2165f29bb8aSDimitry Andric   }
2175f29bb8aSDimitry Andric };
2184b4fe385SDimitry Andric 
2194b4fe385SDimitry Andric // If we're evaluating from inside a lambda that captures a 'this' pointer,
2204b4fe385SDimitry Andric // add a "using" declaration to 'stream' for each capture used in the
2214b4fe385SDimitry Andric // expression (tokenized by 'verifier').
2224b4fe385SDimitry Andric //
2234b4fe385SDimitry Andric // If no 'this' capture exists, generate no using declarations. Instead
2244b4fe385SDimitry Andric // capture lookups will get resolved by the same mechanism as class member
2254b4fe385SDimitry Andric // variable lookup. That's because Clang generates an unnamed structure
2264b4fe385SDimitry Andric // representing the lambda closure whose members are the captured variables.
AddLambdaCaptureDecls(StreamString & stream,StackFrame * frame,TokenVerifier const & verifier)2274b4fe385SDimitry Andric void AddLambdaCaptureDecls(StreamString &stream, StackFrame *frame,
2284b4fe385SDimitry Andric                            TokenVerifier const &verifier) {
2294b4fe385SDimitry Andric   assert(frame);
2304b4fe385SDimitry Andric 
2314b4fe385SDimitry Andric   if (auto thisValSP = ClangExpressionUtil::GetLambdaValueObject(frame)) {
232ac9a064cSDimitry Andric     uint32_t numChildren = thisValSP->GetNumChildrenIgnoringErrors();
2334b4fe385SDimitry Andric     for (uint32_t i = 0; i < numChildren; ++i) {
2347fa27ce4SDimitry Andric       auto childVal = thisValSP->GetChildAtIndex(i);
2354b4fe385SDimitry Andric       ConstString childName(childVal ? childVal->GetName() : ConstString(""));
2364b4fe385SDimitry Andric 
2374b4fe385SDimitry Andric       if (!childName.IsEmpty() && verifier.hasToken(childName.GetStringRef()) &&
2384b4fe385SDimitry Andric           childName != "this") {
2394b4fe385SDimitry Andric         stream.Printf("using $__lldb_local_vars::%s;\n",
2404b4fe385SDimitry Andric                       childName.GetCString());
2414b4fe385SDimitry Andric       }
2424b4fe385SDimitry Andric     }
2434b4fe385SDimitry Andric   }
2444b4fe385SDimitry Andric }
2454b4fe385SDimitry Andric 
2465f29bb8aSDimitry Andric } // namespace
2475f29bb8aSDimitry Andric 
TokenVerifier(std::string body)2485f29bb8aSDimitry Andric TokenVerifier::TokenVerifier(std::string body) {
2495f29bb8aSDimitry Andric   using namespace clang;
2505f29bb8aSDimitry Andric 
2515f29bb8aSDimitry Andric   // We only care about tokens and not their original source locations. If we
2525f29bb8aSDimitry Andric   // move the whole expression to only be in one line we can simplify the
2535f29bb8aSDimitry Andric   // following code that extracts the token contents.
2545f29bb8aSDimitry Andric   std::replace(body.begin(), body.end(), '\n', ' ');
2555f29bb8aSDimitry Andric   std::replace(body.begin(), body.end(), '\r', ' ');
2565f29bb8aSDimitry Andric 
2575f29bb8aSDimitry Andric   FileSystemOptions file_opts;
2585f29bb8aSDimitry Andric   FileManager file_mgr(file_opts,
2595f29bb8aSDimitry Andric                        FileSystem::Instance().GetVirtualFileSystem());
2605f29bb8aSDimitry Andric 
2615f29bb8aSDimitry Andric   // Let's build the actual source code Clang needs and setup some utility
2625f29bb8aSDimitry Andric   // objects.
2635f29bb8aSDimitry Andric   llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_ids(new DiagnosticIDs());
2645f29bb8aSDimitry Andric   llvm::IntrusiveRefCntPtr<DiagnosticOptions> diags_opts(
2655f29bb8aSDimitry Andric       new DiagnosticOptions());
2665f29bb8aSDimitry Andric   DiagnosticsEngine diags(diag_ids, diags_opts);
2675f29bb8aSDimitry Andric   clang::SourceManager SM(diags, file_mgr);
2685f29bb8aSDimitry Andric   auto buf = llvm::MemoryBuffer::getMemBuffer(body);
2695f29bb8aSDimitry Andric 
270b60736ecSDimitry Andric   FileID FID = SM.createFileID(buf->getMemBufferRef());
2715f29bb8aSDimitry Andric 
2725f29bb8aSDimitry Andric   // Let's just enable the latest ObjC and C++ which should get most tokens
2735f29bb8aSDimitry Andric   // right.
2745f29bb8aSDimitry Andric   LangOptions Opts;
2755f29bb8aSDimitry Andric   Opts.ObjC = true;
2765f29bb8aSDimitry Andric   Opts.DollarIdents = true;
2777fa27ce4SDimitry Andric   Opts.CPlusPlus20 = true;
2785f29bb8aSDimitry Andric   Opts.LineComment = true;
2795f29bb8aSDimitry Andric 
280b60736ecSDimitry Andric   Lexer lex(FID, buf->getMemBufferRef(), SM, Opts);
2815f29bb8aSDimitry Andric 
2825f29bb8aSDimitry Andric   Token token;
2835f29bb8aSDimitry Andric   bool exit = false;
2845f29bb8aSDimitry Andric   while (!exit) {
2855f29bb8aSDimitry Andric     // Returns true if this is the last token we get from the lexer.
2865f29bb8aSDimitry Andric     exit = lex.LexFromRawLexer(token);
2875f29bb8aSDimitry Andric 
2885f29bb8aSDimitry Andric     // Extract the column number which we need to extract the token content.
2895f29bb8aSDimitry Andric     // Our expression is just one line, so we don't need to handle any line
2905f29bb8aSDimitry Andric     // numbers here.
2915f29bb8aSDimitry Andric     bool invalid = false;
2925f29bb8aSDimitry Andric     unsigned start = SM.getSpellingColumnNumber(token.getLocation(), &invalid);
2935f29bb8aSDimitry Andric     if (invalid)
2945f29bb8aSDimitry Andric       continue;
2955f29bb8aSDimitry Andric     // Column numbers start at 1, but indexes in our string start at 0.
2965f29bb8aSDimitry Andric     --start;
2975f29bb8aSDimitry Andric 
2985f29bb8aSDimitry Andric     // Annotations don't have a length, so let's skip them.
2995f29bb8aSDimitry Andric     if (token.isAnnotation())
3005f29bb8aSDimitry Andric       continue;
3015f29bb8aSDimitry Andric 
3025f29bb8aSDimitry Andric     // Extract the token string from our source code and store it.
3035f29bb8aSDimitry Andric     std::string token_str = body.substr(start, token.getLength());
3045f29bb8aSDimitry Andric     if (token_str.empty())
3055f29bb8aSDimitry Andric       continue;
3065f29bb8aSDimitry Andric     m_tokens.insert(token_str);
3075f29bb8aSDimitry Andric   }
3085f29bb8aSDimitry Andric }
3095f29bb8aSDimitry Andric 
AddLocalVariableDecls(StreamString & stream,const std::string & expr,StackFrame * frame) const3104b4fe385SDimitry Andric void ClangExpressionSourceCode::AddLocalVariableDecls(StreamString &stream,
3114b4fe385SDimitry Andric                                                       const std::string &expr,
3124b4fe385SDimitry Andric                                                       StackFrame *frame) const {
3134b4fe385SDimitry Andric   assert(frame);
3145f29bb8aSDimitry Andric   TokenVerifier tokens(expr);
3155f29bb8aSDimitry Andric 
3164b4fe385SDimitry Andric   lldb::VariableListSP var_list_sp = frame->GetInScopeVariableList(false, true);
3174b4fe385SDimitry Andric 
31814f1b3e8SDimitry Andric   for (size_t i = 0; i < var_list_sp->GetSize(); i++) {
319f3fbd1c0SDimitry Andric     lldb::VariableSP var_sp = var_list_sp->GetVariableAtIndex(i);
320f3fbd1c0SDimitry Andric 
321f3fbd1c0SDimitry Andric     ConstString var_name = var_sp->GetName();
3225f29bb8aSDimitry Andric 
3234b4fe385SDimitry Andric     if (var_name == "this" && m_wrap_kind == WrapKind::CppMemberFunction) {
3244b4fe385SDimitry Andric       AddLambdaCaptureDecls(stream, frame, tokens);
3254b4fe385SDimitry Andric 
3264b4fe385SDimitry Andric       continue;
3274b4fe385SDimitry Andric     }
3285f29bb8aSDimitry Andric 
3295f29bb8aSDimitry Andric     // We can check for .block_descriptor w/o checking for langauge since this
3305f29bb8aSDimitry Andric     // is not a valid identifier in either C or C++.
3315f29bb8aSDimitry Andric     if (!var_name || var_name == ".block_descriptor")
3325f29bb8aSDimitry Andric       continue;
3335f29bb8aSDimitry Andric 
3345f29bb8aSDimitry Andric     if (!expr.empty() && !tokens.hasToken(var_name.GetStringRef()))
3355f29bb8aSDimitry Andric       continue;
3365f29bb8aSDimitry Andric 
337cfca06d7SDimitry Andric     const bool is_objc = m_wrap_kind == WrapKind::ObjCInstanceMethod ||
338cfca06d7SDimitry Andric                          m_wrap_kind == WrapKind::ObjCStaticMethod;
339cfca06d7SDimitry Andric     if ((var_name == "self" || var_name == "_cmd") && is_objc)
3405f29bb8aSDimitry Andric       continue;
3415f29bb8aSDimitry Andric 
342f3fbd1c0SDimitry Andric     stream.Printf("using $__lldb_local_vars::%s;\n", var_name.AsCString());
343f3fbd1c0SDimitry Andric   }
344f3fbd1c0SDimitry Andric }
345f3fbd1c0SDimitry Andric 
GetText(std::string & text,ExecutionContext & exe_ctx,bool add_locals,bool force_add_all_locals,llvm::ArrayRef<std::string> modules) const3465f29bb8aSDimitry Andric bool ClangExpressionSourceCode::GetText(
347cfca06d7SDimitry Andric     std::string &text, ExecutionContext &exe_ctx, bool add_locals,
348cfca06d7SDimitry Andric     bool force_add_all_locals, llvm::ArrayRef<std::string> modules) const {
3490cac4ca3SEd Maste   const char *target_specific_defines = "typedef signed char BOOL;\n";
3505e95aa85SEd Maste   std::string module_macros;
351b60736ecSDimitry Andric   llvm::raw_string_ostream module_macros_stream(module_macros);
3520cac4ca3SEd Maste 
353f3fbd1c0SDimitry Andric   Target *target = exe_ctx.GetTargetPtr();
35414f1b3e8SDimitry Andric   if (target) {
355ead24645SDimitry Andric     if (target->GetArchitecture().GetMachine() == llvm::Triple::aarch64 ||
356ead24645SDimitry Andric         target->GetArchitecture().GetMachine() == llvm::Triple::aarch64_32) {
3570cac4ca3SEd Maste       target_specific_defines = "typedef bool BOOL;\n";
3580cac4ca3SEd Maste     }
35914f1b3e8SDimitry Andric     if (target->GetArchitecture().GetMachine() == llvm::Triple::x86_64) {
36014f1b3e8SDimitry Andric       if (lldb::PlatformSP platform_sp = target->GetPlatform()) {
361c0981da4SDimitry Andric         if (platform_sp->GetPluginName() == "ios-simulator") {
3620cac4ca3SEd Maste           target_specific_defines = "typedef bool BOOL;\n";
3630cac4ca3SEd Maste         }
3640cac4ca3SEd Maste       }
3650cac4ca3SEd Maste     }
3665e95aa85SEd Maste 
367706b4fc4SDimitry Andric     auto *persistent_vars = llvm::cast<ClangPersistentVariables>(
368706b4fc4SDimitry Andric         target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
369344a3780SDimitry Andric     std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
370344a3780SDimitry Andric         persistent_vars->GetClangModulesDeclVendor();
371344a3780SDimitry Andric     if (decl_vendor) {
37214f1b3e8SDimitry Andric       const ClangModulesDeclVendor::ModuleVector &hand_imported_modules =
37314f1b3e8SDimitry Andric           persistent_vars->GetHandLoadedClangModules();
3745e95aa85SEd Maste       ClangModulesDeclVendor::ModuleVector modules_for_macros;
3755e95aa85SEd Maste 
37614f1b3e8SDimitry Andric       for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules) {
3775e95aa85SEd Maste         modules_for_macros.push_back(module);
3785e95aa85SEd Maste       }
3795e95aa85SEd Maste 
38014f1b3e8SDimitry Andric       if (target->GetEnableAutoImportClangModules()) {
38114f1b3e8SDimitry Andric         if (StackFrame *frame = exe_ctx.GetFramePtr()) {
38214f1b3e8SDimitry Andric           if (Block *block = frame->GetFrameBlock()) {
3835e95aa85SEd Maste             SymbolContext sc;
3845e95aa85SEd Maste 
3855e95aa85SEd Maste             block->CalculateSymbolContext(&sc);
3865e95aa85SEd Maste 
38714f1b3e8SDimitry Andric             if (sc.comp_unit) {
3885e95aa85SEd Maste               StreamString error_stream;
3895e95aa85SEd Maste 
39014f1b3e8SDimitry Andric               decl_vendor->AddModulesForCompileUnit(
39114f1b3e8SDimitry Andric                   *sc.comp_unit, modules_for_macros, error_stream);
3925e95aa85SEd Maste             }
3935e95aa85SEd Maste           }
3945e95aa85SEd Maste         }
3955e95aa85SEd Maste       }
3965e95aa85SEd Maste 
39714f1b3e8SDimitry Andric       decl_vendor->ForEachMacro(
39814f1b3e8SDimitry Andric           modules_for_macros,
399b60736ecSDimitry Andric           [&module_macros_stream](llvm::StringRef token,
400b60736ecSDimitry Andric                                   llvm::StringRef expansion) -> bool {
401b60736ecSDimitry Andric             // Check if the macro hasn't already been defined in the
402b60736ecSDimitry Andric             // g_expression_prefix (which defines a few builtin macros).
403b60736ecSDimitry Andric             module_macros_stream << "#ifndef " << token << "\n";
404b60736ecSDimitry Andric             module_macros_stream << expansion << "\n";
405b60736ecSDimitry Andric             module_macros_stream << "#endif\n";
4065e95aa85SEd Maste             return false;
4075e95aa85SEd Maste           });
4085e95aa85SEd Maste     }
4090cac4ca3SEd Maste   }
4100cac4ca3SEd Maste 
411e81d9d49SDimitry Andric   StreamString debug_macros_stream;
412f3fbd1c0SDimitry Andric   StreamString lldb_local_var_decls;
41314f1b3e8SDimitry Andric   if (StackFrame *frame = exe_ctx.GetFramePtr()) {
414e81d9d49SDimitry Andric     const SymbolContext &sc = frame->GetSymbolContext(
415e81d9d49SDimitry Andric         lldb::eSymbolContextCompUnit | lldb::eSymbolContextLineEntry);
416e81d9d49SDimitry Andric 
41714f1b3e8SDimitry Andric     if (sc.comp_unit && sc.line_entry.IsValid()) {
418e81d9d49SDimitry Andric       DebugMacros *dm = sc.comp_unit->GetDebugMacros();
41914f1b3e8SDimitry Andric       if (dm) {
420ac9a064cSDimitry Andric         AddMacroState state(sc.line_entry.GetFile(), sc.line_entry.line);
421e81d9d49SDimitry Andric         AddMacros(dm, sc.comp_unit, state, debug_macros_stream);
422e81d9d49SDimitry Andric       }
423e81d9d49SDimitry Andric     }
424f3fbd1c0SDimitry Andric 
4255f29bb8aSDimitry Andric     if (add_locals)
42614f1b3e8SDimitry Andric       if (target->GetInjectLocalVariables(&exe_ctx)) {
4274b4fe385SDimitry Andric         AddLocalVariableDecls(lldb_local_var_decls,
4284b4fe385SDimitry Andric                               force_add_all_locals ? "" : m_body, frame);
429f3fbd1c0SDimitry Andric       }
430e81d9d49SDimitry Andric   }
431e81d9d49SDimitry Andric 
43214f1b3e8SDimitry Andric   if (m_wrap) {
4335f29bb8aSDimitry Andric     // Generate a list of @import statements that will import the specified
4345f29bb8aSDimitry Andric     // module into our expression.
4355f29bb8aSDimitry Andric     std::string module_imports;
4365f29bb8aSDimitry Andric     for (const std::string &module : modules) {
4375f29bb8aSDimitry Andric       module_imports.append("@import ");
4385f29bb8aSDimitry Andric       module_imports.append(module);
4395f29bb8aSDimitry Andric       module_imports.append(";\n");
4405f29bb8aSDimitry Andric     }
4415f29bb8aSDimitry Andric 
442f034231aSEd Maste     StreamString wrap_stream;
443f034231aSEd Maste 
444b60736ecSDimitry Andric     wrap_stream.Printf("%s\n%s\n%s\n%s\n%s\n", g_expression_prefix,
445b60736ecSDimitry Andric                        module_macros.c_str(), debug_macros_stream.GetData(),
44614f1b3e8SDimitry Andric                        target_specific_defines, m_prefix.c_str());
4475e95aa85SEd Maste 
44814f1b3e8SDimitry Andric     // First construct a tagged form of the user expression so we can find it
44914f1b3e8SDimitry Andric     // later:
450f3fbd1c0SDimitry Andric     std::string tagged_body;
451ead24645SDimitry Andric     tagged_body.append(m_start_marker);
452f3fbd1c0SDimitry Andric     tagged_body.append(m_body);
453ead24645SDimitry Andric     tagged_body.append(m_end_marker);
454cfca06d7SDimitry Andric 
455cfca06d7SDimitry Andric     switch (m_wrap_kind) {
456cfca06d7SDimitry Andric     case WrapKind::Function:
4575f29bb8aSDimitry Andric       wrap_stream.Printf("%s"
4585f29bb8aSDimitry Andric                          "void                           \n"
459f034231aSEd Maste                          "%s(void *$__lldb_arg)          \n"
460f034231aSEd Maste                          "{                              \n"
461f034231aSEd Maste                          "    %s;                        \n"
462f3fbd1c0SDimitry Andric                          "%s"
463f034231aSEd Maste                          "}                              \n",
4645f29bb8aSDimitry Andric                          module_imports.c_str(), m_name.c_str(),
4655f29bb8aSDimitry Andric                          lldb_local_var_decls.GetData(), tagged_body.c_str());
466f034231aSEd Maste       break;
467cfca06d7SDimitry Andric     case WrapKind::CppMemberFunction:
4685f29bb8aSDimitry Andric       wrap_stream.Printf("%s"
4695f29bb8aSDimitry Andric                          "void                                   \n"
470f3fbd1c0SDimitry Andric                          "$__lldb_class::%s(void *$__lldb_arg)   \n"
471f034231aSEd Maste                          "{                                      \n"
472f034231aSEd Maste                          "    %s;                                \n"
473f3fbd1c0SDimitry Andric                          "%s"
474f034231aSEd Maste                          "}                                      \n",
4755f29bb8aSDimitry Andric                          module_imports.c_str(), m_name.c_str(),
4765f29bb8aSDimitry Andric                          lldb_local_var_decls.GetData(), tagged_body.c_str());
477f034231aSEd Maste       break;
478cfca06d7SDimitry Andric     case WrapKind::ObjCInstanceMethod:
47914f1b3e8SDimitry Andric       wrap_stream.Printf(
4805f29bb8aSDimitry Andric           "%s"
48114f1b3e8SDimitry Andric           "@interface $__lldb_objc_class ($__lldb_category)       \n"
482f034231aSEd Maste           "-(void)%s:(void *)$__lldb_arg;                         \n"
483f034231aSEd Maste           "@end                                                   \n"
484f034231aSEd Maste           "@implementation $__lldb_objc_class ($__lldb_category)  \n"
485f034231aSEd Maste           "-(void)%s:(void *)$__lldb_arg                          \n"
486f034231aSEd Maste           "{                                                      \n"
4875f29bb8aSDimitry Andric           "    %s;                                                \n"
488f3fbd1c0SDimitry Andric           "%s"
489f034231aSEd Maste           "}                                                      \n"
490f034231aSEd Maste           "@end                                                   \n",
4915f29bb8aSDimitry Andric           module_imports.c_str(), m_name.c_str(), m_name.c_str(),
4925f29bb8aSDimitry Andric           lldb_local_var_decls.GetData(), tagged_body.c_str());
493cfca06d7SDimitry Andric       break;
494cfca06d7SDimitry Andric 
495cfca06d7SDimitry Andric     case WrapKind::ObjCStaticMethod:
496cfca06d7SDimitry Andric       wrap_stream.Printf(
497cfca06d7SDimitry Andric           "%s"
498cfca06d7SDimitry Andric           "@interface $__lldb_objc_class ($__lldb_category)        \n"
499cfca06d7SDimitry Andric           "+(void)%s:(void *)$__lldb_arg;                          \n"
500cfca06d7SDimitry Andric           "@end                                                    \n"
501cfca06d7SDimitry Andric           "@implementation $__lldb_objc_class ($__lldb_category)   \n"
502cfca06d7SDimitry Andric           "+(void)%s:(void *)$__lldb_arg                           \n"
503cfca06d7SDimitry Andric           "{                                                       \n"
504cfca06d7SDimitry Andric           "    %s;                                                 \n"
505cfca06d7SDimitry Andric           "%s"
506cfca06d7SDimitry Andric           "}                                                       \n"
507cfca06d7SDimitry Andric           "@end                                                    \n",
508cfca06d7SDimitry Andric           module_imports.c_str(), m_name.c_str(), m_name.c_str(),
509cfca06d7SDimitry Andric           lldb_local_var_decls.GetData(), tagged_body.c_str());
510f034231aSEd Maste       break;
511f034231aSEd Maste     }
512f034231aSEd Maste 
513cfca06d7SDimitry Andric     text = std::string(wrap_stream.GetString());
51414f1b3e8SDimitry Andric   } else {
515f034231aSEd Maste     text.append(m_body);
516f034231aSEd Maste   }
517f034231aSEd Maste 
518f034231aSEd Maste   return true;
519f034231aSEd Maste }
520f3fbd1c0SDimitry Andric 
GetOriginalBodyBounds(std::string transformed_text,size_t & start_loc,size_t & end_loc)5215f29bb8aSDimitry Andric bool ClangExpressionSourceCode::GetOriginalBodyBounds(
522cfca06d7SDimitry Andric     std::string transformed_text, size_t &start_loc, size_t &end_loc) {
523ead24645SDimitry Andric   start_loc = transformed_text.find(m_start_marker);
524f3fbd1c0SDimitry Andric   if (start_loc == std::string::npos)
525f3fbd1c0SDimitry Andric     return false;
526ead24645SDimitry Andric   start_loc += m_start_marker.size();
527ead24645SDimitry Andric   end_loc = transformed_text.find(m_end_marker);
52894994d37SDimitry Andric   return end_loc != std::string::npos;
529f3fbd1c0SDimitry Andric }
530