blob: 07b66275ec1d12fcf1eb45be1490f6c274a0201f [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];
Steve Naroff1d098f62007-11-14 14:34:23 +0000339 SourceLocation LocStart = Method->getLocStart();
340 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000341
Steve Naroff1d098f62007-11-14 14:34:23 +0000342 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
343 Rewrite.InsertText(LocStart, "/* ", 3);
344 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
345 } else {
346 Rewrite.InsertText(LocStart, "// ", 3);
347 }
Steve Naroff423cb562007-10-30 13:30:57 +0000348 }
349}
350
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000351void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
352{
353 for (int i = 0; i < nProperties; i++) {
354 ObjcPropertyDecl *Property = Properties[i];
355 SourceLocation Loc = Property->getLocation();
356
357 Rewrite.ReplaceText(Loc, 0, "// ", 3);
358
359 // FIXME: handle properties that are declared across multiple lines.
360 }
361}
362
Steve Naroff423cb562007-10-30 13:30:57 +0000363void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
364 SourceLocation LocStart = CatDecl->getLocStart();
365
366 // FIXME: handle category headers that are declared across multiple lines.
367 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
368
Steve Naroff71c0a952007-11-13 23:01:27 +0000369 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
370 CatDecl->getInstanceMethods());
371 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
372 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000373 // Lastly, comment out the @end.
374 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
375}
376
Steve Naroff752d6ef2007-10-30 16:42:30 +0000377void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000378 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000379
Steve Naroff752d6ef2007-10-30 16:42:30 +0000380 SourceLocation LocStart = PDecl->getLocStart();
381
382 // FIXME: handle protocol headers that are declared across multiple lines.
383 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
384
Steve Naroff71c0a952007-11-13 23:01:27 +0000385 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
386 PDecl->getInstanceMethods());
387 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
388 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000389 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000390 SourceLocation LocEnd = PDecl->getAtEndLoc();
391 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000392
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000393 // Must comment out @optional/@required
394 const char *startBuf = SM->getCharacterData(LocStart);
395 const char *endBuf = SM->getCharacterData(LocEnd);
396 for (const char *p = startBuf; p < endBuf; p++) {
397 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
398 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000399 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000400 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
401 CommentedOptional.c_str(), CommentedOptional.size());
402
403 }
404 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
405 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000406 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000407 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
408 CommentedRequired.c_str(), CommentedRequired.size());
409
410 }
411 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000412}
413
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000414void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
415 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000416 if (LocStart.isInvalid())
417 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000422void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
423 std::string &ResultStr) {
Fariborz Jahanian7a3279d2007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000429 ResultStr += "\nstatic ";
430 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000431 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000432
433 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000434 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000435
Fariborz Jahanianb7908b52007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000443
444 NamedDecl *MethodContext = OMD->getMethodContext();
445 if (ObjcCategoryImplDecl *CID =
446 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000447 NameStr += CID->getName();
448 NameStr += "_";
Fariborz Jahanian48a0b6a2007-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 Jahanianb7908b52007-11-13 21:02:00 +0000453 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-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 Jahanianb7908b52007-11-13 21:02:00 +0000460 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000461 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000462 // Remember this name for metadata emission
463 MethodInternalNames[OMD] = NameStr;
464 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-11-13 20:04:28 +0000473 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
474 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000498
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000499 if (IMD)
500 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
501 else
502 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000503
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000504 int numMethods = IMD ? IMD->getNumInstanceMethods()
505 : CID->getNumInstanceMethods();
506
507 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000508 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000509 ObjcMethodDecl *OMD;
510 if (IMD)
511 OMD = IMD->getInstanceMethods()[i];
512 else
513 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-11-13 20:04:28 +0000524 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
525 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000526 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000527 ObjcMethodDecl *OMD;
528 if (IMD)
529 OMD = IMD->getClassMethods()[i];
530 else
531 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-11-13 20:04:28 +0000541 if (IMD)
542 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
543 else
544 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000545}
546
Steve Naroffbef11852007-10-26 20:53:56 +0000547void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000548 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000549 if (!ObjcForwardDecls.count(ClassDecl)) {
550 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000551 ResultStr += "#ifndef _REWRITER_typedef_";
552 ResultStr += ClassDecl->getName();
553 ResultStr += "\n";
554 ResultStr += "#define _REWRITER_typedef_";
555 ResultStr += ClassDecl->getName();
556 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000557 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000558 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000559 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000560
561 // Mark this typedef as having been generated.
562 ObjcForwardDecls.insert(ClassDecl);
563 }
Steve Narofff908a872007-10-30 02:23:23 +0000564 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
565
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000566 RewriteProperties(ClassDecl->getNumPropertyDecl(),
567 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000568 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
569 ClassDecl->getInstanceMethods());
570 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
571 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000572
Steve Naroff2feac5e2007-10-30 03:43:13 +0000573 // Lastly, comment out the @end.
574 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000575}
576
Chris Lattnerf04da132007-10-24 17:06:59 +0000577//===----------------------------------------------------------------------===//
578// Function Body / Expression rewriting
579//===----------------------------------------------------------------------===//
580
Steve Narofff3473a72007-11-09 15:20:18 +0000581Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000582 // Otherwise, just rewrite all children.
583 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
584 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000585 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000586 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000587 if (newStmt)
588 *CI = newStmt;
589 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000590
591 // Handle specific things.
592 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
593 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000594
595 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
596 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000597
598 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
599 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000600
Steve Naroff934f2762007-10-24 22:48:43 +0000601 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
602 // Before we rewrite it, put the original message expression in a comment.
603 SourceLocation startLoc = MessExpr->getLocStart();
604 SourceLocation endLoc = MessExpr->getLocEnd();
605
606 const char *startBuf = SM->getCharacterData(startLoc);
607 const char *endBuf = SM->getCharacterData(endLoc);
608
609 std::string messString;
610 messString += "// ";
611 messString.append(startBuf, endBuf-startBuf+1);
612 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000613
Steve Naroff934f2762007-10-24 22:48:43 +0000614 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
615 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
616 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000617 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000618 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000619 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000620
621 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
622 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000623
624 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
625 return RewriteObjcThrowStmt(StmtThrow);
626
Chris Lattnere64b7772007-10-24 16:57:36 +0000627 // Return this stmt unmodified.
628 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000629}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000630
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000631Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000632 // Get the start location and compute the semi location.
633 SourceLocation startLoc = S->getLocStart();
634 const char *startBuf = SM->getCharacterData(startLoc);
635
636 assert((*startBuf == '@') && "bogus @try location");
637
638 std::string buf;
639 // declare a new scope with two variables, _stack and _rethrow.
640 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
641 buf += "int buf[18/*32-bit i386*/];\n";
642 buf += "char *pointers[4];} _stack;\n";
643 buf += "id volatile _rethrow = 0;\n";
644 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000645 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000646
647 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
648
649 startLoc = S->getTryBody()->getLocEnd();
650 startBuf = SM->getCharacterData(startLoc);
651
652 assert((*startBuf == '}') && "bogus @try block");
653
654 SourceLocation lastCurlyLoc = startLoc;
655
656 startLoc = startLoc.getFileLocWithOffset(1);
657 buf = " /* @catch begin */ else {\n";
658 buf += " id _caught = objc_exception_extract(&_stack);\n";
659 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000660 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000661 buf += " _rethrow = objc_exception_extract(&_stack);\n";
662 buf += " else { /* @catch continue */";
663
Chris Lattner28d1fe82007-11-08 04:41:51 +0000664 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000665
666 bool sawIdTypedCatch = false;
667 Stmt *lastCatchBody = 0;
668 ObjcAtCatchStmt *catchList = S->getCatchStmts();
669 while (catchList) {
670 Stmt *catchStmt = catchList->getCatchParamStmt();
671
672 if (catchList == S->getCatchStmts())
673 buf = "if ("; // we are generating code for the first catch clause
674 else
675 buf = "else if (";
676 startLoc = catchList->getLocStart();
677 startBuf = SM->getCharacterData(startLoc);
678
679 assert((*startBuf == '@') && "bogus @catch location");
680
681 const char *lParenLoc = strchr(startBuf, '(');
682
683 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
684 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
685 if (t == Context->getObjcIdType()) {
686 buf += "1) { ";
687 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
688 buf.c_str(), buf.size());
689 sawIdTypedCatch = true;
690 } else if (const PointerType *pType = t->getAsPointerType()) {
691 ObjcInterfaceType *cls; // Should be a pointer to a class.
692
693 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
694 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000695 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000696 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000697 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000698 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
699 buf.c_str(), buf.size());
700 }
701 }
702 // Now rewrite the body...
703 lastCatchBody = catchList->getCatchBody();
704 SourceLocation rParenLoc = catchList->getRParenLoc();
705 SourceLocation bodyLoc = lastCatchBody->getLocStart();
706 const char *bodyBuf = SM->getCharacterData(bodyLoc);
707 const char *rParenBuf = SM->getCharacterData(rParenLoc);
708 assert((*rParenBuf == ')') && "bogus @catch paren location");
709 assert((*bodyBuf == '{') && "bogus @catch body location");
710
711 buf = " = _caught;";
712 // Here we replace ") {" with "= _caught;" (which initializes and
713 // declares the @catch parameter).
714 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
715 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000716 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000717 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000718 }
Steve Naroff75730982007-11-07 04:08:17 +0000719 catchList = catchList->getNextCatchStmt();
720 }
721 // Complete the catch list...
722 if (lastCatchBody) {
723 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
724 const char *bodyBuf = SM->getCharacterData(bodyLoc);
725 assert((*bodyBuf == '}') && "bogus @catch body location");
726 bodyLoc = bodyLoc.getFileLocWithOffset(1);
727 buf = " } } /* @catch end */\n";
728
Chris Lattner28d1fe82007-11-08 04:41:51 +0000729 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000730
731 // Set lastCurlyLoc
732 lastCurlyLoc = lastCatchBody->getLocEnd();
733 }
734 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
735 startLoc = finalStmt->getLocStart();
736 startBuf = SM->getCharacterData(startLoc);
737 assert((*startBuf == '@') && "bogus @finally start");
738
739 buf = "/* @finally */";
740 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
741
742 Stmt *body = finalStmt->getFinallyBody();
743 SourceLocation startLoc = body->getLocStart();
744 SourceLocation endLoc = body->getLocEnd();
745 const char *startBuf = SM->getCharacterData(startLoc);
746 const char *endBuf = SM->getCharacterData(endLoc);
747 assert((*startBuf == '{') && "bogus @finally body location");
748 assert((*endBuf == '}') && "bogus @finally body location");
749
750 startLoc = startLoc.getFileLocWithOffset(1);
751 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000752 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000753 endLoc = endLoc.getFileLocWithOffset(-1);
754 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000755 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000756
757 // Set lastCurlyLoc
758 lastCurlyLoc = body->getLocEnd();
759 }
760 // Now emit the final closing curly brace...
761 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
762 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000763 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000764 return 0;
765}
766
767Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
768 return 0;
769}
770
771Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
772 return 0;
773}
774
Steve Naroff2bd03922007-11-07 15:32:26 +0000775// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
776// the throw expression is typically a message expression that's already
777// been rewritten! (which implies the SourceLocation's are invalid).
778Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
779 // Get the start location and compute the semi location.
780 SourceLocation startLoc = S->getLocStart();
781 const char *startBuf = SM->getCharacterData(startLoc);
782
783 assert((*startBuf == '@') && "bogus @throw location");
784
785 std::string buf;
786 /* void objc_exception_throw(id) __attribute__((noreturn)); */
787 buf = "objc_exception_throw(";
788 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
789 const char *semiBuf = strchr(startBuf, ';');
790 assert((*semiBuf == ';') && "@throw: can't find ';'");
791 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
792 buf = ");";
793 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
794 return 0;
795}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000796
Chris Lattnere64b7772007-10-24 16:57:36 +0000797Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000798 // Create a new string expression.
799 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000800 std::string StrEncoding;
801 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
802 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
803 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000804 SourceLocation(), SourceLocation());
805 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000806 delete Exp;
807 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000808}
809
Steve Naroffb42f8412007-11-05 14:50:49 +0000810Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
811 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
812 // Create a call to sel_registerName("selName").
813 llvm::SmallVector<Expr*, 8> SelExprs;
814 QualType argType = Context->getPointerType(Context->CharTy);
815 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
816 Exp->getSelector().getName().size(),
817 false, argType, SourceLocation(),
818 SourceLocation()));
819 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
820 &SelExprs[0], SelExprs.size());
821 Rewrite.ReplaceStmt(Exp, SelExp);
822 delete Exp;
823 return SelExp;
824}
825
Steve Naroff934f2762007-10-24 22:48:43 +0000826CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
827 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000828 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000829 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000830
831 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000832 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000833
834 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000835 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000836 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
837
838 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000839
Steve Naroff934f2762007-10-24 22:48:43 +0000840 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
841}
842
Steve Naroffd5255f52007-11-01 13:24:47 +0000843static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
844 const char *&startRef, const char *&endRef) {
845 while (startBuf < endBuf) {
846 if (*startBuf == '<')
847 startRef = startBuf; // mark the start.
848 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000849 if (startRef && *startRef == '<') {
850 endRef = startBuf; // mark the end.
851 return true;
852 }
853 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000854 }
855 startBuf++;
856 }
857 return false;
858}
859
860bool RewriteTest::needToScanForQualifiers(QualType T) {
861 // FIXME: we don't currently represent "id <Protocol>" in the type system.
862 if (T == Context->getObjcIdType())
863 return true;
864
865 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000866 Type *pointeeType = pType->getPointeeType().getTypePtr();
867 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
868 return true; // we have "Class <Protocol> *".
869 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000870 return false;
871}
872
873void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
874 const FunctionTypeProto *proto, FunctionDecl *FD) {
875
876 if (needToScanForQualifiers(proto->getResultType())) {
877 // Since types are unique, we need to scan the buffer.
878 SourceLocation Loc = FD->getLocation();
879
880 const char *endBuf = SM->getCharacterData(Loc);
881 const char *startBuf = endBuf;
882 while (*startBuf != ';')
883 startBuf--; // scan backward (from the decl location) for return type.
884 const char *startRef = 0, *endRef = 0;
885 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
886 // Get the locations of the startRef, endRef.
887 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
888 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
889 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000890 Rewrite.InsertText(LessLoc, "/*", 2);
891 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000892 }
893 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000894 // Now check arguments.
895 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
896 if (needToScanForQualifiers(proto->getArgType(i))) {
897 // Since types are unique, we need to scan the buffer.
898 SourceLocation Loc = FD->getLocation();
899
900 const char *startBuf = SM->getCharacterData(Loc);
901 const char *endBuf = startBuf;
902 while (*endBuf != ';')
903 endBuf++; // scan forward (from the decl location) for argument types.
904 const char *startRef = 0, *endRef = 0;
905 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
906 // Get the locations of the startRef, endRef.
907 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
908 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
909 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000910 Rewrite.InsertText(LessLoc, "/*", 2);
911 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000912 }
913 }
914 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000915}
916
Steve Naroff09b266e2007-10-30 23:14:51 +0000917void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
918 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000919 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000920 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000921 return;
922 }
923 // Check for ObjC 'id' and class types that have been adorned with protocol
924 // information (id<p>, C<p>*). The protocol references need to be rewritten!
925 const FunctionType *funcType = FD->getType()->getAsFunctionType();
926 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000927 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
928 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000929}
930
931// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
932void RewriteTest::SynthMsgSendFunctionDecl() {
933 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
934 llvm::SmallVector<QualType, 16> ArgTys;
935 QualType argT = Context->getObjcIdType();
936 assert(!argT.isNull() && "Can't find 'id' type");
937 ArgTys.push_back(argT);
938 argT = Context->getObjcSelType();
939 assert(!argT.isNull() && "Can't find 'SEL' type");
940 ArgTys.push_back(argT);
941 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
942 &ArgTys[0], ArgTys.size(),
943 true /*isVariadic*/);
944 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
945 msgSendIdent, msgSendType,
946 FunctionDecl::Extern, false, 0);
947}
948
949// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
950void RewriteTest::SynthGetClassFunctionDecl() {
951 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
952 llvm::SmallVector<QualType, 16> ArgTys;
953 ArgTys.push_back(Context->getPointerType(
954 Context->CharTy.getQualifiedType(QualType::Const)));
955 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
956 &ArgTys[0], ArgTys.size(),
957 false /*isVariadic*/);
958 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
959 getClassIdent, getClassType,
960 FunctionDecl::Extern, false, 0);
961}
962
Steve Naroff96984642007-11-08 14:30:50 +0000963// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
964void RewriteTest::SynthCFStringFunctionDecl() {
965 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
966 llvm::SmallVector<QualType, 16> ArgTys;
967 ArgTys.push_back(Context->getPointerType(
968 Context->CharTy.getQualifiedType(QualType::Const)));
969 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
970 &ArgTys[0], ArgTys.size(),
971 false /*isVariadic*/);
972 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
973 getClassIdent, getClassType,
974 FunctionDecl::Extern, false, 0);
975}
976
Steve Naroffbeaf2992007-11-03 11:27:19 +0000977Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000978#if 1
979 // This rewrite is specific to GCC, which has builtin support for CFString.
980 if (!CFStringFunctionDecl)
981 SynthCFStringFunctionDecl();
982 // Create a call to __builtin___CFStringMakeConstantString("cstr").
983 llvm::SmallVector<Expr*, 8> StrExpr;
984 StrExpr.push_back(Exp->getString());
985 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
986 &StrExpr[0], StrExpr.size());
987 // cast to NSConstantString *
988 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
989 Rewrite.ReplaceStmt(Exp, cast);
990 delete Exp;
991 return cast;
992#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000993 assert(ConstantStringClassReference && "Can't find constant string reference");
994 llvm::SmallVector<Expr*, 4> InitExprs;
995
996 // Synthesize "(Class)&_NSConstantStringClassReference"
997 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
998 ConstantStringClassReference->getType(),
999 SourceLocation());
1000 QualType expType = Context->getPointerType(ClsRef->getType());
1001 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1002 expType, SourceLocation());
1003 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1004 SourceLocation());
1005 InitExprs.push_back(cast); // set the 'isa'.
1006 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1007 unsigned IntSize = static_cast<unsigned>(
1008 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1009 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1010 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1011 Exp->getLocStart());
1012 InitExprs.push_back(len); // set "int numBytes".
1013
1014 // struct NSConstantString
1015 QualType CFConstantStrType = Context->getCFConstantStringType();
1016 // (struct NSConstantString) { <exprs from above> }
1017 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1018 &InitExprs[0], InitExprs.size(),
1019 SourceLocation());
1020 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1021 // struct NSConstantString *
1022 expType = Context->getPointerType(StrRep->getType());
1023 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1024 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001025 // cast to NSConstantString *
1026 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001027 Rewrite.ReplaceStmt(Exp, cast);
1028 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001029 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001030#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001031}
1032
Steve Naroff934f2762007-10-24 22:48:43 +00001033Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001034 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001035 if (!MsgSendFunctionDecl)
1036 SynthMsgSendFunctionDecl();
1037 if (!GetClassFunctionDecl)
1038 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001039
1040 // Synthesize a call to objc_msgSend().
1041 llvm::SmallVector<Expr*, 8> MsgExprs;
1042 IdentifierInfo *clsName = Exp->getClassName();
1043
1044 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1045 if (clsName) { // class message.
1046 llvm::SmallVector<Expr*, 8> ClsExprs;
1047 QualType argType = Context->getPointerType(Context->CharTy);
1048 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1049 clsName->getLength(),
1050 false, argType, SourceLocation(),
1051 SourceLocation()));
1052 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1053 &ClsExprs[0], ClsExprs.size());
1054 MsgExprs.push_back(Cls);
1055 } else // instance message.
1056 MsgExprs.push_back(Exp->getReceiver());
1057
Steve Naroffbeaf2992007-11-03 11:27:19 +00001058 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001059 llvm::SmallVector<Expr*, 8> SelExprs;
1060 QualType argType = Context->getPointerType(Context->CharTy);
1061 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1062 Exp->getSelector().getName().size(),
1063 false, argType, SourceLocation(),
1064 SourceLocation()));
1065 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1066 &SelExprs[0], SelExprs.size());
1067 MsgExprs.push_back(SelExp);
1068
1069 // Now push any user supplied arguments.
1070 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1071 MsgExprs.push_back(Exp->getArg(i));
1072 // We've transferred the ownership to MsgExprs. Null out the argument in
1073 // the original expression, since we will delete it below.
1074 Exp->setArg(i, 0);
1075 }
Steve Naroffab972d32007-11-04 22:37:50 +00001076 // Generate the funky cast.
1077 CastExpr *cast;
1078 llvm::SmallVector<QualType, 8> ArgTypes;
1079 QualType returnType;
1080
1081 // Push 'id' and 'SEL', the 2 implicit arguments.
1082 ArgTypes.push_back(Context->getObjcIdType());
1083 ArgTypes.push_back(Context->getObjcSelType());
1084 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1085 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001086 for (int i = 0; i < mDecl->getNumParams(); i++) {
1087 QualType t = mDecl->getParamDecl(i)->getType();
1088 if (t == Context->getObjcClassType())
1089 t = Context->getObjcIdType(); // Convert "Class"->"id"
1090 ArgTypes.push_back(t);
1091 }
Steve Naroffab972d32007-11-04 22:37:50 +00001092 returnType = mDecl->getResultType();
1093 } else {
1094 returnType = Context->getObjcIdType();
1095 }
1096 // Get the type, we will need to reference it in a couple spots.
1097 QualType msgSendType = MsgSendFunctionDecl->getType();
1098
1099 // Create a reference to the objc_msgSend() declaration.
1100 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1101
1102 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1103 // If we don't do this cast, we get the following bizarre warning/note:
1104 // xx.m:13: warning: function called through a non-compatible type
1105 // xx.m:13: note: if this code is reached, the program will abort
1106 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1107 SourceLocation());
1108
1109 // Now do the "normal" pointer to function cast.
1110 QualType castType = Context->getFunctionType(returnType,
1111 &ArgTypes[0], ArgTypes.size(),
1112 false/*FIXME:variadic*/);
1113 castType = Context->getPointerType(castType);
1114 cast = new CastExpr(castType, cast, SourceLocation());
1115
1116 // Don't forget the parens to enforce the proper binding.
1117 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1118
1119 const FunctionType *FT = msgSendType->getAsFunctionType();
1120 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1121 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001122 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001123 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001124
Chris Lattnere64b7772007-10-24 16:57:36 +00001125 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001126 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001127}
1128
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001129/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1130/// an objective-c class with ivars.
1131void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1132 std::string &Result) {
1133 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1134 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001135 // Do not synthesize more than once.
1136 if (ObjcSynthesizedStructs.count(CDecl))
1137 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001138 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1139 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1140 // Do it for the root
1141 SynthesizeObjcInternalStruct(RCDecl, Result);
1142 }
1143
Steve Naroff03300712007-11-12 13:56:41 +00001144 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001145 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001146 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001147 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1148 return;
1149
Steve Narofffea763e82007-11-14 19:25:57 +00001150 Result += "\nstruct ";
1151 Result += CDecl->getName();
1152
1153 SourceLocation LocStart = CDecl->getLocStart();
1154 SourceLocation LocEnd = CDecl->getLocEnd();
1155
1156 const char *startBuf = SM->getCharacterData(LocStart);
1157 const char *endBuf = SM->getCharacterData(LocEnd);
1158
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001159 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001160 const char *cursor = strchr(startBuf, '{');
1161 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001162 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001163
1164 // rewrite the original header *without* disturbing the '{'
1165 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1166 Result.c_str(), Result.size());
1167 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1168 Result = "\n struct ";
1169 Result += RCDecl->getName();
1170 Result += " _";
1171 Result += RCDecl->getName();
1172 Result += ";\n";
1173
1174 // insert the super class structure definition.
1175 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1176 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1177 }
1178 cursor++; // past '{'
1179
1180 // Now comment out any visibility specifiers.
1181 while (cursor < endBuf) {
1182 if (*cursor == '@') {
1183 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1184 cursor = strchr(cursor, 'p');
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001185 // FIXME: presence of @public, etc. inside comment results in
1186 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001187 if (!strncmp(cursor, "public", strlen("public")) ||
1188 !strncmp(cursor, "private", strlen("private")) ||
1189 !strncmp(cursor, "protected", strlen("private")))
1190 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001191 }
Steve Narofffea763e82007-11-14 19:25:57 +00001192 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001193 }
Steve Narofffea763e82007-11-14 19:25:57 +00001194 // Don't forget to add a ';'!!
1195 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1196 } else { // we don't have any instance variables - insert super struct.
1197 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1198 Result += " {\n struct ";
1199 Result += RCDecl->getName();
1200 Result += " _";
1201 Result += RCDecl->getName();
1202 Result += ";\n};\n";
1203 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1204 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001205 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001206 // Mark this struct as having been generated.
1207 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001208 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001209}
1210
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001211// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1212/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001213void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001214 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001215 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001216 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001217 const char *ClassName,
1218 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001219 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001220 if (NumMethods > 0 && !objc_impl_method) {
1221 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001222 SEL _cmd;
1223 char *method_types;
1224 void *_imp;
1225 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001226 */
Chris Lattner158ecb92007-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 Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001243 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001244 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001245 // Build _objc_method_list for class's methods if needed
1246 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001247 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-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 Jahanianccd87b02007-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 Jahanian33e1d642007-10-29 22:57:28 +00001259 std::string MethodTypeString;
1260 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1261 Result += "\", \"";
1262 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001263 Result += "\", ";
1264 Result += MethodInternalNames[Methods[0]];
1265 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001266 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001267 Result += "\t ,{(SEL)\"";
1268 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001269 std::string MethodTypeString;
1270 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1271 Result += "\", \"";
1272 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001273 Result += "\", ";
1274 Result += MethodInternalNames[Methods[i]];
1275 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001276 }
1277 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001278 }
Fariborz Jahanian2e6d9352007-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 Jahanianccd87b02007-10-25 20:55:25 +00001285 const char *ClassName,
1286 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001287 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001288 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-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 Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001313 objc_protocol_methods = true;
1314 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001315
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001316 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001317 int NumMethods = PDecl->getNumInstanceMethods();
1318 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001325 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-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 Jahanianccd87b02007-10-25 20:55:25 +00001331 Result += "\t ,{(SEL)\"";
1332 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001333 std::string MethodTypeString;
1334 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1335 Result += "\", \"";
1336 Result += MethodTypeString;
1337 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001338 }
1339 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001340 }
1341
1342 // Output class methods declared in this protocol.
1343 NumMethods = PDecl->getNumClassMethods();
1344 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001353 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-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 Jahanianccd87b02007-10-25 20:55:25 +00001359 Result += "\t ,{(SEL)\"";
1360 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001361 std::string MethodTypeString;
1362 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1363 Result += "\", \"";
1364 Result += MethodTypeString;
1365 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001366 }
1367 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-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 Jahanianccd87b02007-10-25 20:55:25 +00001375 struct _objc_protocol_method_list *instance_methods;
1376 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001377 };
1378 */
1379 static bool objc_protocol = false;
1380 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001400 objc_protocol = true;
1401 }
1402
Fariborz Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001414 else
Fariborz Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001421 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001422 Result += "0\n";
1423 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001424 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001425 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-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 Jahaniane887c092007-10-22 21:41:37 +00001440 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001441 Result += "\t ,&_OBJC_PROTOCOL_";
1442 Result += PDecl->getName();
1443 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001444 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001445 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001446 }
1447}
1448
1449/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1450/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001451void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1452 std::string &Result) {
Fariborz Jahanian2e6d9352007-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 Jahanianbac97d42007-11-13 22:09:49 +00001460
Fariborz Jahanian2e6d9352007-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 Jahanian8e991ba2007-10-25 00:14:44 +00001468 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001469 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-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 Jahanian8e991ba2007-10-25 00:14:44 +00001474 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001475 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001476
1477 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-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 Jahanian2e6d9352007-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 Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001509 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001510 }
Fariborz Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001518
Fariborz Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001525 else
Fariborz Jahanianccd87b02007-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 Jahanianbac97d42007-11-13 22:09:49 +00001536 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001544}
1545
Fariborz Jahanian26e4cd32007-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 Jahanian909f02a2007-11-05 17:47:33 +00001551 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001552 Result += IDecl->getName();
1553 Result += ", ";
1554 Result += ivar->getName();
1555 Result += ")";
1556}
1557
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001558//===----------------------------------------------------------------------===//
1559// Meta Data Emission
1560//===----------------------------------------------------------------------===//
1561
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001562void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1563 std::string &Result) {
Fariborz Jahanian2e6d9352007-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 Naroff03300712007-11-12 13:56:41 +00001569 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001570
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001571 SynthesizeObjcInternalStruct(CDecl, Result);
1572
Fariborz Jahanian2e6d9352007-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 Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001596 objc_ivar = true;
1597 }
1598
Fariborz Jahanianccd87b02007-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 Jahanian2e6d9352007-10-24 19:23:36 +00001606 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1607 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001608 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001609 Result += "\t,{{\"";
1610 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001611 Result += "\", \"";
1612 std::string StrEncoding;
1613 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1614 Result += StrEncoding;
1615 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001616 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1617 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001618 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001619 Result += "\t ,{\"";
1620 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001621 Result += "\", \"";
1622 std::string StrEncoding;
1623 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1624 Result += StrEncoding;
1625 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001626 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1627 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001628 }
1629
1630 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-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 Jahanianccd87b02007-10-25 20:55:25 +00001636 true,
1637 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001638
1639 // Build _objc_method_list for class's class methods if needed
1640 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001641 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001642 false,
1643 "", IDecl->getName(), Result);
1644
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001645 // Protocols referenced in class declaration?
1646 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1647 CDecl->getNumIntfRefProtocols(),
1648 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001649 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001650
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001651
Fariborz Jahaniandeef5182007-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 Jahanian9f0a1cb2007-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 Jahaniandeef5182007-10-23 18:53:48 +00001660 struct _objc_ivar_list *ivars;
1661 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-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 Jahaniandeef5182007-10-23 18:53:48 +00001668 static bool objc_class = false;
1669 if (!objc_class) {
Fariborz Jahanianccd87b02007-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 Jahaniandeef5182007-10-23 18:53:48 +00001684 objc_class = true;
Fariborz Jahanian9f0a1cb2007-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 Jahanianccd87b02007-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 Jahanian9f0a1cb2007-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 Jahanianccd87b02007-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 Jahanian9f0a1cb2007-10-23 00:02:02 +00001723 else
Fariborz Jahanianccd87b02007-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 Jahanian454cb012007-10-24 20:54:23 +00001730 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001731 Result += "\t,0,0,0,0\n";
1732 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001733
1734 // class metadata generation.
Fariborz Jahanianccd87b02007-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 Jahaniandeef5182007-10-23 18:53:48 +00001752 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-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 Jahanian909f02a2007-11-05 17:47:33 +00001758 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001759 Result += CDecl->getName();
1760 Result += ")";
1761 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001762 if (NumIvars > 0) {
1763 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1764 Result += CDecl->getName();
1765 Result += "\n\t";
1766 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001767 else
Fariborz Jahanianccd87b02007-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 Jahaniandeef5182007-10-23 18:53:48 +00001774 else
Fariborz Jahanianccd87b02007-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 Jahaniandeef5182007-10-23 18:53:48 +00001781 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001782 Result += ",0,0,0\n";
1783 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001784}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001785
Fariborz Jahanian7a3279d2007-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 Jahanian545b9ae2007-10-18 19:23:00 +00001790 int ClsDefCount = ClassImplementation.size();
1791 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001792
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001793 if (ClsDefCount == 0 && CatDefCount == 0)
1794 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001795 // Rewrite implemented methods
1796 for (int i = 0; i < ClsDefCount; i++)
1797 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001798
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001799 for (int i = 0; i < CatDefCount; i++)
1800 RewriteImplementationDecl(CategoryImplementation[i]);
1801
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001802 // TODO: This is temporary until we decide how to access objc types in a
1803 // c program
Fariborz Jahanian26e4cd32007-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 Jahanian7a3279d2007-11-13 19:21:13 +00001807
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001808 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001809 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001810 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-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 Jahanianccd87b02007-10-25 20:55:25 +00001814 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001815
Fariborz Jahanian545b9ae2007-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 Jahanianccd87b02007-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 Jahanian545b9ae2007-10-18 19:23:00 +00001835
Fariborz Jahanianccd87b02007-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 Jahanian545b9ae2007-10-18 19:23:00 +00001845
Fariborz Jahanianccd87b02007-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 Jahanian545b9ae2007-10-18 19:23:00 +00001853
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001854 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-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 Jahanianccd87b02007-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 Jahanian26e4cd32007-10-26 19:46:17 +00001875 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1876 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001877 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001878
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001879}
Chris Lattner311ff022007-10-16 22:36:42 +00001880