blob: 92d928cd08ee099cf82b0e1ce7ed93562617ef5e [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);
1181 cursor = strchr(cursor, 'p');
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001182 // FIXME: presence of @public, etc. inside comment results in
1183 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001184 if (!strncmp(cursor, "public", strlen("public")) ||
1185 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001186 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001187 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001188 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001189 // FIXME: If there are cases where '<' is used in ivar declaration part
1190 // of user code, then scan the ivar list and use needToScanForQualifiers
1191 // for type checking.
1192 else if (*cursor == '<') {
1193 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1194 Rewrite.InsertText(atLoc, "/* ", 3);
1195 cursor = strchr(cursor, '>');
1196 cursor++;
1197 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1198 Rewrite.InsertText(atLoc, " */", 3);
1199 }
Steve Narofffea763e82007-11-14 19:25:57 +00001200 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001201 }
Steve Narofffea763e82007-11-14 19:25:57 +00001202 // Don't forget to add a ';'!!
1203 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1204 } else { // we don't have any instance variables - insert super struct.
1205 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1206 Result += " {\n struct ";
1207 Result += RCDecl->getName();
1208 Result += " _";
1209 Result += RCDecl->getName();
1210 Result += ";\n};\n";
1211 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1212 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001213 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001214 // Mark this struct as having been generated.
1215 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001216 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001217}
1218
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001219// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1220/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001221void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001222 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001223 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001224 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001225 const char *ClassName,
1226 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001227 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001228 if (NumMethods > 0 && !objc_impl_method) {
1229 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001230 SEL _cmd;
1231 char *method_types;
1232 void *_imp;
1233 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001234 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001235 Result += "\nstruct _objc_method {\n";
1236 Result += "\tSEL _cmd;\n";
1237 Result += "\tchar *method_types;\n";
1238 Result += "\tvoid *_imp;\n";
1239 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001240
1241 /* struct _objc_method_list {
1242 struct _objc_method_list *next_method;
1243 int method_count;
1244 struct _objc_method method_list[];
1245 }
1246 */
1247 Result += "\nstruct _objc_method_list {\n";
1248 Result += "\tstruct _objc_method_list *next_method;\n";
1249 Result += "\tint method_count;\n";
1250 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001251 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001252 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001253 // Build _objc_method_list for class's methods if needed
1254 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001255 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001256 Result += prefix;
1257 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1258 Result += "_METHODS_";
1259 Result += ClassName;
1260 Result += " __attribute__ ((section (\"__OBJC, __";
1261 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001262 Result += "_meth\")))= ";
1263 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1264
1265 Result += "\t,{{(SEL)\"";
1266 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001267 std::string MethodTypeString;
1268 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1269 Result += "\", \"";
1270 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001271 Result += "\", ";
1272 Result += MethodInternalNames[Methods[0]];
1273 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001274 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001275 Result += "\t ,{(SEL)\"";
1276 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001277 std::string MethodTypeString;
1278 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1279 Result += "\", \"";
1280 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001281 Result += "\", ";
1282 Result += MethodInternalNames[Methods[i]];
1283 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001284 }
1285 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001286 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001287}
1288
1289/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1290void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1291 int NumProtocols,
1292 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001293 const char *ClassName,
1294 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001295 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001296 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001297 for (int i = 0; i < NumProtocols; i++) {
1298 ObjcProtocolDecl *PDecl = Protocols[i];
1299 // Output struct protocol_methods holder of method selector and type.
1300 if (!objc_protocol_methods &&
1301 (PDecl->getNumInstanceMethods() > 0
1302 || PDecl->getNumClassMethods() > 0)) {
1303 /* struct protocol_methods {
1304 SEL _cmd;
1305 char *method_types;
1306 }
1307 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001308 Result += "\nstruct protocol_methods {\n";
1309 Result += "\tSEL _cmd;\n";
1310 Result += "\tchar *method_types;\n";
1311 Result += "};\n";
1312
1313 /* struct _objc_protocol_method_list {
1314 int protocol_method_count;
1315 struct protocol_methods protocols[];
1316 }
1317 */
1318 Result += "\nstruct _objc_protocol_method_list {\n";
1319 Result += "\tint protocol_method_count;\n";
1320 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001321 objc_protocol_methods = true;
1322 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001323
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001324 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001325 int NumMethods = PDecl->getNumInstanceMethods();
1326 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001327 Result += "\nstatic struct _objc_protocol_method_list "
1328 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1329 Result += PDecl->getName();
1330 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1331 "{\n\t" + utostr(NumMethods) + "\n";
1332
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001333 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001334 Result += "\t,{{(SEL)\"";
1335 Result += Methods[0]->getSelector().getName().c_str();
1336 Result += "\", \"\"}\n";
1337
1338 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001339 Result += "\t ,{(SEL)\"";
1340 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001341 std::string MethodTypeString;
1342 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1343 Result += "\", \"";
1344 Result += MethodTypeString;
1345 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001346 }
1347 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001348 }
1349
1350 // Output class methods declared in this protocol.
1351 NumMethods = PDecl->getNumClassMethods();
1352 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001353 Result += "\nstatic struct _objc_protocol_method_list "
1354 "_OBJC_PROTOCOL_CLASS_METHODS_";
1355 Result += PDecl->getName();
1356 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1357 "{\n\t";
1358 Result += utostr(NumMethods);
1359 Result += "\n";
1360
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001361 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001362 Result += "\t,{{(SEL)\"";
1363 Result += Methods[0]->getSelector().getName().c_str();
1364 Result += "\", \"\"}\n";
1365
1366 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001367 Result += "\t ,{(SEL)\"";
1368 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001369 std::string MethodTypeString;
1370 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1371 Result += "\", \"";
1372 Result += MethodTypeString;
1373 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001374 }
1375 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001376 }
1377 // Output:
1378 /* struct _objc_protocol {
1379 // Objective-C 1.0 extensions
1380 struct _objc_protocol_extension *isa;
1381 char *protocol_name;
1382 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001383 struct _objc_protocol_method_list *instance_methods;
1384 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001385 };
1386 */
1387 static bool objc_protocol = false;
1388 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001389 Result += "\nstruct _objc_protocol {\n";
1390 Result += "\tstruct _objc_protocol_extension *isa;\n";
1391 Result += "\tchar *protocol_name;\n";
1392 Result += "\tstruct _objc_protocol **protocol_list;\n";
1393 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1394 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1395 Result += "};\n";
1396
1397 /* struct _objc_protocol_list {
1398 struct _objc_protocol_list *next;
1399 int protocol_count;
1400 struct _objc_protocol *class_protocols[];
1401 }
1402 */
1403 Result += "\nstruct _objc_protocol_list {\n";
1404 Result += "\tstruct _objc_protocol_list *next;\n";
1405 Result += "\tint protocol_count;\n";
1406 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1407 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001408 objc_protocol = true;
1409 }
1410
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001411 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1412 Result += PDecl->getName();
1413 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1414 "{\n\t0, \"";
1415 Result += PDecl->getName();
1416 Result += "\", 0, ";
1417 if (PDecl->getInstanceMethods() > 0) {
1418 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1419 Result += PDecl->getName();
1420 Result += ", ";
1421 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001422 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001423 Result += "0, ";
1424 if (PDecl->getClassMethods() > 0) {
1425 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1426 Result += PDecl->getName();
1427 Result += "\n";
1428 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001429 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001430 Result += "0\n";
1431 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001432 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001433 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001434 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1435 Result += prefix;
1436 Result += "_PROTOCOLS_";
1437 Result += ClassName;
1438 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1439 "{\n\t0, ";
1440 Result += utostr(NumProtocols);
1441 Result += "\n";
1442
1443 Result += "\t,{&_OBJC_PROTOCOL_";
1444 Result += Protocols[0]->getName();
1445 Result += " \n";
1446
1447 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001448 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001449 Result += "\t ,&_OBJC_PROTOCOL_";
1450 Result += PDecl->getName();
1451 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001452 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001453 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001454 }
1455}
1456
1457/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1458/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001459void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1460 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001461 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1462 // Find category declaration for this implementation.
1463 ObjcCategoryDecl *CDecl;
1464 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1465 CDecl = CDecl->getNextClassCategory())
1466 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1467 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001468
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001469 char *FullCategoryName = (char*)alloca(
1470 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1471 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1472
1473 // Build _objc_method_list for class's instance methods if needed
1474 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1475 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001476 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001477 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001478
1479 // Build _objc_method_list for class's class methods if needed
1480 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1481 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001482 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001483 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001484
1485 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001486 // Null CDecl is case of a category implementation with no category interface
1487 if (CDecl)
1488 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1489 CDecl->getNumReferencedProtocols(),
1490 "CATEGORY",
1491 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001492
1493 /* struct _objc_category {
1494 char *category_name;
1495 char *class_name;
1496 struct _objc_method_list *instance_methods;
1497 struct _objc_method_list *class_methods;
1498 struct _objc_protocol_list *protocols;
1499 // Objective-C 1.0 extensions
1500 uint32_t size; // sizeof (struct _objc_category)
1501 struct _objc_property_list *instance_properties; // category's own
1502 // @property decl.
1503 };
1504 */
1505
1506 static bool objc_category = false;
1507 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001508 Result += "\nstruct _objc_category {\n";
1509 Result += "\tchar *category_name;\n";
1510 Result += "\tchar *class_name;\n";
1511 Result += "\tstruct _objc_method_list *instance_methods;\n";
1512 Result += "\tstruct _objc_method_list *class_methods;\n";
1513 Result += "\tstruct _objc_protocol_list *protocols;\n";
1514 Result += "\tunsigned int size;\n";
1515 Result += "\tstruct _objc_property_list *instance_properties;\n";
1516 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001517 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001518 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001519 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1520 Result += FullCategoryName;
1521 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1522 Result += IDecl->getName();
1523 Result += "\"\n\t, \"";
1524 Result += ClassDecl->getName();
1525 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001526
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001527 if (IDecl->getNumInstanceMethods() > 0) {
1528 Result += "\t, (struct _objc_method_list *)"
1529 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1530 Result += FullCategoryName;
1531 Result += "\n";
1532 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001533 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001534 Result += "\t, 0\n";
1535 if (IDecl->getNumClassMethods() > 0) {
1536 Result += "\t, (struct _objc_method_list *)"
1537 "&_OBJC_CATEGORY_CLASS_METHODS_";
1538 Result += FullCategoryName;
1539 Result += "\n";
1540 }
1541 else
1542 Result += "\t, 0\n";
1543
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001544 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001545 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1546 Result += FullCategoryName;
1547 Result += "\n";
1548 }
1549 else
1550 Result += "\t, 0\n";
1551 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001552}
1553
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001554/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1555/// ivar offset.
1556void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1557 ObjcIvarDecl *ivar,
1558 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001559 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001560 Result += IDecl->getName();
1561 Result += ", ";
1562 Result += ivar->getName();
1563 Result += ")";
1564}
1565
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001566//===----------------------------------------------------------------------===//
1567// Meta Data Emission
1568//===----------------------------------------------------------------------===//
1569
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001570void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1571 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001572 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1573
1574 // Build _objc_ivar_list metadata for classes ivars if needed
1575 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1576 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001577 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001578
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001579 SynthesizeObjcInternalStruct(CDecl, Result);
1580
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001581 if (NumIvars > 0) {
1582 static bool objc_ivar = false;
1583 if (!objc_ivar) {
1584 /* struct _objc_ivar {
1585 char *ivar_name;
1586 char *ivar_type;
1587 int ivar_offset;
1588 };
1589 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001590 Result += "\nstruct _objc_ivar {\n";
1591 Result += "\tchar *ivar_name;\n";
1592 Result += "\tchar *ivar_type;\n";
1593 Result += "\tint ivar_offset;\n";
1594 Result += "};\n";
1595
1596 /* struct _objc_ivar_list {
1597 int ivar_count;
1598 struct _objc_ivar ivar_list[];
1599 };
1600 */
1601 Result += "\nstruct _objc_ivar_list {\n";
1602 Result += "\tint ivar_count;\n";
1603 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001604 objc_ivar = true;
1605 }
1606
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001607 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1608 Result += IDecl->getName();
1609 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1610 "{\n\t";
1611 Result += utostr(NumIvars);
1612 Result += "\n";
1613
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001614 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1615 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001616 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001617 Result += "\t,{{\"";
1618 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001619 Result += "\", \"";
1620 std::string StrEncoding;
1621 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1622 Result += StrEncoding;
1623 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001624 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1625 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001626 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001627 Result += "\t ,{\"";
1628 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001629 Result += "\", \"";
1630 std::string StrEncoding;
1631 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1632 Result += StrEncoding;
1633 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001634 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1635 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001636 }
1637
1638 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001639 }
1640
1641 // Build _objc_method_list for class's instance methods if needed
1642 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1643 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001644 true,
1645 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001646
1647 // Build _objc_method_list for class's class methods if needed
1648 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001649 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001650 false,
1651 "", IDecl->getName(), Result);
1652
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001653 // Protocols referenced in class declaration?
1654 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1655 CDecl->getNumIntfRefProtocols(),
1656 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001657 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001658
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001659
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001660 // Declaration of class/meta-class metadata
1661 /* struct _objc_class {
1662 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001663 const char *super_class_name;
1664 char *name;
1665 long version;
1666 long info;
1667 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001668 struct _objc_ivar_list *ivars;
1669 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001670 struct objc_cache *cache;
1671 struct objc_protocol_list *protocols;
1672 const char *ivar_layout;
1673 struct _objc_class_ext *ext;
1674 };
1675 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001676 static bool objc_class = false;
1677 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001678 Result += "\nstruct _objc_class {\n";
1679 Result += "\tstruct _objc_class *isa;\n";
1680 Result += "\tconst char *super_class_name;\n";
1681 Result += "\tchar *name;\n";
1682 Result += "\tlong version;\n";
1683 Result += "\tlong info;\n";
1684 Result += "\tlong instance_size;\n";
1685 Result += "\tstruct _objc_ivar_list *ivars;\n";
1686 Result += "\tstruct _objc_method_list *methods;\n";
1687 Result += "\tstruct objc_cache *cache;\n";
1688 Result += "\tstruct _objc_protocol_list *protocols;\n";
1689 Result += "\tconst char *ivar_layout;\n";
1690 Result += "\tstruct _objc_class_ext *ext;\n";
1691 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001692 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001693 }
1694
1695 // Meta-class metadata generation.
1696 ObjcInterfaceDecl *RootClass = 0;
1697 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1698 while (SuperClass) {
1699 RootClass = SuperClass;
1700 SuperClass = SuperClass->getSuperClass();
1701 }
1702 SuperClass = CDecl->getSuperClass();
1703
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001704 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1705 Result += CDecl->getName();
1706 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1707 "{\n\t(struct _objc_class *)\"";
1708 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1709 Result += "\"";
1710
1711 if (SuperClass) {
1712 Result += ", \"";
1713 Result += SuperClass->getName();
1714 Result += "\", \"";
1715 Result += CDecl->getName();
1716 Result += "\"";
1717 }
1718 else {
1719 Result += ", 0, \"";
1720 Result += CDecl->getName();
1721 Result += "\"";
1722 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001723 // TODO: 'ivars' field for root class is currently set to 0.
1724 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001725 Result += ", 0,2, sizeof(struct _objc_class), 0";
1726 if (CDecl->getNumClassMethods() > 0) {
1727 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1728 Result += CDecl->getName();
1729 Result += "\n";
1730 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001731 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001732 Result += ", 0\n";
1733 if (CDecl->getNumIntfRefProtocols() > 0) {
1734 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1735 Result += CDecl->getName();
1736 Result += ",0,0\n";
1737 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001738 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001739 Result += "\t,0,0,0,0\n";
1740 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001741
1742 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001743 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1744 Result += CDecl->getName();
1745 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1746 "{\n\t&_OBJC_METACLASS_";
1747 Result += CDecl->getName();
1748 if (SuperClass) {
1749 Result += ", \"";
1750 Result += SuperClass->getName();
1751 Result += "\", \"";
1752 Result += CDecl->getName();
1753 Result += "\"";
1754 }
1755 else {
1756 Result += ", 0, \"";
1757 Result += CDecl->getName();
1758 Result += "\"";
1759 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001760 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001761 Result += ", 0,1";
1762 if (!ObjcSynthesizedStructs.count(CDecl))
1763 Result += ",0";
1764 else {
1765 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001766 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001767 Result += CDecl->getName();
1768 Result += ")";
1769 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001770 if (NumIvars > 0) {
1771 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1772 Result += CDecl->getName();
1773 Result += "\n\t";
1774 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001775 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001776 Result += ",0";
1777 if (IDecl->getNumInstanceMethods() > 0) {
1778 Result += ", &_OBJC_INSTANCE_METHODS_";
1779 Result += CDecl->getName();
1780 Result += ", 0\n\t";
1781 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001782 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001783 Result += ",0,0";
1784 if (CDecl->getNumIntfRefProtocols() > 0) {
1785 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1786 Result += CDecl->getName();
1787 Result += ", 0,0\n";
1788 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001789 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001790 Result += ",0,0,0\n";
1791 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001792}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001793
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001794/// RewriteImplementations - This routine rewrites all method implementations
1795/// and emits meta-data.
1796
1797void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001798 int ClsDefCount = ClassImplementation.size();
1799 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001800
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001801 if (ClsDefCount == 0 && CatDefCount == 0)
1802 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001803 // Rewrite implemented methods
1804 for (int i = 0; i < ClsDefCount; i++)
1805 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001806
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001807 for (int i = 0; i < CatDefCount; i++)
1808 RewriteImplementationDecl(CategoryImplementation[i]);
1809
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001810 // This is needed for use of offsetof
1811 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001812
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001813 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001814 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001815 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001816
1817 // For each implemented category, write out all its meta data.
1818 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001820
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001821 // Write objc_symtab metadata
1822 /*
1823 struct _objc_symtab
1824 {
1825 long sel_ref_cnt;
1826 SEL *refs;
1827 short cls_def_cnt;
1828 short cat_def_cnt;
1829 void *defs[cls_def_cnt + cat_def_cnt];
1830 };
1831 */
1832
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001833 Result += "\nstruct _objc_symtab {\n";
1834 Result += "\tlong sel_ref_cnt;\n";
1835 Result += "\tSEL *refs;\n";
1836 Result += "\tshort cls_def_cnt;\n";
1837 Result += "\tshort cat_def_cnt;\n";
1838 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1839 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001840
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001841 Result += "static struct _objc_symtab "
1842 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1843 Result += "\t0, 0, " + utostr(ClsDefCount)
1844 + ", " + utostr(CatDefCount) + "\n";
1845 for (int i = 0; i < ClsDefCount; i++) {
1846 Result += "\t,&_OBJC_CLASS_";
1847 Result += ClassImplementation[i]->getName();
1848 Result += "\n";
1849 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001850
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001851 for (int i = 0; i < CatDefCount; i++) {
1852 Result += "\t,&_OBJC_CATEGORY_";
1853 Result += CategoryImplementation[i]->getClassInterface()->getName();
1854 Result += "_";
1855 Result += CategoryImplementation[i]->getName();
1856 Result += "\n";
1857 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001858
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001859 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001860
1861 // Write objc_module metadata
1862
1863 /*
1864 struct _objc_module {
1865 long version;
1866 long size;
1867 const char *name;
1868 struct _objc_symtab *symtab;
1869 }
1870 */
1871
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001872 Result += "\nstruct _objc_module {\n";
1873 Result += "\tlong version;\n";
1874 Result += "\tlong size;\n";
1875 Result += "\tconst char *name;\n";
1876 Result += "\tstruct _objc_symtab *symtab;\n";
1877 Result += "};\n\n";
1878 Result += "static struct _objc_module "
1879 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001880 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1881 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001882 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001883
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001884}
Chris Lattner311ff022007-10-16 22:36:42 +00001885