blob: 9e17a6ef8cd64e0fd8b5392ef7412d9aa6fb05b4 [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff1ccf4632007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000023using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000025
Chris Lattnerb429ae42007-10-11 00:43:27 +000026namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner74db1682007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000037 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000038
39 FunctionDecl *MsgSendFunctionDecl;
40 FunctionDecl *GetClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000041 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000042 FunctionDecl *CFStringFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000043
Steve Naroff0add5d22007-11-03 11:27:19 +000044 // ObjC string constant support.
45 FileVarDecl *ConstantStringClassReference;
46 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000047
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000048 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000049 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000050 void Initialize(ASTContext &context, unsigned mainFileID) {
51 Context = &context;
52 SM = &Context->SourceMgr;
Chris Lattner569faa62007-10-11 18:38:32 +000053 MainFileID = mainFileID;
Steve Naroffe9780582007-10-23 23:50:29 +000054 MsgSendFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000055 GetClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000056 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000057 CFStringFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000058 ConstantStringClassReference = 0;
59 NSStringRecord = 0;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000060 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Narofffcab7932007-11-05 14:55:35 +000061 // declaring objc_selector outside the parameter list removes a silly
62 // scope related warning...
Steve Naroffd3287d82007-11-07 18:43:40 +000063 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Narofffcab7932007-11-05 14:55:35 +000064 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +000065 "(struct objc_object *, struct objc_selector *, ...);\n"
66 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +000067 "(const char *);\n"
68 "extern void objc_exception_throw(struct objc_object *);\n"
69 "extern void objc_exception_try_enter(void *);\n"
70 "extern void objc_exception_try_exit(void *);\n"
71 "extern struct objc_object *objc_exception_extract(void *);\n"
72 "extern int objc_exception_match"
73 "(struct objc_class *, struct objc_object *, ...);\n";
74
Steve Naroff0744c472007-11-04 22:37:50 +000075 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
76 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +000077 }
Chris Lattner569faa62007-10-11 18:38:32 +000078
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000079 // Top Level Driver code.
80 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000081 void HandleDeclInMainFile(Decl *D);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000082 ~RewriteTest();
83
84 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +000085 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +000086 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000087 void RewriteTabs();
88 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +000089 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +000090 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +000091 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +000092 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +000093 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +000094 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +000095 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +000096 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +000097 void RewriteObjcQualifiedInterfaceTypes(
98 const FunctionTypeProto *proto, FunctionDecl *FD);
99 bool needToScanForQualifiers(QualType T);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000100
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000101 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000102 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000103 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff296b74f2007-11-05 14:50:49 +0000104 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000105 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000106 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000107 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
108 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
109 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000110 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000111 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
112 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000113 void SynthMsgSendFunctionDecl();
114 void SynthGetClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000115 void SynthCFStringFunctionDecl();
116
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000117 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000118 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
119 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000120
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000121 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
122 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000123
Steve Naroffb82c50f2007-11-11 17:19:15 +0000124 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000125 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000126 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000127 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000128 const char *ClassName,
129 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000130
131 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
132 int NumProtocols,
133 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000134 const char *ClassName,
135 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000136 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
137 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000138 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
139 ObjcIvarDecl *ivar,
140 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000141 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000142 };
143}
144
Chris Lattner569faa62007-10-11 18:38:32 +0000145ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000146
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000147//===----------------------------------------------------------------------===//
148// Top Level Driver Code
149//===----------------------------------------------------------------------===//
150
Chris Lattner569faa62007-10-11 18:38:32 +0000151void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000152 // Two cases: either the decl could be in the main file, or it could be in a
153 // #included file. If the former, rewrite it now. If the later, check to see
154 // if we rewrote the #include/#import.
155 SourceLocation Loc = D->getLocation();
156 Loc = SM->getLogicalLoc(Loc);
157
158 // If this is for a builtin, ignore it.
159 if (Loc.isInvalid()) return;
160
Steve Naroffe9780582007-10-23 23:50:29 +0000161 // Look for built-in declarations that we need to refer during the rewrite.
162 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000163 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000164 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
165 // declared in <Foundation/NSString.h>
166 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
167 ConstantStringClassReference = FVD;
168 return;
169 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000170 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
171 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000172 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
173 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000174 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
175 RewriteProtocolDecl(PD);
Steve Naroffe9780582007-10-23 23:50:29 +0000176 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000177 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000178 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
179 return HandleDeclInMainFile(D);
180
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000181 // Otherwise, see if there is a #import in the main file that should be
182 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000183 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000184}
185
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000186/// HandleDeclInMainFile - This is called for each top-level decl defined in the
187/// main file of the input.
188void RewriteTest::HandleDeclInMainFile(Decl *D) {
189 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
190 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000191 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000192
193 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
194 if (Stmt *Body = MD->getBody())
195 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
196 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000197 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
198 ClassImplementation.push_back(CI);
199 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
200 CategoryImplementation.push_back(CI);
201 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
202 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000203 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
204 if (VD->getInit())
205 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
206 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000207 // Nothing yet.
208}
209
210RewriteTest::~RewriteTest() {
211 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000212
213 // Rewrite tabs if we care.
214 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000215
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000216 // Rewrite Objective-c meta data*
217 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000218 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000219
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000220 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
221 // we are done.
222 if (const RewriteBuffer *RewriteBuf =
223 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000224 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000225 std::string S(RewriteBuf->begin(), RewriteBuf->end());
226 printf("%s\n", S.c_str());
227 } else {
228 printf("No changes\n");
229 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000230 // Emit metadata.
231 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000232}
233
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000234//===----------------------------------------------------------------------===//
235// Syntactic (non-AST) Rewriting Code
236//===----------------------------------------------------------------------===//
237
Chris Lattner74db1682007-10-16 21:07:07 +0000238void RewriteTest::RewriteInclude(SourceLocation Loc) {
239 // Rip up the #include stack to the main file.
240 SourceLocation IncLoc = Loc, NextLoc = Loc;
241 do {
242 IncLoc = Loc;
243 Loc = SM->getLogicalLoc(NextLoc);
244 NextLoc = SM->getIncludeLoc(Loc);
245 } while (!NextLoc.isInvalid());
246
247 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
248 // IncLoc indicates the header that was included if it is useful.
249 IncLoc = SM->getLogicalLoc(IncLoc);
250 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
251 Loc == LastIncLoc)
252 return;
253 LastIncLoc = Loc;
254
255 unsigned IncCol = SM->getColumnNumber(Loc);
256 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
257
258 // Replace the #import with #include.
259 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
260}
261
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000262void RewriteTest::RewriteTabs() {
263 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
264 const char *MainBufStart = MainBuf.first;
265 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000266
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000267 // Loop over the whole file, looking for tabs.
268 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
269 if (*BufPtr != '\t')
270 continue;
271
272 // Okay, we found a tab. This tab will turn into at least one character,
273 // but it depends on which 'virtual column' it is in. Compute that now.
274 unsigned VCol = 0;
275 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
276 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
277 ++VCol;
278
279 // Okay, now that we know the virtual column, we know how many spaces to
280 // insert. We assume 8-character tab-stops.
281 unsigned Spaces = 8-(VCol & 7);
282
283 // Get the location of the tab.
284 SourceLocation TabLoc =
285 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
286
287 // Rewrite the single tab character into a sequence of spaces.
288 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
289 }
Chris Lattner569faa62007-10-11 18:38:32 +0000290}
291
292
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000293void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
294 int numDecls = ClassDecl->getNumForwardDecls();
295 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
296
297 // Get the start location and compute the semi location.
298 SourceLocation startLoc = ClassDecl->getLocation();
299 const char *startBuf = SM->getCharacterData(startLoc);
300 const char *semiPtr = strchr(startBuf, ';');
301
302 // Translate to typedef's that forward reference structs with the same name
303 // as the class. As a convenience, we include the original declaration
304 // as a comment.
305 std::string typedefString;
306 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000307 typedefString.append(startBuf, semiPtr-startBuf+1);
308 typedefString += "\n";
309 for (int i = 0; i < numDecls; i++) {
310 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff809b4f02007-10-31 22:11:35 +0000311 if (ObjcForwardDecls.count(ForwardDecl))
312 continue;
Steve Naroff2aeae312007-11-09 12:50:28 +0000313 typedefString += "#ifndef _REWRITER_typedef_";
314 typedefString += ForwardDecl->getName();
315 typedefString += "\n";
316 typedefString += "#define _REWRITER_typedef_";
317 typedefString += ForwardDecl->getName();
318 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000319 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000320 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000321 typedefString += ";\n#endif\n";
Steve Naroff809b4f02007-10-31 22:11:35 +0000322 // Mark this typedef as having been generated.
323 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000324 assert(false && "typedef already output");
Steve Naroff71226032007-10-24 22:48:43 +0000325 }
326
327 // Replace the @class with typedefs corresponding to the classes.
328 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
329 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000330}
331
Steve Naroff18c83382007-11-13 23:01:27 +0000332void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000333 for (int i = 0; i < nMethods; i++) {
334 ObjcMethodDecl *Method = Methods[i];
335 SourceLocation Loc = Method->getLocStart();
336
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000337 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000338
339 // FIXME: handle methods that are declared across multiple lines.
340 }
341}
342
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000343void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
344{
345 for (int i = 0; i < nProperties; i++) {
346 ObjcPropertyDecl *Property = Properties[i];
347 SourceLocation Loc = Property->getLocation();
348
349 Rewrite.ReplaceText(Loc, 0, "// ", 3);
350
351 // FIXME: handle properties that are declared across multiple lines.
352 }
353}
354
Steve Naroff667f1682007-10-30 13:30:57 +0000355void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
356 SourceLocation LocStart = CatDecl->getLocStart();
357
358 // FIXME: handle category headers that are declared across multiple lines.
359 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
360
Steve Naroff18c83382007-11-13 23:01:27 +0000361 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
362 CatDecl->getInstanceMethods());
363 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
364 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000365 // Lastly, comment out the @end.
366 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
367}
368
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000369void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
370 SourceLocation LocStart = PDecl->getLocStart();
371
372 // FIXME: handle protocol headers that are declared across multiple lines.
373 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
374
Steve Naroff18c83382007-11-13 23:01:27 +0000375 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
376 PDecl->getInstanceMethods());
377 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
378 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000379 // Lastly, comment out the @end.
380 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
381}
382
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000383void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
384 std::string &ResultStr) {
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000385 static bool includeObjc = false;
386 if (!includeObjc) {
387 ResultStr += "#include <Objc/objc.h>\n";
388 includeObjc = true;
389 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000390 ResultStr += "\nstatic ";
391 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000392 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000393
394 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000395 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000396
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000397 if (OMD->isInstance())
398 NameStr += "_I_";
399 else
400 NameStr += "_C_";
401
402 NameStr += OMD->getClassInterface()->getName();
403 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000404
405 NamedDecl *MethodContext = OMD->getMethodContext();
406 if (ObjcCategoryImplDecl *CID =
407 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000408 NameStr += CID->getName();
409 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000410 }
411 // Append selector names, replacing ':' with '_'
412 const char *selName = OMD->getSelector().getName().c_str();
413 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000414 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000415 else {
416 std::string selString = OMD->getSelector().getName();
417 int len = selString.size();
418 for (int i = 0; i < len; i++)
419 if (selString[i] == ':')
420 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000421 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000422 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000423 // Remember this name for metadata emission
424 MethodInternalNames[OMD] = NameStr;
425 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000426
427 // Rewrite arguments
428 ResultStr += "(";
429
430 // invisible arguments
431 if (OMD->isInstance()) {
432 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
433 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000434 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
435 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000436 ResultStr += selfTy.getAsString();
437 }
438 else
439 ResultStr += Context->getObjcIdType().getAsString();
440
441 ResultStr += " self, ";
442 ResultStr += Context->getObjcSelType().getAsString();
443 ResultStr += " _cmd";
444
445 // Method arguments.
446 for (int i = 0; i < OMD->getNumParams(); i++) {
447 ParmVarDecl *PDecl = OMD->getParamDecl(i);
448 ResultStr += ", ";
449 ResultStr += PDecl->getType().getAsString();
450 ResultStr += " ";
451 ResultStr += PDecl->getName();
452 }
453 ResultStr += ")";
454
455}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000456void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
457 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
458 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000459
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000460 if (IMD)
461 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
462 else
463 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000464
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000465 int numMethods = IMD ? IMD->getNumInstanceMethods()
466 : CID->getNumInstanceMethods();
467
468 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000469 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000470 ObjcMethodDecl *OMD;
471 if (IMD)
472 OMD = IMD->getInstanceMethods()[i];
473 else
474 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000475 RewriteObjcMethodDecl(OMD, ResultStr);
476 SourceLocation LocStart = OMD->getLocStart();
477 SourceLocation LocEnd = OMD->getBody()->getLocStart();
478
479 const char *startBuf = SM->getCharacterData(LocStart);
480 const char *endBuf = SM->getCharacterData(LocEnd);
481 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
482 ResultStr.c_str(), ResultStr.size());
483 }
484
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000485 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
486 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000487 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000488 ObjcMethodDecl *OMD;
489 if (IMD)
490 OMD = IMD->getClassMethods()[i];
491 else
492 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000493 RewriteObjcMethodDecl(OMD, ResultStr);
494 SourceLocation LocStart = OMD->getLocStart();
495 SourceLocation LocEnd = OMD->getBody()->getLocStart();
496
497 const char *startBuf = SM->getCharacterData(LocStart);
498 const char *endBuf = SM->getCharacterData(LocEnd);
499 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
500 ResultStr.c_str(), ResultStr.size());
501 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000502 if (IMD)
503 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
504 else
505 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000506}
507
Steve Naroff3774dd92007-10-26 20:53:56 +0000508void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000509
510 SourceLocation LocStart = ClassDecl->getLocStart();
511 SourceLocation LocEnd = ClassDecl->getLocEnd();
512
513 const char *startBuf = SM->getCharacterData(LocStart);
514 const char *endBuf = SM->getCharacterData(LocEnd);
515
Steve Naroff1ccf4632007-10-30 03:43:13 +0000516 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Naroffef20ed32007-10-30 02:23:23 +0000517
518 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000519 if (!ObjcForwardDecls.count(ClassDecl)) {
520 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2aeae312007-11-09 12:50:28 +0000521 ResultStr += "#ifndef _REWRITER_typedef_";
522 ResultStr += ClassDecl->getName();
523 ResultStr += "\n";
524 ResultStr += "#define _REWRITER_typedef_";
525 ResultStr += ClassDecl->getName();
526 ResultStr += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000527 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000528 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000529 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000530
531 // Mark this typedef as having been generated.
532 ObjcForwardDecls.insert(ClassDecl);
533 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000534 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
535
Steve Naroff1ccf4632007-10-30 03:43:13 +0000536 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Naroffef20ed32007-10-30 02:23:23 +0000537 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000538 RewriteProperties(ClassDecl->getNumPropertyDecl(),
539 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000540 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
541 ClassDecl->getInstanceMethods());
542 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
543 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000544
Steve Naroff1ccf4632007-10-30 03:43:13 +0000545 // Lastly, comment out the @end.
546 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000547}
548
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000549//===----------------------------------------------------------------------===//
550// Function Body / Expression rewriting
551//===----------------------------------------------------------------------===//
552
Steve Naroff334fbc22007-11-09 15:20:18 +0000553Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000554 // Otherwise, just rewrite all children.
555 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
556 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000557 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000558 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000559 if (newStmt)
560 *CI = newStmt;
561 }
Steve Naroffe9780582007-10-23 23:50:29 +0000562
563 // Handle specific things.
564 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
565 return RewriteAtEncode(AtEncode);
Steve Naroff296b74f2007-11-05 14:50:49 +0000566
567 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
568 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000569
570 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
571 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000572
Steve Naroff71226032007-10-24 22:48:43 +0000573 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
574 // Before we rewrite it, put the original message expression in a comment.
575 SourceLocation startLoc = MessExpr->getLocStart();
576 SourceLocation endLoc = MessExpr->getLocEnd();
577
578 const char *startBuf = SM->getCharacterData(startLoc);
579 const char *endBuf = SM->getCharacterData(endLoc);
580
581 std::string messString;
582 messString += "// ";
583 messString.append(startBuf, endBuf-startBuf+1);
584 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000585
Steve Naroff71226032007-10-24 22:48:43 +0000586 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
587 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
588 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000589 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000590 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000591 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000592
593 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
594 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000595
596 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
597 return RewriteObjcThrowStmt(StmtThrow);
598
Chris Lattner0021f452007-10-24 16:57:36 +0000599 // Return this stmt unmodified.
600 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000601}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000602
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000603Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000604 // Get the start location and compute the semi location.
605 SourceLocation startLoc = S->getLocStart();
606 const char *startBuf = SM->getCharacterData(startLoc);
607
608 assert((*startBuf == '@') && "bogus @try location");
609
610 std::string buf;
611 // declare a new scope with two variables, _stack and _rethrow.
612 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
613 buf += "int buf[18/*32-bit i386*/];\n";
614 buf += "char *pointers[4];} _stack;\n";
615 buf += "id volatile _rethrow = 0;\n";
616 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000617 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000618
619 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
620
621 startLoc = S->getTryBody()->getLocEnd();
622 startBuf = SM->getCharacterData(startLoc);
623
624 assert((*startBuf == '}') && "bogus @try block");
625
626 SourceLocation lastCurlyLoc = startLoc;
627
628 startLoc = startLoc.getFileLocWithOffset(1);
629 buf = " /* @catch begin */ else {\n";
630 buf += " id _caught = objc_exception_extract(&_stack);\n";
631 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000632 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000633 buf += " _rethrow = objc_exception_extract(&_stack);\n";
634 buf += " else { /* @catch continue */";
635
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000636 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000637
638 bool sawIdTypedCatch = false;
639 Stmt *lastCatchBody = 0;
640 ObjcAtCatchStmt *catchList = S->getCatchStmts();
641 while (catchList) {
642 Stmt *catchStmt = catchList->getCatchParamStmt();
643
644 if (catchList == S->getCatchStmts())
645 buf = "if ("; // we are generating code for the first catch clause
646 else
647 buf = "else if (";
648 startLoc = catchList->getLocStart();
649 startBuf = SM->getCharacterData(startLoc);
650
651 assert((*startBuf == '@') && "bogus @catch location");
652
653 const char *lParenLoc = strchr(startBuf, '(');
654
655 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
656 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
657 if (t == Context->getObjcIdType()) {
658 buf += "1) { ";
659 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
660 buf.c_str(), buf.size());
661 sawIdTypedCatch = true;
662 } else if (const PointerType *pType = t->getAsPointerType()) {
663 ObjcInterfaceType *cls; // Should be a pointer to a class.
664
665 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
666 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000667 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000668 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000669 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000670 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
671 buf.c_str(), buf.size());
672 }
673 }
674 // Now rewrite the body...
675 lastCatchBody = catchList->getCatchBody();
676 SourceLocation rParenLoc = catchList->getRParenLoc();
677 SourceLocation bodyLoc = lastCatchBody->getLocStart();
678 const char *bodyBuf = SM->getCharacterData(bodyLoc);
679 const char *rParenBuf = SM->getCharacterData(rParenLoc);
680 assert((*rParenBuf == ')') && "bogus @catch paren location");
681 assert((*bodyBuf == '{') && "bogus @catch body location");
682
683 buf = " = _caught;";
684 // Here we replace ") {" with "= _caught;" (which initializes and
685 // declares the @catch parameter).
686 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
687 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000688 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000689 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000690 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000691 catchList = catchList->getNextCatchStmt();
692 }
693 // Complete the catch list...
694 if (lastCatchBody) {
695 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
696 const char *bodyBuf = SM->getCharacterData(bodyLoc);
697 assert((*bodyBuf == '}') && "bogus @catch body location");
698 bodyLoc = bodyLoc.getFileLocWithOffset(1);
699 buf = " } } /* @catch end */\n";
700
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000701 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000702
703 // Set lastCurlyLoc
704 lastCurlyLoc = lastCatchBody->getLocEnd();
705 }
706 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
707 startLoc = finalStmt->getLocStart();
708 startBuf = SM->getCharacterData(startLoc);
709 assert((*startBuf == '@') && "bogus @finally start");
710
711 buf = "/* @finally */";
712 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
713
714 Stmt *body = finalStmt->getFinallyBody();
715 SourceLocation startLoc = body->getLocStart();
716 SourceLocation endLoc = body->getLocEnd();
717 const char *startBuf = SM->getCharacterData(startLoc);
718 const char *endBuf = SM->getCharacterData(endLoc);
719 assert((*startBuf == '{') && "bogus @finally body location");
720 assert((*endBuf == '}') && "bogus @finally body location");
721
722 startLoc = startLoc.getFileLocWithOffset(1);
723 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000724 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000725 endLoc = endLoc.getFileLocWithOffset(-1);
726 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000727 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000728
729 // Set lastCurlyLoc
730 lastCurlyLoc = body->getLocEnd();
731 }
732 // Now emit the final closing curly brace...
733 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
734 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000735 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000736 return 0;
737}
738
739Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
740 return 0;
741}
742
743Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
744 return 0;
745}
746
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000747// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
748// the throw expression is typically a message expression that's already
749// been rewritten! (which implies the SourceLocation's are invalid).
750Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
751 // Get the start location and compute the semi location.
752 SourceLocation startLoc = S->getLocStart();
753 const char *startBuf = SM->getCharacterData(startLoc);
754
755 assert((*startBuf == '@') && "bogus @throw location");
756
757 std::string buf;
758 /* void objc_exception_throw(id) __attribute__((noreturn)); */
759 buf = "objc_exception_throw(";
760 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
761 const char *semiBuf = strchr(startBuf, ';');
762 assert((*semiBuf == ';') && "@throw: can't find ';'");
763 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
764 buf = ");";
765 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
766 return 0;
767}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000768
Chris Lattner0021f452007-10-24 16:57:36 +0000769Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000770 // Create a new string expression.
771 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000772 std::string StrEncoding;
773 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
774 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
775 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000776 SourceLocation(), SourceLocation());
777 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000778 delete Exp;
779 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000780}
781
Steve Naroff296b74f2007-11-05 14:50:49 +0000782Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
783 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
784 // Create a call to sel_registerName("selName").
785 llvm::SmallVector<Expr*, 8> SelExprs;
786 QualType argType = Context->getPointerType(Context->CharTy);
787 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
788 Exp->getSelector().getName().size(),
789 false, argType, SourceLocation(),
790 SourceLocation()));
791 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
792 &SelExprs[0], SelExprs.size());
793 Rewrite.ReplaceStmt(Exp, SelExp);
794 delete Exp;
795 return SelExp;
796}
797
Steve Naroff71226032007-10-24 22:48:43 +0000798CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
799 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000800 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000801 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000802
803 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000804 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000805
806 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000807 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000808 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
809
810 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000811
Steve Naroff71226032007-10-24 22:48:43 +0000812 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
813}
814
Steve Naroffc8a92d12007-11-01 13:24:47 +0000815static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
816 const char *&startRef, const char *&endRef) {
817 while (startBuf < endBuf) {
818 if (*startBuf == '<')
819 startRef = startBuf; // mark the start.
820 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000821 if (startRef && *startRef == '<') {
822 endRef = startBuf; // mark the end.
823 return true;
824 }
825 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000826 }
827 startBuf++;
828 }
829 return false;
830}
831
832bool RewriteTest::needToScanForQualifiers(QualType T) {
833 // FIXME: we don't currently represent "id <Protocol>" in the type system.
834 if (T == Context->getObjcIdType())
835 return true;
836
837 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000838 Type *pointeeType = pType->getPointeeType().getTypePtr();
839 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
840 return true; // we have "Class <Protocol> *".
841 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000842 return false;
843}
844
845void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
846 const FunctionTypeProto *proto, FunctionDecl *FD) {
847
848 if (needToScanForQualifiers(proto->getResultType())) {
849 // Since types are unique, we need to scan the buffer.
850 SourceLocation Loc = FD->getLocation();
851
852 const char *endBuf = SM->getCharacterData(Loc);
853 const char *startBuf = endBuf;
854 while (*startBuf != ';')
855 startBuf--; // scan backward (from the decl location) for return type.
856 const char *startRef = 0, *endRef = 0;
857 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
858 // Get the locations of the startRef, endRef.
859 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
860 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
861 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000862 Rewrite.InsertText(LessLoc, "/*", 2);
863 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000864 }
865 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000866 // Now check arguments.
867 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
868 if (needToScanForQualifiers(proto->getArgType(i))) {
869 // Since types are unique, we need to scan the buffer.
870 SourceLocation Loc = FD->getLocation();
871
872 const char *startBuf = SM->getCharacterData(Loc);
873 const char *endBuf = startBuf;
874 while (*endBuf != ';')
875 endBuf++; // scan forward (from the decl location) for argument types.
876 const char *startRef = 0, *endRef = 0;
877 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
878 // Get the locations of the startRef, endRef.
879 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
880 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
881 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000882 Rewrite.InsertText(LessLoc, "/*", 2);
883 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000884 }
885 }
886 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000887}
888
Steve Naroff02a82aa2007-10-30 23:14:51 +0000889void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
890 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000891 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000892 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000893 return;
894 }
895 // Check for ObjC 'id' and class types that have been adorned with protocol
896 // information (id<p>, C<p>*). The protocol references need to be rewritten!
897 const FunctionType *funcType = FD->getType()->getAsFunctionType();
898 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000899 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
900 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000901}
902
903// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
904void RewriteTest::SynthMsgSendFunctionDecl() {
905 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
906 llvm::SmallVector<QualType, 16> ArgTys;
907 QualType argT = Context->getObjcIdType();
908 assert(!argT.isNull() && "Can't find 'id' type");
909 ArgTys.push_back(argT);
910 argT = Context->getObjcSelType();
911 assert(!argT.isNull() && "Can't find 'SEL' type");
912 ArgTys.push_back(argT);
913 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
914 &ArgTys[0], ArgTys.size(),
915 true /*isVariadic*/);
916 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
917 msgSendIdent, msgSendType,
918 FunctionDecl::Extern, false, 0);
919}
920
921// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
922void RewriteTest::SynthGetClassFunctionDecl() {
923 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
924 llvm::SmallVector<QualType, 16> ArgTys;
925 ArgTys.push_back(Context->getPointerType(
926 Context->CharTy.getQualifiedType(QualType::Const)));
927 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
928 &ArgTys[0], ArgTys.size(),
929 false /*isVariadic*/);
930 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
931 getClassIdent, getClassType,
932 FunctionDecl::Extern, false, 0);
933}
934
Steve Naroffabb96362007-11-08 14:30:50 +0000935// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
936void RewriteTest::SynthCFStringFunctionDecl() {
937 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
938 llvm::SmallVector<QualType, 16> ArgTys;
939 ArgTys.push_back(Context->getPointerType(
940 Context->CharTy.getQualifiedType(QualType::Const)));
941 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
942 &ArgTys[0], ArgTys.size(),
943 false /*isVariadic*/);
944 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
945 getClassIdent, getClassType,
946 FunctionDecl::Extern, false, 0);
947}
948
Steve Naroff0add5d22007-11-03 11:27:19 +0000949Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +0000950#if 1
951 // This rewrite is specific to GCC, which has builtin support for CFString.
952 if (!CFStringFunctionDecl)
953 SynthCFStringFunctionDecl();
954 // Create a call to __builtin___CFStringMakeConstantString("cstr").
955 llvm::SmallVector<Expr*, 8> StrExpr;
956 StrExpr.push_back(Exp->getString());
957 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
958 &StrExpr[0], StrExpr.size());
959 // cast to NSConstantString *
960 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
961 Rewrite.ReplaceStmt(Exp, cast);
962 delete Exp;
963 return cast;
964#else
Steve Naroff0add5d22007-11-03 11:27:19 +0000965 assert(ConstantStringClassReference && "Can't find constant string reference");
966 llvm::SmallVector<Expr*, 4> InitExprs;
967
968 // Synthesize "(Class)&_NSConstantStringClassReference"
969 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
970 ConstantStringClassReference->getType(),
971 SourceLocation());
972 QualType expType = Context->getPointerType(ClsRef->getType());
973 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
974 expType, SourceLocation());
975 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
976 SourceLocation());
977 InitExprs.push_back(cast); // set the 'isa'.
978 InitExprs.push_back(Exp->getString()); // set "char *bytes".
979 unsigned IntSize = static_cast<unsigned>(
980 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
981 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
982 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
983 Exp->getLocStart());
984 InitExprs.push_back(len); // set "int numBytes".
985
986 // struct NSConstantString
987 QualType CFConstantStrType = Context->getCFConstantStringType();
988 // (struct NSConstantString) { <exprs from above> }
989 InitListExpr *ILE = new InitListExpr(SourceLocation(),
990 &InitExprs[0], InitExprs.size(),
991 SourceLocation());
992 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
993 // struct NSConstantString *
994 expType = Context->getPointerType(StrRep->getType());
995 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
996 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +0000997 // cast to NSConstantString *
998 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +0000999 Rewrite.ReplaceStmt(Exp, cast);
1000 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001001 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001002#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001003}
1004
Steve Naroff71226032007-10-24 22:48:43 +00001005Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +00001006 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +00001007 if (!MsgSendFunctionDecl)
1008 SynthMsgSendFunctionDecl();
1009 if (!GetClassFunctionDecl)
1010 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +00001011
1012 // Synthesize a call to objc_msgSend().
1013 llvm::SmallVector<Expr*, 8> MsgExprs;
1014 IdentifierInfo *clsName = Exp->getClassName();
1015
1016 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1017 if (clsName) { // class message.
1018 llvm::SmallVector<Expr*, 8> ClsExprs;
1019 QualType argType = Context->getPointerType(Context->CharTy);
1020 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1021 clsName->getLength(),
1022 false, argType, SourceLocation(),
1023 SourceLocation()));
1024 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1025 &ClsExprs[0], ClsExprs.size());
1026 MsgExprs.push_back(Cls);
1027 } else // instance message.
1028 MsgExprs.push_back(Exp->getReceiver());
1029
Steve Naroff0add5d22007-11-03 11:27:19 +00001030 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001031 llvm::SmallVector<Expr*, 8> SelExprs;
1032 QualType argType = Context->getPointerType(Context->CharTy);
1033 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1034 Exp->getSelector().getName().size(),
1035 false, argType, SourceLocation(),
1036 SourceLocation()));
1037 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1038 &SelExprs[0], SelExprs.size());
1039 MsgExprs.push_back(SelExp);
1040
1041 // Now push any user supplied arguments.
1042 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1043 MsgExprs.push_back(Exp->getArg(i));
1044 // We've transferred the ownership to MsgExprs. Null out the argument in
1045 // the original expression, since we will delete it below.
1046 Exp->setArg(i, 0);
1047 }
Steve Naroff0744c472007-11-04 22:37:50 +00001048 // Generate the funky cast.
1049 CastExpr *cast;
1050 llvm::SmallVector<QualType, 8> ArgTypes;
1051 QualType returnType;
1052
1053 // Push 'id' and 'SEL', the 2 implicit arguments.
1054 ArgTypes.push_back(Context->getObjcIdType());
1055 ArgTypes.push_back(Context->getObjcSelType());
1056 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1057 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001058 for (int i = 0; i < mDecl->getNumParams(); i++) {
1059 QualType t = mDecl->getParamDecl(i)->getType();
1060 if (t == Context->getObjcClassType())
1061 t = Context->getObjcIdType(); // Convert "Class"->"id"
1062 ArgTypes.push_back(t);
1063 }
Steve Naroff0744c472007-11-04 22:37:50 +00001064 returnType = mDecl->getResultType();
1065 } else {
1066 returnType = Context->getObjcIdType();
1067 }
1068 // Get the type, we will need to reference it in a couple spots.
1069 QualType msgSendType = MsgSendFunctionDecl->getType();
1070
1071 // Create a reference to the objc_msgSend() declaration.
1072 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1073
1074 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1075 // If we don't do this cast, we get the following bizarre warning/note:
1076 // xx.m:13: warning: function called through a non-compatible type
1077 // xx.m:13: note: if this code is reached, the program will abort
1078 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1079 SourceLocation());
1080
1081 // Now do the "normal" pointer to function cast.
1082 QualType castType = Context->getFunctionType(returnType,
1083 &ArgTypes[0], ArgTypes.size(),
1084 false/*FIXME:variadic*/);
1085 castType = Context->getPointerType(castType);
1086 cast = new CastExpr(castType, cast, SourceLocation());
1087
1088 // Don't forget the parens to enforce the proper binding.
1089 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1090
1091 const FunctionType *FT = msgSendType->getAsFunctionType();
1092 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1093 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001094 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001095 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001096
Chris Lattner0021f452007-10-24 16:57:36 +00001097 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001098 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001099}
1100
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001101/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1102/// an objective-c class with ivars.
1103void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1104 std::string &Result) {
1105 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1106 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001107 // Do not synthesize more than once.
1108 if (ObjcSynthesizedStructs.count(CDecl))
1109 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001110 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1111 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1112 // Do it for the root
1113 SynthesizeObjcInternalStruct(RCDecl, Result);
1114 }
1115
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001116 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001117 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +00001118 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001119 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1120 return;
1121
Steve Naroffb1147382007-11-01 17:12:31 +00001122 Result += "\nstruct ";
1123 Result += CDecl->getName();
1124 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1125 Result += " {\n struct ";
1126 Result += RCDecl->getName();
1127 Result += " _";
1128 Result += RCDecl->getName();
1129 Result += ";\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001130 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001131 else
1132 Result += " {";
Steve Naroff809b4f02007-10-31 22:11:35 +00001133
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001134 if (NumIvars > 0) {
1135 SourceLocation LocStart = CDecl->getLocStart();
1136 SourceLocation LocEnd = CDecl->getLocEnd();
1137
1138 const char *startBuf = SM->getCharacterData(LocStart);
1139 const char *endBuf = SM->getCharacterData(LocEnd);
1140 startBuf = strchr(startBuf, '{');
1141 assert((startBuf && endBuf)
1142 && "SynthesizeObjcInternalStruct - malformed @interface");
1143 startBuf++; // past '{'
1144 while (startBuf < endBuf) {
1145 if (*startBuf == '@') {
1146 startBuf = strchr(startBuf, 'p');
1147 // FIXME: presence of @public, etc. inside comment results in
1148 // this transformation as well, which is still correct c-code.
1149 if (!strncmp(startBuf, "public", strlen("public"))) {
1150 startBuf += strlen("public");
1151 Result += "/* @public */";
1152 }
1153 else if (!strncmp(startBuf, "private", strlen("private"))) {
1154 startBuf += strlen("private");
1155 Result += "/* @private */";
1156 }
1157 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1158 startBuf += strlen("protected");
1159 Result += "/* @protected */";
1160 }
1161 }
1162 Result += *startBuf++;
1163 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001164 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001165
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001166 Result += "};\n";
1167 // Mark this struct as having been generated.
1168 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001169 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001170}
1171
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001172// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1173/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001174void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001175 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001176 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001177 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001178 const char *ClassName,
1179 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001180 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001181 if (NumMethods > 0 && !objc_impl_method) {
1182 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001183 SEL _cmd;
1184 char *method_types;
1185 void *_imp;
1186 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001187 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001188 Result += "\nstruct _objc_method {\n";
1189 Result += "\tSEL _cmd;\n";
1190 Result += "\tchar *method_types;\n";
1191 Result += "\tvoid *_imp;\n";
1192 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001193
1194 /* struct _objc_method_list {
1195 struct _objc_method_list *next_method;
1196 int method_count;
1197 struct _objc_method method_list[];
1198 }
1199 */
1200 Result += "\nstruct _objc_method_list {\n";
1201 Result += "\tstruct _objc_method_list *next_method;\n";
1202 Result += "\tint method_count;\n";
1203 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001204 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001205 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001206 // Build _objc_method_list for class's methods if needed
1207 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001208 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001209 Result += prefix;
1210 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1211 Result += "_METHODS_";
1212 Result += ClassName;
1213 Result += " __attribute__ ((section (\"__OBJC, __";
1214 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001215 Result += "_meth\")))= ";
1216 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1217
1218 Result += "\t,{{(SEL)\"";
1219 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001220 std::string MethodTypeString;
1221 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1222 Result += "\", \"";
1223 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001224 Result += "\", ";
1225 Result += MethodInternalNames[Methods[0]];
1226 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001227 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001228 Result += "\t ,{(SEL)\"";
1229 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001230 std::string MethodTypeString;
1231 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1232 Result += "\", \"";
1233 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001234 Result += "\", ";
1235 Result += MethodInternalNames[Methods[i]];
1236 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001237 }
1238 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001239 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001240}
1241
1242/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1243void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1244 int NumProtocols,
1245 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001246 const char *ClassName,
1247 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001248 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001249 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001250 for (int i = 0; i < NumProtocols; i++) {
1251 ObjcProtocolDecl *PDecl = Protocols[i];
1252 // Output struct protocol_methods holder of method selector and type.
1253 if (!objc_protocol_methods &&
1254 (PDecl->getNumInstanceMethods() > 0
1255 || PDecl->getNumClassMethods() > 0)) {
1256 /* struct protocol_methods {
1257 SEL _cmd;
1258 char *method_types;
1259 }
1260 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001261 Result += "\nstruct protocol_methods {\n";
1262 Result += "\tSEL _cmd;\n";
1263 Result += "\tchar *method_types;\n";
1264 Result += "};\n";
1265
1266 /* struct _objc_protocol_method_list {
1267 int protocol_method_count;
1268 struct protocol_methods protocols[];
1269 }
1270 */
1271 Result += "\nstruct _objc_protocol_method_list {\n";
1272 Result += "\tint protocol_method_count;\n";
1273 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001274 objc_protocol_methods = true;
1275 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001276
Fariborz Jahanian04455192007-10-22 21:41:37 +00001277 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001278 int NumMethods = PDecl->getNumInstanceMethods();
1279 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001280 Result += "\nstatic struct _objc_protocol_method_list "
1281 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1282 Result += PDecl->getName();
1283 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1284 "{\n\t" + utostr(NumMethods) + "\n";
1285
Fariborz Jahanian04455192007-10-22 21:41:37 +00001286 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001287 Result += "\t,{{(SEL)\"";
1288 Result += Methods[0]->getSelector().getName().c_str();
1289 Result += "\", \"\"}\n";
1290
1291 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001292 Result += "\t ,{(SEL)\"";
1293 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001294 std::string MethodTypeString;
1295 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1296 Result += "\", \"";
1297 Result += MethodTypeString;
1298 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001299 }
1300 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001301 }
1302
1303 // Output class methods declared in this protocol.
1304 NumMethods = PDecl->getNumClassMethods();
1305 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001306 Result += "\nstatic struct _objc_protocol_method_list "
1307 "_OBJC_PROTOCOL_CLASS_METHODS_";
1308 Result += PDecl->getName();
1309 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1310 "{\n\t";
1311 Result += utostr(NumMethods);
1312 Result += "\n";
1313
Fariborz Jahanian04455192007-10-22 21:41:37 +00001314 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001315 Result += "\t,{{(SEL)\"";
1316 Result += Methods[0]->getSelector().getName().c_str();
1317 Result += "\", \"\"}\n";
1318
1319 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001320 Result += "\t ,{(SEL)\"";
1321 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001322 std::string MethodTypeString;
1323 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1324 Result += "\", \"";
1325 Result += MethodTypeString;
1326 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001327 }
1328 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001329 }
1330 // Output:
1331 /* struct _objc_protocol {
1332 // Objective-C 1.0 extensions
1333 struct _objc_protocol_extension *isa;
1334 char *protocol_name;
1335 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001336 struct _objc_protocol_method_list *instance_methods;
1337 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001338 };
1339 */
1340 static bool objc_protocol = false;
1341 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001342 Result += "\nstruct _objc_protocol {\n";
1343 Result += "\tstruct _objc_protocol_extension *isa;\n";
1344 Result += "\tchar *protocol_name;\n";
1345 Result += "\tstruct _objc_protocol **protocol_list;\n";
1346 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1347 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1348 Result += "};\n";
1349
1350 /* struct _objc_protocol_list {
1351 struct _objc_protocol_list *next;
1352 int protocol_count;
1353 struct _objc_protocol *class_protocols[];
1354 }
1355 */
1356 Result += "\nstruct _objc_protocol_list {\n";
1357 Result += "\tstruct _objc_protocol_list *next;\n";
1358 Result += "\tint protocol_count;\n";
1359 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1360 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001361 objc_protocol = true;
1362 }
1363
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001364 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1365 Result += PDecl->getName();
1366 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1367 "{\n\t0, \"";
1368 Result += PDecl->getName();
1369 Result += "\", 0, ";
1370 if (PDecl->getInstanceMethods() > 0) {
1371 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1372 Result += PDecl->getName();
1373 Result += ", ";
1374 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001375 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001376 Result += "0, ";
1377 if (PDecl->getClassMethods() > 0) {
1378 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1379 Result += PDecl->getName();
1380 Result += "\n";
1381 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001382 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001383 Result += "0\n";
1384 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001385 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001386 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001387 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1388 Result += prefix;
1389 Result += "_PROTOCOLS_";
1390 Result += ClassName;
1391 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1392 "{\n\t0, ";
1393 Result += utostr(NumProtocols);
1394 Result += "\n";
1395
1396 Result += "\t,{&_OBJC_PROTOCOL_";
1397 Result += Protocols[0]->getName();
1398 Result += " \n";
1399
1400 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001401 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001402 Result += "\t ,&_OBJC_PROTOCOL_";
1403 Result += PDecl->getName();
1404 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001405 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001406 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001407 }
1408}
1409
1410/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1411/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001412void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1413 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001414 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1415 // Find category declaration for this implementation.
1416 ObjcCategoryDecl *CDecl;
1417 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1418 CDecl = CDecl->getNextClassCategory())
1419 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1420 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001421
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001422 char *FullCategoryName = (char*)alloca(
1423 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1424 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1425
1426 // Build _objc_method_list for class's instance methods if needed
1427 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1428 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001429 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001430 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001431
1432 // Build _objc_method_list for class's class methods if needed
1433 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1434 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001435 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001436 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001437
1438 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001439 // Null CDecl is case of a category implementation with no category interface
1440 if (CDecl)
1441 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1442 CDecl->getNumReferencedProtocols(),
1443 "CATEGORY",
1444 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001445
1446 /* struct _objc_category {
1447 char *category_name;
1448 char *class_name;
1449 struct _objc_method_list *instance_methods;
1450 struct _objc_method_list *class_methods;
1451 struct _objc_protocol_list *protocols;
1452 // Objective-C 1.0 extensions
1453 uint32_t size; // sizeof (struct _objc_category)
1454 struct _objc_property_list *instance_properties; // category's own
1455 // @property decl.
1456 };
1457 */
1458
1459 static bool objc_category = false;
1460 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001461 Result += "\nstruct _objc_category {\n";
1462 Result += "\tchar *category_name;\n";
1463 Result += "\tchar *class_name;\n";
1464 Result += "\tstruct _objc_method_list *instance_methods;\n";
1465 Result += "\tstruct _objc_method_list *class_methods;\n";
1466 Result += "\tstruct _objc_protocol_list *protocols;\n";
1467 Result += "\tunsigned int size;\n";
1468 Result += "\tstruct _objc_property_list *instance_properties;\n";
1469 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001470 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001471 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001472 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1473 Result += FullCategoryName;
1474 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1475 Result += IDecl->getName();
1476 Result += "\"\n\t, \"";
1477 Result += ClassDecl->getName();
1478 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001479
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001480 if (IDecl->getNumInstanceMethods() > 0) {
1481 Result += "\t, (struct _objc_method_list *)"
1482 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1483 Result += FullCategoryName;
1484 Result += "\n";
1485 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001486 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001487 Result += "\t, 0\n";
1488 if (IDecl->getNumClassMethods() > 0) {
1489 Result += "\t, (struct _objc_method_list *)"
1490 "&_OBJC_CATEGORY_CLASS_METHODS_";
1491 Result += FullCategoryName;
1492 Result += "\n";
1493 }
1494 else
1495 Result += "\t, 0\n";
1496
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001497 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001498 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1499 Result += FullCategoryName;
1500 Result += "\n";
1501 }
1502 else
1503 Result += "\t, 0\n";
1504 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001505}
1506
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001507/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1508/// ivar offset.
1509void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1510 ObjcIvarDecl *ivar,
1511 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001512 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001513 Result += IDecl->getName();
1514 Result += ", ";
1515 Result += ivar->getName();
1516 Result += ")";
1517}
1518
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001519//===----------------------------------------------------------------------===//
1520// Meta Data Emission
1521//===----------------------------------------------------------------------===//
1522
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001523void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1524 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001525 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1526
1527 // Build _objc_ivar_list metadata for classes ivars if needed
1528 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1529 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001530 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001531
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001532 SynthesizeObjcInternalStruct(CDecl, Result);
1533
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001534 if (NumIvars > 0) {
1535 static bool objc_ivar = false;
1536 if (!objc_ivar) {
1537 /* struct _objc_ivar {
1538 char *ivar_name;
1539 char *ivar_type;
1540 int ivar_offset;
1541 };
1542 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001543 Result += "\nstruct _objc_ivar {\n";
1544 Result += "\tchar *ivar_name;\n";
1545 Result += "\tchar *ivar_type;\n";
1546 Result += "\tint ivar_offset;\n";
1547 Result += "};\n";
1548
1549 /* struct _objc_ivar_list {
1550 int ivar_count;
1551 struct _objc_ivar ivar_list[];
1552 };
1553 */
1554 Result += "\nstruct _objc_ivar_list {\n";
1555 Result += "\tint ivar_count;\n";
1556 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001557 objc_ivar = true;
1558 }
1559
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001560 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1561 Result += IDecl->getName();
1562 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1563 "{\n\t";
1564 Result += utostr(NumIvars);
1565 Result += "\n";
1566
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001567 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1568 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001569 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001570 Result += "\t,{{\"";
1571 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001572 Result += "\", \"";
1573 std::string StrEncoding;
1574 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1575 Result += StrEncoding;
1576 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001577 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1578 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001579 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001580 Result += "\t ,{\"";
1581 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001582 Result += "\", \"";
1583 std::string StrEncoding;
1584 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1585 Result += StrEncoding;
1586 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001587 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1588 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001589 }
1590
1591 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001592 }
1593
1594 // Build _objc_method_list for class's instance methods if needed
1595 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1596 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001597 true,
1598 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001599
1600 // Build _objc_method_list for class's class methods if needed
1601 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001602 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001603 false,
1604 "", IDecl->getName(), Result);
1605
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001606 // Protocols referenced in class declaration?
1607 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1608 CDecl->getNumIntfRefProtocols(),
1609 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001610 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001611
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001612
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001613 // Declaration of class/meta-class metadata
1614 /* struct _objc_class {
1615 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001616 const char *super_class_name;
1617 char *name;
1618 long version;
1619 long info;
1620 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001621 struct _objc_ivar_list *ivars;
1622 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001623 struct objc_cache *cache;
1624 struct objc_protocol_list *protocols;
1625 const char *ivar_layout;
1626 struct _objc_class_ext *ext;
1627 };
1628 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001629 static bool objc_class = false;
1630 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001631 Result += "\nstruct _objc_class {\n";
1632 Result += "\tstruct _objc_class *isa;\n";
1633 Result += "\tconst char *super_class_name;\n";
1634 Result += "\tchar *name;\n";
1635 Result += "\tlong version;\n";
1636 Result += "\tlong info;\n";
1637 Result += "\tlong instance_size;\n";
1638 Result += "\tstruct _objc_ivar_list *ivars;\n";
1639 Result += "\tstruct _objc_method_list *methods;\n";
1640 Result += "\tstruct objc_cache *cache;\n";
1641 Result += "\tstruct _objc_protocol_list *protocols;\n";
1642 Result += "\tconst char *ivar_layout;\n";
1643 Result += "\tstruct _objc_class_ext *ext;\n";
1644 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001645 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001646 }
1647
1648 // Meta-class metadata generation.
1649 ObjcInterfaceDecl *RootClass = 0;
1650 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1651 while (SuperClass) {
1652 RootClass = SuperClass;
1653 SuperClass = SuperClass->getSuperClass();
1654 }
1655 SuperClass = CDecl->getSuperClass();
1656
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001657 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1658 Result += CDecl->getName();
1659 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1660 "{\n\t(struct _objc_class *)\"";
1661 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1662 Result += "\"";
1663
1664 if (SuperClass) {
1665 Result += ", \"";
1666 Result += SuperClass->getName();
1667 Result += "\", \"";
1668 Result += CDecl->getName();
1669 Result += "\"";
1670 }
1671 else {
1672 Result += ", 0, \"";
1673 Result += CDecl->getName();
1674 Result += "\"";
1675 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001676 // TODO: 'ivars' field for root class is currently set to 0.
1677 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001678 Result += ", 0,2, sizeof(struct _objc_class), 0";
1679 if (CDecl->getNumClassMethods() > 0) {
1680 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1681 Result += CDecl->getName();
1682 Result += "\n";
1683 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001684 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001685 Result += ", 0\n";
1686 if (CDecl->getNumIntfRefProtocols() > 0) {
1687 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1688 Result += CDecl->getName();
1689 Result += ",0,0\n";
1690 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001691 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001692 Result += "\t,0,0,0,0\n";
1693 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001694
1695 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001696 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1697 Result += CDecl->getName();
1698 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1699 "{\n\t&_OBJC_METACLASS_";
1700 Result += CDecl->getName();
1701 if (SuperClass) {
1702 Result += ", \"";
1703 Result += SuperClass->getName();
1704 Result += "\", \"";
1705 Result += CDecl->getName();
1706 Result += "\"";
1707 }
1708 else {
1709 Result += ", 0, \"";
1710 Result += CDecl->getName();
1711 Result += "\"";
1712 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001713 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001714 Result += ", 0,1";
1715 if (!ObjcSynthesizedStructs.count(CDecl))
1716 Result += ",0";
1717 else {
1718 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001719 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001720 Result += CDecl->getName();
1721 Result += ")";
1722 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001723 if (NumIvars > 0) {
1724 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1725 Result += CDecl->getName();
1726 Result += "\n\t";
1727 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001728 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001729 Result += ",0";
1730 if (IDecl->getNumInstanceMethods() > 0) {
1731 Result += ", &_OBJC_INSTANCE_METHODS_";
1732 Result += CDecl->getName();
1733 Result += ", 0\n\t";
1734 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001735 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001736 Result += ",0,0";
1737 if (CDecl->getNumIntfRefProtocols() > 0) {
1738 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1739 Result += CDecl->getName();
1740 Result += ", 0,0\n";
1741 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001742 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001743 Result += ",0,0,0\n";
1744 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001745}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001746
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001747/// RewriteImplementations - This routine rewrites all method implementations
1748/// and emits meta-data.
1749
1750void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001751 int ClsDefCount = ClassImplementation.size();
1752 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001753
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001754 if (ClsDefCount == 0 && CatDefCount == 0)
1755 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001756 // Rewrite implemented methods
1757 for (int i = 0; i < ClsDefCount; i++)
1758 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001759
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001760 for (int i = 0; i < CatDefCount; i++)
1761 RewriteImplementationDecl(CategoryImplementation[i]);
1762
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001763 // TODO: This is temporary until we decide how to access objc types in a
1764 // c program
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001765 Result += "#include <Objc/objc.h>\n";
1766 // This is needed for use of offsetof
1767 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001768
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001769 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001770 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001771 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001772
1773 // For each implemented category, write out all its meta data.
1774 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001775 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001776
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001777 // Write objc_symtab metadata
1778 /*
1779 struct _objc_symtab
1780 {
1781 long sel_ref_cnt;
1782 SEL *refs;
1783 short cls_def_cnt;
1784 short cat_def_cnt;
1785 void *defs[cls_def_cnt + cat_def_cnt];
1786 };
1787 */
1788
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001789 Result += "\nstruct _objc_symtab {\n";
1790 Result += "\tlong sel_ref_cnt;\n";
1791 Result += "\tSEL *refs;\n";
1792 Result += "\tshort cls_def_cnt;\n";
1793 Result += "\tshort cat_def_cnt;\n";
1794 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1795 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001796
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001797 Result += "static struct _objc_symtab "
1798 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1799 Result += "\t0, 0, " + utostr(ClsDefCount)
1800 + ", " + utostr(CatDefCount) + "\n";
1801 for (int i = 0; i < ClsDefCount; i++) {
1802 Result += "\t,&_OBJC_CLASS_";
1803 Result += ClassImplementation[i]->getName();
1804 Result += "\n";
1805 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001806
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001807 for (int i = 0; i < CatDefCount; i++) {
1808 Result += "\t,&_OBJC_CATEGORY_";
1809 Result += CategoryImplementation[i]->getClassInterface()->getName();
1810 Result += "_";
1811 Result += CategoryImplementation[i]->getName();
1812 Result += "\n";
1813 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001814
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001815 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001816
1817 // Write objc_module metadata
1818
1819 /*
1820 struct _objc_module {
1821 long version;
1822 long size;
1823 const char *name;
1824 struct _objc_symtab *symtab;
1825 }
1826 */
1827
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001828 Result += "\nstruct _objc_module {\n";
1829 Result += "\tlong version;\n";
1830 Result += "\tlong size;\n";
1831 Result += "\tconst char *name;\n";
1832 Result += "\tstruct _objc_symtab *symtab;\n";
1833 Result += "};\n\n";
1834 Result += "static struct _objc_module "
1835 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001836 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1837 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001838 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001839
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001840}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001841