blob: b78e776f182b77d44048a1c95b12a41b2225ba2d [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);
Fariborz Jahanian016a1882007-11-14 00:42:16 +000094 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +000095 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +000096 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +000097 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +000098 void RewriteObjcQualifiedInterfaceTypes(
99 const FunctionTypeProto *proto, FunctionDecl *FD);
100 bool needToScanForQualifiers(QualType T);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000101
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000102 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000103 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000104 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff296b74f2007-11-05 14:50:49 +0000105 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000106 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000107 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000108 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
109 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
110 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000111 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000112 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
113 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000114 void SynthMsgSendFunctionDecl();
115 void SynthGetClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000116 void SynthCFStringFunctionDecl();
117
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000118 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000119 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
120 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000121
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000122 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
123 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000124
Steve Naroffb82c50f2007-11-11 17:19:15 +0000125 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000126 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000127 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000128 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000129 const char *ClassName,
130 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000131
132 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
133 int NumProtocols,
134 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000135 const char *ClassName,
136 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000137 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
138 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000139 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
140 ObjcIvarDecl *ivar,
141 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000142 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000143 };
144}
145
Chris Lattner569faa62007-10-11 18:38:32 +0000146ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000147
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000148//===----------------------------------------------------------------------===//
149// Top Level Driver Code
150//===----------------------------------------------------------------------===//
151
Chris Lattner569faa62007-10-11 18:38:32 +0000152void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000153 // Two cases: either the decl could be in the main file, or it could be in a
154 // #included file. If the former, rewrite it now. If the later, check to see
155 // if we rewrote the #include/#import.
156 SourceLocation Loc = D->getLocation();
157 Loc = SM->getLogicalLoc(Loc);
158
159 // If this is for a builtin, ignore it.
160 if (Loc.isInvalid()) return;
161
Steve Naroffe9780582007-10-23 23:50:29 +0000162 // Look for built-in declarations that we need to refer during the rewrite.
163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000164 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000165 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
166 // declared in <Foundation/NSString.h>
167 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
168 ConstantStringClassReference = FVD;
169 return;
170 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000171 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
172 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000173 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
174 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000175 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
176 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000177 } else if (ObjcForwardProtocolDecl *FP =
178 dyn_cast<ObjcForwardProtocolDecl>(D)){
179 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000180 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000181 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000182 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
183 return HandleDeclInMainFile(D);
184
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000185 // Otherwise, see if there is a #import in the main file that should be
186 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000187 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000188}
189
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000190/// HandleDeclInMainFile - This is called for each top-level decl defined in the
191/// main file of the input.
192void RewriteTest::HandleDeclInMainFile(Decl *D) {
193 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
194 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000195 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000196
197 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
198 if (Stmt *Body = MD->getBody())
199 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
200 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000201 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
202 ClassImplementation.push_back(CI);
203 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
204 CategoryImplementation.push_back(CI);
205 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
206 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000207 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
208 if (VD->getInit())
209 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
210 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000211 // Nothing yet.
212}
213
214RewriteTest::~RewriteTest() {
215 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000216
217 // Rewrite tabs if we care.
218 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000219
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000220 // Rewrite Objective-c meta data*
221 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000222 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000223
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000224 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
225 // we are done.
226 if (const RewriteBuffer *RewriteBuf =
227 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000228 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000229 std::string S(RewriteBuf->begin(), RewriteBuf->end());
230 printf("%s\n", S.c_str());
231 } else {
232 printf("No changes\n");
233 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000234 // Emit metadata.
235 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000236}
237
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000238//===----------------------------------------------------------------------===//
239// Syntactic (non-AST) Rewriting Code
240//===----------------------------------------------------------------------===//
241
Chris Lattner74db1682007-10-16 21:07:07 +0000242void RewriteTest::RewriteInclude(SourceLocation Loc) {
243 // Rip up the #include stack to the main file.
244 SourceLocation IncLoc = Loc, NextLoc = Loc;
245 do {
246 IncLoc = Loc;
247 Loc = SM->getLogicalLoc(NextLoc);
248 NextLoc = SM->getIncludeLoc(Loc);
249 } while (!NextLoc.isInvalid());
250
251 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
252 // IncLoc indicates the header that was included if it is useful.
253 IncLoc = SM->getLogicalLoc(IncLoc);
254 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
255 Loc == LastIncLoc)
256 return;
257 LastIncLoc = Loc;
258
259 unsigned IncCol = SM->getColumnNumber(Loc);
260 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
261
262 // Replace the #import with #include.
263 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
264}
265
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000266void RewriteTest::RewriteTabs() {
267 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
268 const char *MainBufStart = MainBuf.first;
269 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000270
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000271 // Loop over the whole file, looking for tabs.
272 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
273 if (*BufPtr != '\t')
274 continue;
275
276 // Okay, we found a tab. This tab will turn into at least one character,
277 // but it depends on which 'virtual column' it is in. Compute that now.
278 unsigned VCol = 0;
279 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
280 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
281 ++VCol;
282
283 // Okay, now that we know the virtual column, we know how many spaces to
284 // insert. We assume 8-character tab-stops.
285 unsigned Spaces = 8-(VCol & 7);
286
287 // Get the location of the tab.
288 SourceLocation TabLoc =
289 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
290
291 // Rewrite the single tab character into a sequence of spaces.
292 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
293 }
Chris Lattner569faa62007-10-11 18:38:32 +0000294}
295
296
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000297void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
298 int numDecls = ClassDecl->getNumForwardDecls();
299 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
300
301 // Get the start location and compute the semi location.
302 SourceLocation startLoc = ClassDecl->getLocation();
303 const char *startBuf = SM->getCharacterData(startLoc);
304 const char *semiPtr = strchr(startBuf, ';');
305
306 // Translate to typedef's that forward reference structs with the same name
307 // as the class. As a convenience, we include the original declaration
308 // as a comment.
309 std::string typedefString;
310 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000311 typedefString.append(startBuf, semiPtr-startBuf+1);
312 typedefString += "\n";
313 for (int i = 0; i < numDecls; i++) {
314 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff809b4f02007-10-31 22:11:35 +0000315 if (ObjcForwardDecls.count(ForwardDecl))
316 continue;
Steve Naroff2aeae312007-11-09 12:50:28 +0000317 typedefString += "#ifndef _REWRITER_typedef_";
318 typedefString += ForwardDecl->getName();
319 typedefString += "\n";
320 typedefString += "#define _REWRITER_typedef_";
321 typedefString += ForwardDecl->getName();
322 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000323 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000324 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000325 typedefString += ";\n#endif\n";
Steve Naroff809b4f02007-10-31 22:11:35 +0000326 // Mark this typedef as having been generated.
327 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000328 assert(false && "typedef already output");
Steve Naroff71226032007-10-24 22:48:43 +0000329 }
330
331 // Replace the @class with typedefs corresponding to the classes.
332 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
333 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000334}
335
Steve Naroff18c83382007-11-13 23:01:27 +0000336void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000337 for (int i = 0; i < nMethods; i++) {
338 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000339 SourceLocation LocStart = Method->getLocStart();
340 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000341
Steve Narofffbfb46d2007-11-14 14:34:23 +0000342 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
343 Rewrite.InsertText(LocStart, "/* ", 3);
344 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
345 } else {
346 Rewrite.InsertText(LocStart, "// ", 3);
347 }
Steve Naroff667f1682007-10-30 13:30:57 +0000348 }
349}
350
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000351void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
352{
353 for (int i = 0; i < nProperties; i++) {
354 ObjcPropertyDecl *Property = Properties[i];
355 SourceLocation Loc = Property->getLocation();
356
357 Rewrite.ReplaceText(Loc, 0, "// ", 3);
358
359 // FIXME: handle properties that are declared across multiple lines.
360 }
361}
362
Steve Naroff667f1682007-10-30 13:30:57 +0000363void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
364 SourceLocation LocStart = CatDecl->getLocStart();
365
366 // FIXME: handle category headers that are declared across multiple lines.
367 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
368
Steve Naroff18c83382007-11-13 23:01:27 +0000369 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
370 CatDecl->getInstanceMethods());
371 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
372 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000373 // Lastly, comment out the @end.
374 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
375}
376
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000377void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000378 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
379 const char *MainBufStart = MainBuf.first;
380
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000381 SourceLocation LocStart = PDecl->getLocStart();
382
383 // FIXME: handle protocol headers that are declared across multiple lines.
384 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
385
Steve Naroff18c83382007-11-13 23:01:27 +0000386 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
387 PDecl->getInstanceMethods());
388 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
389 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000390 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000391 SourceLocation LocEnd = PDecl->getAtEndLoc();
392 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000393
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000394 // Must comment out @optional/@required
395 const char *startBuf = SM->getCharacterData(LocStart);
396 const char *endBuf = SM->getCharacterData(LocEnd);
397 for (const char *p = startBuf; p < endBuf; p++) {
398 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
399 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000400 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000401 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
402 CommentedOptional.c_str(), CommentedOptional.size());
403
404 }
405 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
406 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000407 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000408 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
409 CommentedRequired.c_str(), CommentedRequired.size());
410
411 }
412 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000413}
414
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000415void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
416 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000417 if (LocStart.isInvalid())
418 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000419 // FIXME: handle forward protocol that are declared across multiple lines.
420 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
421}
422
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000423void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
424 std::string &ResultStr) {
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000425 static bool includeObjc = false;
426 if (!includeObjc) {
427 ResultStr += "#include <Objc/objc.h>\n";
428 includeObjc = true;
429 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000430 ResultStr += "\nstatic ";
431 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000432 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000433
434 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000435 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000436
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000437 if (OMD->isInstance())
438 NameStr += "_I_";
439 else
440 NameStr += "_C_";
441
442 NameStr += OMD->getClassInterface()->getName();
443 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000444
445 NamedDecl *MethodContext = OMD->getMethodContext();
446 if (ObjcCategoryImplDecl *CID =
447 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000448 NameStr += CID->getName();
449 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000450 }
451 // Append selector names, replacing ':' with '_'
452 const char *selName = OMD->getSelector().getName().c_str();
453 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000454 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000455 else {
456 std::string selString = OMD->getSelector().getName();
457 int len = selString.size();
458 for (int i = 0; i < len; i++)
459 if (selString[i] == ':')
460 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000461 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000462 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000463 // Remember this name for metadata emission
464 MethodInternalNames[OMD] = NameStr;
465 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000466
467 // Rewrite arguments
468 ResultStr += "(";
469
470 // invisible arguments
471 if (OMD->isInstance()) {
472 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
473 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000474 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
475 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000476 ResultStr += selfTy.getAsString();
477 }
478 else
479 ResultStr += Context->getObjcIdType().getAsString();
480
481 ResultStr += " self, ";
482 ResultStr += Context->getObjcSelType().getAsString();
483 ResultStr += " _cmd";
484
485 // Method arguments.
486 for (int i = 0; i < OMD->getNumParams(); i++) {
487 ParmVarDecl *PDecl = OMD->getParamDecl(i);
488 ResultStr += ", ";
489 ResultStr += PDecl->getType().getAsString();
490 ResultStr += " ";
491 ResultStr += PDecl->getName();
492 }
493 ResultStr += ")";
494
495}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000496void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
497 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
498 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000499
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000500 if (IMD)
501 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
502 else
503 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000504
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000505 int numMethods = IMD ? IMD->getNumInstanceMethods()
506 : CID->getNumInstanceMethods();
507
508 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000509 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000510 ObjcMethodDecl *OMD;
511 if (IMD)
512 OMD = IMD->getInstanceMethods()[i];
513 else
514 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000515 RewriteObjcMethodDecl(OMD, ResultStr);
516 SourceLocation LocStart = OMD->getLocStart();
517 SourceLocation LocEnd = OMD->getBody()->getLocStart();
518
519 const char *startBuf = SM->getCharacterData(LocStart);
520 const char *endBuf = SM->getCharacterData(LocEnd);
521 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
522 ResultStr.c_str(), ResultStr.size());
523 }
524
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000525 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
526 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000527 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000528 ObjcMethodDecl *OMD;
529 if (IMD)
530 OMD = IMD->getClassMethods()[i];
531 else
532 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000533 RewriteObjcMethodDecl(OMD, ResultStr);
534 SourceLocation LocStart = OMD->getLocStart();
535 SourceLocation LocEnd = OMD->getBody()->getLocStart();
536
537 const char *startBuf = SM->getCharacterData(LocStart);
538 const char *endBuf = SM->getCharacterData(LocEnd);
539 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
540 ResultStr.c_str(), ResultStr.size());
541 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000542 if (IMD)
543 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
544 else
545 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000546}
547
Steve Naroff3774dd92007-10-26 20:53:56 +0000548void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000549
550 SourceLocation LocStart = ClassDecl->getLocStart();
551 SourceLocation LocEnd = ClassDecl->getLocEnd();
552
553 const char *startBuf = SM->getCharacterData(LocStart);
554 const char *endBuf = SM->getCharacterData(LocEnd);
555
Steve Naroff1ccf4632007-10-30 03:43:13 +0000556 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Naroffef20ed32007-10-30 02:23:23 +0000557
558 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000559 if (!ObjcForwardDecls.count(ClassDecl)) {
560 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2aeae312007-11-09 12:50:28 +0000561 ResultStr += "#ifndef _REWRITER_typedef_";
562 ResultStr += ClassDecl->getName();
563 ResultStr += "\n";
564 ResultStr += "#define _REWRITER_typedef_";
565 ResultStr += ClassDecl->getName();
566 ResultStr += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000567 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000568 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000569 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000570
571 // Mark this typedef as having been generated.
572 ObjcForwardDecls.insert(ClassDecl);
573 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000574 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
575
Steve Naroff1ccf4632007-10-30 03:43:13 +0000576 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Naroffef20ed32007-10-30 02:23:23 +0000577 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000578 RewriteProperties(ClassDecl->getNumPropertyDecl(),
579 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000580 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
581 ClassDecl->getInstanceMethods());
582 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
583 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000584
Steve Naroff1ccf4632007-10-30 03:43:13 +0000585 // Lastly, comment out the @end.
586 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000587}
588
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000589//===----------------------------------------------------------------------===//
590// Function Body / Expression rewriting
591//===----------------------------------------------------------------------===//
592
Steve Naroff334fbc22007-11-09 15:20:18 +0000593Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000594 // Otherwise, just rewrite all children.
595 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
596 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000597 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000598 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000599 if (newStmt)
600 *CI = newStmt;
601 }
Steve Naroffe9780582007-10-23 23:50:29 +0000602
603 // Handle specific things.
604 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
605 return RewriteAtEncode(AtEncode);
Steve Naroff296b74f2007-11-05 14:50:49 +0000606
607 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
608 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000609
610 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
611 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000612
Steve Naroff71226032007-10-24 22:48:43 +0000613 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
614 // Before we rewrite it, put the original message expression in a comment.
615 SourceLocation startLoc = MessExpr->getLocStart();
616 SourceLocation endLoc = MessExpr->getLocEnd();
617
618 const char *startBuf = SM->getCharacterData(startLoc);
619 const char *endBuf = SM->getCharacterData(endLoc);
620
621 std::string messString;
622 messString += "// ";
623 messString.append(startBuf, endBuf-startBuf+1);
624 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000625
Steve Naroff71226032007-10-24 22:48:43 +0000626 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
627 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
628 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000629 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000630 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000631 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000632
633 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
634 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000635
636 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
637 return RewriteObjcThrowStmt(StmtThrow);
638
Chris Lattner0021f452007-10-24 16:57:36 +0000639 // Return this stmt unmodified.
640 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000641}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000642
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000643Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000644 // Get the start location and compute the semi location.
645 SourceLocation startLoc = S->getLocStart();
646 const char *startBuf = SM->getCharacterData(startLoc);
647
648 assert((*startBuf == '@') && "bogus @try location");
649
650 std::string buf;
651 // declare a new scope with two variables, _stack and _rethrow.
652 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
653 buf += "int buf[18/*32-bit i386*/];\n";
654 buf += "char *pointers[4];} _stack;\n";
655 buf += "id volatile _rethrow = 0;\n";
656 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000657 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000658
659 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
660
661 startLoc = S->getTryBody()->getLocEnd();
662 startBuf = SM->getCharacterData(startLoc);
663
664 assert((*startBuf == '}') && "bogus @try block");
665
666 SourceLocation lastCurlyLoc = startLoc;
667
668 startLoc = startLoc.getFileLocWithOffset(1);
669 buf = " /* @catch begin */ else {\n";
670 buf += " id _caught = objc_exception_extract(&_stack);\n";
671 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000672 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000673 buf += " _rethrow = objc_exception_extract(&_stack);\n";
674 buf += " else { /* @catch continue */";
675
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000676 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000677
678 bool sawIdTypedCatch = false;
679 Stmt *lastCatchBody = 0;
680 ObjcAtCatchStmt *catchList = S->getCatchStmts();
681 while (catchList) {
682 Stmt *catchStmt = catchList->getCatchParamStmt();
683
684 if (catchList == S->getCatchStmts())
685 buf = "if ("; // we are generating code for the first catch clause
686 else
687 buf = "else if (";
688 startLoc = catchList->getLocStart();
689 startBuf = SM->getCharacterData(startLoc);
690
691 assert((*startBuf == '@') && "bogus @catch location");
692
693 const char *lParenLoc = strchr(startBuf, '(');
694
695 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
696 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
697 if (t == Context->getObjcIdType()) {
698 buf += "1) { ";
699 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
700 buf.c_str(), buf.size());
701 sawIdTypedCatch = true;
702 } else if (const PointerType *pType = t->getAsPointerType()) {
703 ObjcInterfaceType *cls; // Should be a pointer to a class.
704
705 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
706 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000707 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000708 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000709 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000710 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
711 buf.c_str(), buf.size());
712 }
713 }
714 // Now rewrite the body...
715 lastCatchBody = catchList->getCatchBody();
716 SourceLocation rParenLoc = catchList->getRParenLoc();
717 SourceLocation bodyLoc = lastCatchBody->getLocStart();
718 const char *bodyBuf = SM->getCharacterData(bodyLoc);
719 const char *rParenBuf = SM->getCharacterData(rParenLoc);
720 assert((*rParenBuf == ')') && "bogus @catch paren location");
721 assert((*bodyBuf == '{') && "bogus @catch body location");
722
723 buf = " = _caught;";
724 // Here we replace ") {" with "= _caught;" (which initializes and
725 // declares the @catch parameter).
726 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
727 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000728 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000729 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000730 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000731 catchList = catchList->getNextCatchStmt();
732 }
733 // Complete the catch list...
734 if (lastCatchBody) {
735 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
736 const char *bodyBuf = SM->getCharacterData(bodyLoc);
737 assert((*bodyBuf == '}') && "bogus @catch body location");
738 bodyLoc = bodyLoc.getFileLocWithOffset(1);
739 buf = " } } /* @catch end */\n";
740
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000741 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000742
743 // Set lastCurlyLoc
744 lastCurlyLoc = lastCatchBody->getLocEnd();
745 }
746 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
747 startLoc = finalStmt->getLocStart();
748 startBuf = SM->getCharacterData(startLoc);
749 assert((*startBuf == '@') && "bogus @finally start");
750
751 buf = "/* @finally */";
752 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
753
754 Stmt *body = finalStmt->getFinallyBody();
755 SourceLocation startLoc = body->getLocStart();
756 SourceLocation endLoc = body->getLocEnd();
757 const char *startBuf = SM->getCharacterData(startLoc);
758 const char *endBuf = SM->getCharacterData(endLoc);
759 assert((*startBuf == '{') && "bogus @finally body location");
760 assert((*endBuf == '}') && "bogus @finally body location");
761
762 startLoc = startLoc.getFileLocWithOffset(1);
763 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000764 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000765 endLoc = endLoc.getFileLocWithOffset(-1);
766 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000767 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000768
769 // Set lastCurlyLoc
770 lastCurlyLoc = body->getLocEnd();
771 }
772 // Now emit the final closing curly brace...
773 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
774 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000775 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000776 return 0;
777}
778
779Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
780 return 0;
781}
782
783Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
784 return 0;
785}
786
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000787// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
788// the throw expression is typically a message expression that's already
789// been rewritten! (which implies the SourceLocation's are invalid).
790Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
791 // Get the start location and compute the semi location.
792 SourceLocation startLoc = S->getLocStart();
793 const char *startBuf = SM->getCharacterData(startLoc);
794
795 assert((*startBuf == '@') && "bogus @throw location");
796
797 std::string buf;
798 /* void objc_exception_throw(id) __attribute__((noreturn)); */
799 buf = "objc_exception_throw(";
800 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
801 const char *semiBuf = strchr(startBuf, ';');
802 assert((*semiBuf == ';') && "@throw: can't find ';'");
803 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
804 buf = ");";
805 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
806 return 0;
807}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000808
Chris Lattner0021f452007-10-24 16:57:36 +0000809Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000810 // Create a new string expression.
811 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000812 std::string StrEncoding;
813 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
814 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
815 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000816 SourceLocation(), SourceLocation());
817 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000818 delete Exp;
819 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000820}
821
Steve Naroff296b74f2007-11-05 14:50:49 +0000822Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
823 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
824 // Create a call to sel_registerName("selName").
825 llvm::SmallVector<Expr*, 8> SelExprs;
826 QualType argType = Context->getPointerType(Context->CharTy);
827 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
828 Exp->getSelector().getName().size(),
829 false, argType, SourceLocation(),
830 SourceLocation()));
831 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
832 &SelExprs[0], SelExprs.size());
833 Rewrite.ReplaceStmt(Exp, SelExp);
834 delete Exp;
835 return SelExp;
836}
837
Steve Naroff71226032007-10-24 22:48:43 +0000838CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
839 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000840 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000841 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000842
843 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000844 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000845
846 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000847 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000848 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
849
850 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000851
Steve Naroff71226032007-10-24 22:48:43 +0000852 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
853}
854
Steve Naroffc8a92d12007-11-01 13:24:47 +0000855static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
856 const char *&startRef, const char *&endRef) {
857 while (startBuf < endBuf) {
858 if (*startBuf == '<')
859 startRef = startBuf; // mark the start.
860 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000861 if (startRef && *startRef == '<') {
862 endRef = startBuf; // mark the end.
863 return true;
864 }
865 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000866 }
867 startBuf++;
868 }
869 return false;
870}
871
872bool RewriteTest::needToScanForQualifiers(QualType T) {
873 // FIXME: we don't currently represent "id <Protocol>" in the type system.
874 if (T == Context->getObjcIdType())
875 return true;
876
877 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000878 Type *pointeeType = pType->getPointeeType().getTypePtr();
879 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
880 return true; // we have "Class <Protocol> *".
881 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000882 return false;
883}
884
885void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
886 const FunctionTypeProto *proto, FunctionDecl *FD) {
887
888 if (needToScanForQualifiers(proto->getResultType())) {
889 // Since types are unique, we need to scan the buffer.
890 SourceLocation Loc = FD->getLocation();
891
892 const char *endBuf = SM->getCharacterData(Loc);
893 const char *startBuf = endBuf;
894 while (*startBuf != ';')
895 startBuf--; // scan backward (from the decl location) for return type.
896 const char *startRef = 0, *endRef = 0;
897 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
898 // Get the locations of the startRef, endRef.
899 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
900 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
901 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000902 Rewrite.InsertText(LessLoc, "/*", 2);
903 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000904 }
905 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000906 // Now check arguments.
907 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
908 if (needToScanForQualifiers(proto->getArgType(i))) {
909 // Since types are unique, we need to scan the buffer.
910 SourceLocation Loc = FD->getLocation();
911
912 const char *startBuf = SM->getCharacterData(Loc);
913 const char *endBuf = startBuf;
914 while (*endBuf != ';')
915 endBuf++; // scan forward (from the decl location) for argument types.
916 const char *startRef = 0, *endRef = 0;
917 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
918 // Get the locations of the startRef, endRef.
919 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
920 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
921 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000922 Rewrite.InsertText(LessLoc, "/*", 2);
923 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000924 }
925 }
926 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000927}
928
Steve Naroff02a82aa2007-10-30 23:14:51 +0000929void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
930 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000931 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000932 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000933 return;
934 }
935 // Check for ObjC 'id' and class types that have been adorned with protocol
936 // information (id<p>, C<p>*). The protocol references need to be rewritten!
937 const FunctionType *funcType = FD->getType()->getAsFunctionType();
938 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000939 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
940 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000941}
942
943// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
944void RewriteTest::SynthMsgSendFunctionDecl() {
945 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
946 llvm::SmallVector<QualType, 16> ArgTys;
947 QualType argT = Context->getObjcIdType();
948 assert(!argT.isNull() && "Can't find 'id' type");
949 ArgTys.push_back(argT);
950 argT = Context->getObjcSelType();
951 assert(!argT.isNull() && "Can't find 'SEL' type");
952 ArgTys.push_back(argT);
953 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
954 &ArgTys[0], ArgTys.size(),
955 true /*isVariadic*/);
956 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
957 msgSendIdent, msgSendType,
958 FunctionDecl::Extern, false, 0);
959}
960
961// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
962void RewriteTest::SynthGetClassFunctionDecl() {
963 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
964 llvm::SmallVector<QualType, 16> ArgTys;
965 ArgTys.push_back(Context->getPointerType(
966 Context->CharTy.getQualifiedType(QualType::Const)));
967 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
968 &ArgTys[0], ArgTys.size(),
969 false /*isVariadic*/);
970 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
971 getClassIdent, getClassType,
972 FunctionDecl::Extern, false, 0);
973}
974
Steve Naroffabb96362007-11-08 14:30:50 +0000975// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
976void RewriteTest::SynthCFStringFunctionDecl() {
977 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
978 llvm::SmallVector<QualType, 16> ArgTys;
979 ArgTys.push_back(Context->getPointerType(
980 Context->CharTy.getQualifiedType(QualType::Const)));
981 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
982 &ArgTys[0], ArgTys.size(),
983 false /*isVariadic*/);
984 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
985 getClassIdent, getClassType,
986 FunctionDecl::Extern, false, 0);
987}
988
Steve Naroff0add5d22007-11-03 11:27:19 +0000989Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +0000990#if 1
991 // This rewrite is specific to GCC, which has builtin support for CFString.
992 if (!CFStringFunctionDecl)
993 SynthCFStringFunctionDecl();
994 // Create a call to __builtin___CFStringMakeConstantString("cstr").
995 llvm::SmallVector<Expr*, 8> StrExpr;
996 StrExpr.push_back(Exp->getString());
997 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
998 &StrExpr[0], StrExpr.size());
999 // cast to NSConstantString *
1000 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1001 Rewrite.ReplaceStmt(Exp, cast);
1002 delete Exp;
1003 return cast;
1004#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001005 assert(ConstantStringClassReference && "Can't find constant string reference");
1006 llvm::SmallVector<Expr*, 4> InitExprs;
1007
1008 // Synthesize "(Class)&_NSConstantStringClassReference"
1009 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1010 ConstantStringClassReference->getType(),
1011 SourceLocation());
1012 QualType expType = Context->getPointerType(ClsRef->getType());
1013 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1014 expType, SourceLocation());
1015 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1016 SourceLocation());
1017 InitExprs.push_back(cast); // set the 'isa'.
1018 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1019 unsigned IntSize = static_cast<unsigned>(
1020 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1021 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1022 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1023 Exp->getLocStart());
1024 InitExprs.push_back(len); // set "int numBytes".
1025
1026 // struct NSConstantString
1027 QualType CFConstantStrType = Context->getCFConstantStringType();
1028 // (struct NSConstantString) { <exprs from above> }
1029 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1030 &InitExprs[0], InitExprs.size(),
1031 SourceLocation());
1032 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1033 // struct NSConstantString *
1034 expType = Context->getPointerType(StrRep->getType());
1035 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1036 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001037 // cast to NSConstantString *
1038 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001039 Rewrite.ReplaceStmt(Exp, cast);
1040 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001041 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001042#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001043}
1044
Steve Naroff71226032007-10-24 22:48:43 +00001045Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +00001046 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +00001047 if (!MsgSendFunctionDecl)
1048 SynthMsgSendFunctionDecl();
1049 if (!GetClassFunctionDecl)
1050 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +00001051
1052 // Synthesize a call to objc_msgSend().
1053 llvm::SmallVector<Expr*, 8> MsgExprs;
1054 IdentifierInfo *clsName = Exp->getClassName();
1055
1056 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1057 if (clsName) { // class message.
1058 llvm::SmallVector<Expr*, 8> ClsExprs;
1059 QualType argType = Context->getPointerType(Context->CharTy);
1060 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1061 clsName->getLength(),
1062 false, argType, SourceLocation(),
1063 SourceLocation()));
1064 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1065 &ClsExprs[0], ClsExprs.size());
1066 MsgExprs.push_back(Cls);
1067 } else // instance message.
1068 MsgExprs.push_back(Exp->getReceiver());
1069
Steve Naroff0add5d22007-11-03 11:27:19 +00001070 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001071 llvm::SmallVector<Expr*, 8> SelExprs;
1072 QualType argType = Context->getPointerType(Context->CharTy);
1073 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1074 Exp->getSelector().getName().size(),
1075 false, argType, SourceLocation(),
1076 SourceLocation()));
1077 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1078 &SelExprs[0], SelExprs.size());
1079 MsgExprs.push_back(SelExp);
1080
1081 // Now push any user supplied arguments.
1082 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1083 MsgExprs.push_back(Exp->getArg(i));
1084 // We've transferred the ownership to MsgExprs. Null out the argument in
1085 // the original expression, since we will delete it below.
1086 Exp->setArg(i, 0);
1087 }
Steve Naroff0744c472007-11-04 22:37:50 +00001088 // Generate the funky cast.
1089 CastExpr *cast;
1090 llvm::SmallVector<QualType, 8> ArgTypes;
1091 QualType returnType;
1092
1093 // Push 'id' and 'SEL', the 2 implicit arguments.
1094 ArgTypes.push_back(Context->getObjcIdType());
1095 ArgTypes.push_back(Context->getObjcSelType());
1096 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1097 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001098 for (int i = 0; i < mDecl->getNumParams(); i++) {
1099 QualType t = mDecl->getParamDecl(i)->getType();
1100 if (t == Context->getObjcClassType())
1101 t = Context->getObjcIdType(); // Convert "Class"->"id"
1102 ArgTypes.push_back(t);
1103 }
Steve Naroff0744c472007-11-04 22:37:50 +00001104 returnType = mDecl->getResultType();
1105 } else {
1106 returnType = Context->getObjcIdType();
1107 }
1108 // Get the type, we will need to reference it in a couple spots.
1109 QualType msgSendType = MsgSendFunctionDecl->getType();
1110
1111 // Create a reference to the objc_msgSend() declaration.
1112 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1113
1114 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1115 // If we don't do this cast, we get the following bizarre warning/note:
1116 // xx.m:13: warning: function called through a non-compatible type
1117 // xx.m:13: note: if this code is reached, the program will abort
1118 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1119 SourceLocation());
1120
1121 // Now do the "normal" pointer to function cast.
1122 QualType castType = Context->getFunctionType(returnType,
1123 &ArgTypes[0], ArgTypes.size(),
1124 false/*FIXME:variadic*/);
1125 castType = Context->getPointerType(castType);
1126 cast = new CastExpr(castType, cast, SourceLocation());
1127
1128 // Don't forget the parens to enforce the proper binding.
1129 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1130
1131 const FunctionType *FT = msgSendType->getAsFunctionType();
1132 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1133 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001134 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001135 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001136
Chris Lattner0021f452007-10-24 16:57:36 +00001137 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001138 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001139}
1140
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001141/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1142/// an objective-c class with ivars.
1143void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1144 std::string &Result) {
1145 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1146 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001147 // Do not synthesize more than once.
1148 if (ObjcSynthesizedStructs.count(CDecl))
1149 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001150 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1151 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1152 // Do it for the root
1153 SynthesizeObjcInternalStruct(RCDecl, Result);
1154 }
1155
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001156 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001157 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +00001158 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001159 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1160 return;
1161
Steve Naroffb1147382007-11-01 17:12:31 +00001162 Result += "\nstruct ";
1163 Result += CDecl->getName();
1164 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1165 Result += " {\n struct ";
1166 Result += RCDecl->getName();
1167 Result += " _";
1168 Result += RCDecl->getName();
1169 Result += ";\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001170 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001171 else
1172 Result += " {";
Steve Naroff809b4f02007-10-31 22:11:35 +00001173
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001174 if (NumIvars > 0) {
1175 SourceLocation LocStart = CDecl->getLocStart();
1176 SourceLocation LocEnd = CDecl->getLocEnd();
1177
1178 const char *startBuf = SM->getCharacterData(LocStart);
1179 const char *endBuf = SM->getCharacterData(LocEnd);
1180 startBuf = strchr(startBuf, '{');
1181 assert((startBuf && endBuf)
1182 && "SynthesizeObjcInternalStruct - malformed @interface");
1183 startBuf++; // past '{'
1184 while (startBuf < endBuf) {
1185 if (*startBuf == '@') {
1186 startBuf = strchr(startBuf, 'p');
1187 // FIXME: presence of @public, etc. inside comment results in
1188 // this transformation as well, which is still correct c-code.
1189 if (!strncmp(startBuf, "public", strlen("public"))) {
1190 startBuf += strlen("public");
1191 Result += "/* @public */";
1192 }
1193 else if (!strncmp(startBuf, "private", strlen("private"))) {
1194 startBuf += strlen("private");
1195 Result += "/* @private */";
1196 }
1197 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1198 startBuf += strlen("protected");
1199 Result += "/* @protected */";
1200 }
1201 }
1202 Result += *startBuf++;
1203 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001204 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001205
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001206 Result += "};\n";
1207 // Mark this struct as having been generated.
1208 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001209 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001210}
1211
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001212// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1213/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001214void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001215 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001216 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001217 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001218 const char *ClassName,
1219 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001220 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001221 if (NumMethods > 0 && !objc_impl_method) {
1222 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001223 SEL _cmd;
1224 char *method_types;
1225 void *_imp;
1226 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001227 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001228 Result += "\nstruct _objc_method {\n";
1229 Result += "\tSEL _cmd;\n";
1230 Result += "\tchar *method_types;\n";
1231 Result += "\tvoid *_imp;\n";
1232 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001233
1234 /* struct _objc_method_list {
1235 struct _objc_method_list *next_method;
1236 int method_count;
1237 struct _objc_method method_list[];
1238 }
1239 */
1240 Result += "\nstruct _objc_method_list {\n";
1241 Result += "\tstruct _objc_method_list *next_method;\n";
1242 Result += "\tint method_count;\n";
1243 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001244 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001245 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001246 // Build _objc_method_list for class's methods if needed
1247 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001248 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001249 Result += prefix;
1250 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1251 Result += "_METHODS_";
1252 Result += ClassName;
1253 Result += " __attribute__ ((section (\"__OBJC, __";
1254 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001255 Result += "_meth\")))= ";
1256 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1257
1258 Result += "\t,{{(SEL)\"";
1259 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001260 std::string MethodTypeString;
1261 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1262 Result += "\", \"";
1263 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001264 Result += "\", ";
1265 Result += MethodInternalNames[Methods[0]];
1266 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001267 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001268 Result += "\t ,{(SEL)\"";
1269 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001270 std::string MethodTypeString;
1271 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1272 Result += "\", \"";
1273 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001274 Result += "\", ";
1275 Result += MethodInternalNames[Methods[i]];
1276 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001277 }
1278 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001279 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001280}
1281
1282/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1283void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1284 int NumProtocols,
1285 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001286 const char *ClassName,
1287 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001288 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001289 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001290 for (int i = 0; i < NumProtocols; i++) {
1291 ObjcProtocolDecl *PDecl = Protocols[i];
1292 // Output struct protocol_methods holder of method selector and type.
1293 if (!objc_protocol_methods &&
1294 (PDecl->getNumInstanceMethods() > 0
1295 || PDecl->getNumClassMethods() > 0)) {
1296 /* struct protocol_methods {
1297 SEL _cmd;
1298 char *method_types;
1299 }
1300 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001301 Result += "\nstruct protocol_methods {\n";
1302 Result += "\tSEL _cmd;\n";
1303 Result += "\tchar *method_types;\n";
1304 Result += "};\n";
1305
1306 /* struct _objc_protocol_method_list {
1307 int protocol_method_count;
1308 struct protocol_methods protocols[];
1309 }
1310 */
1311 Result += "\nstruct _objc_protocol_method_list {\n";
1312 Result += "\tint protocol_method_count;\n";
1313 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001314 objc_protocol_methods = true;
1315 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001316
Fariborz Jahanian04455192007-10-22 21:41:37 +00001317 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001318 int NumMethods = PDecl->getNumInstanceMethods();
1319 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001320 Result += "\nstatic struct _objc_protocol_method_list "
1321 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1322 Result += PDecl->getName();
1323 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1324 "{\n\t" + utostr(NumMethods) + "\n";
1325
Fariborz Jahanian04455192007-10-22 21:41:37 +00001326 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001327 Result += "\t,{{(SEL)\"";
1328 Result += Methods[0]->getSelector().getName().c_str();
1329 Result += "\", \"\"}\n";
1330
1331 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001332 Result += "\t ,{(SEL)\"";
1333 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001334 std::string MethodTypeString;
1335 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1336 Result += "\", \"";
1337 Result += MethodTypeString;
1338 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001339 }
1340 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001341 }
1342
1343 // Output class methods declared in this protocol.
1344 NumMethods = PDecl->getNumClassMethods();
1345 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001346 Result += "\nstatic struct _objc_protocol_method_list "
1347 "_OBJC_PROTOCOL_CLASS_METHODS_";
1348 Result += PDecl->getName();
1349 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1350 "{\n\t";
1351 Result += utostr(NumMethods);
1352 Result += "\n";
1353
Fariborz Jahanian04455192007-10-22 21:41:37 +00001354 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001355 Result += "\t,{{(SEL)\"";
1356 Result += Methods[0]->getSelector().getName().c_str();
1357 Result += "\", \"\"}\n";
1358
1359 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001360 Result += "\t ,{(SEL)\"";
1361 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001362 std::string MethodTypeString;
1363 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1364 Result += "\", \"";
1365 Result += MethodTypeString;
1366 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001367 }
1368 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001369 }
1370 // Output:
1371 /* struct _objc_protocol {
1372 // Objective-C 1.0 extensions
1373 struct _objc_protocol_extension *isa;
1374 char *protocol_name;
1375 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001376 struct _objc_protocol_method_list *instance_methods;
1377 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001378 };
1379 */
1380 static bool objc_protocol = false;
1381 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001382 Result += "\nstruct _objc_protocol {\n";
1383 Result += "\tstruct _objc_protocol_extension *isa;\n";
1384 Result += "\tchar *protocol_name;\n";
1385 Result += "\tstruct _objc_protocol **protocol_list;\n";
1386 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1387 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1388 Result += "};\n";
1389
1390 /* struct _objc_protocol_list {
1391 struct _objc_protocol_list *next;
1392 int protocol_count;
1393 struct _objc_protocol *class_protocols[];
1394 }
1395 */
1396 Result += "\nstruct _objc_protocol_list {\n";
1397 Result += "\tstruct _objc_protocol_list *next;\n";
1398 Result += "\tint protocol_count;\n";
1399 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1400 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001401 objc_protocol = true;
1402 }
1403
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001404 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1405 Result += PDecl->getName();
1406 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1407 "{\n\t0, \"";
1408 Result += PDecl->getName();
1409 Result += "\", 0, ";
1410 if (PDecl->getInstanceMethods() > 0) {
1411 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1412 Result += PDecl->getName();
1413 Result += ", ";
1414 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001415 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001416 Result += "0, ";
1417 if (PDecl->getClassMethods() > 0) {
1418 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1419 Result += PDecl->getName();
1420 Result += "\n";
1421 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001422 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001423 Result += "0\n";
1424 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001425 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001426 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001427 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1428 Result += prefix;
1429 Result += "_PROTOCOLS_";
1430 Result += ClassName;
1431 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1432 "{\n\t0, ";
1433 Result += utostr(NumProtocols);
1434 Result += "\n";
1435
1436 Result += "\t,{&_OBJC_PROTOCOL_";
1437 Result += Protocols[0]->getName();
1438 Result += " \n";
1439
1440 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001441 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001442 Result += "\t ,&_OBJC_PROTOCOL_";
1443 Result += PDecl->getName();
1444 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001445 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001446 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001447 }
1448}
1449
1450/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1451/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001452void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1453 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001454 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1455 // Find category declaration for this implementation.
1456 ObjcCategoryDecl *CDecl;
1457 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1458 CDecl = CDecl->getNextClassCategory())
1459 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1460 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001461
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001462 char *FullCategoryName = (char*)alloca(
1463 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1464 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1465
1466 // Build _objc_method_list for class's instance methods if needed
1467 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1468 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001469 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001470 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001471
1472 // Build _objc_method_list for class's class methods if needed
1473 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1474 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001475 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001476 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001477
1478 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001479 // Null CDecl is case of a category implementation with no category interface
1480 if (CDecl)
1481 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1482 CDecl->getNumReferencedProtocols(),
1483 "CATEGORY",
1484 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001485
1486 /* struct _objc_category {
1487 char *category_name;
1488 char *class_name;
1489 struct _objc_method_list *instance_methods;
1490 struct _objc_method_list *class_methods;
1491 struct _objc_protocol_list *protocols;
1492 // Objective-C 1.0 extensions
1493 uint32_t size; // sizeof (struct _objc_category)
1494 struct _objc_property_list *instance_properties; // category's own
1495 // @property decl.
1496 };
1497 */
1498
1499 static bool objc_category = false;
1500 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001501 Result += "\nstruct _objc_category {\n";
1502 Result += "\tchar *category_name;\n";
1503 Result += "\tchar *class_name;\n";
1504 Result += "\tstruct _objc_method_list *instance_methods;\n";
1505 Result += "\tstruct _objc_method_list *class_methods;\n";
1506 Result += "\tstruct _objc_protocol_list *protocols;\n";
1507 Result += "\tunsigned int size;\n";
1508 Result += "\tstruct _objc_property_list *instance_properties;\n";
1509 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001510 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001511 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001512 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1513 Result += FullCategoryName;
1514 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1515 Result += IDecl->getName();
1516 Result += "\"\n\t, \"";
1517 Result += ClassDecl->getName();
1518 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001519
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001520 if (IDecl->getNumInstanceMethods() > 0) {
1521 Result += "\t, (struct _objc_method_list *)"
1522 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1523 Result += FullCategoryName;
1524 Result += "\n";
1525 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001526 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001527 Result += "\t, 0\n";
1528 if (IDecl->getNumClassMethods() > 0) {
1529 Result += "\t, (struct _objc_method_list *)"
1530 "&_OBJC_CATEGORY_CLASS_METHODS_";
1531 Result += FullCategoryName;
1532 Result += "\n";
1533 }
1534 else
1535 Result += "\t, 0\n";
1536
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001537 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001538 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1539 Result += FullCategoryName;
1540 Result += "\n";
1541 }
1542 else
1543 Result += "\t, 0\n";
1544 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001545}
1546
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001547/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1548/// ivar offset.
1549void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1550 ObjcIvarDecl *ivar,
1551 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001552 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001553 Result += IDecl->getName();
1554 Result += ", ";
1555 Result += ivar->getName();
1556 Result += ")";
1557}
1558
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001559//===----------------------------------------------------------------------===//
1560// Meta Data Emission
1561//===----------------------------------------------------------------------===//
1562
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001563void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1564 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001565 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1566
1567 // Build _objc_ivar_list metadata for classes ivars if needed
1568 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1569 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001570 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001571
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001572 SynthesizeObjcInternalStruct(CDecl, Result);
1573
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001574 if (NumIvars > 0) {
1575 static bool objc_ivar = false;
1576 if (!objc_ivar) {
1577 /* struct _objc_ivar {
1578 char *ivar_name;
1579 char *ivar_type;
1580 int ivar_offset;
1581 };
1582 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001583 Result += "\nstruct _objc_ivar {\n";
1584 Result += "\tchar *ivar_name;\n";
1585 Result += "\tchar *ivar_type;\n";
1586 Result += "\tint ivar_offset;\n";
1587 Result += "};\n";
1588
1589 /* struct _objc_ivar_list {
1590 int ivar_count;
1591 struct _objc_ivar ivar_list[];
1592 };
1593 */
1594 Result += "\nstruct _objc_ivar_list {\n";
1595 Result += "\tint ivar_count;\n";
1596 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001597 objc_ivar = true;
1598 }
1599
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001600 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1601 Result += IDecl->getName();
1602 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1603 "{\n\t";
1604 Result += utostr(NumIvars);
1605 Result += "\n";
1606
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001607 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1608 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001609 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001610 Result += "\t,{{\"";
1611 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001612 Result += "\", \"";
1613 std::string StrEncoding;
1614 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1615 Result += StrEncoding;
1616 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001617 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1618 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001619 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001620 Result += "\t ,{\"";
1621 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001622 Result += "\", \"";
1623 std::string StrEncoding;
1624 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1625 Result += StrEncoding;
1626 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001627 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1628 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001629 }
1630
1631 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001632 }
1633
1634 // Build _objc_method_list for class's instance methods if needed
1635 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1636 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001637 true,
1638 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001639
1640 // Build _objc_method_list for class's class methods if needed
1641 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001642 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001643 false,
1644 "", IDecl->getName(), Result);
1645
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001646 // Protocols referenced in class declaration?
1647 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1648 CDecl->getNumIntfRefProtocols(),
1649 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001650 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001651
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001652
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001653 // Declaration of class/meta-class metadata
1654 /* struct _objc_class {
1655 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001656 const char *super_class_name;
1657 char *name;
1658 long version;
1659 long info;
1660 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001661 struct _objc_ivar_list *ivars;
1662 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001663 struct objc_cache *cache;
1664 struct objc_protocol_list *protocols;
1665 const char *ivar_layout;
1666 struct _objc_class_ext *ext;
1667 };
1668 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001669 static bool objc_class = false;
1670 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001671 Result += "\nstruct _objc_class {\n";
1672 Result += "\tstruct _objc_class *isa;\n";
1673 Result += "\tconst char *super_class_name;\n";
1674 Result += "\tchar *name;\n";
1675 Result += "\tlong version;\n";
1676 Result += "\tlong info;\n";
1677 Result += "\tlong instance_size;\n";
1678 Result += "\tstruct _objc_ivar_list *ivars;\n";
1679 Result += "\tstruct _objc_method_list *methods;\n";
1680 Result += "\tstruct objc_cache *cache;\n";
1681 Result += "\tstruct _objc_protocol_list *protocols;\n";
1682 Result += "\tconst char *ivar_layout;\n";
1683 Result += "\tstruct _objc_class_ext *ext;\n";
1684 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001685 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001686 }
1687
1688 // Meta-class metadata generation.
1689 ObjcInterfaceDecl *RootClass = 0;
1690 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1691 while (SuperClass) {
1692 RootClass = SuperClass;
1693 SuperClass = SuperClass->getSuperClass();
1694 }
1695 SuperClass = CDecl->getSuperClass();
1696
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001697 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1698 Result += CDecl->getName();
1699 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1700 "{\n\t(struct _objc_class *)\"";
1701 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1702 Result += "\"";
1703
1704 if (SuperClass) {
1705 Result += ", \"";
1706 Result += SuperClass->getName();
1707 Result += "\", \"";
1708 Result += CDecl->getName();
1709 Result += "\"";
1710 }
1711 else {
1712 Result += ", 0, \"";
1713 Result += CDecl->getName();
1714 Result += "\"";
1715 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001716 // TODO: 'ivars' field for root class is currently set to 0.
1717 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001718 Result += ", 0,2, sizeof(struct _objc_class), 0";
1719 if (CDecl->getNumClassMethods() > 0) {
1720 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1721 Result += CDecl->getName();
1722 Result += "\n";
1723 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001724 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001725 Result += ", 0\n";
1726 if (CDecl->getNumIntfRefProtocols() > 0) {
1727 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1728 Result += CDecl->getName();
1729 Result += ",0,0\n";
1730 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001731 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001732 Result += "\t,0,0,0,0\n";
1733 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001734
1735 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001736 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1737 Result += CDecl->getName();
1738 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1739 "{\n\t&_OBJC_METACLASS_";
1740 Result += CDecl->getName();
1741 if (SuperClass) {
1742 Result += ", \"";
1743 Result += SuperClass->getName();
1744 Result += "\", \"";
1745 Result += CDecl->getName();
1746 Result += "\"";
1747 }
1748 else {
1749 Result += ", 0, \"";
1750 Result += CDecl->getName();
1751 Result += "\"";
1752 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001753 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001754 Result += ", 0,1";
1755 if (!ObjcSynthesizedStructs.count(CDecl))
1756 Result += ",0";
1757 else {
1758 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001759 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001760 Result += CDecl->getName();
1761 Result += ")";
1762 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001763 if (NumIvars > 0) {
1764 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1765 Result += CDecl->getName();
1766 Result += "\n\t";
1767 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001768 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001769 Result += ",0";
1770 if (IDecl->getNumInstanceMethods() > 0) {
1771 Result += ", &_OBJC_INSTANCE_METHODS_";
1772 Result += CDecl->getName();
1773 Result += ", 0\n\t";
1774 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001775 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001776 Result += ",0,0";
1777 if (CDecl->getNumIntfRefProtocols() > 0) {
1778 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1779 Result += CDecl->getName();
1780 Result += ", 0,0\n";
1781 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001782 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001783 Result += ",0,0,0\n";
1784 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001785}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001786
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001787/// RewriteImplementations - This routine rewrites all method implementations
1788/// and emits meta-data.
1789
1790void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001791 int ClsDefCount = ClassImplementation.size();
1792 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001793
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001794 if (ClsDefCount == 0 && CatDefCount == 0)
1795 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001796 // Rewrite implemented methods
1797 for (int i = 0; i < ClsDefCount; i++)
1798 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001799
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001800 for (int i = 0; i < CatDefCount; i++)
1801 RewriteImplementationDecl(CategoryImplementation[i]);
1802
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001803 // TODO: This is temporary until we decide how to access objc types in a
1804 // c program
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001805 Result += "#include <Objc/objc.h>\n";
1806 // This is needed for use of offsetof
1807 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001808
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001809 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001810 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001811 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001812
1813 // For each implemented category, write out all its meta data.
1814 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001815 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001816
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001817 // Write objc_symtab metadata
1818 /*
1819 struct _objc_symtab
1820 {
1821 long sel_ref_cnt;
1822 SEL *refs;
1823 short cls_def_cnt;
1824 short cat_def_cnt;
1825 void *defs[cls_def_cnt + cat_def_cnt];
1826 };
1827 */
1828
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001829 Result += "\nstruct _objc_symtab {\n";
1830 Result += "\tlong sel_ref_cnt;\n";
1831 Result += "\tSEL *refs;\n";
1832 Result += "\tshort cls_def_cnt;\n";
1833 Result += "\tshort cat_def_cnt;\n";
1834 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1835 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001836
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001837 Result += "static struct _objc_symtab "
1838 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1839 Result += "\t0, 0, " + utostr(ClsDefCount)
1840 + ", " + utostr(CatDefCount) + "\n";
1841 for (int i = 0; i < ClsDefCount; i++) {
1842 Result += "\t,&_OBJC_CLASS_";
1843 Result += ClassImplementation[i]->getName();
1844 Result += "\n";
1845 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001846
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001847 for (int i = 0; i < CatDefCount; i++) {
1848 Result += "\t,&_OBJC_CATEGORY_";
1849 Result += CategoryImplementation[i]->getClassInterface()->getName();
1850 Result += "_";
1851 Result += CategoryImplementation[i]->getName();
1852 Result += "\n";
1853 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001854
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001855 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001856
1857 // Write objc_module metadata
1858
1859 /*
1860 struct _objc_module {
1861 long version;
1862 long size;
1863 const char *name;
1864 struct _objc_symtab *symtab;
1865 }
1866 */
1867
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001868 Result += "\nstruct _objc_module {\n";
1869 Result += "\tlong version;\n";
1870 Result += "\tlong size;\n";
1871 Result += "\tconst char *name;\n";
1872 Result += "\tstruct _objc_symtab *symtab;\n";
1873 Result += "};\n\n";
1874 Result += "static struct _objc_module "
1875 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001876 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1877 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001878 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001879
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001880}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001881