blob: d953e08581eef8b879bcd26d4da1cc8c5762ada9 [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 Naroff8749be52007-10-31 22:11:35 +0000316 if (ObjcForwardDecls.count(ForwardDecl))
317 continue;
Steve Naroff32174822007-11-09 12:50:28 +0000318 typedefString += "#ifndef _REWRITER_typedef_";
319 typedefString += ForwardDecl->getName();
320 typedefString += "\n";
321 typedefString += "#define _REWRITER_typedef_";
322 typedefString += ForwardDecl->getName();
323 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000324 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000325 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000326 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000327 // Mark this typedef as having been generated.
328 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000329 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000330 }
331
332 // Replace the @class with typedefs corresponding to the classes.
333 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
334 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000335}
336
Steve Naroff71c0a952007-11-13 23:01:27 +0000337void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000338 for (int i = 0; i < nMethods; i++) {
339 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000340 SourceLocation LocStart = Method->getLocStart();
341 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000342
Steve Naroff1d098f62007-11-14 14:34:23 +0000343 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
344 Rewrite.InsertText(LocStart, "/* ", 3);
345 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
346 } else {
347 Rewrite.InsertText(LocStart, "// ", 3);
348 }
Steve Naroff423cb562007-10-30 13:30:57 +0000349 }
350}
351
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000352void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
353{
354 for (int i = 0; i < nProperties; i++) {
355 ObjcPropertyDecl *Property = Properties[i];
356 SourceLocation Loc = Property->getLocation();
357
358 Rewrite.ReplaceText(Loc, 0, "// ", 3);
359
360 // FIXME: handle properties that are declared across multiple lines.
361 }
362}
363
Steve Naroff423cb562007-10-30 13:30:57 +0000364void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
365 SourceLocation LocStart = CatDecl->getLocStart();
366
367 // FIXME: handle category headers that are declared across multiple lines.
368 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
369
Steve Naroff71c0a952007-11-13 23:01:27 +0000370 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
371 CatDecl->getInstanceMethods());
372 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
373 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000374 // Lastly, comment out the @end.
375 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
376}
377
Steve Naroff752d6ef2007-10-30 16:42:30 +0000378void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000379 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000380
Steve Naroff752d6ef2007-10-30 16:42:30 +0000381 SourceLocation LocStart = PDecl->getLocStart();
382
383 // FIXME: handle protocol headers that are declared across multiple lines.
384 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
385
Steve Naroff71c0a952007-11-13 23:01:27 +0000386 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
387 PDecl->getInstanceMethods());
388 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
389 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000390 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000391 SourceLocation LocEnd = PDecl->getAtEndLoc();
392 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000393
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000394 // Must comment out @optional/@required
395 const char *startBuf = SM->getCharacterData(LocStart);
396 const char *endBuf = SM->getCharacterData(LocEnd);
397 for (const char *p = startBuf; p < endBuf; p++) {
398 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
399 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000400 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000401 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
402 CommentedOptional.c_str(), CommentedOptional.size());
403
404 }
405 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
406 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000407 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000408 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
409 CommentedRequired.c_str(), CommentedRequired.size());
410
411 }
412 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000413}
414
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000415void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
416 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000417 if (LocStart.isInvalid())
418 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000419 // FIXME: handle forward protocol that are declared across multiple lines.
420 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
421}
422
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000423void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
424 std::string &ResultStr) {
425 ResultStr += "\nstatic ";
426 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000427 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000428
429 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000430 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000431
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000432 if (OMD->isInstance())
433 NameStr += "_I_";
434 else
435 NameStr += "_C_";
436
437 NameStr += OMD->getClassInterface()->getName();
438 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000439
440 NamedDecl *MethodContext = OMD->getMethodContext();
441 if (ObjcCategoryImplDecl *CID =
442 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000443 NameStr += CID->getName();
444 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000445 }
446 // Append selector names, replacing ':' with '_'
447 const char *selName = OMD->getSelector().getName().c_str();
448 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000449 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000450 else {
451 std::string selString = OMD->getSelector().getName();
452 int len = selString.size();
453 for (int i = 0; i < len; i++)
454 if (selString[i] == ':')
455 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000456 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000457 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000458 // Remember this name for metadata emission
459 MethodInternalNames[OMD] = NameStr;
460 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000461
462 // Rewrite arguments
463 ResultStr += "(";
464
465 // invisible arguments
466 if (OMD->isInstance()) {
467 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
468 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000469 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
470 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000471 ResultStr += selfTy.getAsString();
472 }
473 else
474 ResultStr += Context->getObjcIdType().getAsString();
475
476 ResultStr += " self, ";
477 ResultStr += Context->getObjcSelType().getAsString();
478 ResultStr += " _cmd";
479
480 // Method arguments.
481 for (int i = 0; i < OMD->getNumParams(); i++) {
482 ParmVarDecl *PDecl = OMD->getParamDecl(i);
483 ResultStr += ", ";
484 ResultStr += PDecl->getType().getAsString();
485 ResultStr += " ";
486 ResultStr += PDecl->getName();
487 }
488 ResultStr += ")";
489
490}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000491void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
492 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
493 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000494
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000495 if (IMD)
496 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
497 else
498 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000499
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000500 int numMethods = IMD ? IMD->getNumInstanceMethods()
501 : CID->getNumInstanceMethods();
502
503 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000504 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000505 ObjcMethodDecl *OMD;
506 if (IMD)
507 OMD = IMD->getInstanceMethods()[i];
508 else
509 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000510 RewriteObjcMethodDecl(OMD, ResultStr);
511 SourceLocation LocStart = OMD->getLocStart();
512 SourceLocation LocEnd = OMD->getBody()->getLocStart();
513
514 const char *startBuf = SM->getCharacterData(LocStart);
515 const char *endBuf = SM->getCharacterData(LocEnd);
516 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
517 ResultStr.c_str(), ResultStr.size());
518 }
519
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000520 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
521 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000522 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000523 ObjcMethodDecl *OMD;
524 if (IMD)
525 OMD = IMD->getClassMethods()[i];
526 else
527 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000528 RewriteObjcMethodDecl(OMD, ResultStr);
529 SourceLocation LocStart = OMD->getLocStart();
530 SourceLocation LocEnd = OMD->getBody()->getLocStart();
531
532 const char *startBuf = SM->getCharacterData(LocStart);
533 const char *endBuf = SM->getCharacterData(LocEnd);
534 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
535 ResultStr.c_str(), ResultStr.size());
536 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000537 if (IMD)
538 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
539 else
540 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000541}
542
Steve Naroffbef11852007-10-26 20:53:56 +0000543void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000544 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000545 if (!ObjcForwardDecls.count(ClassDecl)) {
546 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000547 ResultStr += "#ifndef _REWRITER_typedef_";
548 ResultStr += ClassDecl->getName();
549 ResultStr += "\n";
550 ResultStr += "#define _REWRITER_typedef_";
551 ResultStr += ClassDecl->getName();
552 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000553 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000554 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000555 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000556
557 // Mark this typedef as having been generated.
558 ObjcForwardDecls.insert(ClassDecl);
559 }
Steve Narofff908a872007-10-30 02:23:23 +0000560 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
561
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000562 RewriteProperties(ClassDecl->getNumPropertyDecl(),
563 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000564 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
565 ClassDecl->getInstanceMethods());
566 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
567 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000568
Steve Naroff2feac5e2007-10-30 03:43:13 +0000569 // Lastly, comment out the @end.
570 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000571}
572
Chris Lattnerf04da132007-10-24 17:06:59 +0000573//===----------------------------------------------------------------------===//
574// Function Body / Expression rewriting
575//===----------------------------------------------------------------------===//
576
Steve Narofff3473a72007-11-09 15:20:18 +0000577Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000578 // Otherwise, just rewrite all children.
579 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
580 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000581 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000582 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000583 if (newStmt)
584 *CI = newStmt;
585 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000586
587 // Handle specific things.
588 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
589 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000590
591 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
592 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000593
594 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
595 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000596
Steve Naroff934f2762007-10-24 22:48:43 +0000597 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
598 // Before we rewrite it, put the original message expression in a comment.
599 SourceLocation startLoc = MessExpr->getLocStart();
600 SourceLocation endLoc = MessExpr->getLocEnd();
601
602 const char *startBuf = SM->getCharacterData(startLoc);
603 const char *endBuf = SM->getCharacterData(endLoc);
604
605 std::string messString;
606 messString += "// ";
607 messString.append(startBuf, endBuf-startBuf+1);
608 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000609
Steve Naroff934f2762007-10-24 22:48:43 +0000610 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
611 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
612 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000613 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000614 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000615 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000616
617 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
618 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000619
620 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
621 return RewriteObjcThrowStmt(StmtThrow);
622
Chris Lattnere64b7772007-10-24 16:57:36 +0000623 // Return this stmt unmodified.
624 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000625}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000626
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000627Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000628 // Get the start location and compute the semi location.
629 SourceLocation startLoc = S->getLocStart();
630 const char *startBuf = SM->getCharacterData(startLoc);
631
632 assert((*startBuf == '@') && "bogus @try location");
633
634 std::string buf;
635 // declare a new scope with two variables, _stack and _rethrow.
636 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
637 buf += "int buf[18/*32-bit i386*/];\n";
638 buf += "char *pointers[4];} _stack;\n";
639 buf += "id volatile _rethrow = 0;\n";
640 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000641 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000642
643 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
644
645 startLoc = S->getTryBody()->getLocEnd();
646 startBuf = SM->getCharacterData(startLoc);
647
648 assert((*startBuf == '}') && "bogus @try block");
649
650 SourceLocation lastCurlyLoc = startLoc;
651
652 startLoc = startLoc.getFileLocWithOffset(1);
653 buf = " /* @catch begin */ else {\n";
654 buf += " id _caught = objc_exception_extract(&_stack);\n";
655 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000656 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000657 buf += " _rethrow = objc_exception_extract(&_stack);\n";
658 buf += " else { /* @catch continue */";
659
Chris Lattner28d1fe82007-11-08 04:41:51 +0000660 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000661
662 bool sawIdTypedCatch = false;
663 Stmt *lastCatchBody = 0;
664 ObjcAtCatchStmt *catchList = S->getCatchStmts();
665 while (catchList) {
666 Stmt *catchStmt = catchList->getCatchParamStmt();
667
668 if (catchList == S->getCatchStmts())
669 buf = "if ("; // we are generating code for the first catch clause
670 else
671 buf = "else if (";
672 startLoc = catchList->getLocStart();
673 startBuf = SM->getCharacterData(startLoc);
674
675 assert((*startBuf == '@') && "bogus @catch location");
676
677 const char *lParenLoc = strchr(startBuf, '(');
678
679 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
680 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
681 if (t == Context->getObjcIdType()) {
682 buf += "1) { ";
683 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
684 buf.c_str(), buf.size());
685 sawIdTypedCatch = true;
686 } else if (const PointerType *pType = t->getAsPointerType()) {
687 ObjcInterfaceType *cls; // Should be a pointer to a class.
688
689 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
690 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000691 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000692 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000693 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000694 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
695 buf.c_str(), buf.size());
696 }
697 }
698 // Now rewrite the body...
699 lastCatchBody = catchList->getCatchBody();
700 SourceLocation rParenLoc = catchList->getRParenLoc();
701 SourceLocation bodyLoc = lastCatchBody->getLocStart();
702 const char *bodyBuf = SM->getCharacterData(bodyLoc);
703 const char *rParenBuf = SM->getCharacterData(rParenLoc);
704 assert((*rParenBuf == ')') && "bogus @catch paren location");
705 assert((*bodyBuf == '{') && "bogus @catch body location");
706
707 buf = " = _caught;";
708 // Here we replace ") {" with "= _caught;" (which initializes and
709 // declares the @catch parameter).
710 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
711 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000712 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000713 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000714 }
Steve Naroff75730982007-11-07 04:08:17 +0000715 catchList = catchList->getNextCatchStmt();
716 }
717 // Complete the catch list...
718 if (lastCatchBody) {
719 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
720 const char *bodyBuf = SM->getCharacterData(bodyLoc);
721 assert((*bodyBuf == '}') && "bogus @catch body location");
722 bodyLoc = bodyLoc.getFileLocWithOffset(1);
723 buf = " } } /* @catch end */\n";
724
Chris Lattner28d1fe82007-11-08 04:41:51 +0000725 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000726
727 // Set lastCurlyLoc
728 lastCurlyLoc = lastCatchBody->getLocEnd();
729 }
730 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
731 startLoc = finalStmt->getLocStart();
732 startBuf = SM->getCharacterData(startLoc);
733 assert((*startBuf == '@') && "bogus @finally start");
734
735 buf = "/* @finally */";
736 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
737
738 Stmt *body = finalStmt->getFinallyBody();
739 SourceLocation startLoc = body->getLocStart();
740 SourceLocation endLoc = body->getLocEnd();
741 const char *startBuf = SM->getCharacterData(startLoc);
742 const char *endBuf = SM->getCharacterData(endLoc);
743 assert((*startBuf == '{') && "bogus @finally body location");
744 assert((*endBuf == '}') && "bogus @finally body location");
745
746 startLoc = startLoc.getFileLocWithOffset(1);
747 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000748 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000749 endLoc = endLoc.getFileLocWithOffset(-1);
750 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000751 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000752
753 // Set lastCurlyLoc
754 lastCurlyLoc = body->getLocEnd();
755 }
756 // Now emit the final closing curly brace...
757 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
758 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000759 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000760 return 0;
761}
762
763Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
764 return 0;
765}
766
767Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
768 return 0;
769}
770
Steve Naroff2bd03922007-11-07 15:32:26 +0000771// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
772// the throw expression is typically a message expression that's already
773// been rewritten! (which implies the SourceLocation's are invalid).
774Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
775 // Get the start location and compute the semi location.
776 SourceLocation startLoc = S->getLocStart();
777 const char *startBuf = SM->getCharacterData(startLoc);
778
779 assert((*startBuf == '@') && "bogus @throw location");
780
781 std::string buf;
782 /* void objc_exception_throw(id) __attribute__((noreturn)); */
783 buf = "objc_exception_throw(";
784 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
785 const char *semiBuf = strchr(startBuf, ';');
786 assert((*semiBuf == ';') && "@throw: can't find ';'");
787 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
788 buf = ");";
789 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
790 return 0;
791}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000792
Chris Lattnere64b7772007-10-24 16:57:36 +0000793Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000794 // Create a new string expression.
795 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000796 std::string StrEncoding;
797 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
798 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
799 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000800 SourceLocation(), SourceLocation());
801 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000802 delete Exp;
803 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000804}
805
Steve Naroffb42f8412007-11-05 14:50:49 +0000806Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
807 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
808 // Create a call to sel_registerName("selName").
809 llvm::SmallVector<Expr*, 8> SelExprs;
810 QualType argType = Context->getPointerType(Context->CharTy);
811 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
812 Exp->getSelector().getName().size(),
813 false, argType, SourceLocation(),
814 SourceLocation()));
815 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
816 &SelExprs[0], SelExprs.size());
817 Rewrite.ReplaceStmt(Exp, SelExp);
818 delete Exp;
819 return SelExp;
820}
821
Steve Naroff934f2762007-10-24 22:48:43 +0000822CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
823 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000824 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000825 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000826
827 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000828 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000829
830 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000831 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000832 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
833
834 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000835
Steve Naroff934f2762007-10-24 22:48:43 +0000836 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
837}
838
Steve Naroffd5255f52007-11-01 13:24:47 +0000839static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
840 const char *&startRef, const char *&endRef) {
841 while (startBuf < endBuf) {
842 if (*startBuf == '<')
843 startRef = startBuf; // mark the start.
844 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000845 if (startRef && *startRef == '<') {
846 endRef = startBuf; // mark the end.
847 return true;
848 }
849 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000850 }
851 startBuf++;
852 }
853 return false;
854}
855
856bool RewriteTest::needToScanForQualifiers(QualType T) {
857 // FIXME: we don't currently represent "id <Protocol>" in the type system.
858 if (T == Context->getObjcIdType())
859 return true;
860
861 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000862 Type *pointeeType = pType->getPointeeType().getTypePtr();
863 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
864 return true; // we have "Class <Protocol> *".
865 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000866 return false;
867}
868
869void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
870 const FunctionTypeProto *proto, FunctionDecl *FD) {
871
872 if (needToScanForQualifiers(proto->getResultType())) {
873 // Since types are unique, we need to scan the buffer.
874 SourceLocation Loc = FD->getLocation();
875
876 const char *endBuf = SM->getCharacterData(Loc);
877 const char *startBuf = endBuf;
878 while (*startBuf != ';')
879 startBuf--; // scan backward (from the decl location) for return type.
880 const char *startRef = 0, *endRef = 0;
881 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
882 // Get the locations of the startRef, endRef.
883 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
884 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
885 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000886 Rewrite.InsertText(LessLoc, "/*", 2);
887 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000888 }
889 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000890 // Now check arguments.
891 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
892 if (needToScanForQualifiers(proto->getArgType(i))) {
893 // Since types are unique, we need to scan the buffer.
894 SourceLocation Loc = FD->getLocation();
895
896 const char *startBuf = SM->getCharacterData(Loc);
897 const char *endBuf = startBuf;
898 while (*endBuf != ';')
899 endBuf++; // scan forward (from the decl location) for argument types.
900 const char *startRef = 0, *endRef = 0;
901 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
902 // Get the locations of the startRef, endRef.
903 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
904 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
905 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000906 Rewrite.InsertText(LessLoc, "/*", 2);
907 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000908 }
909 }
910 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000911}
912
Steve Naroff09b266e2007-10-30 23:14:51 +0000913void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
914 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000915 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000916 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000917 return;
918 }
919 // Check for ObjC 'id' and class types that have been adorned with protocol
920 // information (id<p>, C<p>*). The protocol references need to be rewritten!
921 const FunctionType *funcType = FD->getType()->getAsFunctionType();
922 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000923 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
924 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000925}
926
927// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
928void RewriteTest::SynthMsgSendFunctionDecl() {
929 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
930 llvm::SmallVector<QualType, 16> ArgTys;
931 QualType argT = Context->getObjcIdType();
932 assert(!argT.isNull() && "Can't find 'id' type");
933 ArgTys.push_back(argT);
934 argT = Context->getObjcSelType();
935 assert(!argT.isNull() && "Can't find 'SEL' type");
936 ArgTys.push_back(argT);
937 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
938 &ArgTys[0], ArgTys.size(),
939 true /*isVariadic*/);
940 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
941 msgSendIdent, msgSendType,
942 FunctionDecl::Extern, false, 0);
943}
944
945// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
946void RewriteTest::SynthGetClassFunctionDecl() {
947 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
948 llvm::SmallVector<QualType, 16> ArgTys;
949 ArgTys.push_back(Context->getPointerType(
950 Context->CharTy.getQualifiedType(QualType::Const)));
951 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
952 &ArgTys[0], ArgTys.size(),
953 false /*isVariadic*/);
954 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
955 getClassIdent, getClassType,
956 FunctionDecl::Extern, false, 0);
957}
958
Steve Naroff96984642007-11-08 14:30:50 +0000959// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
960void RewriteTest::SynthCFStringFunctionDecl() {
961 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
962 llvm::SmallVector<QualType, 16> ArgTys;
963 ArgTys.push_back(Context->getPointerType(
964 Context->CharTy.getQualifiedType(QualType::Const)));
965 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
966 &ArgTys[0], ArgTys.size(),
967 false /*isVariadic*/);
968 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
969 getClassIdent, getClassType,
970 FunctionDecl::Extern, false, 0);
971}
972
Steve Naroffbeaf2992007-11-03 11:27:19 +0000973Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000974#if 1
975 // This rewrite is specific to GCC, which has builtin support for CFString.
976 if (!CFStringFunctionDecl)
977 SynthCFStringFunctionDecl();
978 // Create a call to __builtin___CFStringMakeConstantString("cstr").
979 llvm::SmallVector<Expr*, 8> StrExpr;
980 StrExpr.push_back(Exp->getString());
981 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
982 &StrExpr[0], StrExpr.size());
983 // cast to NSConstantString *
984 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
985 Rewrite.ReplaceStmt(Exp, cast);
986 delete Exp;
987 return cast;
988#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000989 assert(ConstantStringClassReference && "Can't find constant string reference");
990 llvm::SmallVector<Expr*, 4> InitExprs;
991
992 // Synthesize "(Class)&_NSConstantStringClassReference"
993 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
994 ConstantStringClassReference->getType(),
995 SourceLocation());
996 QualType expType = Context->getPointerType(ClsRef->getType());
997 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
998 expType, SourceLocation());
999 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1000 SourceLocation());
1001 InitExprs.push_back(cast); // set the 'isa'.
1002 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1003 unsigned IntSize = static_cast<unsigned>(
1004 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1005 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1006 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1007 Exp->getLocStart());
1008 InitExprs.push_back(len); // set "int numBytes".
1009
1010 // struct NSConstantString
1011 QualType CFConstantStrType = Context->getCFConstantStringType();
1012 // (struct NSConstantString) { <exprs from above> }
1013 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1014 &InitExprs[0], InitExprs.size(),
1015 SourceLocation());
1016 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1017 // struct NSConstantString *
1018 expType = Context->getPointerType(StrRep->getType());
1019 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1020 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001021 // cast to NSConstantString *
1022 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001023 Rewrite.ReplaceStmt(Exp, cast);
1024 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001025 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001026#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001027}
1028
Steve Naroff934f2762007-10-24 22:48:43 +00001029Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001030 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001031 if (!MsgSendFunctionDecl)
1032 SynthMsgSendFunctionDecl();
1033 if (!GetClassFunctionDecl)
1034 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001035
1036 // Synthesize a call to objc_msgSend().
1037 llvm::SmallVector<Expr*, 8> MsgExprs;
1038 IdentifierInfo *clsName = Exp->getClassName();
1039
1040 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1041 if (clsName) { // class message.
1042 llvm::SmallVector<Expr*, 8> ClsExprs;
1043 QualType argType = Context->getPointerType(Context->CharTy);
1044 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1045 clsName->getLength(),
1046 false, argType, SourceLocation(),
1047 SourceLocation()));
1048 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1049 &ClsExprs[0], ClsExprs.size());
1050 MsgExprs.push_back(Cls);
1051 } else // instance message.
1052 MsgExprs.push_back(Exp->getReceiver());
1053
Steve Naroffbeaf2992007-11-03 11:27:19 +00001054 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001055 llvm::SmallVector<Expr*, 8> SelExprs;
1056 QualType argType = Context->getPointerType(Context->CharTy);
1057 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1058 Exp->getSelector().getName().size(),
1059 false, argType, SourceLocation(),
1060 SourceLocation()));
1061 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1062 &SelExprs[0], SelExprs.size());
1063 MsgExprs.push_back(SelExp);
1064
1065 // Now push any user supplied arguments.
1066 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1067 MsgExprs.push_back(Exp->getArg(i));
1068 // We've transferred the ownership to MsgExprs. Null out the argument in
1069 // the original expression, since we will delete it below.
1070 Exp->setArg(i, 0);
1071 }
Steve Naroffab972d32007-11-04 22:37:50 +00001072 // Generate the funky cast.
1073 CastExpr *cast;
1074 llvm::SmallVector<QualType, 8> ArgTypes;
1075 QualType returnType;
1076
1077 // Push 'id' and 'SEL', the 2 implicit arguments.
1078 ArgTypes.push_back(Context->getObjcIdType());
1079 ArgTypes.push_back(Context->getObjcSelType());
1080 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1081 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001082 for (int i = 0; i < mDecl->getNumParams(); i++) {
1083 QualType t = mDecl->getParamDecl(i)->getType();
1084 if (t == Context->getObjcClassType())
1085 t = Context->getObjcIdType(); // Convert "Class"->"id"
1086 ArgTypes.push_back(t);
1087 }
Steve Naroffab972d32007-11-04 22:37:50 +00001088 returnType = mDecl->getResultType();
1089 } else {
1090 returnType = Context->getObjcIdType();
1091 }
1092 // Get the type, we will need to reference it in a couple spots.
1093 QualType msgSendType = MsgSendFunctionDecl->getType();
1094
1095 // Create a reference to the objc_msgSend() declaration.
1096 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1097
1098 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1099 // If we don't do this cast, we get the following bizarre warning/note:
1100 // xx.m:13: warning: function called through a non-compatible type
1101 // xx.m:13: note: if this code is reached, the program will abort
1102 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1103 SourceLocation());
1104
1105 // Now do the "normal" pointer to function cast.
1106 QualType castType = Context->getFunctionType(returnType,
1107 &ArgTypes[0], ArgTypes.size(),
1108 false/*FIXME:variadic*/);
1109 castType = Context->getPointerType(castType);
1110 cast = new CastExpr(castType, cast, SourceLocation());
1111
1112 // Don't forget the parens to enforce the proper binding.
1113 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1114
1115 const FunctionType *FT = msgSendType->getAsFunctionType();
1116 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1117 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001118 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001119 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001120
Chris Lattnere64b7772007-10-24 16:57:36 +00001121 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001122 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001123}
1124
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001125/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1126/// an objective-c class with ivars.
1127void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1128 std::string &Result) {
1129 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1130 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001131 // Do not synthesize more than once.
1132 if (ObjcSynthesizedStructs.count(CDecl))
1133 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001134 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1135 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1136 // Do it for the root
1137 SynthesizeObjcInternalStruct(RCDecl, Result);
1138 }
1139
Steve Naroff03300712007-11-12 13:56:41 +00001140 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001141 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001142 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001143 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1144 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001145 // FIXME: This has potential of causing problem. If
1146 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001147 Result += "\nstruct ";
1148 Result += CDecl->getName();
1149
1150 SourceLocation LocStart = CDecl->getLocStart();
1151 SourceLocation LocEnd = CDecl->getLocEnd();
1152
1153 const char *startBuf = SM->getCharacterData(LocStart);
1154 const char *endBuf = SM->getCharacterData(LocEnd);
1155
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001156 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001157 const char *cursor = strchr(startBuf, '{');
1158 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001159 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001160
1161 // rewrite the original header *without* disturbing the '{'
1162 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1163 Result.c_str(), Result.size());
1164 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1165 Result = "\n struct ";
1166 Result += RCDecl->getName();
1167 Result += " _";
1168 Result += RCDecl->getName();
1169 Result += ";\n";
1170
1171 // insert the super class structure definition.
1172 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1173 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1174 }
1175 cursor++; // past '{'
1176
1177 // Now comment out any visibility specifiers.
1178 while (cursor < endBuf) {
1179 if (*cursor == '@') {
1180 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001181 // Skip whitespace.
1182 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1183 /*scan*/;
1184
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001185 // FIXME: presence of @public, etc. inside comment results in
1186 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001187 if (!strncmp(cursor, "public", strlen("public")) ||
1188 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001189 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001190 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001191 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001192 // FIXME: If there are cases where '<' is used in ivar declaration part
1193 // of user code, then scan the ivar list and use needToScanForQualifiers
1194 // for type checking.
1195 else if (*cursor == '<') {
1196 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1197 Rewrite.InsertText(atLoc, "/* ", 3);
1198 cursor = strchr(cursor, '>');
1199 cursor++;
1200 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1201 Rewrite.InsertText(atLoc, " */", 3);
1202 }
Steve Narofffea763e82007-11-14 19:25:57 +00001203 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001204 }
Steve Narofffea763e82007-11-14 19:25:57 +00001205 // Don't forget to add a ';'!!
1206 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1207 } else { // we don't have any instance variables - insert super struct.
1208 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1209 Result += " {\n struct ";
1210 Result += RCDecl->getName();
1211 Result += " _";
1212 Result += RCDecl->getName();
1213 Result += ";\n};\n";
1214 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1215 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001216 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001217 // Mark this struct as having been generated.
1218 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001219 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001220}
1221
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001222// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1223/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001224void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001225 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001226 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001227 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001228 const char *ClassName,
1229 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001230 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001231 if (NumMethods > 0 && !objc_impl_method) {
1232 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001233 SEL _cmd;
1234 char *method_types;
1235 void *_imp;
1236 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001237 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001238 Result += "\nstruct _objc_method {\n";
1239 Result += "\tSEL _cmd;\n";
1240 Result += "\tchar *method_types;\n";
1241 Result += "\tvoid *_imp;\n";
1242 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001243
1244 /* struct _objc_method_list {
1245 struct _objc_method_list *next_method;
1246 int method_count;
1247 struct _objc_method method_list[];
1248 }
1249 */
1250 Result += "\nstruct _objc_method_list {\n";
1251 Result += "\tstruct _objc_method_list *next_method;\n";
1252 Result += "\tint method_count;\n";
1253 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001254 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001255 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001256 // Build _objc_method_list for class's methods if needed
1257 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001258 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001259 Result += prefix;
1260 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1261 Result += "_METHODS_";
1262 Result += ClassName;
1263 Result += " __attribute__ ((section (\"__OBJC, __";
1264 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001265 Result += "_meth\")))= ";
1266 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1267
1268 Result += "\t,{{(SEL)\"";
1269 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001270 std::string MethodTypeString;
1271 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1272 Result += "\", \"";
1273 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001274 Result += "\", ";
1275 Result += MethodInternalNames[Methods[0]];
1276 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001277 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001278 Result += "\t ,{(SEL)\"";
1279 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001280 std::string MethodTypeString;
1281 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1282 Result += "\", \"";
1283 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001284 Result += "\", ";
1285 Result += MethodInternalNames[Methods[i]];
1286 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001287 }
1288 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001289 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001290}
1291
1292/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1293void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1294 int NumProtocols,
1295 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001296 const char *ClassName,
1297 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001298 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001299 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001300 for (int i = 0; i < NumProtocols; i++) {
1301 ObjcProtocolDecl *PDecl = Protocols[i];
1302 // Output struct protocol_methods holder of method selector and type.
1303 if (!objc_protocol_methods &&
1304 (PDecl->getNumInstanceMethods() > 0
1305 || PDecl->getNumClassMethods() > 0)) {
1306 /* struct protocol_methods {
1307 SEL _cmd;
1308 char *method_types;
1309 }
1310 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001311 Result += "\nstruct protocol_methods {\n";
1312 Result += "\tSEL _cmd;\n";
1313 Result += "\tchar *method_types;\n";
1314 Result += "};\n";
1315
1316 /* struct _objc_protocol_method_list {
1317 int protocol_method_count;
1318 struct protocol_methods protocols[];
1319 }
1320 */
1321 Result += "\nstruct _objc_protocol_method_list {\n";
1322 Result += "\tint protocol_method_count;\n";
1323 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001324 objc_protocol_methods = true;
1325 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001326
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001327 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001328 int NumMethods = PDecl->getNumInstanceMethods();
1329 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001330 Result += "\nstatic struct _objc_protocol_method_list "
1331 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1332 Result += PDecl->getName();
1333 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1334 "{\n\t" + utostr(NumMethods) + "\n";
1335
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001336 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001337 Result += "\t,{{(SEL)\"";
1338 Result += Methods[0]->getSelector().getName().c_str();
1339 Result += "\", \"\"}\n";
1340
1341 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001342 Result += "\t ,{(SEL)\"";
1343 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001344 std::string MethodTypeString;
1345 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1346 Result += "\", \"";
1347 Result += MethodTypeString;
1348 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001349 }
1350 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001351 }
1352
1353 // Output class methods declared in this protocol.
1354 NumMethods = PDecl->getNumClassMethods();
1355 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001356 Result += "\nstatic struct _objc_protocol_method_list "
1357 "_OBJC_PROTOCOL_CLASS_METHODS_";
1358 Result += PDecl->getName();
1359 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1360 "{\n\t";
1361 Result += utostr(NumMethods);
1362 Result += "\n";
1363
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001364 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001365 Result += "\t,{{(SEL)\"";
1366 Result += Methods[0]->getSelector().getName().c_str();
1367 Result += "\", \"\"}\n";
1368
1369 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001370 Result += "\t ,{(SEL)\"";
1371 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001372 std::string MethodTypeString;
1373 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1374 Result += "\", \"";
1375 Result += MethodTypeString;
1376 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001377 }
1378 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001379 }
1380 // Output:
1381 /* struct _objc_protocol {
1382 // Objective-C 1.0 extensions
1383 struct _objc_protocol_extension *isa;
1384 char *protocol_name;
1385 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001386 struct _objc_protocol_method_list *instance_methods;
1387 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001388 };
1389 */
1390 static bool objc_protocol = false;
1391 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001392 Result += "\nstruct _objc_protocol {\n";
1393 Result += "\tstruct _objc_protocol_extension *isa;\n";
1394 Result += "\tchar *protocol_name;\n";
1395 Result += "\tstruct _objc_protocol **protocol_list;\n";
1396 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1397 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1398 Result += "};\n";
1399
1400 /* struct _objc_protocol_list {
1401 struct _objc_protocol_list *next;
1402 int protocol_count;
1403 struct _objc_protocol *class_protocols[];
1404 }
1405 */
1406 Result += "\nstruct _objc_protocol_list {\n";
1407 Result += "\tstruct _objc_protocol_list *next;\n";
1408 Result += "\tint protocol_count;\n";
1409 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1410 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001411 objc_protocol = true;
1412 }
1413
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001414 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1415 Result += PDecl->getName();
1416 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1417 "{\n\t0, \"";
1418 Result += PDecl->getName();
1419 Result += "\", 0, ";
1420 if (PDecl->getInstanceMethods() > 0) {
1421 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1422 Result += PDecl->getName();
1423 Result += ", ";
1424 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001425 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001426 Result += "0, ";
1427 if (PDecl->getClassMethods() > 0) {
1428 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1429 Result += PDecl->getName();
1430 Result += "\n";
1431 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001432 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001433 Result += "0\n";
1434 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001435 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001436 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001437 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1438 Result += prefix;
1439 Result += "_PROTOCOLS_";
1440 Result += ClassName;
1441 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1442 "{\n\t0, ";
1443 Result += utostr(NumProtocols);
1444 Result += "\n";
1445
1446 Result += "\t,{&_OBJC_PROTOCOL_";
1447 Result += Protocols[0]->getName();
1448 Result += " \n";
1449
1450 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001451 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001452 Result += "\t ,&_OBJC_PROTOCOL_";
1453 Result += PDecl->getName();
1454 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001455 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001456 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001457 }
1458}
1459
1460/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1461/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001462void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1463 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001464 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1465 // Find category declaration for this implementation.
1466 ObjcCategoryDecl *CDecl;
1467 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1468 CDecl = CDecl->getNextClassCategory())
1469 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1470 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001471
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001472 char *FullCategoryName = (char*)alloca(
1473 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1474 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1475
1476 // Build _objc_method_list for class's instance methods if needed
1477 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1478 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001479 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001480 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001481
1482 // Build _objc_method_list for class's class methods if needed
1483 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1484 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001485 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001486 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001487
1488 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001489 // Null CDecl is case of a category implementation with no category interface
1490 if (CDecl)
1491 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1492 CDecl->getNumReferencedProtocols(),
1493 "CATEGORY",
1494 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001495
1496 /* struct _objc_category {
1497 char *category_name;
1498 char *class_name;
1499 struct _objc_method_list *instance_methods;
1500 struct _objc_method_list *class_methods;
1501 struct _objc_protocol_list *protocols;
1502 // Objective-C 1.0 extensions
1503 uint32_t size; // sizeof (struct _objc_category)
1504 struct _objc_property_list *instance_properties; // category's own
1505 // @property decl.
1506 };
1507 */
1508
1509 static bool objc_category = false;
1510 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001511 Result += "\nstruct _objc_category {\n";
1512 Result += "\tchar *category_name;\n";
1513 Result += "\tchar *class_name;\n";
1514 Result += "\tstruct _objc_method_list *instance_methods;\n";
1515 Result += "\tstruct _objc_method_list *class_methods;\n";
1516 Result += "\tstruct _objc_protocol_list *protocols;\n";
1517 Result += "\tunsigned int size;\n";
1518 Result += "\tstruct _objc_property_list *instance_properties;\n";
1519 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001520 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001521 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001522 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1523 Result += FullCategoryName;
1524 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1525 Result += IDecl->getName();
1526 Result += "\"\n\t, \"";
1527 Result += ClassDecl->getName();
1528 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001529
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001530 if (IDecl->getNumInstanceMethods() > 0) {
1531 Result += "\t, (struct _objc_method_list *)"
1532 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1533 Result += FullCategoryName;
1534 Result += "\n";
1535 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001536 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001537 Result += "\t, 0\n";
1538 if (IDecl->getNumClassMethods() > 0) {
1539 Result += "\t, (struct _objc_method_list *)"
1540 "&_OBJC_CATEGORY_CLASS_METHODS_";
1541 Result += FullCategoryName;
1542 Result += "\n";
1543 }
1544 else
1545 Result += "\t, 0\n";
1546
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001547 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001548 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1549 Result += FullCategoryName;
1550 Result += "\n";
1551 }
1552 else
1553 Result += "\t, 0\n";
1554 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001555}
1556
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001557/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1558/// ivar offset.
1559void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1560 ObjcIvarDecl *ivar,
1561 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001562 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001563 Result += IDecl->getName();
1564 Result += ", ";
1565 Result += ivar->getName();
1566 Result += ")";
1567}
1568
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001569//===----------------------------------------------------------------------===//
1570// Meta Data Emission
1571//===----------------------------------------------------------------------===//
1572
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001573void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1574 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001575 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1576
1577 // Build _objc_ivar_list metadata for classes ivars if needed
1578 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1579 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001580 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001581
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001582 SynthesizeObjcInternalStruct(CDecl, Result);
1583
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001584 if (NumIvars > 0) {
1585 static bool objc_ivar = false;
1586 if (!objc_ivar) {
1587 /* struct _objc_ivar {
1588 char *ivar_name;
1589 char *ivar_type;
1590 int ivar_offset;
1591 };
1592 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001593 Result += "\nstruct _objc_ivar {\n";
1594 Result += "\tchar *ivar_name;\n";
1595 Result += "\tchar *ivar_type;\n";
1596 Result += "\tint ivar_offset;\n";
1597 Result += "};\n";
1598
1599 /* struct _objc_ivar_list {
1600 int ivar_count;
1601 struct _objc_ivar ivar_list[];
1602 };
1603 */
1604 Result += "\nstruct _objc_ivar_list {\n";
1605 Result += "\tint ivar_count;\n";
1606 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001607 objc_ivar = true;
1608 }
1609
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001610 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1611 Result += IDecl->getName();
1612 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1613 "{\n\t";
1614 Result += utostr(NumIvars);
1615 Result += "\n";
1616
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001617 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1618 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001619 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001620 Result += "\t,{{\"";
1621 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001622 Result += "\", \"";
1623 std::string StrEncoding;
1624 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1625 Result += StrEncoding;
1626 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001627 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1628 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001629 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001630 Result += "\t ,{\"";
1631 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001632 Result += "\", \"";
1633 std::string StrEncoding;
1634 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1635 Result += StrEncoding;
1636 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001637 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1638 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001639 }
1640
1641 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001642 }
1643
1644 // Build _objc_method_list for class's instance methods if needed
1645 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1646 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001647 true,
1648 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001649
1650 // Build _objc_method_list for class's class methods if needed
1651 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001652 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001653 false,
1654 "", IDecl->getName(), Result);
1655
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001656 // Protocols referenced in class declaration?
1657 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1658 CDecl->getNumIntfRefProtocols(),
1659 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001660 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001661
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001662
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001663 // Declaration of class/meta-class metadata
1664 /* struct _objc_class {
1665 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001666 const char *super_class_name;
1667 char *name;
1668 long version;
1669 long info;
1670 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001671 struct _objc_ivar_list *ivars;
1672 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001673 struct objc_cache *cache;
1674 struct objc_protocol_list *protocols;
1675 const char *ivar_layout;
1676 struct _objc_class_ext *ext;
1677 };
1678 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001679 static bool objc_class = false;
1680 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001681 Result += "\nstruct _objc_class {\n";
1682 Result += "\tstruct _objc_class *isa;\n";
1683 Result += "\tconst char *super_class_name;\n";
1684 Result += "\tchar *name;\n";
1685 Result += "\tlong version;\n";
1686 Result += "\tlong info;\n";
1687 Result += "\tlong instance_size;\n";
1688 Result += "\tstruct _objc_ivar_list *ivars;\n";
1689 Result += "\tstruct _objc_method_list *methods;\n";
1690 Result += "\tstruct objc_cache *cache;\n";
1691 Result += "\tstruct _objc_protocol_list *protocols;\n";
1692 Result += "\tconst char *ivar_layout;\n";
1693 Result += "\tstruct _objc_class_ext *ext;\n";
1694 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001695 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001696 }
1697
1698 // Meta-class metadata generation.
1699 ObjcInterfaceDecl *RootClass = 0;
1700 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1701 while (SuperClass) {
1702 RootClass = SuperClass;
1703 SuperClass = SuperClass->getSuperClass();
1704 }
1705 SuperClass = CDecl->getSuperClass();
1706
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001707 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1708 Result += CDecl->getName();
1709 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1710 "{\n\t(struct _objc_class *)\"";
1711 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1712 Result += "\"";
1713
1714 if (SuperClass) {
1715 Result += ", \"";
1716 Result += SuperClass->getName();
1717 Result += "\", \"";
1718 Result += CDecl->getName();
1719 Result += "\"";
1720 }
1721 else {
1722 Result += ", 0, \"";
1723 Result += CDecl->getName();
1724 Result += "\"";
1725 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001726 // TODO: 'ivars' field for root class is currently set to 0.
1727 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001728 Result += ", 0,2, sizeof(struct _objc_class), 0";
1729 if (CDecl->getNumClassMethods() > 0) {
1730 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1731 Result += CDecl->getName();
1732 Result += "\n";
1733 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001734 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001735 Result += ", 0\n";
1736 if (CDecl->getNumIntfRefProtocols() > 0) {
1737 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1738 Result += CDecl->getName();
1739 Result += ",0,0\n";
1740 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001741 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001742 Result += "\t,0,0,0,0\n";
1743 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001744
1745 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001746 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1747 Result += CDecl->getName();
1748 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1749 "{\n\t&_OBJC_METACLASS_";
1750 Result += CDecl->getName();
1751 if (SuperClass) {
1752 Result += ", \"";
1753 Result += SuperClass->getName();
1754 Result += "\", \"";
1755 Result += CDecl->getName();
1756 Result += "\"";
1757 }
1758 else {
1759 Result += ", 0, \"";
1760 Result += CDecl->getName();
1761 Result += "\"";
1762 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001763 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001764 Result += ", 0,1";
1765 if (!ObjcSynthesizedStructs.count(CDecl))
1766 Result += ",0";
1767 else {
1768 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001769 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001770 Result += CDecl->getName();
1771 Result += ")";
1772 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001773 if (NumIvars > 0) {
1774 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1775 Result += CDecl->getName();
1776 Result += "\n\t";
1777 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001778 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001779 Result += ",0";
1780 if (IDecl->getNumInstanceMethods() > 0) {
1781 Result += ", &_OBJC_INSTANCE_METHODS_";
1782 Result += CDecl->getName();
1783 Result += ", 0\n\t";
1784 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001785 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001786 Result += ",0,0";
1787 if (CDecl->getNumIntfRefProtocols() > 0) {
1788 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1789 Result += CDecl->getName();
1790 Result += ", 0,0\n";
1791 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001792 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001793 Result += ",0,0,0\n";
1794 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001795}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001796
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001797/// RewriteImplementations - This routine rewrites all method implementations
1798/// and emits meta-data.
1799
1800void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001801 int ClsDefCount = ClassImplementation.size();
1802 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001803
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001804 if (ClsDefCount == 0 && CatDefCount == 0)
1805 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001806 // Rewrite implemented methods
1807 for (int i = 0; i < ClsDefCount; i++)
1808 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001809
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001810 for (int i = 0; i < CatDefCount; i++)
1811 RewriteImplementationDecl(CategoryImplementation[i]);
1812
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001813 // This is needed for use of offsetof
1814 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001815
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001816 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001817 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001818 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001819
1820 // For each implemented category, write out all its meta data.
1821 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001822 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001823
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001824 // Write objc_symtab metadata
1825 /*
1826 struct _objc_symtab
1827 {
1828 long sel_ref_cnt;
1829 SEL *refs;
1830 short cls_def_cnt;
1831 short cat_def_cnt;
1832 void *defs[cls_def_cnt + cat_def_cnt];
1833 };
1834 */
1835
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001836 Result += "\nstruct _objc_symtab {\n";
1837 Result += "\tlong sel_ref_cnt;\n";
1838 Result += "\tSEL *refs;\n";
1839 Result += "\tshort cls_def_cnt;\n";
1840 Result += "\tshort cat_def_cnt;\n";
1841 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1842 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001843
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001844 Result += "static struct _objc_symtab "
1845 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1846 Result += "\t0, 0, " + utostr(ClsDefCount)
1847 + ", " + utostr(CatDefCount) + "\n";
1848 for (int i = 0; i < ClsDefCount; i++) {
1849 Result += "\t,&_OBJC_CLASS_";
1850 Result += ClassImplementation[i]->getName();
1851 Result += "\n";
1852 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001853
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001854 for (int i = 0; i < CatDefCount; i++) {
1855 Result += "\t,&_OBJC_CATEGORY_";
1856 Result += CategoryImplementation[i]->getClassInterface()->getName();
1857 Result += "_";
1858 Result += CategoryImplementation[i]->getName();
1859 Result += "\n";
1860 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001861
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001862 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001863
1864 // Write objc_module metadata
1865
1866 /*
1867 struct _objc_module {
1868 long version;
1869 long size;
1870 const char *name;
1871 struct _objc_symtab *symtab;
1872 }
1873 */
1874
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001875 Result += "\nstruct _objc_module {\n";
1876 Result += "\tlong version;\n";
1877 Result += "\tlong size;\n";
1878 Result += "\tconst char *name;\n";
1879 Result += "\tstruct _objc_symtab *symtab;\n";
1880 Result += "};\n\n";
1881 Result += "static struct _objc_module "
1882 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001883 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1884 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001885 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001886
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001887}
Chris Lattner311ff022007-10-16 22:36:42 +00001888