blob: cd1e994bbfe8b04b3207ae270c8ed1c31d95dce0 [file] [log] [blame]
Chris Lattner77cd2a02007-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 Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000037 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000038
39 FunctionDecl *MsgSendFunctionDecl;
40 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000041 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000042 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
Steve Naroffbeaf2992007-11-03 11:27:19 +000044 // ObjC string constant support.
45 FileVarDecl *ConstantStringClassReference;
46 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000047
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000048 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000049 public:
Chris Lattner01c57482007-10-17 22:35:30 +000050 void Initialize(ASTContext &context, unsigned mainFileID) {
51 Context = &context;
52 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000053 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000054 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000055 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000056 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000057 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000058 ConstantStringClassReference = 0;
59 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000060 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000061 // declaring objc_selector outside the parameter list removes a silly
62 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000063 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000064 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000065 "(struct objc_object *, struct objc_selector *, ...);\n"
66 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-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 Naroffab972d32007-11-04 22:37:50 +000075 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
76 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000077 }
Chris Lattner8a12c272007-10-11 18:38:32 +000078
Chris Lattnerf04da132007-10-24 17:06:59 +000079 // Top Level Driver code.
80 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000081 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000082 ~RewriteTest();
83
84 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000085 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000086 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000087 void RewriteTabs();
88 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000089 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +000090 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000091 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000092 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000093 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +000094 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +000095 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000096 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000097 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000098 void RewriteObjcQualifiedInterfaceTypes(
99 const FunctionTypeProto *proto, FunctionDecl *FD);
100 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +0000101
Chris Lattnerf04da132007-10-24 17:06:59 +0000102 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000103 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000104 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000105 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000106 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000107 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000108 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
109 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
110 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000111 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000112 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
113 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000114 void SynthMsgSendFunctionDecl();
115 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000116 void SynthCFStringFunctionDecl();
117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000119 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
120 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000121
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000122 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
123 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124
Steve Naroff0416fb92007-11-11 17:19:15 +0000125 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000126 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000127 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000128 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000129 const char *ClassName,
130 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000131
132 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
133 int NumProtocols,
134 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000135 const char *ClassName,
136 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000137 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
138 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000139 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
140 ObjcIvarDecl *ivar,
141 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000142 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000143 };
144}
145
Chris Lattner8a12c272007-10-11 18:38:32 +0000146ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000147
Chris Lattnerf04da132007-10-24 17:06:59 +0000148//===----------------------------------------------------------------------===//
149// Top Level Driver Code
150//===----------------------------------------------------------------------===//
151
Chris Lattner8a12c272007-10-11 18:38:32 +0000152void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-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 Naroffebf2b562007-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 Naroff09b266e2007-10-30 23:14:51 +0000164 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-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 Naroffbef11852007-10-26 20:53:56 +0000171 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
172 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000173 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
174 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000175 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
176 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000177 } else if (ObjcForwardProtocolDecl *FP =
178 dyn_cast<ObjcForwardProtocolDecl>(D)){
179 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000180 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000181 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000182 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
183 return HandleDeclInMainFile(D);
184
Chris Lattnerf04da132007-10-24 17:06:59 +0000185 // Otherwise, see if there is a #import in the main file that should be
186 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000187 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000188}
189
Chris Lattnerf04da132007-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 Narofff3473a72007-11-09 15:20:18 +0000195 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-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 Lattnerf04da132007-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 Narofff3473a72007-11-09 15:20:18 +0000207 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
208 if (VD->getInit())
209 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
210 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000211 // Nothing yet.
212}
213
214RewriteTest::~RewriteTest() {
215 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000216
217 // Rewrite tabs if we care.
218 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000219
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000220 // Rewrite Objective-c meta data*
221 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000222 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000223
Chris Lattnerf04da132007-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 Naroffbeaf2992007-11-03 11:27:19 +0000228 //printf("Changed:\n");
Chris Lattnerf04da132007-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 Jahanian4402d812007-11-07 18:40:28 +0000234 // Emit metadata.
235 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000236}
237
Chris Lattnerf04da132007-10-24 17:06:59 +0000238//===----------------------------------------------------------------------===//
239// Syntactic (non-AST) Rewriting Code
240//===----------------------------------------------------------------------===//
241
Chris Lattner2c64b7b2007-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 Lattnerf04da132007-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 Jahanian545b9ae2007-10-18 19:23:00 +0000270
Chris Lattnerf04da132007-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 Lattner8a12c272007-10-11 18:38:32 +0000294}
295
296
Chris Lattnerf04da132007-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 Naroff934f2762007-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 Naroff8749be52007-10-31 22:11:35 +0000315 if (ObjcForwardDecls.count(ForwardDecl))
316 continue;
Steve Naroff32174822007-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 Naroff352336b2007-11-05 14:36:37 +0000323 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000324 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000325 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000326 // Mark this typedef as having been generated.
327 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000328 assert(false && "typedef already output");
Steve Naroff934f2762007-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 Lattnerf04da132007-10-24 17:06:59 +0000334}
335
Steve Naroff71c0a952007-11-13 23:01:27 +0000336void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-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 Lattner28d1fe82007-11-08 04:41:51 +0000341 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000342
343 // FIXME: handle methods that are declared across multiple lines.
344 }
345}
346
Fariborz Jahanian957cf652007-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 Naroff423cb562007-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 Naroff71c0a952007-11-13 23:01:27 +0000365 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
366 CatDecl->getInstanceMethods());
367 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
368 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000369 // Lastly, comment out the @end.
370 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
371}
372
Steve Naroff752d6ef2007-10-30 16:42:30 +0000373void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
374 SourceLocation LocStart = PDecl->getLocStart();
375
376 // FIXME: handle protocol headers that are declared across multiple lines.
377 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
378
Steve Naroff71c0a952007-11-13 23:01:27 +0000379 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
380 PDecl->getInstanceMethods());
381 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
382 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000383 // Lastly, comment out the @end.
384 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
385}
386
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000387void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
388 SourceLocation LocStart = PDecl->getLocation();
389 // FIXME: handle forward protocol that are declared across multiple lines.
390 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
391}
392
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000393void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
394 std::string &ResultStr) {
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000395 static bool includeObjc = false;
396 if (!includeObjc) {
397 ResultStr += "#include <Objc/objc.h>\n";
398 includeObjc = true;
399 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000400 ResultStr += "\nstatic ";
401 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000402 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000403
404 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000405 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000406
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000407 if (OMD->isInstance())
408 NameStr += "_I_";
409 else
410 NameStr += "_C_";
411
412 NameStr += OMD->getClassInterface()->getName();
413 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000414
415 NamedDecl *MethodContext = OMD->getMethodContext();
416 if (ObjcCategoryImplDecl *CID =
417 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000418 NameStr += CID->getName();
419 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000420 }
421 // Append selector names, replacing ':' with '_'
422 const char *selName = OMD->getSelector().getName().c_str();
423 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000424 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000425 else {
426 std::string selString = OMD->getSelector().getName();
427 int len = selString.size();
428 for (int i = 0; i < len; i++)
429 if (selString[i] == ':')
430 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000431 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000432 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000433 // Remember this name for metadata emission
434 MethodInternalNames[OMD] = NameStr;
435 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000436
437 // Rewrite arguments
438 ResultStr += "(";
439
440 // invisible arguments
441 if (OMD->isInstance()) {
442 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
443 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000444 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
445 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000446 ResultStr += selfTy.getAsString();
447 }
448 else
449 ResultStr += Context->getObjcIdType().getAsString();
450
451 ResultStr += " self, ";
452 ResultStr += Context->getObjcSelType().getAsString();
453 ResultStr += " _cmd";
454
455 // Method arguments.
456 for (int i = 0; i < OMD->getNumParams(); i++) {
457 ParmVarDecl *PDecl = OMD->getParamDecl(i);
458 ResultStr += ", ";
459 ResultStr += PDecl->getType().getAsString();
460 ResultStr += " ";
461 ResultStr += PDecl->getName();
462 }
463 ResultStr += ")";
464
465}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000466void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
467 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
468 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000469
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000470 if (IMD)
471 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
472 else
473 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000474
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000475 int numMethods = IMD ? IMD->getNumInstanceMethods()
476 : CID->getNumInstanceMethods();
477
478 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000479 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000480 ObjcMethodDecl *OMD;
481 if (IMD)
482 OMD = IMD->getInstanceMethods()[i];
483 else
484 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000485 RewriteObjcMethodDecl(OMD, ResultStr);
486 SourceLocation LocStart = OMD->getLocStart();
487 SourceLocation LocEnd = OMD->getBody()->getLocStart();
488
489 const char *startBuf = SM->getCharacterData(LocStart);
490 const char *endBuf = SM->getCharacterData(LocEnd);
491 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
492 ResultStr.c_str(), ResultStr.size());
493 }
494
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000495 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
496 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000497 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000498 ObjcMethodDecl *OMD;
499 if (IMD)
500 OMD = IMD->getClassMethods()[i];
501 else
502 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000503 RewriteObjcMethodDecl(OMD, ResultStr);
504 SourceLocation LocStart = OMD->getLocStart();
505 SourceLocation LocEnd = OMD->getBody()->getLocStart();
506
507 const char *startBuf = SM->getCharacterData(LocStart);
508 const char *endBuf = SM->getCharacterData(LocEnd);
509 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
510 ResultStr.c_str(), ResultStr.size());
511 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000512 if (IMD)
513 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
514 else
515 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000516}
517
Steve Naroffbef11852007-10-26 20:53:56 +0000518void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000519
520 SourceLocation LocStart = ClassDecl->getLocStart();
521 SourceLocation LocEnd = ClassDecl->getLocEnd();
522
523 const char *startBuf = SM->getCharacterData(LocStart);
524 const char *endBuf = SM->getCharacterData(LocEnd);
525
Steve Naroff2feac5e2007-10-30 03:43:13 +0000526 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000527
528 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000529 if (!ObjcForwardDecls.count(ClassDecl)) {
530 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000531 ResultStr += "#ifndef _REWRITER_typedef_";
532 ResultStr += ClassDecl->getName();
533 ResultStr += "\n";
534 ResultStr += "#define _REWRITER_typedef_";
535 ResultStr += ClassDecl->getName();
536 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000537 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000538 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000539 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000540
541 // Mark this typedef as having been generated.
542 ObjcForwardDecls.insert(ClassDecl);
543 }
Steve Narofff908a872007-10-30 02:23:23 +0000544 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
545
Steve Naroff2feac5e2007-10-30 03:43:13 +0000546 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000547 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000548 RewriteProperties(ClassDecl->getNumPropertyDecl(),
549 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000550 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
551 ClassDecl->getInstanceMethods());
552 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
553 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000554
Steve Naroff2feac5e2007-10-30 03:43:13 +0000555 // Lastly, comment out the @end.
556 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000557}
558
Chris Lattnerf04da132007-10-24 17:06:59 +0000559//===----------------------------------------------------------------------===//
560// Function Body / Expression rewriting
561//===----------------------------------------------------------------------===//
562
Steve Narofff3473a72007-11-09 15:20:18 +0000563Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000564 // Otherwise, just rewrite all children.
565 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
566 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000567 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000568 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000569 if (newStmt)
570 *CI = newStmt;
571 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000572
573 // Handle specific things.
574 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
575 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000576
577 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
578 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000579
580 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
581 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000582
Steve Naroff934f2762007-10-24 22:48:43 +0000583 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
584 // Before we rewrite it, put the original message expression in a comment.
585 SourceLocation startLoc = MessExpr->getLocStart();
586 SourceLocation endLoc = MessExpr->getLocEnd();
587
588 const char *startBuf = SM->getCharacterData(startLoc);
589 const char *endBuf = SM->getCharacterData(endLoc);
590
591 std::string messString;
592 messString += "// ";
593 messString.append(startBuf, endBuf-startBuf+1);
594 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000595
Steve Naroff934f2762007-10-24 22:48:43 +0000596 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
597 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
598 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000599 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000600 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000601 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000602
603 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
604 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000605
606 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
607 return RewriteObjcThrowStmt(StmtThrow);
608
Chris Lattnere64b7772007-10-24 16:57:36 +0000609 // Return this stmt unmodified.
610 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000611}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000612
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000613Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000614 // Get the start location and compute the semi location.
615 SourceLocation startLoc = S->getLocStart();
616 const char *startBuf = SM->getCharacterData(startLoc);
617
618 assert((*startBuf == '@') && "bogus @try location");
619
620 std::string buf;
621 // declare a new scope with two variables, _stack and _rethrow.
622 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
623 buf += "int buf[18/*32-bit i386*/];\n";
624 buf += "char *pointers[4];} _stack;\n";
625 buf += "id volatile _rethrow = 0;\n";
626 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000627 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000628
629 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
630
631 startLoc = S->getTryBody()->getLocEnd();
632 startBuf = SM->getCharacterData(startLoc);
633
634 assert((*startBuf == '}') && "bogus @try block");
635
636 SourceLocation lastCurlyLoc = startLoc;
637
638 startLoc = startLoc.getFileLocWithOffset(1);
639 buf = " /* @catch begin */ else {\n";
640 buf += " id _caught = objc_exception_extract(&_stack);\n";
641 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000642 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000643 buf += " _rethrow = objc_exception_extract(&_stack);\n";
644 buf += " else { /* @catch continue */";
645
Chris Lattner28d1fe82007-11-08 04:41:51 +0000646 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000647
648 bool sawIdTypedCatch = false;
649 Stmt *lastCatchBody = 0;
650 ObjcAtCatchStmt *catchList = S->getCatchStmts();
651 while (catchList) {
652 Stmt *catchStmt = catchList->getCatchParamStmt();
653
654 if (catchList == S->getCatchStmts())
655 buf = "if ("; // we are generating code for the first catch clause
656 else
657 buf = "else if (";
658 startLoc = catchList->getLocStart();
659 startBuf = SM->getCharacterData(startLoc);
660
661 assert((*startBuf == '@') && "bogus @catch location");
662
663 const char *lParenLoc = strchr(startBuf, '(');
664
665 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
666 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
667 if (t == Context->getObjcIdType()) {
668 buf += "1) { ";
669 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
670 buf.c_str(), buf.size());
671 sawIdTypedCatch = true;
672 } else if (const PointerType *pType = t->getAsPointerType()) {
673 ObjcInterfaceType *cls; // Should be a pointer to a class.
674
675 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
676 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000677 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000678 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000679 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000680 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
681 buf.c_str(), buf.size());
682 }
683 }
684 // Now rewrite the body...
685 lastCatchBody = catchList->getCatchBody();
686 SourceLocation rParenLoc = catchList->getRParenLoc();
687 SourceLocation bodyLoc = lastCatchBody->getLocStart();
688 const char *bodyBuf = SM->getCharacterData(bodyLoc);
689 const char *rParenBuf = SM->getCharacterData(rParenLoc);
690 assert((*rParenBuf == ')') && "bogus @catch paren location");
691 assert((*bodyBuf == '{') && "bogus @catch body location");
692
693 buf = " = _caught;";
694 // Here we replace ") {" with "= _caught;" (which initializes and
695 // declares the @catch parameter).
696 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
697 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000698 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000699 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000700 }
Steve Naroff75730982007-11-07 04:08:17 +0000701 catchList = catchList->getNextCatchStmt();
702 }
703 // Complete the catch list...
704 if (lastCatchBody) {
705 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
706 const char *bodyBuf = SM->getCharacterData(bodyLoc);
707 assert((*bodyBuf == '}') && "bogus @catch body location");
708 bodyLoc = bodyLoc.getFileLocWithOffset(1);
709 buf = " } } /* @catch end */\n";
710
Chris Lattner28d1fe82007-11-08 04:41:51 +0000711 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000712
713 // Set lastCurlyLoc
714 lastCurlyLoc = lastCatchBody->getLocEnd();
715 }
716 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
717 startLoc = finalStmt->getLocStart();
718 startBuf = SM->getCharacterData(startLoc);
719 assert((*startBuf == '@') && "bogus @finally start");
720
721 buf = "/* @finally */";
722 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
723
724 Stmt *body = finalStmt->getFinallyBody();
725 SourceLocation startLoc = body->getLocStart();
726 SourceLocation endLoc = body->getLocEnd();
727 const char *startBuf = SM->getCharacterData(startLoc);
728 const char *endBuf = SM->getCharacterData(endLoc);
729 assert((*startBuf == '{') && "bogus @finally body location");
730 assert((*endBuf == '}') && "bogus @finally body location");
731
732 startLoc = startLoc.getFileLocWithOffset(1);
733 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000734 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000735 endLoc = endLoc.getFileLocWithOffset(-1);
736 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000737 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000738
739 // Set lastCurlyLoc
740 lastCurlyLoc = body->getLocEnd();
741 }
742 // Now emit the final closing curly brace...
743 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
744 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000745 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000746 return 0;
747}
748
749Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
750 return 0;
751}
752
753Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
754 return 0;
755}
756
Steve Naroff2bd03922007-11-07 15:32:26 +0000757// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
758// the throw expression is typically a message expression that's already
759// been rewritten! (which implies the SourceLocation's are invalid).
760Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
761 // Get the start location and compute the semi location.
762 SourceLocation startLoc = S->getLocStart();
763 const char *startBuf = SM->getCharacterData(startLoc);
764
765 assert((*startBuf == '@') && "bogus @throw location");
766
767 std::string buf;
768 /* void objc_exception_throw(id) __attribute__((noreturn)); */
769 buf = "objc_exception_throw(";
770 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
771 const char *semiBuf = strchr(startBuf, ';');
772 assert((*semiBuf == ';') && "@throw: can't find ';'");
773 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
774 buf = ");";
775 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
776 return 0;
777}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000778
Chris Lattnere64b7772007-10-24 16:57:36 +0000779Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000780 // Create a new string expression.
781 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000782 std::string StrEncoding;
783 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
784 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
785 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000786 SourceLocation(), SourceLocation());
787 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000788 delete Exp;
789 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000790}
791
Steve Naroffb42f8412007-11-05 14:50:49 +0000792Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
793 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
794 // Create a call to sel_registerName("selName").
795 llvm::SmallVector<Expr*, 8> SelExprs;
796 QualType argType = Context->getPointerType(Context->CharTy);
797 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
798 Exp->getSelector().getName().size(),
799 false, argType, SourceLocation(),
800 SourceLocation()));
801 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
802 &SelExprs[0], SelExprs.size());
803 Rewrite.ReplaceStmt(Exp, SelExp);
804 delete Exp;
805 return SelExp;
806}
807
Steve Naroff934f2762007-10-24 22:48:43 +0000808CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
809 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000810 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000811 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000812
813 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000814 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000815
816 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000817 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000818 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
819
820 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000821
Steve Naroff934f2762007-10-24 22:48:43 +0000822 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
823}
824
Steve Naroffd5255f52007-11-01 13:24:47 +0000825static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
826 const char *&startRef, const char *&endRef) {
827 while (startBuf < endBuf) {
828 if (*startBuf == '<')
829 startRef = startBuf; // mark the start.
830 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000831 if (startRef && *startRef == '<') {
832 endRef = startBuf; // mark the end.
833 return true;
834 }
835 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000836 }
837 startBuf++;
838 }
839 return false;
840}
841
842bool RewriteTest::needToScanForQualifiers(QualType T) {
843 // FIXME: we don't currently represent "id <Protocol>" in the type system.
844 if (T == Context->getObjcIdType())
845 return true;
846
847 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000848 Type *pointeeType = pType->getPointeeType().getTypePtr();
849 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
850 return true; // we have "Class <Protocol> *".
851 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000852 return false;
853}
854
855void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
856 const FunctionTypeProto *proto, FunctionDecl *FD) {
857
858 if (needToScanForQualifiers(proto->getResultType())) {
859 // Since types are unique, we need to scan the buffer.
860 SourceLocation Loc = FD->getLocation();
861
862 const char *endBuf = SM->getCharacterData(Loc);
863 const char *startBuf = endBuf;
864 while (*startBuf != ';')
865 startBuf--; // scan backward (from the decl location) for return type.
866 const char *startRef = 0, *endRef = 0;
867 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
868 // Get the locations of the startRef, endRef.
869 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
870 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
871 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000872 Rewrite.InsertText(LessLoc, "/*", 2);
873 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000874 }
875 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000876 // Now check arguments.
877 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
878 if (needToScanForQualifiers(proto->getArgType(i))) {
879 // Since types are unique, we need to scan the buffer.
880 SourceLocation Loc = FD->getLocation();
881
882 const char *startBuf = SM->getCharacterData(Loc);
883 const char *endBuf = startBuf;
884 while (*endBuf != ';')
885 endBuf++; // scan forward (from the decl location) for argument types.
886 const char *startRef = 0, *endRef = 0;
887 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
888 // Get the locations of the startRef, endRef.
889 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
890 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
891 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000892 Rewrite.InsertText(LessLoc, "/*", 2);
893 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000894 }
895 }
896 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000897}
898
Steve Naroff09b266e2007-10-30 23:14:51 +0000899void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
900 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000901 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000902 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000903 return;
904 }
905 // Check for ObjC 'id' and class types that have been adorned with protocol
906 // information (id<p>, C<p>*). The protocol references need to be rewritten!
907 const FunctionType *funcType = FD->getType()->getAsFunctionType();
908 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000909 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
910 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000911}
912
913// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
914void RewriteTest::SynthMsgSendFunctionDecl() {
915 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
916 llvm::SmallVector<QualType, 16> ArgTys;
917 QualType argT = Context->getObjcIdType();
918 assert(!argT.isNull() && "Can't find 'id' type");
919 ArgTys.push_back(argT);
920 argT = Context->getObjcSelType();
921 assert(!argT.isNull() && "Can't find 'SEL' type");
922 ArgTys.push_back(argT);
923 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
924 &ArgTys[0], ArgTys.size(),
925 true /*isVariadic*/);
926 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
927 msgSendIdent, msgSendType,
928 FunctionDecl::Extern, false, 0);
929}
930
931// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
932void RewriteTest::SynthGetClassFunctionDecl() {
933 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
934 llvm::SmallVector<QualType, 16> ArgTys;
935 ArgTys.push_back(Context->getPointerType(
936 Context->CharTy.getQualifiedType(QualType::Const)));
937 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
938 &ArgTys[0], ArgTys.size(),
939 false /*isVariadic*/);
940 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
941 getClassIdent, getClassType,
942 FunctionDecl::Extern, false, 0);
943}
944
Steve Naroff96984642007-11-08 14:30:50 +0000945// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
946void RewriteTest::SynthCFStringFunctionDecl() {
947 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
948 llvm::SmallVector<QualType, 16> ArgTys;
949 ArgTys.push_back(Context->getPointerType(
950 Context->CharTy.getQualifiedType(QualType::Const)));
951 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
952 &ArgTys[0], ArgTys.size(),
953 false /*isVariadic*/);
954 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
955 getClassIdent, getClassType,
956 FunctionDecl::Extern, false, 0);
957}
958
Steve Naroffbeaf2992007-11-03 11:27:19 +0000959Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000960#if 1
961 // This rewrite is specific to GCC, which has builtin support for CFString.
962 if (!CFStringFunctionDecl)
963 SynthCFStringFunctionDecl();
964 // Create a call to __builtin___CFStringMakeConstantString("cstr").
965 llvm::SmallVector<Expr*, 8> StrExpr;
966 StrExpr.push_back(Exp->getString());
967 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
968 &StrExpr[0], StrExpr.size());
969 // cast to NSConstantString *
970 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
971 Rewrite.ReplaceStmt(Exp, cast);
972 delete Exp;
973 return cast;
974#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000975 assert(ConstantStringClassReference && "Can't find constant string reference");
976 llvm::SmallVector<Expr*, 4> InitExprs;
977
978 // Synthesize "(Class)&_NSConstantStringClassReference"
979 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
980 ConstantStringClassReference->getType(),
981 SourceLocation());
982 QualType expType = Context->getPointerType(ClsRef->getType());
983 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
984 expType, SourceLocation());
985 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
986 SourceLocation());
987 InitExprs.push_back(cast); // set the 'isa'.
988 InitExprs.push_back(Exp->getString()); // set "char *bytes".
989 unsigned IntSize = static_cast<unsigned>(
990 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
991 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
992 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
993 Exp->getLocStart());
994 InitExprs.push_back(len); // set "int numBytes".
995
996 // struct NSConstantString
997 QualType CFConstantStrType = Context->getCFConstantStringType();
998 // (struct NSConstantString) { <exprs from above> }
999 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1000 &InitExprs[0], InitExprs.size(),
1001 SourceLocation());
1002 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1003 // struct NSConstantString *
1004 expType = Context->getPointerType(StrRep->getType());
1005 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1006 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001007 // cast to NSConstantString *
1008 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001009 Rewrite.ReplaceStmt(Exp, cast);
1010 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001011 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001012#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001013}
1014
Steve Naroff934f2762007-10-24 22:48:43 +00001015Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001016 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001017 if (!MsgSendFunctionDecl)
1018 SynthMsgSendFunctionDecl();
1019 if (!GetClassFunctionDecl)
1020 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001021
1022 // Synthesize a call to objc_msgSend().
1023 llvm::SmallVector<Expr*, 8> MsgExprs;
1024 IdentifierInfo *clsName = Exp->getClassName();
1025
1026 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1027 if (clsName) { // class message.
1028 llvm::SmallVector<Expr*, 8> ClsExprs;
1029 QualType argType = Context->getPointerType(Context->CharTy);
1030 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1031 clsName->getLength(),
1032 false, argType, SourceLocation(),
1033 SourceLocation()));
1034 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1035 &ClsExprs[0], ClsExprs.size());
1036 MsgExprs.push_back(Cls);
1037 } else // instance message.
1038 MsgExprs.push_back(Exp->getReceiver());
1039
Steve Naroffbeaf2992007-11-03 11:27:19 +00001040 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001041 llvm::SmallVector<Expr*, 8> SelExprs;
1042 QualType argType = Context->getPointerType(Context->CharTy);
1043 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1044 Exp->getSelector().getName().size(),
1045 false, argType, SourceLocation(),
1046 SourceLocation()));
1047 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1048 &SelExprs[0], SelExprs.size());
1049 MsgExprs.push_back(SelExp);
1050
1051 // Now push any user supplied arguments.
1052 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1053 MsgExprs.push_back(Exp->getArg(i));
1054 // We've transferred the ownership to MsgExprs. Null out the argument in
1055 // the original expression, since we will delete it below.
1056 Exp->setArg(i, 0);
1057 }
Steve Naroffab972d32007-11-04 22:37:50 +00001058 // Generate the funky cast.
1059 CastExpr *cast;
1060 llvm::SmallVector<QualType, 8> ArgTypes;
1061 QualType returnType;
1062
1063 // Push 'id' and 'SEL', the 2 implicit arguments.
1064 ArgTypes.push_back(Context->getObjcIdType());
1065 ArgTypes.push_back(Context->getObjcSelType());
1066 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1067 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001068 for (int i = 0; i < mDecl->getNumParams(); i++) {
1069 QualType t = mDecl->getParamDecl(i)->getType();
1070 if (t == Context->getObjcClassType())
1071 t = Context->getObjcIdType(); // Convert "Class"->"id"
1072 ArgTypes.push_back(t);
1073 }
Steve Naroffab972d32007-11-04 22:37:50 +00001074 returnType = mDecl->getResultType();
1075 } else {
1076 returnType = Context->getObjcIdType();
1077 }
1078 // Get the type, we will need to reference it in a couple spots.
1079 QualType msgSendType = MsgSendFunctionDecl->getType();
1080
1081 // Create a reference to the objc_msgSend() declaration.
1082 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1083
1084 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1085 // If we don't do this cast, we get the following bizarre warning/note:
1086 // xx.m:13: warning: function called through a non-compatible type
1087 // xx.m:13: note: if this code is reached, the program will abort
1088 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1089 SourceLocation());
1090
1091 // Now do the "normal" pointer to function cast.
1092 QualType castType = Context->getFunctionType(returnType,
1093 &ArgTypes[0], ArgTypes.size(),
1094 false/*FIXME:variadic*/);
1095 castType = Context->getPointerType(castType);
1096 cast = new CastExpr(castType, cast, SourceLocation());
1097
1098 // Don't forget the parens to enforce the proper binding.
1099 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1100
1101 const FunctionType *FT = msgSendType->getAsFunctionType();
1102 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1103 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001104 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001105 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001106
Chris Lattnere64b7772007-10-24 16:57:36 +00001107 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001108 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001109}
1110
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001111/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1112/// an objective-c class with ivars.
1113void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1114 std::string &Result) {
1115 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1116 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001117 // Do not synthesize more than once.
1118 if (ObjcSynthesizedStructs.count(CDecl))
1119 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001120 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1121 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1122 // Do it for the root
1123 SynthesizeObjcInternalStruct(RCDecl, Result);
1124 }
1125
Steve Naroff03300712007-11-12 13:56:41 +00001126 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001127 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001128 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001129 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1130 return;
1131
Steve Naroff04960052007-11-01 17:12:31 +00001132 Result += "\nstruct ";
1133 Result += CDecl->getName();
1134 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1135 Result += " {\n struct ";
1136 Result += RCDecl->getName();
1137 Result += " _";
1138 Result += RCDecl->getName();
1139 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001140 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001141 else
1142 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +00001143
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001144 if (NumIvars > 0) {
1145 SourceLocation LocStart = CDecl->getLocStart();
1146 SourceLocation LocEnd = CDecl->getLocEnd();
1147
1148 const char *startBuf = SM->getCharacterData(LocStart);
1149 const char *endBuf = SM->getCharacterData(LocEnd);
1150 startBuf = strchr(startBuf, '{');
1151 assert((startBuf && endBuf)
1152 && "SynthesizeObjcInternalStruct - malformed @interface");
1153 startBuf++; // past '{'
1154 while (startBuf < endBuf) {
1155 if (*startBuf == '@') {
1156 startBuf = strchr(startBuf, 'p');
1157 // FIXME: presence of @public, etc. inside comment results in
1158 // this transformation as well, which is still correct c-code.
1159 if (!strncmp(startBuf, "public", strlen("public"))) {
1160 startBuf += strlen("public");
1161 Result += "/* @public */";
1162 }
1163 else if (!strncmp(startBuf, "private", strlen("private"))) {
1164 startBuf += strlen("private");
1165 Result += "/* @private */";
1166 }
1167 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1168 startBuf += strlen("protected");
1169 Result += "/* @protected */";
1170 }
1171 }
1172 Result += *startBuf++;
1173 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001174 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001175
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001176 Result += "};\n";
1177 // Mark this struct as having been generated.
1178 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001179 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001180}
1181
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001182// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1183/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001184void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001185 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001186 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001187 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001188 const char *ClassName,
1189 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001190 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001191 if (NumMethods > 0 && !objc_impl_method) {
1192 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001193 SEL _cmd;
1194 char *method_types;
1195 void *_imp;
1196 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001197 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001198 Result += "\nstruct _objc_method {\n";
1199 Result += "\tSEL _cmd;\n";
1200 Result += "\tchar *method_types;\n";
1201 Result += "\tvoid *_imp;\n";
1202 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001203
1204 /* struct _objc_method_list {
1205 struct _objc_method_list *next_method;
1206 int method_count;
1207 struct _objc_method method_list[];
1208 }
1209 */
1210 Result += "\nstruct _objc_method_list {\n";
1211 Result += "\tstruct _objc_method_list *next_method;\n";
1212 Result += "\tint method_count;\n";
1213 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001214 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001215 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001216 // Build _objc_method_list for class's methods if needed
1217 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001218 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001219 Result += prefix;
1220 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1221 Result += "_METHODS_";
1222 Result += ClassName;
1223 Result += " __attribute__ ((section (\"__OBJC, __";
1224 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001225 Result += "_meth\")))= ";
1226 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1227
1228 Result += "\t,{{(SEL)\"";
1229 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001230 std::string MethodTypeString;
1231 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1232 Result += "\", \"";
1233 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001234 Result += "\", ";
1235 Result += MethodInternalNames[Methods[0]];
1236 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001237 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001238 Result += "\t ,{(SEL)\"";
1239 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001240 std::string MethodTypeString;
1241 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1242 Result += "\", \"";
1243 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001244 Result += "\", ";
1245 Result += MethodInternalNames[Methods[i]];
1246 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001247 }
1248 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001249 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001250}
1251
1252/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1253void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1254 int NumProtocols,
1255 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001256 const char *ClassName,
1257 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001258 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001259 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001260 for (int i = 0; i < NumProtocols; i++) {
1261 ObjcProtocolDecl *PDecl = Protocols[i];
1262 // Output struct protocol_methods holder of method selector and type.
1263 if (!objc_protocol_methods &&
1264 (PDecl->getNumInstanceMethods() > 0
1265 || PDecl->getNumClassMethods() > 0)) {
1266 /* struct protocol_methods {
1267 SEL _cmd;
1268 char *method_types;
1269 }
1270 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001271 Result += "\nstruct protocol_methods {\n";
1272 Result += "\tSEL _cmd;\n";
1273 Result += "\tchar *method_types;\n";
1274 Result += "};\n";
1275
1276 /* struct _objc_protocol_method_list {
1277 int protocol_method_count;
1278 struct protocol_methods protocols[];
1279 }
1280 */
1281 Result += "\nstruct _objc_protocol_method_list {\n";
1282 Result += "\tint protocol_method_count;\n";
1283 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001284 objc_protocol_methods = true;
1285 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001286
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001287 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001288 int NumMethods = PDecl->getNumInstanceMethods();
1289 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001290 Result += "\nstatic struct _objc_protocol_method_list "
1291 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1292 Result += PDecl->getName();
1293 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1294 "{\n\t" + utostr(NumMethods) + "\n";
1295
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001296 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001297 Result += "\t,{{(SEL)\"";
1298 Result += Methods[0]->getSelector().getName().c_str();
1299 Result += "\", \"\"}\n";
1300
1301 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001302 Result += "\t ,{(SEL)\"";
1303 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001304 std::string MethodTypeString;
1305 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1306 Result += "\", \"";
1307 Result += MethodTypeString;
1308 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001309 }
1310 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001311 }
1312
1313 // Output class methods declared in this protocol.
1314 NumMethods = PDecl->getNumClassMethods();
1315 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001316 Result += "\nstatic struct _objc_protocol_method_list "
1317 "_OBJC_PROTOCOL_CLASS_METHODS_";
1318 Result += PDecl->getName();
1319 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1320 "{\n\t";
1321 Result += utostr(NumMethods);
1322 Result += "\n";
1323
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001324 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001325 Result += "\t,{{(SEL)\"";
1326 Result += Methods[0]->getSelector().getName().c_str();
1327 Result += "\", \"\"}\n";
1328
1329 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001330 Result += "\t ,{(SEL)\"";
1331 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001332 std::string MethodTypeString;
1333 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1334 Result += "\", \"";
1335 Result += MethodTypeString;
1336 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001337 }
1338 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001339 }
1340 // Output:
1341 /* struct _objc_protocol {
1342 // Objective-C 1.0 extensions
1343 struct _objc_protocol_extension *isa;
1344 char *protocol_name;
1345 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001346 struct _objc_protocol_method_list *instance_methods;
1347 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001348 };
1349 */
1350 static bool objc_protocol = false;
1351 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001352 Result += "\nstruct _objc_protocol {\n";
1353 Result += "\tstruct _objc_protocol_extension *isa;\n";
1354 Result += "\tchar *protocol_name;\n";
1355 Result += "\tstruct _objc_protocol **protocol_list;\n";
1356 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1357 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1358 Result += "};\n";
1359
1360 /* struct _objc_protocol_list {
1361 struct _objc_protocol_list *next;
1362 int protocol_count;
1363 struct _objc_protocol *class_protocols[];
1364 }
1365 */
1366 Result += "\nstruct _objc_protocol_list {\n";
1367 Result += "\tstruct _objc_protocol_list *next;\n";
1368 Result += "\tint protocol_count;\n";
1369 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1370 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001371 objc_protocol = true;
1372 }
1373
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001374 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1375 Result += PDecl->getName();
1376 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1377 "{\n\t0, \"";
1378 Result += PDecl->getName();
1379 Result += "\", 0, ";
1380 if (PDecl->getInstanceMethods() > 0) {
1381 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1382 Result += PDecl->getName();
1383 Result += ", ";
1384 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001385 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001386 Result += "0, ";
1387 if (PDecl->getClassMethods() > 0) {
1388 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1389 Result += PDecl->getName();
1390 Result += "\n";
1391 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001392 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001393 Result += "0\n";
1394 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001395 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001396 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001397 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1398 Result += prefix;
1399 Result += "_PROTOCOLS_";
1400 Result += ClassName;
1401 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1402 "{\n\t0, ";
1403 Result += utostr(NumProtocols);
1404 Result += "\n";
1405
1406 Result += "\t,{&_OBJC_PROTOCOL_";
1407 Result += Protocols[0]->getName();
1408 Result += " \n";
1409
1410 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001411 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001412 Result += "\t ,&_OBJC_PROTOCOL_";
1413 Result += PDecl->getName();
1414 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001415 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001416 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001417 }
1418}
1419
1420/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1421/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001422void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1423 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001424 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1425 // Find category declaration for this implementation.
1426 ObjcCategoryDecl *CDecl;
1427 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1428 CDecl = CDecl->getNextClassCategory())
1429 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1430 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001431
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001432 char *FullCategoryName = (char*)alloca(
1433 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1434 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1435
1436 // Build _objc_method_list for class's instance methods if needed
1437 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1438 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001439 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001440 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001441
1442 // Build _objc_method_list for class's class methods if needed
1443 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1444 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001445 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001446 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001447
1448 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001449 // Null CDecl is case of a category implementation with no category interface
1450 if (CDecl)
1451 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1452 CDecl->getNumReferencedProtocols(),
1453 "CATEGORY",
1454 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001455
1456 /* struct _objc_category {
1457 char *category_name;
1458 char *class_name;
1459 struct _objc_method_list *instance_methods;
1460 struct _objc_method_list *class_methods;
1461 struct _objc_protocol_list *protocols;
1462 // Objective-C 1.0 extensions
1463 uint32_t size; // sizeof (struct _objc_category)
1464 struct _objc_property_list *instance_properties; // category's own
1465 // @property decl.
1466 };
1467 */
1468
1469 static bool objc_category = false;
1470 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001471 Result += "\nstruct _objc_category {\n";
1472 Result += "\tchar *category_name;\n";
1473 Result += "\tchar *class_name;\n";
1474 Result += "\tstruct _objc_method_list *instance_methods;\n";
1475 Result += "\tstruct _objc_method_list *class_methods;\n";
1476 Result += "\tstruct _objc_protocol_list *protocols;\n";
1477 Result += "\tunsigned int size;\n";
1478 Result += "\tstruct _objc_property_list *instance_properties;\n";
1479 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001480 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001481 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001482 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1483 Result += FullCategoryName;
1484 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1485 Result += IDecl->getName();
1486 Result += "\"\n\t, \"";
1487 Result += ClassDecl->getName();
1488 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001489
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001490 if (IDecl->getNumInstanceMethods() > 0) {
1491 Result += "\t, (struct _objc_method_list *)"
1492 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1493 Result += FullCategoryName;
1494 Result += "\n";
1495 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001496 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001497 Result += "\t, 0\n";
1498 if (IDecl->getNumClassMethods() > 0) {
1499 Result += "\t, (struct _objc_method_list *)"
1500 "&_OBJC_CATEGORY_CLASS_METHODS_";
1501 Result += FullCategoryName;
1502 Result += "\n";
1503 }
1504 else
1505 Result += "\t, 0\n";
1506
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001507 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001508 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1509 Result += FullCategoryName;
1510 Result += "\n";
1511 }
1512 else
1513 Result += "\t, 0\n";
1514 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001515}
1516
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001517/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1518/// ivar offset.
1519void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1520 ObjcIvarDecl *ivar,
1521 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001522 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001523 Result += IDecl->getName();
1524 Result += ", ";
1525 Result += ivar->getName();
1526 Result += ")";
1527}
1528
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001529//===----------------------------------------------------------------------===//
1530// Meta Data Emission
1531//===----------------------------------------------------------------------===//
1532
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001533void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1534 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001535 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1536
1537 // Build _objc_ivar_list metadata for classes ivars if needed
1538 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1539 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001540 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001541
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001542 SynthesizeObjcInternalStruct(CDecl, Result);
1543
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001544 if (NumIvars > 0) {
1545 static bool objc_ivar = false;
1546 if (!objc_ivar) {
1547 /* struct _objc_ivar {
1548 char *ivar_name;
1549 char *ivar_type;
1550 int ivar_offset;
1551 };
1552 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001553 Result += "\nstruct _objc_ivar {\n";
1554 Result += "\tchar *ivar_name;\n";
1555 Result += "\tchar *ivar_type;\n";
1556 Result += "\tint ivar_offset;\n";
1557 Result += "};\n";
1558
1559 /* struct _objc_ivar_list {
1560 int ivar_count;
1561 struct _objc_ivar ivar_list[];
1562 };
1563 */
1564 Result += "\nstruct _objc_ivar_list {\n";
1565 Result += "\tint ivar_count;\n";
1566 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001567 objc_ivar = true;
1568 }
1569
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001570 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1571 Result += IDecl->getName();
1572 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1573 "{\n\t";
1574 Result += utostr(NumIvars);
1575 Result += "\n";
1576
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001577 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1578 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001579 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001580 Result += "\t,{{\"";
1581 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001582 Result += "\", \"";
1583 std::string StrEncoding;
1584 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1585 Result += StrEncoding;
1586 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001587 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1588 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001589 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001590 Result += "\t ,{\"";
1591 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001592 Result += "\", \"";
1593 std::string StrEncoding;
1594 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1595 Result += StrEncoding;
1596 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001597 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1598 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001599 }
1600
1601 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001602 }
1603
1604 // Build _objc_method_list for class's instance methods if needed
1605 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1606 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001607 true,
1608 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001609
1610 // Build _objc_method_list for class's class methods if needed
1611 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001612 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001613 false,
1614 "", IDecl->getName(), Result);
1615
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001616 // Protocols referenced in class declaration?
1617 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1618 CDecl->getNumIntfRefProtocols(),
1619 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001620 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001621
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001622
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001623 // Declaration of class/meta-class metadata
1624 /* struct _objc_class {
1625 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001626 const char *super_class_name;
1627 char *name;
1628 long version;
1629 long info;
1630 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001631 struct _objc_ivar_list *ivars;
1632 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001633 struct objc_cache *cache;
1634 struct objc_protocol_list *protocols;
1635 const char *ivar_layout;
1636 struct _objc_class_ext *ext;
1637 };
1638 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001639 static bool objc_class = false;
1640 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001641 Result += "\nstruct _objc_class {\n";
1642 Result += "\tstruct _objc_class *isa;\n";
1643 Result += "\tconst char *super_class_name;\n";
1644 Result += "\tchar *name;\n";
1645 Result += "\tlong version;\n";
1646 Result += "\tlong info;\n";
1647 Result += "\tlong instance_size;\n";
1648 Result += "\tstruct _objc_ivar_list *ivars;\n";
1649 Result += "\tstruct _objc_method_list *methods;\n";
1650 Result += "\tstruct objc_cache *cache;\n";
1651 Result += "\tstruct _objc_protocol_list *protocols;\n";
1652 Result += "\tconst char *ivar_layout;\n";
1653 Result += "\tstruct _objc_class_ext *ext;\n";
1654 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001655 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001656 }
1657
1658 // Meta-class metadata generation.
1659 ObjcInterfaceDecl *RootClass = 0;
1660 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1661 while (SuperClass) {
1662 RootClass = SuperClass;
1663 SuperClass = SuperClass->getSuperClass();
1664 }
1665 SuperClass = CDecl->getSuperClass();
1666
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001667 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1668 Result += CDecl->getName();
1669 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1670 "{\n\t(struct _objc_class *)\"";
1671 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1672 Result += "\"";
1673
1674 if (SuperClass) {
1675 Result += ", \"";
1676 Result += SuperClass->getName();
1677 Result += "\", \"";
1678 Result += CDecl->getName();
1679 Result += "\"";
1680 }
1681 else {
1682 Result += ", 0, \"";
1683 Result += CDecl->getName();
1684 Result += "\"";
1685 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001686 // TODO: 'ivars' field for root class is currently set to 0.
1687 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001688 Result += ", 0,2, sizeof(struct _objc_class), 0";
1689 if (CDecl->getNumClassMethods() > 0) {
1690 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1691 Result += CDecl->getName();
1692 Result += "\n";
1693 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001694 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001695 Result += ", 0\n";
1696 if (CDecl->getNumIntfRefProtocols() > 0) {
1697 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1698 Result += CDecl->getName();
1699 Result += ",0,0\n";
1700 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001701 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001702 Result += "\t,0,0,0,0\n";
1703 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001704
1705 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001706 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1707 Result += CDecl->getName();
1708 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1709 "{\n\t&_OBJC_METACLASS_";
1710 Result += CDecl->getName();
1711 if (SuperClass) {
1712 Result += ", \"";
1713 Result += SuperClass->getName();
1714 Result += "\", \"";
1715 Result += CDecl->getName();
1716 Result += "\"";
1717 }
1718 else {
1719 Result += ", 0, \"";
1720 Result += CDecl->getName();
1721 Result += "\"";
1722 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001723 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001724 Result += ", 0,1";
1725 if (!ObjcSynthesizedStructs.count(CDecl))
1726 Result += ",0";
1727 else {
1728 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001729 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001730 Result += CDecl->getName();
1731 Result += ")";
1732 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001733 if (NumIvars > 0) {
1734 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1735 Result += CDecl->getName();
1736 Result += "\n\t";
1737 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001738 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001739 Result += ",0";
1740 if (IDecl->getNumInstanceMethods() > 0) {
1741 Result += ", &_OBJC_INSTANCE_METHODS_";
1742 Result += CDecl->getName();
1743 Result += ", 0\n\t";
1744 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001745 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001746 Result += ",0,0";
1747 if (CDecl->getNumIntfRefProtocols() > 0) {
1748 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1749 Result += CDecl->getName();
1750 Result += ", 0,0\n";
1751 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001752 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001753 Result += ",0,0,0\n";
1754 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001755}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001756
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001757/// RewriteImplementations - This routine rewrites all method implementations
1758/// and emits meta-data.
1759
1760void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001761 int ClsDefCount = ClassImplementation.size();
1762 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001763
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001764 if (ClsDefCount == 0 && CatDefCount == 0)
1765 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001766 // Rewrite implemented methods
1767 for (int i = 0; i < ClsDefCount; i++)
1768 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001769
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001770 for (int i = 0; i < CatDefCount; i++)
1771 RewriteImplementationDecl(CategoryImplementation[i]);
1772
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001773 // TODO: This is temporary until we decide how to access objc types in a
1774 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001775 Result += "#include <Objc/objc.h>\n";
1776 // This is needed for use of offsetof
1777 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001778
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001779 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001780 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001781 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001782
1783 // For each implemented category, write out all its meta data.
1784 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001785 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001786
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001787 // Write objc_symtab metadata
1788 /*
1789 struct _objc_symtab
1790 {
1791 long sel_ref_cnt;
1792 SEL *refs;
1793 short cls_def_cnt;
1794 short cat_def_cnt;
1795 void *defs[cls_def_cnt + cat_def_cnt];
1796 };
1797 */
1798
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001799 Result += "\nstruct _objc_symtab {\n";
1800 Result += "\tlong sel_ref_cnt;\n";
1801 Result += "\tSEL *refs;\n";
1802 Result += "\tshort cls_def_cnt;\n";
1803 Result += "\tshort cat_def_cnt;\n";
1804 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1805 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001806
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001807 Result += "static struct _objc_symtab "
1808 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1809 Result += "\t0, 0, " + utostr(ClsDefCount)
1810 + ", " + utostr(CatDefCount) + "\n";
1811 for (int i = 0; i < ClsDefCount; i++) {
1812 Result += "\t,&_OBJC_CLASS_";
1813 Result += ClassImplementation[i]->getName();
1814 Result += "\n";
1815 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001816
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001817 for (int i = 0; i < CatDefCount; i++) {
1818 Result += "\t,&_OBJC_CATEGORY_";
1819 Result += CategoryImplementation[i]->getClassInterface()->getName();
1820 Result += "_";
1821 Result += CategoryImplementation[i]->getName();
1822 Result += "\n";
1823 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001824
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001825 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001826
1827 // Write objc_module metadata
1828
1829 /*
1830 struct _objc_module {
1831 long version;
1832 long size;
1833 const char *name;
1834 struct _objc_symtab *symtab;
1835 }
1836 */
1837
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001838 Result += "\nstruct _objc_module {\n";
1839 Result += "\tlong version;\n";
1840 Result += "\tlong size;\n";
1841 Result += "\tconst char *name;\n";
1842 Result += "\tstruct _objc_symtab *symtab;\n";
1843 Result += "};\n\n";
1844 Result += "static struct _objc_module "
1845 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001846 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1847 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001848 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001849
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001850}
Chris Lattner311ff022007-10-16 22:36:42 +00001851