blob: 286b493ddb3928af3116c419edba329103323ea2 [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"
Fariborz Jahanian95673922007-11-14 22:26:25 +000073 "(struct objc_class *, struct objc_object *, ...);\n"
74 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +000075
Steve Naroffab972d32007-11-04 22:37:50 +000076 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
77 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000078 }
Chris Lattner8a12c272007-10-11 18:38:32 +000079
Chris Lattnerf04da132007-10-24 17:06:59 +000080 // Top Level Driver code.
81 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000082 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000083 ~RewriteTest();
84
85 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000086 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000087 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000088 void RewriteTabs();
89 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000090 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +000091 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000092 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000093 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000094 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +000095 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +000096 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000097 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000098 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000099 void RewriteObjcQualifiedInterfaceTypes(
100 const FunctionTypeProto *proto, FunctionDecl *FD);
101 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +0000102
Chris Lattnerf04da132007-10-24 17:06:59 +0000103 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000104 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000105 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000106 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000107 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000108 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000109 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
110 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
111 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000112 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000113 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
114 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000115 void SynthMsgSendFunctionDecl();
116 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000117 void SynthCFStringFunctionDecl();
118
Chris Lattnerf04da132007-10-24 17:06:59 +0000119 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
121 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000122
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000123 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
124 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000125
Steve Naroff0416fb92007-11-11 17:19:15 +0000126 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000127 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000128 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000129 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000130 const char *ClassName,
131 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000132
133 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
134 int NumProtocols,
135 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000136 const char *ClassName,
137 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000138 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
139 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000140 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
141 ObjcIvarDecl *ivar,
142 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000143 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000144 };
145}
146
Chris Lattner8a12c272007-10-11 18:38:32 +0000147ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000148
Chris Lattnerf04da132007-10-24 17:06:59 +0000149//===----------------------------------------------------------------------===//
150// Top Level Driver Code
151//===----------------------------------------------------------------------===//
152
Chris Lattner8a12c272007-10-11 18:38:32 +0000153void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000154 // Two cases: either the decl could be in the main file, or it could be in a
155 // #included file. If the former, rewrite it now. If the later, check to see
156 // if we rewrote the #include/#import.
157 SourceLocation Loc = D->getLocation();
158 Loc = SM->getLogicalLoc(Loc);
159
160 // If this is for a builtin, ignore it.
161 if (Loc.isInvalid()) return;
162
Steve Naroffebf2b562007-10-23 23:50:29 +0000163 // Look for built-in declarations that we need to refer during the rewrite.
164 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000165 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000166 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
167 // declared in <Foundation/NSString.h>
168 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
169 ConstantStringClassReference = FVD;
170 return;
171 }
Steve Naroffbef11852007-10-26 20:53:56 +0000172 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
173 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000174 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
175 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000176 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
177 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000178 } else if (ObjcForwardProtocolDecl *FP =
179 dyn_cast<ObjcForwardProtocolDecl>(D)){
180 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000181 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000182 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000183 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
184 return HandleDeclInMainFile(D);
185
Chris Lattnerf04da132007-10-24 17:06:59 +0000186 // Otherwise, see if there is a #import in the main file that should be
187 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000188 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000189}
190
Chris Lattnerf04da132007-10-24 17:06:59 +0000191/// HandleDeclInMainFile - This is called for each top-level decl defined in the
192/// main file of the input.
193void RewriteTest::HandleDeclInMainFile(Decl *D) {
194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
195 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000196 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000197
198 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
199 if (Stmt *Body = MD->getBody())
200 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
201 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000202 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
203 ClassImplementation.push_back(CI);
204 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
205 CategoryImplementation.push_back(CI);
206 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
207 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000208 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
209 if (VD->getInit())
210 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
211 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000212 // Nothing yet.
213}
214
215RewriteTest::~RewriteTest() {
216 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000217
218 // Rewrite tabs if we care.
219 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000220
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000221 // Rewrite Objective-c meta data*
222 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000223 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000224
Chris Lattnerf04da132007-10-24 17:06:59 +0000225 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
226 // we are done.
227 if (const RewriteBuffer *RewriteBuf =
228 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000229 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000230 std::string S(RewriteBuf->begin(), RewriteBuf->end());
231 printf("%s\n", S.c_str());
232 } else {
233 printf("No changes\n");
234 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000235 // Emit metadata.
236 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000237}
238
Chris Lattnerf04da132007-10-24 17:06:59 +0000239//===----------------------------------------------------------------------===//
240// Syntactic (non-AST) Rewriting Code
241//===----------------------------------------------------------------------===//
242
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000243void RewriteTest::RewriteInclude(SourceLocation Loc) {
244 // Rip up the #include stack to the main file.
245 SourceLocation IncLoc = Loc, NextLoc = Loc;
246 do {
247 IncLoc = Loc;
248 Loc = SM->getLogicalLoc(NextLoc);
249 NextLoc = SM->getIncludeLoc(Loc);
250 } while (!NextLoc.isInvalid());
251
252 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
253 // IncLoc indicates the header that was included if it is useful.
254 IncLoc = SM->getLogicalLoc(IncLoc);
255 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
256 Loc == LastIncLoc)
257 return;
258 LastIncLoc = Loc;
259
260 unsigned IncCol = SM->getColumnNumber(Loc);
261 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
262
263 // Replace the #import with #include.
264 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
265}
266
Chris Lattnerf04da132007-10-24 17:06:59 +0000267void RewriteTest::RewriteTabs() {
268 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
269 const char *MainBufStart = MainBuf.first;
270 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000271
Chris Lattnerf04da132007-10-24 17:06:59 +0000272 // Loop over the whole file, looking for tabs.
273 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
274 if (*BufPtr != '\t')
275 continue;
276
277 // Okay, we found a tab. This tab will turn into at least one character,
278 // but it depends on which 'virtual column' it is in. Compute that now.
279 unsigned VCol = 0;
280 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
281 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
282 ++VCol;
283
284 // Okay, now that we know the virtual column, we know how many spaces to
285 // insert. We assume 8-character tab-stops.
286 unsigned Spaces = 8-(VCol & 7);
287
288 // Get the location of the tab.
289 SourceLocation TabLoc =
290 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
291
292 // Rewrite the single tab character into a sequence of spaces.
293 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
294 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000295}
296
297
Chris Lattnerf04da132007-10-24 17:06:59 +0000298void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
299 int numDecls = ClassDecl->getNumForwardDecls();
300 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
301
302 // Get the start location and compute the semi location.
303 SourceLocation startLoc = ClassDecl->getLocation();
304 const char *startBuf = SM->getCharacterData(startLoc);
305 const char *semiPtr = strchr(startBuf, ';');
306
307 // Translate to typedef's that forward reference structs with the same name
308 // as the class. As a convenience, we include the original declaration
309 // as a comment.
310 std::string typedefString;
311 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000312 typedefString.append(startBuf, semiPtr-startBuf+1);
313 typedefString += "\n";
314 for (int i = 0; i < numDecls; i++) {
315 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000316 typedefString += "#ifndef _REWRITER_typedef_";
317 typedefString += ForwardDecl->getName();
318 typedefString += "\n";
319 typedefString += "#define _REWRITER_typedef_";
320 typedefString += ForwardDecl->getName();
321 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000322 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000323 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000324 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000325 }
326
327 // Replace the @class with typedefs corresponding to the classes.
328 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
329 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000330}
331
Steve Naroff71c0a952007-11-13 23:01:27 +0000332void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000333 for (int i = 0; i < nMethods; i++) {
334 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000335 SourceLocation LocStart = Method->getLocStart();
336 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000337
Steve Naroff1d098f62007-11-14 14:34:23 +0000338 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
339 Rewrite.InsertText(LocStart, "/* ", 3);
340 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
341 } else {
342 Rewrite.InsertText(LocStart, "// ", 3);
343 }
Steve Naroff423cb562007-10-30 13:30:57 +0000344 }
345}
346
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000347void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
348{
349 for (int i = 0; i < nProperties; i++) {
350 ObjcPropertyDecl *Property = Properties[i];
351 SourceLocation Loc = Property->getLocation();
352
353 Rewrite.ReplaceText(Loc, 0, "// ", 3);
354
355 // FIXME: handle properties that are declared across multiple lines.
356 }
357}
358
Steve Naroff423cb562007-10-30 13:30:57 +0000359void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
360 SourceLocation LocStart = CatDecl->getLocStart();
361
362 // FIXME: handle category headers that are declared across multiple lines.
363 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
364
Steve Naroff71c0a952007-11-13 23:01:27 +0000365 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
366 CatDecl->getInstanceMethods());
367 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
368 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000369 // Lastly, comment out the @end.
370 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
371}
372
Steve Naroff752d6ef2007-10-30 16:42:30 +0000373void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000374 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000375
Steve Naroff752d6ef2007-10-30 16:42:30 +0000376 SourceLocation LocStart = PDecl->getLocStart();
377
378 // FIXME: handle protocol headers that are declared across multiple lines.
379 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
380
Steve Naroff71c0a952007-11-13 23:01:27 +0000381 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
382 PDecl->getInstanceMethods());
383 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
384 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000385 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000386 SourceLocation LocEnd = PDecl->getAtEndLoc();
387 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000388
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000389 // Must comment out @optional/@required
390 const char *startBuf = SM->getCharacterData(LocStart);
391 const char *endBuf = SM->getCharacterData(LocEnd);
392 for (const char *p = startBuf; p < endBuf; p++) {
393 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
394 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000395 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000396 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
397 CommentedOptional.c_str(), CommentedOptional.size());
398
399 }
400 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
401 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000402 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000403 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
404 CommentedRequired.c_str(), CommentedRequired.size());
405
406 }
407 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000408}
409
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000410void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
411 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000412 if (LocStart.isInvalid())
413 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000414 // FIXME: handle forward protocol that are declared across multiple lines.
415 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
416}
417
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000418void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
419 std::string &ResultStr) {
420 ResultStr += "\nstatic ";
421 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000422 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000423
424 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000425 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000426
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000427 if (OMD->isInstance())
428 NameStr += "_I_";
429 else
430 NameStr += "_C_";
431
432 NameStr += OMD->getClassInterface()->getName();
433 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000434
435 NamedDecl *MethodContext = OMD->getMethodContext();
436 if (ObjcCategoryImplDecl *CID =
437 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000438 NameStr += CID->getName();
439 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000440 }
441 // Append selector names, replacing ':' with '_'
442 const char *selName = OMD->getSelector().getName().c_str();
443 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000444 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000445 else {
446 std::string selString = OMD->getSelector().getName();
447 int len = selString.size();
448 for (int i = 0; i < len; i++)
449 if (selString[i] == ':')
450 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000451 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000452 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000453 // Remember this name for metadata emission
454 MethodInternalNames[OMD] = NameStr;
455 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000456
457 // Rewrite arguments
458 ResultStr += "(";
459
460 // invisible arguments
461 if (OMD->isInstance()) {
462 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
463 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000464 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
465 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000466 ResultStr += selfTy.getAsString();
467 }
468 else
469 ResultStr += Context->getObjcIdType().getAsString();
470
471 ResultStr += " self, ";
472 ResultStr += Context->getObjcSelType().getAsString();
473 ResultStr += " _cmd";
474
475 // Method arguments.
476 for (int i = 0; i < OMD->getNumParams(); i++) {
477 ParmVarDecl *PDecl = OMD->getParamDecl(i);
478 ResultStr += ", ";
479 ResultStr += PDecl->getType().getAsString();
480 ResultStr += " ";
481 ResultStr += PDecl->getName();
482 }
483 ResultStr += ")";
484
485}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000486void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
487 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
488 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000489
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000490 if (IMD)
491 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
492 else
493 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000494
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000495 int numMethods = IMD ? IMD->getNumInstanceMethods()
496 : CID->getNumInstanceMethods();
497
498 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000499 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000500 ObjcMethodDecl *OMD;
501 if (IMD)
502 OMD = IMD->getInstanceMethods()[i];
503 else
504 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000505 RewriteObjcMethodDecl(OMD, ResultStr);
506 SourceLocation LocStart = OMD->getLocStart();
507 SourceLocation LocEnd = OMD->getBody()->getLocStart();
508
509 const char *startBuf = SM->getCharacterData(LocStart);
510 const char *endBuf = SM->getCharacterData(LocEnd);
511 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
512 ResultStr.c_str(), ResultStr.size());
513 }
514
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000515 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
516 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000517 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000518 ObjcMethodDecl *OMD;
519 if (IMD)
520 OMD = IMD->getClassMethods()[i];
521 else
522 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000523 RewriteObjcMethodDecl(OMD, ResultStr);
524 SourceLocation LocStart = OMD->getLocStart();
525 SourceLocation LocEnd = OMD->getBody()->getLocStart();
526
527 const char *startBuf = SM->getCharacterData(LocStart);
528 const char *endBuf = SM->getCharacterData(LocEnd);
529 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
530 ResultStr.c_str(), ResultStr.size());
531 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000532 if (IMD)
533 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
534 else
535 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000536}
537
Steve Naroffbef11852007-10-26 20:53:56 +0000538void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000539 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000540 if (!ObjcForwardDecls.count(ClassDecl)) {
541 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000542 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000543 ResultStr += ClassDecl->getName();
544 ResultStr += "\n";
545 ResultStr += "#define _REWRITER_typedef_";
546 ResultStr += ClassDecl->getName();
547 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000548 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000549 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000550 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000551
552 // Mark this typedef as having been generated.
553 ObjcForwardDecls.insert(ClassDecl);
554 }
Steve Narofff908a872007-10-30 02:23:23 +0000555 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
556
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000557 RewriteProperties(ClassDecl->getNumPropertyDecl(),
558 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000559 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
560 ClassDecl->getInstanceMethods());
561 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
562 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000563
Steve Naroff2feac5e2007-10-30 03:43:13 +0000564 // Lastly, comment out the @end.
565 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000566}
567
Chris Lattnerf04da132007-10-24 17:06:59 +0000568//===----------------------------------------------------------------------===//
569// Function Body / Expression rewriting
570//===----------------------------------------------------------------------===//
571
Steve Narofff3473a72007-11-09 15:20:18 +0000572Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000573 // Otherwise, just rewrite all children.
574 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
575 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000576 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000577 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000578 if (newStmt)
579 *CI = newStmt;
580 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000581
582 // Handle specific things.
583 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
584 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000585
586 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
587 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000588
589 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
590 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000591
Steve Naroff934f2762007-10-24 22:48:43 +0000592 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
593 // Before we rewrite it, put the original message expression in a comment.
594 SourceLocation startLoc = MessExpr->getLocStart();
595 SourceLocation endLoc = MessExpr->getLocEnd();
596
597 const char *startBuf = SM->getCharacterData(startLoc);
598 const char *endBuf = SM->getCharacterData(endLoc);
599
600 std::string messString;
601 messString += "// ";
602 messString.append(startBuf, endBuf-startBuf+1);
603 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000604
Steve Naroff934f2762007-10-24 22:48:43 +0000605 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
606 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
607 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000608 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000609 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000610 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000611
612 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
613 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000614
615 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
616 return RewriteObjcThrowStmt(StmtThrow);
617
Chris Lattnere64b7772007-10-24 16:57:36 +0000618 // Return this stmt unmodified.
619 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000620}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000621
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000622Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000623 // Get the start location and compute the semi location.
624 SourceLocation startLoc = S->getLocStart();
625 const char *startBuf = SM->getCharacterData(startLoc);
626
627 assert((*startBuf == '@') && "bogus @try location");
628
629 std::string buf;
630 // declare a new scope with two variables, _stack and _rethrow.
631 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
632 buf += "int buf[18/*32-bit i386*/];\n";
633 buf += "char *pointers[4];} _stack;\n";
634 buf += "id volatile _rethrow = 0;\n";
635 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000636 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000637
638 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
639
640 startLoc = S->getTryBody()->getLocEnd();
641 startBuf = SM->getCharacterData(startLoc);
642
643 assert((*startBuf == '}') && "bogus @try block");
644
645 SourceLocation lastCurlyLoc = startLoc;
646
647 startLoc = startLoc.getFileLocWithOffset(1);
648 buf = " /* @catch begin */ else {\n";
649 buf += " id _caught = objc_exception_extract(&_stack);\n";
650 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000651 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000652 buf += " _rethrow = objc_exception_extract(&_stack);\n";
653 buf += " else { /* @catch continue */";
654
Chris Lattner28d1fe82007-11-08 04:41:51 +0000655 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000656
657 bool sawIdTypedCatch = false;
658 Stmt *lastCatchBody = 0;
659 ObjcAtCatchStmt *catchList = S->getCatchStmts();
660 while (catchList) {
661 Stmt *catchStmt = catchList->getCatchParamStmt();
662
663 if (catchList == S->getCatchStmts())
664 buf = "if ("; // we are generating code for the first catch clause
665 else
666 buf = "else if (";
667 startLoc = catchList->getLocStart();
668 startBuf = SM->getCharacterData(startLoc);
669
670 assert((*startBuf == '@') && "bogus @catch location");
671
672 const char *lParenLoc = strchr(startBuf, '(');
673
674 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
675 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
676 if (t == Context->getObjcIdType()) {
677 buf += "1) { ";
678 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
679 buf.c_str(), buf.size());
680 sawIdTypedCatch = true;
681 } else if (const PointerType *pType = t->getAsPointerType()) {
682 ObjcInterfaceType *cls; // Should be a pointer to a class.
683
684 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
685 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000686 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000687 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000688 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000689 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
690 buf.c_str(), buf.size());
691 }
692 }
693 // Now rewrite the body...
694 lastCatchBody = catchList->getCatchBody();
695 SourceLocation rParenLoc = catchList->getRParenLoc();
696 SourceLocation bodyLoc = lastCatchBody->getLocStart();
697 const char *bodyBuf = SM->getCharacterData(bodyLoc);
698 const char *rParenBuf = SM->getCharacterData(rParenLoc);
699 assert((*rParenBuf == ')') && "bogus @catch paren location");
700 assert((*bodyBuf == '{') && "bogus @catch body location");
701
702 buf = " = _caught;";
703 // Here we replace ") {" with "= _caught;" (which initializes and
704 // declares the @catch parameter).
705 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
706 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000707 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000708 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000709 }
Steve Naroff75730982007-11-07 04:08:17 +0000710 catchList = catchList->getNextCatchStmt();
711 }
712 // Complete the catch list...
713 if (lastCatchBody) {
714 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
715 const char *bodyBuf = SM->getCharacterData(bodyLoc);
716 assert((*bodyBuf == '}') && "bogus @catch body location");
717 bodyLoc = bodyLoc.getFileLocWithOffset(1);
718 buf = " } } /* @catch end */\n";
719
Chris Lattner28d1fe82007-11-08 04:41:51 +0000720 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000721
722 // Set lastCurlyLoc
723 lastCurlyLoc = lastCatchBody->getLocEnd();
724 }
725 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
726 startLoc = finalStmt->getLocStart();
727 startBuf = SM->getCharacterData(startLoc);
728 assert((*startBuf == '@') && "bogus @finally start");
729
730 buf = "/* @finally */";
731 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
732
733 Stmt *body = finalStmt->getFinallyBody();
734 SourceLocation startLoc = body->getLocStart();
735 SourceLocation endLoc = body->getLocEnd();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *endBuf = SM->getCharacterData(endLoc);
738 assert((*startBuf == '{') && "bogus @finally body location");
739 assert((*endBuf == '}') && "bogus @finally body location");
740
741 startLoc = startLoc.getFileLocWithOffset(1);
742 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000743 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000744 endLoc = endLoc.getFileLocWithOffset(-1);
745 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000746 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000747
748 // Set lastCurlyLoc
749 lastCurlyLoc = body->getLocEnd();
750 }
751 // Now emit the final closing curly brace...
752 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
753 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000754 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000755 return 0;
756}
757
758Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
759 return 0;
760}
761
762Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
763 return 0;
764}
765
Steve Naroff2bd03922007-11-07 15:32:26 +0000766// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
767// the throw expression is typically a message expression that's already
768// been rewritten! (which implies the SourceLocation's are invalid).
769Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
770 // Get the start location and compute the semi location.
771 SourceLocation startLoc = S->getLocStart();
772 const char *startBuf = SM->getCharacterData(startLoc);
773
774 assert((*startBuf == '@') && "bogus @throw location");
775
776 std::string buf;
777 /* void objc_exception_throw(id) __attribute__((noreturn)); */
778 buf = "objc_exception_throw(";
779 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
780 const char *semiBuf = strchr(startBuf, ';');
781 assert((*semiBuf == ';') && "@throw: can't find ';'");
782 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
783 buf = ");";
784 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
785 return 0;
786}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000787
Chris Lattnere64b7772007-10-24 16:57:36 +0000788Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000789 // Create a new string expression.
790 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000791 std::string StrEncoding;
792 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
793 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
794 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000795 SourceLocation(), SourceLocation());
796 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000797 delete Exp;
798 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000799}
800
Steve Naroffb42f8412007-11-05 14:50:49 +0000801Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
802 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
803 // Create a call to sel_registerName("selName").
804 llvm::SmallVector<Expr*, 8> SelExprs;
805 QualType argType = Context->getPointerType(Context->CharTy);
806 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
807 Exp->getSelector().getName().size(),
808 false, argType, SourceLocation(),
809 SourceLocation()));
810 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
811 &SelExprs[0], SelExprs.size());
812 Rewrite.ReplaceStmt(Exp, SelExp);
813 delete Exp;
814 return SelExp;
815}
816
Steve Naroff934f2762007-10-24 22:48:43 +0000817CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
818 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000819 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000820 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000821
822 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000823 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000824
825 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000826 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000827 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
828
829 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000830
Steve Naroff934f2762007-10-24 22:48:43 +0000831 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
832}
833
Steve Naroffd5255f52007-11-01 13:24:47 +0000834static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
835 const char *&startRef, const char *&endRef) {
836 while (startBuf < endBuf) {
837 if (*startBuf == '<')
838 startRef = startBuf; // mark the start.
839 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000840 if (startRef && *startRef == '<') {
841 endRef = startBuf; // mark the end.
842 return true;
843 }
844 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000845 }
846 startBuf++;
847 }
848 return false;
849}
850
851bool RewriteTest::needToScanForQualifiers(QualType T) {
852 // FIXME: we don't currently represent "id <Protocol>" in the type system.
853 if (T == Context->getObjcIdType())
854 return true;
855
856 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000857 Type *pointeeType = pType->getPointeeType().getTypePtr();
858 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
859 return true; // we have "Class <Protocol> *".
860 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000861 return false;
862}
863
864void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
865 const FunctionTypeProto *proto, FunctionDecl *FD) {
866
867 if (needToScanForQualifiers(proto->getResultType())) {
868 // Since types are unique, we need to scan the buffer.
869 SourceLocation Loc = FD->getLocation();
870
871 const char *endBuf = SM->getCharacterData(Loc);
872 const char *startBuf = endBuf;
873 while (*startBuf != ';')
874 startBuf--; // scan backward (from the decl location) for return type.
875 const char *startRef = 0, *endRef = 0;
876 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
877 // Get the locations of the startRef, endRef.
878 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
879 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
880 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000881 Rewrite.InsertText(LessLoc, "/*", 2);
882 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000883 }
884 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000885 // Now check arguments.
886 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
887 if (needToScanForQualifiers(proto->getArgType(i))) {
888 // Since types are unique, we need to scan the buffer.
889 SourceLocation Loc = FD->getLocation();
890
891 const char *startBuf = SM->getCharacterData(Loc);
892 const char *endBuf = startBuf;
893 while (*endBuf != ';')
894 endBuf++; // scan forward (from the decl location) for argument types.
895 const char *startRef = 0, *endRef = 0;
896 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
897 // Get the locations of the startRef, endRef.
898 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
899 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
900 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000901 Rewrite.InsertText(LessLoc, "/*", 2);
902 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000903 }
904 }
905 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000906}
907
Steve Naroff09b266e2007-10-30 23:14:51 +0000908void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
909 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000910 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000911 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000912 return;
913 }
914 // Check for ObjC 'id' and class types that have been adorned with protocol
915 // information (id<p>, C<p>*). The protocol references need to be rewritten!
916 const FunctionType *funcType = FD->getType()->getAsFunctionType();
917 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000918 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
919 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000920}
921
922// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
923void RewriteTest::SynthMsgSendFunctionDecl() {
924 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
925 llvm::SmallVector<QualType, 16> ArgTys;
926 QualType argT = Context->getObjcIdType();
927 assert(!argT.isNull() && "Can't find 'id' type");
928 ArgTys.push_back(argT);
929 argT = Context->getObjcSelType();
930 assert(!argT.isNull() && "Can't find 'SEL' type");
931 ArgTys.push_back(argT);
932 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
933 &ArgTys[0], ArgTys.size(),
934 true /*isVariadic*/);
935 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
936 msgSendIdent, msgSendType,
937 FunctionDecl::Extern, false, 0);
938}
939
940// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
941void RewriteTest::SynthGetClassFunctionDecl() {
942 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
943 llvm::SmallVector<QualType, 16> ArgTys;
944 ArgTys.push_back(Context->getPointerType(
945 Context->CharTy.getQualifiedType(QualType::Const)));
946 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
947 &ArgTys[0], ArgTys.size(),
948 false /*isVariadic*/);
949 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
950 getClassIdent, getClassType,
951 FunctionDecl::Extern, false, 0);
952}
953
Steve Naroff96984642007-11-08 14:30:50 +0000954// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
955void RewriteTest::SynthCFStringFunctionDecl() {
956 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
957 llvm::SmallVector<QualType, 16> ArgTys;
958 ArgTys.push_back(Context->getPointerType(
959 Context->CharTy.getQualifiedType(QualType::Const)));
960 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
961 &ArgTys[0], ArgTys.size(),
962 false /*isVariadic*/);
963 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
964 getClassIdent, getClassType,
965 FunctionDecl::Extern, false, 0);
966}
967
Steve Naroffbeaf2992007-11-03 11:27:19 +0000968Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000969#if 1
970 // This rewrite is specific to GCC, which has builtin support for CFString.
971 if (!CFStringFunctionDecl)
972 SynthCFStringFunctionDecl();
973 // Create a call to __builtin___CFStringMakeConstantString("cstr").
974 llvm::SmallVector<Expr*, 8> StrExpr;
975 StrExpr.push_back(Exp->getString());
976 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
977 &StrExpr[0], StrExpr.size());
978 // cast to NSConstantString *
979 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
980 Rewrite.ReplaceStmt(Exp, cast);
981 delete Exp;
982 return cast;
983#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000984 assert(ConstantStringClassReference && "Can't find constant string reference");
985 llvm::SmallVector<Expr*, 4> InitExprs;
986
987 // Synthesize "(Class)&_NSConstantStringClassReference"
988 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
989 ConstantStringClassReference->getType(),
990 SourceLocation());
991 QualType expType = Context->getPointerType(ClsRef->getType());
992 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
993 expType, SourceLocation());
994 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
995 SourceLocation());
996 InitExprs.push_back(cast); // set the 'isa'.
997 InitExprs.push_back(Exp->getString()); // set "char *bytes".
998 unsigned IntSize = static_cast<unsigned>(
999 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1000 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1001 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1002 Exp->getLocStart());
1003 InitExprs.push_back(len); // set "int numBytes".
1004
1005 // struct NSConstantString
1006 QualType CFConstantStrType = Context->getCFConstantStringType();
1007 // (struct NSConstantString) { <exprs from above> }
1008 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1009 &InitExprs[0], InitExprs.size(),
1010 SourceLocation());
1011 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1012 // struct NSConstantString *
1013 expType = Context->getPointerType(StrRep->getType());
1014 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1015 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001016 // cast to NSConstantString *
1017 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001018 Rewrite.ReplaceStmt(Exp, cast);
1019 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001020 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001021#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001022}
1023
Steve Naroff934f2762007-10-24 22:48:43 +00001024Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001025 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001026 if (!MsgSendFunctionDecl)
1027 SynthMsgSendFunctionDecl();
1028 if (!GetClassFunctionDecl)
1029 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001030
1031 // Synthesize a call to objc_msgSend().
1032 llvm::SmallVector<Expr*, 8> MsgExprs;
1033 IdentifierInfo *clsName = Exp->getClassName();
1034
1035 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1036 if (clsName) { // class message.
1037 llvm::SmallVector<Expr*, 8> ClsExprs;
1038 QualType argType = Context->getPointerType(Context->CharTy);
1039 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1040 clsName->getLength(),
1041 false, argType, SourceLocation(),
1042 SourceLocation()));
1043 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1044 &ClsExprs[0], ClsExprs.size());
1045 MsgExprs.push_back(Cls);
1046 } else // instance message.
1047 MsgExprs.push_back(Exp->getReceiver());
1048
Steve Naroffbeaf2992007-11-03 11:27:19 +00001049 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001050 llvm::SmallVector<Expr*, 8> SelExprs;
1051 QualType argType = Context->getPointerType(Context->CharTy);
1052 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1053 Exp->getSelector().getName().size(),
1054 false, argType, SourceLocation(),
1055 SourceLocation()));
1056 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1057 &SelExprs[0], SelExprs.size());
1058 MsgExprs.push_back(SelExp);
1059
1060 // Now push any user supplied arguments.
1061 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1062 MsgExprs.push_back(Exp->getArg(i));
1063 // We've transferred the ownership to MsgExprs. Null out the argument in
1064 // the original expression, since we will delete it below.
1065 Exp->setArg(i, 0);
1066 }
Steve Naroffab972d32007-11-04 22:37:50 +00001067 // Generate the funky cast.
1068 CastExpr *cast;
1069 llvm::SmallVector<QualType, 8> ArgTypes;
1070 QualType returnType;
1071
1072 // Push 'id' and 'SEL', the 2 implicit arguments.
1073 ArgTypes.push_back(Context->getObjcIdType());
1074 ArgTypes.push_back(Context->getObjcSelType());
1075 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1076 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001077 for (int i = 0; i < mDecl->getNumParams(); i++) {
1078 QualType t = mDecl->getParamDecl(i)->getType();
1079 if (t == Context->getObjcClassType())
1080 t = Context->getObjcIdType(); // Convert "Class"->"id"
1081 ArgTypes.push_back(t);
1082 }
Steve Naroffab972d32007-11-04 22:37:50 +00001083 returnType = mDecl->getResultType();
1084 } else {
1085 returnType = Context->getObjcIdType();
1086 }
1087 // Get the type, we will need to reference it in a couple spots.
1088 QualType msgSendType = MsgSendFunctionDecl->getType();
1089
1090 // Create a reference to the objc_msgSend() declaration.
1091 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1092
1093 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1094 // If we don't do this cast, we get the following bizarre warning/note:
1095 // xx.m:13: warning: function called through a non-compatible type
1096 // xx.m:13: note: if this code is reached, the program will abort
1097 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1098 SourceLocation());
1099
1100 // Now do the "normal" pointer to function cast.
1101 QualType castType = Context->getFunctionType(returnType,
1102 &ArgTypes[0], ArgTypes.size(),
1103 false/*FIXME:variadic*/);
1104 castType = Context->getPointerType(castType);
1105 cast = new CastExpr(castType, cast, SourceLocation());
1106
1107 // Don't forget the parens to enforce the proper binding.
1108 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1109
1110 const FunctionType *FT = msgSendType->getAsFunctionType();
1111 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1112 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001113 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001114 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001115
Chris Lattnere64b7772007-10-24 16:57:36 +00001116 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001117 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001118}
1119
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001120/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1121/// an objective-c class with ivars.
1122void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1123 std::string &Result) {
1124 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1125 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001126 // Do not synthesize more than once.
1127 if (ObjcSynthesizedStructs.count(CDecl))
1128 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001129 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1130 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1131 // Do it for the root
1132 SynthesizeObjcInternalStruct(RCDecl, Result);
1133 }
1134
Steve Naroff03300712007-11-12 13:56:41 +00001135 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001136 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001137 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001138 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1139 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001140 // FIXME: This has potential of causing problem. If
1141 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001142 Result += "\nstruct ";
1143 Result += CDecl->getName();
1144
1145 SourceLocation LocStart = CDecl->getLocStart();
1146 SourceLocation LocEnd = CDecl->getLocEnd();
1147
1148 const char *startBuf = SM->getCharacterData(LocStart);
1149 const char *endBuf = SM->getCharacterData(LocEnd);
1150
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001151 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001152 const char *cursor = strchr(startBuf, '{');
1153 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001154 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001155
1156 // rewrite the original header *without* disturbing the '{'
1157 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1158 Result.c_str(), Result.size());
1159 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1160 Result = "\n struct ";
1161 Result += RCDecl->getName();
1162 Result += " _";
1163 Result += RCDecl->getName();
1164 Result += ";\n";
1165
1166 // insert the super class structure definition.
1167 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1168 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1169 }
1170 cursor++; // past '{'
1171
1172 // Now comment out any visibility specifiers.
1173 while (cursor < endBuf) {
1174 if (*cursor == '@') {
1175 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001176 // Skip whitespace.
1177 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1178 /*scan*/;
1179
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001180 // FIXME: presence of @public, etc. inside comment results in
1181 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001182 if (!strncmp(cursor, "public", strlen("public")) ||
1183 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001184 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001185 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001186 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001187 // FIXME: If there are cases where '<' is used in ivar declaration part
1188 // of user code, then scan the ivar list and use needToScanForQualifiers
1189 // for type checking.
1190 else if (*cursor == '<') {
1191 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1192 Rewrite.InsertText(atLoc, "/* ", 3);
1193 cursor = strchr(cursor, '>');
1194 cursor++;
1195 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1196 Rewrite.InsertText(atLoc, " */", 3);
1197 }
Steve Narofffea763e82007-11-14 19:25:57 +00001198 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001199 }
Steve Narofffea763e82007-11-14 19:25:57 +00001200 // Don't forget to add a ';'!!
1201 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1202 } else { // we don't have any instance variables - insert super struct.
1203 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1204 Result += " {\n struct ";
1205 Result += RCDecl->getName();
1206 Result += " _";
1207 Result += RCDecl->getName();
1208 Result += ";\n};\n";
1209 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1210 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001211 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001212 // Mark this struct as having been generated.
1213 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001214 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001215}
1216
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001217// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1218/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001219void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001220 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001221 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001222 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001223 const char *ClassName,
1224 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001225 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001226 if (NumMethods > 0 && !objc_impl_method) {
1227 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001228 SEL _cmd;
1229 char *method_types;
1230 void *_imp;
1231 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001232 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001233 Result += "\nstruct _objc_method {\n";
1234 Result += "\tSEL _cmd;\n";
1235 Result += "\tchar *method_types;\n";
1236 Result += "\tvoid *_imp;\n";
1237 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001238
1239 /* struct _objc_method_list {
1240 struct _objc_method_list *next_method;
1241 int method_count;
1242 struct _objc_method method_list[];
1243 }
1244 */
1245 Result += "\nstruct _objc_method_list {\n";
1246 Result += "\tstruct _objc_method_list *next_method;\n";
1247 Result += "\tint method_count;\n";
1248 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001249 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001250 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001251 // Build _objc_method_list for class's methods if needed
1252 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001253 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001254 Result += prefix;
1255 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1256 Result += "_METHODS_";
1257 Result += ClassName;
1258 Result += " __attribute__ ((section (\"__OBJC, __";
1259 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001260 Result += "_meth\")))= ";
1261 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1262
1263 Result += "\t,{{(SEL)\"";
1264 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001265 std::string MethodTypeString;
1266 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1267 Result += "\", \"";
1268 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001269 Result += "\", ";
1270 Result += MethodInternalNames[Methods[0]];
1271 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001272 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001273 Result += "\t ,{(SEL)\"";
1274 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001275 std::string MethodTypeString;
1276 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1277 Result += "\", \"";
1278 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001279 Result += "\", ";
1280 Result += MethodInternalNames[Methods[i]];
1281 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001282 }
1283 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001284 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001285}
1286
1287/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1288void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1289 int NumProtocols,
1290 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001291 const char *ClassName,
1292 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001293 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001294 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001295 for (int i = 0; i < NumProtocols; i++) {
1296 ObjcProtocolDecl *PDecl = Protocols[i];
1297 // Output struct protocol_methods holder of method selector and type.
1298 if (!objc_protocol_methods &&
1299 (PDecl->getNumInstanceMethods() > 0
1300 || PDecl->getNumClassMethods() > 0)) {
1301 /* struct protocol_methods {
1302 SEL _cmd;
1303 char *method_types;
1304 }
1305 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001306 Result += "\nstruct protocol_methods {\n";
1307 Result += "\tSEL _cmd;\n";
1308 Result += "\tchar *method_types;\n";
1309 Result += "};\n";
1310
1311 /* struct _objc_protocol_method_list {
1312 int protocol_method_count;
1313 struct protocol_methods protocols[];
1314 }
1315 */
1316 Result += "\nstruct _objc_protocol_method_list {\n";
1317 Result += "\tint protocol_method_count;\n";
1318 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001319 objc_protocol_methods = true;
1320 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001321
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001322 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001323 int NumMethods = PDecl->getNumInstanceMethods();
1324 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001325 Result += "\nstatic struct _objc_protocol_method_list "
1326 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1327 Result += PDecl->getName();
1328 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1329 "{\n\t" + utostr(NumMethods) + "\n";
1330
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001331 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001332 Result += "\t,{{(SEL)\"";
1333 Result += Methods[0]->getSelector().getName().c_str();
1334 Result += "\", \"\"}\n";
1335
1336 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001337 Result += "\t ,{(SEL)\"";
1338 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001339 std::string MethodTypeString;
1340 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1341 Result += "\", \"";
1342 Result += MethodTypeString;
1343 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001344 }
1345 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001346 }
1347
1348 // Output class methods declared in this protocol.
1349 NumMethods = PDecl->getNumClassMethods();
1350 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001351 Result += "\nstatic struct _objc_protocol_method_list "
1352 "_OBJC_PROTOCOL_CLASS_METHODS_";
1353 Result += PDecl->getName();
1354 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1355 "{\n\t";
1356 Result += utostr(NumMethods);
1357 Result += "\n";
1358
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001359 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001360 Result += "\t,{{(SEL)\"";
1361 Result += Methods[0]->getSelector().getName().c_str();
1362 Result += "\", \"\"}\n";
1363
1364 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001365 Result += "\t ,{(SEL)\"";
1366 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001367 std::string MethodTypeString;
1368 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1369 Result += "\", \"";
1370 Result += MethodTypeString;
1371 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001372 }
1373 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001374 }
1375 // Output:
1376 /* struct _objc_protocol {
1377 // Objective-C 1.0 extensions
1378 struct _objc_protocol_extension *isa;
1379 char *protocol_name;
1380 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001381 struct _objc_protocol_method_list *instance_methods;
1382 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001383 };
1384 */
1385 static bool objc_protocol = false;
1386 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001387 Result += "\nstruct _objc_protocol {\n";
1388 Result += "\tstruct _objc_protocol_extension *isa;\n";
1389 Result += "\tchar *protocol_name;\n";
1390 Result += "\tstruct _objc_protocol **protocol_list;\n";
1391 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1392 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1393 Result += "};\n";
1394
1395 /* struct _objc_protocol_list {
1396 struct _objc_protocol_list *next;
1397 int protocol_count;
1398 struct _objc_protocol *class_protocols[];
1399 }
1400 */
1401 Result += "\nstruct _objc_protocol_list {\n";
1402 Result += "\tstruct _objc_protocol_list *next;\n";
1403 Result += "\tint protocol_count;\n";
1404 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1405 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001406 objc_protocol = true;
1407 }
1408
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001409 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1410 Result += PDecl->getName();
1411 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1412 "{\n\t0, \"";
1413 Result += PDecl->getName();
1414 Result += "\", 0, ";
1415 if (PDecl->getInstanceMethods() > 0) {
1416 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1417 Result += PDecl->getName();
1418 Result += ", ";
1419 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001420 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001421 Result += "0, ";
1422 if (PDecl->getClassMethods() > 0) {
1423 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1424 Result += PDecl->getName();
1425 Result += "\n";
1426 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001427 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001428 Result += "0\n";
1429 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001430 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001431 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001432 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1433 Result += prefix;
1434 Result += "_PROTOCOLS_";
1435 Result += ClassName;
1436 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1437 "{\n\t0, ";
1438 Result += utostr(NumProtocols);
1439 Result += "\n";
1440
1441 Result += "\t,{&_OBJC_PROTOCOL_";
1442 Result += Protocols[0]->getName();
1443 Result += " \n";
1444
1445 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001446 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001447 Result += "\t ,&_OBJC_PROTOCOL_";
1448 Result += PDecl->getName();
1449 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001450 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001451 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001452 }
1453}
1454
1455/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1456/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001457void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1458 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001459 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1460 // Find category declaration for this implementation.
1461 ObjcCategoryDecl *CDecl;
1462 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1463 CDecl = CDecl->getNextClassCategory())
1464 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1465 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001466
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001467 char *FullCategoryName = (char*)alloca(
1468 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1469 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1470
1471 // Build _objc_method_list for class's instance methods if needed
1472 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1473 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001474 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001475 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001476
1477 // Build _objc_method_list for class's class methods if needed
1478 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1479 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001480 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001481 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001482
1483 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001484 // Null CDecl is case of a category implementation with no category interface
1485 if (CDecl)
1486 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1487 CDecl->getNumReferencedProtocols(),
1488 "CATEGORY",
1489 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001490
1491 /* struct _objc_category {
1492 char *category_name;
1493 char *class_name;
1494 struct _objc_method_list *instance_methods;
1495 struct _objc_method_list *class_methods;
1496 struct _objc_protocol_list *protocols;
1497 // Objective-C 1.0 extensions
1498 uint32_t size; // sizeof (struct _objc_category)
1499 struct _objc_property_list *instance_properties; // category's own
1500 // @property decl.
1501 };
1502 */
1503
1504 static bool objc_category = false;
1505 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001506 Result += "\nstruct _objc_category {\n";
1507 Result += "\tchar *category_name;\n";
1508 Result += "\tchar *class_name;\n";
1509 Result += "\tstruct _objc_method_list *instance_methods;\n";
1510 Result += "\tstruct _objc_method_list *class_methods;\n";
1511 Result += "\tstruct _objc_protocol_list *protocols;\n";
1512 Result += "\tunsigned int size;\n";
1513 Result += "\tstruct _objc_property_list *instance_properties;\n";
1514 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001515 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001516 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001517 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1518 Result += FullCategoryName;
1519 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1520 Result += IDecl->getName();
1521 Result += "\"\n\t, \"";
1522 Result += ClassDecl->getName();
1523 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001524
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001525 if (IDecl->getNumInstanceMethods() > 0) {
1526 Result += "\t, (struct _objc_method_list *)"
1527 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1528 Result += FullCategoryName;
1529 Result += "\n";
1530 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001531 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001532 Result += "\t, 0\n";
1533 if (IDecl->getNumClassMethods() > 0) {
1534 Result += "\t, (struct _objc_method_list *)"
1535 "&_OBJC_CATEGORY_CLASS_METHODS_";
1536 Result += FullCategoryName;
1537 Result += "\n";
1538 }
1539 else
1540 Result += "\t, 0\n";
1541
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001542 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001543 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1544 Result += FullCategoryName;
1545 Result += "\n";
1546 }
1547 else
1548 Result += "\t, 0\n";
1549 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001550}
1551
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001552/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1553/// ivar offset.
1554void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1555 ObjcIvarDecl *ivar,
1556 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001557 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001558 Result += IDecl->getName();
1559 Result += ", ";
1560 Result += ivar->getName();
1561 Result += ")";
1562}
1563
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001564//===----------------------------------------------------------------------===//
1565// Meta Data Emission
1566//===----------------------------------------------------------------------===//
1567
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001568void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1569 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001570 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1571
1572 // Build _objc_ivar_list metadata for classes ivars if needed
1573 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1574 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001575 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001576
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001577 SynthesizeObjcInternalStruct(CDecl, Result);
1578
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001579 if (NumIvars > 0) {
1580 static bool objc_ivar = false;
1581 if (!objc_ivar) {
1582 /* struct _objc_ivar {
1583 char *ivar_name;
1584 char *ivar_type;
1585 int ivar_offset;
1586 };
1587 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001588 Result += "\nstruct _objc_ivar {\n";
1589 Result += "\tchar *ivar_name;\n";
1590 Result += "\tchar *ivar_type;\n";
1591 Result += "\tint ivar_offset;\n";
1592 Result += "};\n";
1593
1594 /* struct _objc_ivar_list {
1595 int ivar_count;
1596 struct _objc_ivar ivar_list[];
1597 };
1598 */
1599 Result += "\nstruct _objc_ivar_list {\n";
1600 Result += "\tint ivar_count;\n";
1601 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001602 objc_ivar = true;
1603 }
1604
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001605 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1606 Result += IDecl->getName();
1607 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1608 "{\n\t";
1609 Result += utostr(NumIvars);
1610 Result += "\n";
1611
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001612 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1613 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001614 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001615 Result += "\t,{{\"";
1616 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001617 Result += "\", \"";
1618 std::string StrEncoding;
1619 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1620 Result += StrEncoding;
1621 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001622 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1623 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001624 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001625 Result += "\t ,{\"";
1626 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001627 Result += "\", \"";
1628 std::string StrEncoding;
1629 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1630 Result += StrEncoding;
1631 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001632 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1633 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001634 }
1635
1636 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001637 }
1638
1639 // Build _objc_method_list for class's instance methods if needed
1640 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1641 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001642 true,
1643 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001644
1645 // Build _objc_method_list for class's class methods if needed
1646 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001647 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001648 false,
1649 "", IDecl->getName(), Result);
1650
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001651 // Protocols referenced in class declaration?
1652 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1653 CDecl->getNumIntfRefProtocols(),
1654 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001655 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001656
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001657
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001658 // Declaration of class/meta-class metadata
1659 /* struct _objc_class {
1660 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001661 const char *super_class_name;
1662 char *name;
1663 long version;
1664 long info;
1665 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001666 struct _objc_ivar_list *ivars;
1667 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001668 struct objc_cache *cache;
1669 struct objc_protocol_list *protocols;
1670 const char *ivar_layout;
1671 struct _objc_class_ext *ext;
1672 };
1673 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001674 static bool objc_class = false;
1675 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001676 Result += "\nstruct _objc_class {\n";
1677 Result += "\tstruct _objc_class *isa;\n";
1678 Result += "\tconst char *super_class_name;\n";
1679 Result += "\tchar *name;\n";
1680 Result += "\tlong version;\n";
1681 Result += "\tlong info;\n";
1682 Result += "\tlong instance_size;\n";
1683 Result += "\tstruct _objc_ivar_list *ivars;\n";
1684 Result += "\tstruct _objc_method_list *methods;\n";
1685 Result += "\tstruct objc_cache *cache;\n";
1686 Result += "\tstruct _objc_protocol_list *protocols;\n";
1687 Result += "\tconst char *ivar_layout;\n";
1688 Result += "\tstruct _objc_class_ext *ext;\n";
1689 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001690 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001691 }
1692
1693 // Meta-class metadata generation.
1694 ObjcInterfaceDecl *RootClass = 0;
1695 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1696 while (SuperClass) {
1697 RootClass = SuperClass;
1698 SuperClass = SuperClass->getSuperClass();
1699 }
1700 SuperClass = CDecl->getSuperClass();
1701
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001702 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1703 Result += CDecl->getName();
1704 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1705 "{\n\t(struct _objc_class *)\"";
1706 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1707 Result += "\"";
1708
1709 if (SuperClass) {
1710 Result += ", \"";
1711 Result += SuperClass->getName();
1712 Result += "\", \"";
1713 Result += CDecl->getName();
1714 Result += "\"";
1715 }
1716 else {
1717 Result += ", 0, \"";
1718 Result += CDecl->getName();
1719 Result += "\"";
1720 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001721 // TODO: 'ivars' field for root class is currently set to 0.
1722 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001723 Result += ", 0,2, sizeof(struct _objc_class), 0";
1724 if (CDecl->getNumClassMethods() > 0) {
1725 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1726 Result += CDecl->getName();
1727 Result += "\n";
1728 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001729 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001730 Result += ", 0\n";
1731 if (CDecl->getNumIntfRefProtocols() > 0) {
1732 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1733 Result += CDecl->getName();
1734 Result += ",0,0\n";
1735 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001736 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001737 Result += "\t,0,0,0,0\n";
1738 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001739
1740 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001741 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1742 Result += CDecl->getName();
1743 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1744 "{\n\t&_OBJC_METACLASS_";
1745 Result += CDecl->getName();
1746 if (SuperClass) {
1747 Result += ", \"";
1748 Result += SuperClass->getName();
1749 Result += "\", \"";
1750 Result += CDecl->getName();
1751 Result += "\"";
1752 }
1753 else {
1754 Result += ", 0, \"";
1755 Result += CDecl->getName();
1756 Result += "\"";
1757 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001758 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001759 Result += ", 0,1";
1760 if (!ObjcSynthesizedStructs.count(CDecl))
1761 Result += ",0";
1762 else {
1763 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001764 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001765 Result += CDecl->getName();
1766 Result += ")";
1767 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001768 if (NumIvars > 0) {
1769 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1770 Result += CDecl->getName();
1771 Result += "\n\t";
1772 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001773 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001774 Result += ",0";
1775 if (IDecl->getNumInstanceMethods() > 0) {
1776 Result += ", &_OBJC_INSTANCE_METHODS_";
1777 Result += CDecl->getName();
1778 Result += ", 0\n\t";
1779 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001780 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001781 Result += ",0,0";
1782 if (CDecl->getNumIntfRefProtocols() > 0) {
1783 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1784 Result += CDecl->getName();
1785 Result += ", 0,0\n";
1786 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001787 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001788 Result += ",0,0,0\n";
1789 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001790}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001791
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001792/// RewriteImplementations - This routine rewrites all method implementations
1793/// and emits meta-data.
1794
1795void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001796 int ClsDefCount = ClassImplementation.size();
1797 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001798
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001799 if (ClsDefCount == 0 && CatDefCount == 0)
1800 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001801 // Rewrite implemented methods
1802 for (int i = 0; i < ClsDefCount; i++)
1803 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001804
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001805 for (int i = 0; i < CatDefCount; i++)
1806 RewriteImplementationDecl(CategoryImplementation[i]);
1807
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001808 // This is needed for use of offsetof
1809 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001810
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001811 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001812 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001813 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001814
1815 // For each implemented category, write out all its meta data.
1816 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001817 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001818
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001819 // Write objc_symtab metadata
1820 /*
1821 struct _objc_symtab
1822 {
1823 long sel_ref_cnt;
1824 SEL *refs;
1825 short cls_def_cnt;
1826 short cat_def_cnt;
1827 void *defs[cls_def_cnt + cat_def_cnt];
1828 };
1829 */
1830
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001831 Result += "\nstruct _objc_symtab {\n";
1832 Result += "\tlong sel_ref_cnt;\n";
1833 Result += "\tSEL *refs;\n";
1834 Result += "\tshort cls_def_cnt;\n";
1835 Result += "\tshort cat_def_cnt;\n";
1836 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1837 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001838
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001839 Result += "static struct _objc_symtab "
1840 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1841 Result += "\t0, 0, " + utostr(ClsDefCount)
1842 + ", " + utostr(CatDefCount) + "\n";
1843 for (int i = 0; i < ClsDefCount; i++) {
1844 Result += "\t,&_OBJC_CLASS_";
1845 Result += ClassImplementation[i]->getName();
1846 Result += "\n";
1847 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001848
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001849 for (int i = 0; i < CatDefCount; i++) {
1850 Result += "\t,&_OBJC_CATEGORY_";
1851 Result += CategoryImplementation[i]->getClassInterface()->getName();
1852 Result += "_";
1853 Result += CategoryImplementation[i]->getName();
1854 Result += "\n";
1855 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001856
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001857 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001858
1859 // Write objc_module metadata
1860
1861 /*
1862 struct _objc_module {
1863 long version;
1864 long size;
1865 const char *name;
1866 struct _objc_symtab *symtab;
1867 }
1868 */
1869
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001870 Result += "\nstruct _objc_module {\n";
1871 Result += "\tlong version;\n";
1872 Result += "\tlong size;\n";
1873 Result += "\tconst char *name;\n";
1874 Result += "\tstruct _objc_symtab *symtab;\n";
1875 Result += "};\n\n";
1876 Result += "static struct _objc_module "
1877 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001878 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1879 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001880 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001881
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001882}
Chris Lattner311ff022007-10-16 22:36:42 +00001883