blob: 78cd90e9a91f266dd520f107919dd2ad7a1a7679 [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];
339 SourceLocation Loc = Method->getLocStart();
340
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000341 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000342
343 // FIXME: handle methods that are declared across multiple lines.
344 }
345}
346
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000347void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
348{
349 for (int i = 0; i < nProperties; i++) {
350 ObjcPropertyDecl *Property = Properties[i];
351 SourceLocation Loc = Property->getLocation();
352
353 Rewrite.ReplaceText(Loc, 0, "// ", 3);
354
355 // FIXME: handle properties that are declared across multiple lines.
356 }
357}
358
Steve Naroff667f1682007-10-30 13:30:57 +0000359void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
360 SourceLocation LocStart = CatDecl->getLocStart();
361
362 // FIXME: handle category headers that are declared across multiple lines.
363 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
364
Steve Naroff18c83382007-11-13 23:01:27 +0000365 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
366 CatDecl->getInstanceMethods());
367 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
368 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000369 // Lastly, comment out the @end.
370 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
371}
372
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000373void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000374 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
375 const char *MainBufStart = MainBuf.first;
376
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000377 SourceLocation LocStart = PDecl->getLocStart();
378
379 // FIXME: handle protocol headers that are declared across multiple lines.
380 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
381
Steve Naroff18c83382007-11-13 23:01:27 +0000382 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
383 PDecl->getInstanceMethods());
384 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
385 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000386 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000387 SourceLocation LocEnd = PDecl->getAtEndLoc();
388 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff0540f3f2007-11-14 03:37:28 +0000389#if 0
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000390 // Must comment out @optional/@required
391 const char *startBuf = SM->getCharacterData(LocStart);
392 const char *endBuf = SM->getCharacterData(LocEnd);
393 for (const char *p = startBuf; p < endBuf; p++) {
394 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
395 std::string CommentedOptional = "/* @optional */";
396 SourceLocation OptionalLoc = SourceLocation::getFileLoc(MainFileID,
397 p-MainBufStart);
398 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
399 CommentedOptional.c_str(), CommentedOptional.size());
400
401 }
402 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
403 std::string CommentedRequired = "/* @required */";
404 SourceLocation OptionalLoc = SourceLocation::getFileLoc(MainFileID,
405 p-MainBufStart);
406 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
407 CommentedRequired.c_str(), CommentedRequired.size());
408
409 }
410 }
Steve Naroff0540f3f2007-11-14 03:37:28 +0000411#endif
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000412}
413
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000414void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
415 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000416 if (LocStart.isInvalid())
417 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000418 // FIXME: handle forward protocol that are declared across multiple lines.
419 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
420}
421
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000422void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
423 std::string &ResultStr) {
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000424 static bool includeObjc = false;
425 if (!includeObjc) {
426 ResultStr += "#include <Objc/objc.h>\n";
427 includeObjc = true;
428 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000429 ResultStr += "\nstatic ";
430 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000431 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000432
433 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000434 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000435
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000436 if (OMD->isInstance())
437 NameStr += "_I_";
438 else
439 NameStr += "_C_";
440
441 NameStr += OMD->getClassInterface()->getName();
442 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000443
444 NamedDecl *MethodContext = OMD->getMethodContext();
445 if (ObjcCategoryImplDecl *CID =
446 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000447 NameStr += CID->getName();
448 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000449 }
450 // Append selector names, replacing ':' with '_'
451 const char *selName = OMD->getSelector().getName().c_str();
452 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000453 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000454 else {
455 std::string selString = OMD->getSelector().getName();
456 int len = selString.size();
457 for (int i = 0; i < len; i++)
458 if (selString[i] == ':')
459 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000460 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000461 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000462 // Remember this name for metadata emission
463 MethodInternalNames[OMD] = NameStr;
464 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000465
466 // Rewrite arguments
467 ResultStr += "(";
468
469 // invisible arguments
470 if (OMD->isInstance()) {
471 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
472 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000473 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
474 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000475 ResultStr += selfTy.getAsString();
476 }
477 else
478 ResultStr += Context->getObjcIdType().getAsString();
479
480 ResultStr += " self, ";
481 ResultStr += Context->getObjcSelType().getAsString();
482 ResultStr += " _cmd";
483
484 // Method arguments.
485 for (int i = 0; i < OMD->getNumParams(); i++) {
486 ParmVarDecl *PDecl = OMD->getParamDecl(i);
487 ResultStr += ", ";
488 ResultStr += PDecl->getType().getAsString();
489 ResultStr += " ";
490 ResultStr += PDecl->getName();
491 }
492 ResultStr += ")";
493
494}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000495void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
496 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
497 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000498
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000499 if (IMD)
500 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
501 else
502 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000503
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000504 int numMethods = IMD ? IMD->getNumInstanceMethods()
505 : CID->getNumInstanceMethods();
506
507 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000508 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000509 ObjcMethodDecl *OMD;
510 if (IMD)
511 OMD = IMD->getInstanceMethods()[i];
512 else
513 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000514 RewriteObjcMethodDecl(OMD, ResultStr);
515 SourceLocation LocStart = OMD->getLocStart();
516 SourceLocation LocEnd = OMD->getBody()->getLocStart();
517
518 const char *startBuf = SM->getCharacterData(LocStart);
519 const char *endBuf = SM->getCharacterData(LocEnd);
520 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
521 ResultStr.c_str(), ResultStr.size());
522 }
523
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000524 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
525 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000526 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000527 ObjcMethodDecl *OMD;
528 if (IMD)
529 OMD = IMD->getClassMethods()[i];
530 else
531 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000532 RewriteObjcMethodDecl(OMD, ResultStr);
533 SourceLocation LocStart = OMD->getLocStart();
534 SourceLocation LocEnd = OMD->getBody()->getLocStart();
535
536 const char *startBuf = SM->getCharacterData(LocStart);
537 const char *endBuf = SM->getCharacterData(LocEnd);
538 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
539 ResultStr.c_str(), ResultStr.size());
540 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000541 if (IMD)
542 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
543 else
544 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000545}
546
Steve Naroff3774dd92007-10-26 20:53:56 +0000547void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000548
549 SourceLocation LocStart = ClassDecl->getLocStart();
550 SourceLocation LocEnd = ClassDecl->getLocEnd();
551
552 const char *startBuf = SM->getCharacterData(LocStart);
553 const char *endBuf = SM->getCharacterData(LocEnd);
554
Steve Naroff1ccf4632007-10-30 03:43:13 +0000555 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Naroffef20ed32007-10-30 02:23:23 +0000556
557 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000558 if (!ObjcForwardDecls.count(ClassDecl)) {
559 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2aeae312007-11-09 12:50:28 +0000560 ResultStr += "#ifndef _REWRITER_typedef_";
561 ResultStr += ClassDecl->getName();
562 ResultStr += "\n";
563 ResultStr += "#define _REWRITER_typedef_";
564 ResultStr += ClassDecl->getName();
565 ResultStr += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000566 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000567 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000568 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000569
570 // Mark this typedef as having been generated.
571 ObjcForwardDecls.insert(ClassDecl);
572 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000573 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
574
Steve Naroff1ccf4632007-10-30 03:43:13 +0000575 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Naroffef20ed32007-10-30 02:23:23 +0000576 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000577 RewriteProperties(ClassDecl->getNumPropertyDecl(),
578 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000579 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
580 ClassDecl->getInstanceMethods());
581 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
582 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000583
Steve Naroff1ccf4632007-10-30 03:43:13 +0000584 // Lastly, comment out the @end.
585 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000586}
587
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000588//===----------------------------------------------------------------------===//
589// Function Body / Expression rewriting
590//===----------------------------------------------------------------------===//
591
Steve Naroff334fbc22007-11-09 15:20:18 +0000592Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000593 // Otherwise, just rewrite all children.
594 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
595 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000596 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000597 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000598 if (newStmt)
599 *CI = newStmt;
600 }
Steve Naroffe9780582007-10-23 23:50:29 +0000601
602 // Handle specific things.
603 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
604 return RewriteAtEncode(AtEncode);
Steve Naroff296b74f2007-11-05 14:50:49 +0000605
606 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
607 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000608
609 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
610 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000611
Steve Naroff71226032007-10-24 22:48:43 +0000612 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
613 // Before we rewrite it, put the original message expression in a comment.
614 SourceLocation startLoc = MessExpr->getLocStart();
615 SourceLocation endLoc = MessExpr->getLocEnd();
616
617 const char *startBuf = SM->getCharacterData(startLoc);
618 const char *endBuf = SM->getCharacterData(endLoc);
619
620 std::string messString;
621 messString += "// ";
622 messString.append(startBuf, endBuf-startBuf+1);
623 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000624
Steve Naroff71226032007-10-24 22:48:43 +0000625 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
626 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
627 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000628 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000629 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000630 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000631
632 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
633 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000634
635 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
636 return RewriteObjcThrowStmt(StmtThrow);
637
Chris Lattner0021f452007-10-24 16:57:36 +0000638 // Return this stmt unmodified.
639 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000640}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000641
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000642Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000643 // Get the start location and compute the semi location.
644 SourceLocation startLoc = S->getLocStart();
645 const char *startBuf = SM->getCharacterData(startLoc);
646
647 assert((*startBuf == '@') && "bogus @try location");
648
649 std::string buf;
650 // declare a new scope with two variables, _stack and _rethrow.
651 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
652 buf += "int buf[18/*32-bit i386*/];\n";
653 buf += "char *pointers[4];} _stack;\n";
654 buf += "id volatile _rethrow = 0;\n";
655 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000656 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000657
658 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
659
660 startLoc = S->getTryBody()->getLocEnd();
661 startBuf = SM->getCharacterData(startLoc);
662
663 assert((*startBuf == '}') && "bogus @try block");
664
665 SourceLocation lastCurlyLoc = startLoc;
666
667 startLoc = startLoc.getFileLocWithOffset(1);
668 buf = " /* @catch begin */ else {\n";
669 buf += " id _caught = objc_exception_extract(&_stack);\n";
670 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000671 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000672 buf += " _rethrow = objc_exception_extract(&_stack);\n";
673 buf += " else { /* @catch continue */";
674
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000675 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000676
677 bool sawIdTypedCatch = false;
678 Stmt *lastCatchBody = 0;
679 ObjcAtCatchStmt *catchList = S->getCatchStmts();
680 while (catchList) {
681 Stmt *catchStmt = catchList->getCatchParamStmt();
682
683 if (catchList == S->getCatchStmts())
684 buf = "if ("; // we are generating code for the first catch clause
685 else
686 buf = "else if (";
687 startLoc = catchList->getLocStart();
688 startBuf = SM->getCharacterData(startLoc);
689
690 assert((*startBuf == '@') && "bogus @catch location");
691
692 const char *lParenLoc = strchr(startBuf, '(');
693
694 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
695 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
696 if (t == Context->getObjcIdType()) {
697 buf += "1) { ";
698 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
699 buf.c_str(), buf.size());
700 sawIdTypedCatch = true;
701 } else if (const PointerType *pType = t->getAsPointerType()) {
702 ObjcInterfaceType *cls; // Should be a pointer to a class.
703
704 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
705 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000706 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000707 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000708 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000709 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
710 buf.c_str(), buf.size());
711 }
712 }
713 // Now rewrite the body...
714 lastCatchBody = catchList->getCatchBody();
715 SourceLocation rParenLoc = catchList->getRParenLoc();
716 SourceLocation bodyLoc = lastCatchBody->getLocStart();
717 const char *bodyBuf = SM->getCharacterData(bodyLoc);
718 const char *rParenBuf = SM->getCharacterData(rParenLoc);
719 assert((*rParenBuf == ')') && "bogus @catch paren location");
720 assert((*bodyBuf == '{') && "bogus @catch body location");
721
722 buf = " = _caught;";
723 // Here we replace ") {" with "= _caught;" (which initializes and
724 // declares the @catch parameter).
725 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
726 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000727 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000728 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000729 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000730 catchList = catchList->getNextCatchStmt();
731 }
732 // Complete the catch list...
733 if (lastCatchBody) {
734 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
735 const char *bodyBuf = SM->getCharacterData(bodyLoc);
736 assert((*bodyBuf == '}') && "bogus @catch body location");
737 bodyLoc = bodyLoc.getFileLocWithOffset(1);
738 buf = " } } /* @catch end */\n";
739
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000740 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000741
742 // Set lastCurlyLoc
743 lastCurlyLoc = lastCatchBody->getLocEnd();
744 }
745 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
746 startLoc = finalStmt->getLocStart();
747 startBuf = SM->getCharacterData(startLoc);
748 assert((*startBuf == '@') && "bogus @finally start");
749
750 buf = "/* @finally */";
751 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
752
753 Stmt *body = finalStmt->getFinallyBody();
754 SourceLocation startLoc = body->getLocStart();
755 SourceLocation endLoc = body->getLocEnd();
756 const char *startBuf = SM->getCharacterData(startLoc);
757 const char *endBuf = SM->getCharacterData(endLoc);
758 assert((*startBuf == '{') && "bogus @finally body location");
759 assert((*endBuf == '}') && "bogus @finally body location");
760
761 startLoc = startLoc.getFileLocWithOffset(1);
762 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000763 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000764 endLoc = endLoc.getFileLocWithOffset(-1);
765 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000766 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000767
768 // Set lastCurlyLoc
769 lastCurlyLoc = body->getLocEnd();
770 }
771 // Now emit the final closing curly brace...
772 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
773 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000774 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000775 return 0;
776}
777
778Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
779 return 0;
780}
781
782Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
783 return 0;
784}
785
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000786// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
787// the throw expression is typically a message expression that's already
788// been rewritten! (which implies the SourceLocation's are invalid).
789Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
790 // Get the start location and compute the semi location.
791 SourceLocation startLoc = S->getLocStart();
792 const char *startBuf = SM->getCharacterData(startLoc);
793
794 assert((*startBuf == '@') && "bogus @throw location");
795
796 std::string buf;
797 /* void objc_exception_throw(id) __attribute__((noreturn)); */
798 buf = "objc_exception_throw(";
799 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
800 const char *semiBuf = strchr(startBuf, ';');
801 assert((*semiBuf == ';') && "@throw: can't find ';'");
802 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
803 buf = ");";
804 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
805 return 0;
806}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000807
Chris Lattner0021f452007-10-24 16:57:36 +0000808Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000809 // Create a new string expression.
810 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000811 std::string StrEncoding;
812 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
813 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
814 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000815 SourceLocation(), SourceLocation());
816 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000817 delete Exp;
818 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000819}
820
Steve Naroff296b74f2007-11-05 14:50:49 +0000821Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
822 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
823 // Create a call to sel_registerName("selName").
824 llvm::SmallVector<Expr*, 8> SelExprs;
825 QualType argType = Context->getPointerType(Context->CharTy);
826 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
827 Exp->getSelector().getName().size(),
828 false, argType, SourceLocation(),
829 SourceLocation()));
830 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
831 &SelExprs[0], SelExprs.size());
832 Rewrite.ReplaceStmt(Exp, SelExp);
833 delete Exp;
834 return SelExp;
835}
836
Steve Naroff71226032007-10-24 22:48:43 +0000837CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
838 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000839 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000840 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000841
842 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000843 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000844
845 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000846 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000847 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
848
849 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000850
Steve Naroff71226032007-10-24 22:48:43 +0000851 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
852}
853
Steve Naroffc8a92d12007-11-01 13:24:47 +0000854static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
855 const char *&startRef, const char *&endRef) {
856 while (startBuf < endBuf) {
857 if (*startBuf == '<')
858 startRef = startBuf; // mark the start.
859 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000860 if (startRef && *startRef == '<') {
861 endRef = startBuf; // mark the end.
862 return true;
863 }
864 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000865 }
866 startBuf++;
867 }
868 return false;
869}
870
871bool RewriteTest::needToScanForQualifiers(QualType T) {
872 // FIXME: we don't currently represent "id <Protocol>" in the type system.
873 if (T == Context->getObjcIdType())
874 return true;
875
876 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000877 Type *pointeeType = pType->getPointeeType().getTypePtr();
878 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
879 return true; // we have "Class <Protocol> *".
880 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000881 return false;
882}
883
884void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
885 const FunctionTypeProto *proto, FunctionDecl *FD) {
886
887 if (needToScanForQualifiers(proto->getResultType())) {
888 // Since types are unique, we need to scan the buffer.
889 SourceLocation Loc = FD->getLocation();
890
891 const char *endBuf = SM->getCharacterData(Loc);
892 const char *startBuf = endBuf;
893 while (*startBuf != ';')
894 startBuf--; // scan backward (from the decl location) for return type.
895 const char *startRef = 0, *endRef = 0;
896 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
897 // Get the locations of the startRef, endRef.
898 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
899 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
900 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000901 Rewrite.InsertText(LessLoc, "/*", 2);
902 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000903 }
904 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000905 // Now check arguments.
906 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
907 if (needToScanForQualifiers(proto->getArgType(i))) {
908 // Since types are unique, we need to scan the buffer.
909 SourceLocation Loc = FD->getLocation();
910
911 const char *startBuf = SM->getCharacterData(Loc);
912 const char *endBuf = startBuf;
913 while (*endBuf != ';')
914 endBuf++; // scan forward (from the decl location) for argument types.
915 const char *startRef = 0, *endRef = 0;
916 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
917 // Get the locations of the startRef, endRef.
918 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
919 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
920 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000921 Rewrite.InsertText(LessLoc, "/*", 2);
922 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000923 }
924 }
925 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000926}
927
Steve Naroff02a82aa2007-10-30 23:14:51 +0000928void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
929 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000930 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000931 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000932 return;
933 }
934 // Check for ObjC 'id' and class types that have been adorned with protocol
935 // information (id<p>, C<p>*). The protocol references need to be rewritten!
936 const FunctionType *funcType = FD->getType()->getAsFunctionType();
937 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000938 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
939 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000940}
941
942// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
943void RewriteTest::SynthMsgSendFunctionDecl() {
944 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
945 llvm::SmallVector<QualType, 16> ArgTys;
946 QualType argT = Context->getObjcIdType();
947 assert(!argT.isNull() && "Can't find 'id' type");
948 ArgTys.push_back(argT);
949 argT = Context->getObjcSelType();
950 assert(!argT.isNull() && "Can't find 'SEL' type");
951 ArgTys.push_back(argT);
952 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
953 &ArgTys[0], ArgTys.size(),
954 true /*isVariadic*/);
955 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
956 msgSendIdent, msgSendType,
957 FunctionDecl::Extern, false, 0);
958}
959
960// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
961void RewriteTest::SynthGetClassFunctionDecl() {
962 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
963 llvm::SmallVector<QualType, 16> ArgTys;
964 ArgTys.push_back(Context->getPointerType(
965 Context->CharTy.getQualifiedType(QualType::Const)));
966 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
967 &ArgTys[0], ArgTys.size(),
968 false /*isVariadic*/);
969 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
970 getClassIdent, getClassType,
971 FunctionDecl::Extern, false, 0);
972}
973
Steve Naroffabb96362007-11-08 14:30:50 +0000974// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
975void RewriteTest::SynthCFStringFunctionDecl() {
976 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
977 llvm::SmallVector<QualType, 16> ArgTys;
978 ArgTys.push_back(Context->getPointerType(
979 Context->CharTy.getQualifiedType(QualType::Const)));
980 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
981 &ArgTys[0], ArgTys.size(),
982 false /*isVariadic*/);
983 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
984 getClassIdent, getClassType,
985 FunctionDecl::Extern, false, 0);
986}
987
Steve Naroff0add5d22007-11-03 11:27:19 +0000988Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +0000989#if 1
990 // This rewrite is specific to GCC, which has builtin support for CFString.
991 if (!CFStringFunctionDecl)
992 SynthCFStringFunctionDecl();
993 // Create a call to __builtin___CFStringMakeConstantString("cstr").
994 llvm::SmallVector<Expr*, 8> StrExpr;
995 StrExpr.push_back(Exp->getString());
996 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
997 &StrExpr[0], StrExpr.size());
998 // cast to NSConstantString *
999 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1000 Rewrite.ReplaceStmt(Exp, cast);
1001 delete Exp;
1002 return cast;
1003#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001004 assert(ConstantStringClassReference && "Can't find constant string reference");
1005 llvm::SmallVector<Expr*, 4> InitExprs;
1006
1007 // Synthesize "(Class)&_NSConstantStringClassReference"
1008 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1009 ConstantStringClassReference->getType(),
1010 SourceLocation());
1011 QualType expType = Context->getPointerType(ClsRef->getType());
1012 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1013 expType, SourceLocation());
1014 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1015 SourceLocation());
1016 InitExprs.push_back(cast); // set the 'isa'.
1017 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1018 unsigned IntSize = static_cast<unsigned>(
1019 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1020 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1021 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1022 Exp->getLocStart());
1023 InitExprs.push_back(len); // set "int numBytes".
1024
1025 // struct NSConstantString
1026 QualType CFConstantStrType = Context->getCFConstantStringType();
1027 // (struct NSConstantString) { <exprs from above> }
1028 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1029 &InitExprs[0], InitExprs.size(),
1030 SourceLocation());
1031 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1032 // struct NSConstantString *
1033 expType = Context->getPointerType(StrRep->getType());
1034 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1035 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001036 // cast to NSConstantString *
1037 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001038 Rewrite.ReplaceStmt(Exp, cast);
1039 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001040 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001041#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001042}
1043
Steve Naroff71226032007-10-24 22:48:43 +00001044Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +00001045 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +00001046 if (!MsgSendFunctionDecl)
1047 SynthMsgSendFunctionDecl();
1048 if (!GetClassFunctionDecl)
1049 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +00001050
1051 // Synthesize a call to objc_msgSend().
1052 llvm::SmallVector<Expr*, 8> MsgExprs;
1053 IdentifierInfo *clsName = Exp->getClassName();
1054
1055 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1056 if (clsName) { // class message.
1057 llvm::SmallVector<Expr*, 8> ClsExprs;
1058 QualType argType = Context->getPointerType(Context->CharTy);
1059 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1060 clsName->getLength(),
1061 false, argType, SourceLocation(),
1062 SourceLocation()));
1063 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1064 &ClsExprs[0], ClsExprs.size());
1065 MsgExprs.push_back(Cls);
1066 } else // instance message.
1067 MsgExprs.push_back(Exp->getReceiver());
1068
Steve Naroff0add5d22007-11-03 11:27:19 +00001069 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001070 llvm::SmallVector<Expr*, 8> SelExprs;
1071 QualType argType = Context->getPointerType(Context->CharTy);
1072 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1073 Exp->getSelector().getName().size(),
1074 false, argType, SourceLocation(),
1075 SourceLocation()));
1076 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1077 &SelExprs[0], SelExprs.size());
1078 MsgExprs.push_back(SelExp);
1079
1080 // Now push any user supplied arguments.
1081 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1082 MsgExprs.push_back(Exp->getArg(i));
1083 // We've transferred the ownership to MsgExprs. Null out the argument in
1084 // the original expression, since we will delete it below.
1085 Exp->setArg(i, 0);
1086 }
Steve Naroff0744c472007-11-04 22:37:50 +00001087 // Generate the funky cast.
1088 CastExpr *cast;
1089 llvm::SmallVector<QualType, 8> ArgTypes;
1090 QualType returnType;
1091
1092 // Push 'id' and 'SEL', the 2 implicit arguments.
1093 ArgTypes.push_back(Context->getObjcIdType());
1094 ArgTypes.push_back(Context->getObjcSelType());
1095 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1096 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001097 for (int i = 0; i < mDecl->getNumParams(); i++) {
1098 QualType t = mDecl->getParamDecl(i)->getType();
1099 if (t == Context->getObjcClassType())
1100 t = Context->getObjcIdType(); // Convert "Class"->"id"
1101 ArgTypes.push_back(t);
1102 }
Steve Naroff0744c472007-11-04 22:37:50 +00001103 returnType = mDecl->getResultType();
1104 } else {
1105 returnType = Context->getObjcIdType();
1106 }
1107 // Get the type, we will need to reference it in a couple spots.
1108 QualType msgSendType = MsgSendFunctionDecl->getType();
1109
1110 // Create a reference to the objc_msgSend() declaration.
1111 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1112
1113 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1114 // If we don't do this cast, we get the following bizarre warning/note:
1115 // xx.m:13: warning: function called through a non-compatible type
1116 // xx.m:13: note: if this code is reached, the program will abort
1117 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1118 SourceLocation());
1119
1120 // Now do the "normal" pointer to function cast.
1121 QualType castType = Context->getFunctionType(returnType,
1122 &ArgTypes[0], ArgTypes.size(),
1123 false/*FIXME:variadic*/);
1124 castType = Context->getPointerType(castType);
1125 cast = new CastExpr(castType, cast, SourceLocation());
1126
1127 // Don't forget the parens to enforce the proper binding.
1128 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1129
1130 const FunctionType *FT = msgSendType->getAsFunctionType();
1131 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1132 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001133 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001134 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001135
Chris Lattner0021f452007-10-24 16:57:36 +00001136 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001137 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001138}
1139
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001140/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1141/// an objective-c class with ivars.
1142void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1143 std::string &Result) {
1144 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1145 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001146 // Do not synthesize more than once.
1147 if (ObjcSynthesizedStructs.count(CDecl))
1148 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001149 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1150 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1151 // Do it for the root
1152 SynthesizeObjcInternalStruct(RCDecl, Result);
1153 }
1154
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001155 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001156 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +00001157 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001158 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1159 return;
1160
Steve Naroffb1147382007-11-01 17:12:31 +00001161 Result += "\nstruct ";
1162 Result += CDecl->getName();
1163 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1164 Result += " {\n struct ";
1165 Result += RCDecl->getName();
1166 Result += " _";
1167 Result += RCDecl->getName();
1168 Result += ";\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001169 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001170 else
1171 Result += " {";
Steve Naroff809b4f02007-10-31 22:11:35 +00001172
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001173 if (NumIvars > 0) {
1174 SourceLocation LocStart = CDecl->getLocStart();
1175 SourceLocation LocEnd = CDecl->getLocEnd();
1176
1177 const char *startBuf = SM->getCharacterData(LocStart);
1178 const char *endBuf = SM->getCharacterData(LocEnd);
1179 startBuf = strchr(startBuf, '{');
1180 assert((startBuf && endBuf)
1181 && "SynthesizeObjcInternalStruct - malformed @interface");
1182 startBuf++; // past '{'
1183 while (startBuf < endBuf) {
1184 if (*startBuf == '@') {
1185 startBuf = strchr(startBuf, 'p');
1186 // FIXME: presence of @public, etc. inside comment results in
1187 // this transformation as well, which is still correct c-code.
1188 if (!strncmp(startBuf, "public", strlen("public"))) {
1189 startBuf += strlen("public");
1190 Result += "/* @public */";
1191 }
1192 else if (!strncmp(startBuf, "private", strlen("private"))) {
1193 startBuf += strlen("private");
1194 Result += "/* @private */";
1195 }
1196 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1197 startBuf += strlen("protected");
1198 Result += "/* @protected */";
1199 }
1200 }
1201 Result += *startBuf++;
1202 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001203 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001204
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001205 Result += "};\n";
1206 // Mark this struct as having been generated.
1207 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001208 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001209}
1210
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001211// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1212/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001213void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001214 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001215 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001216 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001217 const char *ClassName,
1218 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001219 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001220 if (NumMethods > 0 && !objc_impl_method) {
1221 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001222 SEL _cmd;
1223 char *method_types;
1224 void *_imp;
1225 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001226 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001227 Result += "\nstruct _objc_method {\n";
1228 Result += "\tSEL _cmd;\n";
1229 Result += "\tchar *method_types;\n";
1230 Result += "\tvoid *_imp;\n";
1231 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001232
1233 /* struct _objc_method_list {
1234 struct _objc_method_list *next_method;
1235 int method_count;
1236 struct _objc_method method_list[];
1237 }
1238 */
1239 Result += "\nstruct _objc_method_list {\n";
1240 Result += "\tstruct _objc_method_list *next_method;\n";
1241 Result += "\tint method_count;\n";
1242 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001243 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001244 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001245 // Build _objc_method_list for class's methods if needed
1246 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001247 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001248 Result += prefix;
1249 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1250 Result += "_METHODS_";
1251 Result += ClassName;
1252 Result += " __attribute__ ((section (\"__OBJC, __";
1253 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001254 Result += "_meth\")))= ";
1255 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1256
1257 Result += "\t,{{(SEL)\"";
1258 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001259 std::string MethodTypeString;
1260 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1261 Result += "\", \"";
1262 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001263 Result += "\", ";
1264 Result += MethodInternalNames[Methods[0]];
1265 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001266 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001267 Result += "\t ,{(SEL)\"";
1268 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001269 std::string MethodTypeString;
1270 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1271 Result += "\", \"";
1272 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001273 Result += "\", ";
1274 Result += MethodInternalNames[Methods[i]];
1275 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001276 }
1277 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001278 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001279}
1280
1281/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1282void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1283 int NumProtocols,
1284 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001285 const char *ClassName,
1286 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001287 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001288 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001289 for (int i = 0; i < NumProtocols; i++) {
1290 ObjcProtocolDecl *PDecl = Protocols[i];
1291 // Output struct protocol_methods holder of method selector and type.
1292 if (!objc_protocol_methods &&
1293 (PDecl->getNumInstanceMethods() > 0
1294 || PDecl->getNumClassMethods() > 0)) {
1295 /* struct protocol_methods {
1296 SEL _cmd;
1297 char *method_types;
1298 }
1299 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001300 Result += "\nstruct protocol_methods {\n";
1301 Result += "\tSEL _cmd;\n";
1302 Result += "\tchar *method_types;\n";
1303 Result += "};\n";
1304
1305 /* struct _objc_protocol_method_list {
1306 int protocol_method_count;
1307 struct protocol_methods protocols[];
1308 }
1309 */
1310 Result += "\nstruct _objc_protocol_method_list {\n";
1311 Result += "\tint protocol_method_count;\n";
1312 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001313 objc_protocol_methods = true;
1314 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001315
Fariborz Jahanian04455192007-10-22 21:41:37 +00001316 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001317 int NumMethods = PDecl->getNumInstanceMethods();
1318 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001319 Result += "\nstatic struct _objc_protocol_method_list "
1320 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1321 Result += PDecl->getName();
1322 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1323 "{\n\t" + utostr(NumMethods) + "\n";
1324
Fariborz Jahanian04455192007-10-22 21:41:37 +00001325 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001326 Result += "\t,{{(SEL)\"";
1327 Result += Methods[0]->getSelector().getName().c_str();
1328 Result += "\", \"\"}\n";
1329
1330 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001331 Result += "\t ,{(SEL)\"";
1332 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001333 std::string MethodTypeString;
1334 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1335 Result += "\", \"";
1336 Result += MethodTypeString;
1337 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001338 }
1339 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001340 }
1341
1342 // Output class methods declared in this protocol.
1343 NumMethods = PDecl->getNumClassMethods();
1344 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001345 Result += "\nstatic struct _objc_protocol_method_list "
1346 "_OBJC_PROTOCOL_CLASS_METHODS_";
1347 Result += PDecl->getName();
1348 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1349 "{\n\t";
1350 Result += utostr(NumMethods);
1351 Result += "\n";
1352
Fariborz Jahanian04455192007-10-22 21:41:37 +00001353 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001354 Result += "\t,{{(SEL)\"";
1355 Result += Methods[0]->getSelector().getName().c_str();
1356 Result += "\", \"\"}\n";
1357
1358 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001359 Result += "\t ,{(SEL)\"";
1360 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001361 std::string MethodTypeString;
1362 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1363 Result += "\", \"";
1364 Result += MethodTypeString;
1365 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001366 }
1367 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001368 }
1369 // Output:
1370 /* struct _objc_protocol {
1371 // Objective-C 1.0 extensions
1372 struct _objc_protocol_extension *isa;
1373 char *protocol_name;
1374 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001375 struct _objc_protocol_method_list *instance_methods;
1376 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001377 };
1378 */
1379 static bool objc_protocol = false;
1380 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001381 Result += "\nstruct _objc_protocol {\n";
1382 Result += "\tstruct _objc_protocol_extension *isa;\n";
1383 Result += "\tchar *protocol_name;\n";
1384 Result += "\tstruct _objc_protocol **protocol_list;\n";
1385 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1386 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1387 Result += "};\n";
1388
1389 /* struct _objc_protocol_list {
1390 struct _objc_protocol_list *next;
1391 int protocol_count;
1392 struct _objc_protocol *class_protocols[];
1393 }
1394 */
1395 Result += "\nstruct _objc_protocol_list {\n";
1396 Result += "\tstruct _objc_protocol_list *next;\n";
1397 Result += "\tint protocol_count;\n";
1398 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1399 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001400 objc_protocol = true;
1401 }
1402
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001403 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1404 Result += PDecl->getName();
1405 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1406 "{\n\t0, \"";
1407 Result += PDecl->getName();
1408 Result += "\", 0, ";
1409 if (PDecl->getInstanceMethods() > 0) {
1410 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1411 Result += PDecl->getName();
1412 Result += ", ";
1413 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001414 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001415 Result += "0, ";
1416 if (PDecl->getClassMethods() > 0) {
1417 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1418 Result += PDecl->getName();
1419 Result += "\n";
1420 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001421 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001422 Result += "0\n";
1423 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001424 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001425 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001426 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1427 Result += prefix;
1428 Result += "_PROTOCOLS_";
1429 Result += ClassName;
1430 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1431 "{\n\t0, ";
1432 Result += utostr(NumProtocols);
1433 Result += "\n";
1434
1435 Result += "\t,{&_OBJC_PROTOCOL_";
1436 Result += Protocols[0]->getName();
1437 Result += " \n";
1438
1439 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001440 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001441 Result += "\t ,&_OBJC_PROTOCOL_";
1442 Result += PDecl->getName();
1443 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001444 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001445 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001446 }
1447}
1448
1449/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1450/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001451void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1452 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001453 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1454 // Find category declaration for this implementation.
1455 ObjcCategoryDecl *CDecl;
1456 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1457 CDecl = CDecl->getNextClassCategory())
1458 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1459 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001460
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001461 char *FullCategoryName = (char*)alloca(
1462 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1463 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1464
1465 // Build _objc_method_list for class's instance methods if needed
1466 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1467 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001468 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001469 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001470
1471 // Build _objc_method_list for class's class methods if needed
1472 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1473 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001474 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001475 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001476
1477 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001478 // Null CDecl is case of a category implementation with no category interface
1479 if (CDecl)
1480 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1481 CDecl->getNumReferencedProtocols(),
1482 "CATEGORY",
1483 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001484
1485 /* struct _objc_category {
1486 char *category_name;
1487 char *class_name;
1488 struct _objc_method_list *instance_methods;
1489 struct _objc_method_list *class_methods;
1490 struct _objc_protocol_list *protocols;
1491 // Objective-C 1.0 extensions
1492 uint32_t size; // sizeof (struct _objc_category)
1493 struct _objc_property_list *instance_properties; // category's own
1494 // @property decl.
1495 };
1496 */
1497
1498 static bool objc_category = false;
1499 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001500 Result += "\nstruct _objc_category {\n";
1501 Result += "\tchar *category_name;\n";
1502 Result += "\tchar *class_name;\n";
1503 Result += "\tstruct _objc_method_list *instance_methods;\n";
1504 Result += "\tstruct _objc_method_list *class_methods;\n";
1505 Result += "\tstruct _objc_protocol_list *protocols;\n";
1506 Result += "\tunsigned int size;\n";
1507 Result += "\tstruct _objc_property_list *instance_properties;\n";
1508 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001509 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001510 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001511 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1512 Result += FullCategoryName;
1513 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1514 Result += IDecl->getName();
1515 Result += "\"\n\t, \"";
1516 Result += ClassDecl->getName();
1517 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001518
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001519 if (IDecl->getNumInstanceMethods() > 0) {
1520 Result += "\t, (struct _objc_method_list *)"
1521 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1522 Result += FullCategoryName;
1523 Result += "\n";
1524 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001525 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001526 Result += "\t, 0\n";
1527 if (IDecl->getNumClassMethods() > 0) {
1528 Result += "\t, (struct _objc_method_list *)"
1529 "&_OBJC_CATEGORY_CLASS_METHODS_";
1530 Result += FullCategoryName;
1531 Result += "\n";
1532 }
1533 else
1534 Result += "\t, 0\n";
1535
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001536 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001537 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1538 Result += FullCategoryName;
1539 Result += "\n";
1540 }
1541 else
1542 Result += "\t, 0\n";
1543 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001544}
1545
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001546/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1547/// ivar offset.
1548void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1549 ObjcIvarDecl *ivar,
1550 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001551 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001552 Result += IDecl->getName();
1553 Result += ", ";
1554 Result += ivar->getName();
1555 Result += ")";
1556}
1557
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001558//===----------------------------------------------------------------------===//
1559// Meta Data Emission
1560//===----------------------------------------------------------------------===//
1561
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001562void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1563 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001564 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1565
1566 // Build _objc_ivar_list metadata for classes ivars if needed
1567 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1568 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001569 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001570
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001571 SynthesizeObjcInternalStruct(CDecl, Result);
1572
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001573 if (NumIvars > 0) {
1574 static bool objc_ivar = false;
1575 if (!objc_ivar) {
1576 /* struct _objc_ivar {
1577 char *ivar_name;
1578 char *ivar_type;
1579 int ivar_offset;
1580 };
1581 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001582 Result += "\nstruct _objc_ivar {\n";
1583 Result += "\tchar *ivar_name;\n";
1584 Result += "\tchar *ivar_type;\n";
1585 Result += "\tint ivar_offset;\n";
1586 Result += "};\n";
1587
1588 /* struct _objc_ivar_list {
1589 int ivar_count;
1590 struct _objc_ivar ivar_list[];
1591 };
1592 */
1593 Result += "\nstruct _objc_ivar_list {\n";
1594 Result += "\tint ivar_count;\n";
1595 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001596 objc_ivar = true;
1597 }
1598
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001599 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1600 Result += IDecl->getName();
1601 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1602 "{\n\t";
1603 Result += utostr(NumIvars);
1604 Result += "\n";
1605
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001606 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1607 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001608 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001609 Result += "\t,{{\"";
1610 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001611 Result += "\", \"";
1612 std::string StrEncoding;
1613 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1614 Result += StrEncoding;
1615 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001616 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1617 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001618 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001619 Result += "\t ,{\"";
1620 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001621 Result += "\", \"";
1622 std::string StrEncoding;
1623 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1624 Result += StrEncoding;
1625 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001626 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1627 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001628 }
1629
1630 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001631 }
1632
1633 // Build _objc_method_list for class's instance methods if needed
1634 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1635 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001636 true,
1637 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001638
1639 // Build _objc_method_list for class's class methods if needed
1640 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001641 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001642 false,
1643 "", IDecl->getName(), Result);
1644
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001645 // Protocols referenced in class declaration?
1646 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1647 CDecl->getNumIntfRefProtocols(),
1648 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001649 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001650
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001651
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001652 // Declaration of class/meta-class metadata
1653 /* struct _objc_class {
1654 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001655 const char *super_class_name;
1656 char *name;
1657 long version;
1658 long info;
1659 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001660 struct _objc_ivar_list *ivars;
1661 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001662 struct objc_cache *cache;
1663 struct objc_protocol_list *protocols;
1664 const char *ivar_layout;
1665 struct _objc_class_ext *ext;
1666 };
1667 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001668 static bool objc_class = false;
1669 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001670 Result += "\nstruct _objc_class {\n";
1671 Result += "\tstruct _objc_class *isa;\n";
1672 Result += "\tconst char *super_class_name;\n";
1673 Result += "\tchar *name;\n";
1674 Result += "\tlong version;\n";
1675 Result += "\tlong info;\n";
1676 Result += "\tlong instance_size;\n";
1677 Result += "\tstruct _objc_ivar_list *ivars;\n";
1678 Result += "\tstruct _objc_method_list *methods;\n";
1679 Result += "\tstruct objc_cache *cache;\n";
1680 Result += "\tstruct _objc_protocol_list *protocols;\n";
1681 Result += "\tconst char *ivar_layout;\n";
1682 Result += "\tstruct _objc_class_ext *ext;\n";
1683 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001684 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001685 }
1686
1687 // Meta-class metadata generation.
1688 ObjcInterfaceDecl *RootClass = 0;
1689 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1690 while (SuperClass) {
1691 RootClass = SuperClass;
1692 SuperClass = SuperClass->getSuperClass();
1693 }
1694 SuperClass = CDecl->getSuperClass();
1695
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001696 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1697 Result += CDecl->getName();
1698 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1699 "{\n\t(struct _objc_class *)\"";
1700 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1701 Result += "\"";
1702
1703 if (SuperClass) {
1704 Result += ", \"";
1705 Result += SuperClass->getName();
1706 Result += "\", \"";
1707 Result += CDecl->getName();
1708 Result += "\"";
1709 }
1710 else {
1711 Result += ", 0, \"";
1712 Result += CDecl->getName();
1713 Result += "\"";
1714 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001715 // TODO: 'ivars' field for root class is currently set to 0.
1716 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001717 Result += ", 0,2, sizeof(struct _objc_class), 0";
1718 if (CDecl->getNumClassMethods() > 0) {
1719 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1720 Result += CDecl->getName();
1721 Result += "\n";
1722 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001723 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001724 Result += ", 0\n";
1725 if (CDecl->getNumIntfRefProtocols() > 0) {
1726 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1727 Result += CDecl->getName();
1728 Result += ",0,0\n";
1729 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001730 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001731 Result += "\t,0,0,0,0\n";
1732 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001733
1734 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001735 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1736 Result += CDecl->getName();
1737 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1738 "{\n\t&_OBJC_METACLASS_";
1739 Result += CDecl->getName();
1740 if (SuperClass) {
1741 Result += ", \"";
1742 Result += SuperClass->getName();
1743 Result += "\", \"";
1744 Result += CDecl->getName();
1745 Result += "\"";
1746 }
1747 else {
1748 Result += ", 0, \"";
1749 Result += CDecl->getName();
1750 Result += "\"";
1751 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001752 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001753 Result += ", 0,1";
1754 if (!ObjcSynthesizedStructs.count(CDecl))
1755 Result += ",0";
1756 else {
1757 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001758 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001759 Result += CDecl->getName();
1760 Result += ")";
1761 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001762 if (NumIvars > 0) {
1763 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1764 Result += CDecl->getName();
1765 Result += "\n\t";
1766 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001767 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001768 Result += ",0";
1769 if (IDecl->getNumInstanceMethods() > 0) {
1770 Result += ", &_OBJC_INSTANCE_METHODS_";
1771 Result += CDecl->getName();
1772 Result += ", 0\n\t";
1773 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001774 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001775 Result += ",0,0";
1776 if (CDecl->getNumIntfRefProtocols() > 0) {
1777 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1778 Result += CDecl->getName();
1779 Result += ", 0,0\n";
1780 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001781 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001782 Result += ",0,0,0\n";
1783 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001784}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001785
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001786/// RewriteImplementations - This routine rewrites all method implementations
1787/// and emits meta-data.
1788
1789void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001790 int ClsDefCount = ClassImplementation.size();
1791 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001792
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001793 if (ClsDefCount == 0 && CatDefCount == 0)
1794 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001795 // Rewrite implemented methods
1796 for (int i = 0; i < ClsDefCount; i++)
1797 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001798
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001799 for (int i = 0; i < CatDefCount; i++)
1800 RewriteImplementationDecl(CategoryImplementation[i]);
1801
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001802 // TODO: This is temporary until we decide how to access objc types in a
1803 // c program
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001804 Result += "#include <Objc/objc.h>\n";
1805 // This is needed for use of offsetof
1806 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001807
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001808 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001809 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001810 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001811
1812 // For each implemented category, write out all its meta data.
1813 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001814 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001815
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001816 // Write objc_symtab metadata
1817 /*
1818 struct _objc_symtab
1819 {
1820 long sel_ref_cnt;
1821 SEL *refs;
1822 short cls_def_cnt;
1823 short cat_def_cnt;
1824 void *defs[cls_def_cnt + cat_def_cnt];
1825 };
1826 */
1827
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001828 Result += "\nstruct _objc_symtab {\n";
1829 Result += "\tlong sel_ref_cnt;\n";
1830 Result += "\tSEL *refs;\n";
1831 Result += "\tshort cls_def_cnt;\n";
1832 Result += "\tshort cat_def_cnt;\n";
1833 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1834 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001835
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001836 Result += "static struct _objc_symtab "
1837 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1838 Result += "\t0, 0, " + utostr(ClsDefCount)
1839 + ", " + utostr(CatDefCount) + "\n";
1840 for (int i = 0; i < ClsDefCount; i++) {
1841 Result += "\t,&_OBJC_CLASS_";
1842 Result += ClassImplementation[i]->getName();
1843 Result += "\n";
1844 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001845
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001846 for (int i = 0; i < CatDefCount; i++) {
1847 Result += "\t,&_OBJC_CATEGORY_";
1848 Result += CategoryImplementation[i]->getClassInterface()->getName();
1849 Result += "_";
1850 Result += CategoryImplementation[i]->getName();
1851 Result += "\n";
1852 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001853
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001854 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001855
1856 // Write objc_module metadata
1857
1858 /*
1859 struct _objc_module {
1860 long version;
1861 long size;
1862 const char *name;
1863 struct _objc_symtab *symtab;
1864 }
1865 */
1866
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001867 Result += "\nstruct _objc_module {\n";
1868 Result += "\tlong version;\n";
1869 Result += "\tlong size;\n";
1870 Result += "\tconst char *name;\n";
1871 Result += "\tstruct _objc_symtab *symtab;\n";
1872 Result += "};\n\n";
1873 Result += "static struct _objc_module "
1874 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001875 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1876 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001877 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001878
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001879}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001880