blob: 5538a900b1bdc86a4db34ae525afb40fe9e2579b [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000037 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000038
39 FunctionDecl *MsgSendFunctionDecl;
40 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000041 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000042 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
Steve Naroffbeaf2992007-11-03 11:27:19 +000044 // ObjC string constant support.
45 FileVarDecl *ConstantStringClassReference;
46 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000047
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000048 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000049 public:
Chris Lattner01c57482007-10-17 22:35:30 +000050 void Initialize(ASTContext &context, unsigned mainFileID) {
51 Context = &context;
52 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000053 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000054 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000055 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000056 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000057 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000058 ConstantStringClassReference = 0;
59 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000060 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000061 // declaring objc_selector outside the parameter list removes a silly
62 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000063 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000064 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000065 "(struct objc_object *, struct objc_selector *, ...);\n"
66 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000067 "(const char *);\n"
68 "extern void objc_exception_throw(struct objc_object *);\n"
69 "extern void objc_exception_try_enter(void *);\n"
70 "extern void objc_exception_try_exit(void *);\n"
71 "extern struct objc_object *objc_exception_extract(void *);\n"
72 "extern int objc_exception_match"
73 "(struct objc_class *, struct objc_object *, ...);\n";
74
Steve Naroffab972d32007-11-04 22:37:50 +000075 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
76 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000077 }
Chris Lattner8a12c272007-10-11 18:38:32 +000078
Chris Lattnerf04da132007-10-24 17:06:59 +000079 // Top Level Driver code.
80 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000081 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000082 ~RewriteTest();
83
84 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000085 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000086 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000087 void RewriteTabs();
88 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000089 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +000090 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000091 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000092 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000093 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +000094 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +000095 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000096 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000097 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000098 void RewriteObjcQualifiedInterfaceTypes(
99 const FunctionTypeProto *proto, FunctionDecl *FD);
100 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +0000101
Chris Lattnerf04da132007-10-24 17:06:59 +0000102 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000103 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000104 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000105 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000106 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000107 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000108 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
109 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
110 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000111 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000112 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
113 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000114 void SynthMsgSendFunctionDecl();
115 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000116 void SynthCFStringFunctionDecl();
117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000119 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
120 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000121
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000122 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
123 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124
Steve Naroff0416fb92007-11-11 17:19:15 +0000125 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000126 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000127 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000128 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000129 const char *ClassName,
130 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000131
132 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
133 int NumProtocols,
134 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000135 const char *ClassName,
136 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000137 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
138 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000139 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
140 ObjcIvarDecl *ivar,
141 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000142 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000143 };
144}
145
Chris Lattner8a12c272007-10-11 18:38:32 +0000146ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000147
Chris Lattnerf04da132007-10-24 17:06:59 +0000148//===----------------------------------------------------------------------===//
149// Top Level Driver Code
150//===----------------------------------------------------------------------===//
151
Chris Lattner8a12c272007-10-11 18:38:32 +0000152void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000153 // Two cases: either the decl could be in the main file, or it could be in a
154 // #included file. If the former, rewrite it now. If the later, check to see
155 // if we rewrote the #include/#import.
156 SourceLocation Loc = D->getLocation();
157 Loc = SM->getLogicalLoc(Loc);
158
159 // If this is for a builtin, ignore it.
160 if (Loc.isInvalid()) return;
161
Steve Naroffebf2b562007-10-23 23:50:29 +0000162 // Look for built-in declarations that we need to refer during the rewrite.
163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000164 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000165 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
166 // declared in <Foundation/NSString.h>
167 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
168 ConstantStringClassReference = FVD;
169 return;
170 }
Steve Naroffbef11852007-10-26 20:53:56 +0000171 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
172 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000173 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
174 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000175 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
176 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000177 } else if (ObjcForwardProtocolDecl *FP =
178 dyn_cast<ObjcForwardProtocolDecl>(D)){
179 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000180 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000181 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000182 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
183 return HandleDeclInMainFile(D);
184
Chris Lattnerf04da132007-10-24 17:06:59 +0000185 // Otherwise, see if there is a #import in the main file that should be
186 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000187 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000188}
189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190/// HandleDeclInMainFile - This is called for each top-level decl defined in the
191/// main file of the input.
192void RewriteTest::HandleDeclInMainFile(Decl *D) {
193 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
194 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000195 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000196
197 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
198 if (Stmt *Body = MD->getBody())
199 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
200 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000201 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
202 ClassImplementation.push_back(CI);
203 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
204 CategoryImplementation.push_back(CI);
205 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
206 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000207 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
208 if (VD->getInit())
209 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
210 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000211 // Nothing yet.
212}
213
214RewriteTest::~RewriteTest() {
215 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000216
217 // Rewrite tabs if we care.
218 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000219
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000220 // Rewrite Objective-c meta data*
221 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000222 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000223
Chris Lattnerf04da132007-10-24 17:06:59 +0000224 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
225 // we are done.
226 if (const RewriteBuffer *RewriteBuf =
227 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000228 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000229 std::string S(RewriteBuf->begin(), RewriteBuf->end());
230 printf("%s\n", S.c_str());
231 } else {
232 printf("No changes\n");
233 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000234 // Emit metadata.
235 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000236}
237
Chris Lattnerf04da132007-10-24 17:06:59 +0000238//===----------------------------------------------------------------------===//
239// Syntactic (non-AST) Rewriting Code
240//===----------------------------------------------------------------------===//
241
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000242void RewriteTest::RewriteInclude(SourceLocation Loc) {
243 // Rip up the #include stack to the main file.
244 SourceLocation IncLoc = Loc, NextLoc = Loc;
245 do {
246 IncLoc = Loc;
247 Loc = SM->getLogicalLoc(NextLoc);
248 NextLoc = SM->getIncludeLoc(Loc);
249 } while (!NextLoc.isInvalid());
250
251 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
252 // IncLoc indicates the header that was included if it is useful.
253 IncLoc = SM->getLogicalLoc(IncLoc);
254 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
255 Loc == LastIncLoc)
256 return;
257 LastIncLoc = Loc;
258
259 unsigned IncCol = SM->getColumnNumber(Loc);
260 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
261
262 // Replace the #import with #include.
263 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
264}
265
Chris Lattnerf04da132007-10-24 17:06:59 +0000266void RewriteTest::RewriteTabs() {
267 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
268 const char *MainBufStart = MainBuf.first;
269 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000270
Chris Lattnerf04da132007-10-24 17:06:59 +0000271 // Loop over the whole file, looking for tabs.
272 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
273 if (*BufPtr != '\t')
274 continue;
275
276 // Okay, we found a tab. This tab will turn into at least one character,
277 // but it depends on which 'virtual column' it is in. Compute that now.
278 unsigned VCol = 0;
279 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
280 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
281 ++VCol;
282
283 // Okay, now that we know the virtual column, we know how many spaces to
284 // insert. We assume 8-character tab-stops.
285 unsigned Spaces = 8-(VCol & 7);
286
287 // Get the location of the tab.
288 SourceLocation TabLoc =
289 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
290
291 // Rewrite the single tab character into a sequence of spaces.
292 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
293 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000294}
295
296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
298 int numDecls = ClassDecl->getNumForwardDecls();
299 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
300
301 // Get the start location and compute the semi location.
302 SourceLocation startLoc = ClassDecl->getLocation();
303 const char *startBuf = SM->getCharacterData(startLoc);
304 const char *semiPtr = strchr(startBuf, ';');
305
306 // Translate to typedef's that forward reference structs with the same name
307 // as the class. As a convenience, we include the original declaration
308 // as a comment.
309 std::string typedefString;
310 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000311 typedefString.append(startBuf, semiPtr-startBuf+1);
312 typedefString += "\n";
313 for (int i = 0; i < numDecls; i++) {
314 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000315 if (ObjcForwardDecls.count(ForwardDecl))
316 continue;
Steve Naroff32174822007-11-09 12:50:28 +0000317 typedefString += "#ifndef _REWRITER_typedef_";
318 typedefString += ForwardDecl->getName();
319 typedefString += "\n";
320 typedefString += "#define _REWRITER_typedef_";
321 typedefString += ForwardDecl->getName();
322 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000323 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000324 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000325 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000326 // Mark this typedef as having been generated.
327 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000328 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000329 }
330
331 // Replace the @class with typedefs corresponding to the classes.
332 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
333 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000334}
335
Steve Naroff71c0a952007-11-13 23:01:27 +0000336void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000337 for (int i = 0; i < nMethods; i++) {
338 ObjcMethodDecl *Method = Methods[i];
339 SourceLocation Loc = Method->getLocStart();
340
Chris Lattner28d1fe82007-11-08 04:41:51 +0000341 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000342
343 // FIXME: handle methods that are declared across multiple lines.
344 }
345}
346
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000347void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
348{
349 for (int i = 0; i < nProperties; i++) {
350 ObjcPropertyDecl *Property = Properties[i];
351 SourceLocation Loc = Property->getLocation();
352
353 Rewrite.ReplaceText(Loc, 0, "// ", 3);
354
355 // FIXME: handle properties that are declared across multiple lines.
356 }
357}
358
Steve Naroff423cb562007-10-30 13:30:57 +0000359void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
360 SourceLocation LocStart = CatDecl->getLocStart();
361
362 // FIXME: handle category headers that are declared across multiple lines.
363 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
364
Steve Naroff71c0a952007-11-13 23:01:27 +0000365 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
366 CatDecl->getInstanceMethods());
367 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
368 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000369 // Lastly, comment out the @end.
370 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
371}
372
Steve Naroff752d6ef2007-10-30 16:42:30 +0000373void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000374 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
375 const char *MainBufStart = MainBuf.first;
376
Steve Naroff752d6ef2007-10-30 16:42:30 +0000377 SourceLocation LocStart = PDecl->getLocStart();
378
379 // FIXME: handle protocol headers that are declared across multiple lines.
380 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
381
Steve Naroff71c0a952007-11-13 23:01:27 +0000382 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
383 PDecl->getInstanceMethods());
384 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
385 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000386 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000387 SourceLocation LocEnd = PDecl->getAtEndLoc();
388 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
389
390 // Must comment out @optional/@required
391 const char *startBuf = SM->getCharacterData(LocStart);
392 const char *endBuf = SM->getCharacterData(LocEnd);
393 for (const char *p = startBuf; p < endBuf; p++) {
394 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
395 std::string CommentedOptional = "/* @optional */";
396 SourceLocation OptionalLoc = SourceLocation::getFileLoc(MainFileID,
397 p-MainBufStart);
398 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
399 CommentedOptional.c_str(), CommentedOptional.size());
400
401 }
402 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
403 std::string CommentedRequired = "/* @required */";
404 SourceLocation OptionalLoc = SourceLocation::getFileLoc(MainFileID,
405 p-MainBufStart);
406 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
407 CommentedRequired.c_str(), CommentedRequired.size());
408
409 }
410 }
411
Steve Naroff752d6ef2007-10-30 16:42:30 +0000412}
413
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000414void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
415 SourceLocation LocStart = PDecl->getLocation();
416 // FIXME: handle forward protocol that are declared across multiple lines.
417 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
418}
419
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000420void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
421 std::string &ResultStr) {
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000422 static bool includeObjc = false;
423 if (!includeObjc) {
424 ResultStr += "#include <Objc/objc.h>\n";
425 includeObjc = true;
426 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000427 ResultStr += "\nstatic ";
428 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000429 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000430
431 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000432 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000433
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000434 if (OMD->isInstance())
435 NameStr += "_I_";
436 else
437 NameStr += "_C_";
438
439 NameStr += OMD->getClassInterface()->getName();
440 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000441
442 NamedDecl *MethodContext = OMD->getMethodContext();
443 if (ObjcCategoryImplDecl *CID =
444 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000445 NameStr += CID->getName();
446 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000447 }
448 // Append selector names, replacing ':' with '_'
449 const char *selName = OMD->getSelector().getName().c_str();
450 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000451 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000452 else {
453 std::string selString = OMD->getSelector().getName();
454 int len = selString.size();
455 for (int i = 0; i < len; i++)
456 if (selString[i] == ':')
457 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000458 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000459 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000460 // Remember this name for metadata emission
461 MethodInternalNames[OMD] = NameStr;
462 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000463
464 // Rewrite arguments
465 ResultStr += "(";
466
467 // invisible arguments
468 if (OMD->isInstance()) {
469 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
470 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000471 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
472 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000473 ResultStr += selfTy.getAsString();
474 }
475 else
476 ResultStr += Context->getObjcIdType().getAsString();
477
478 ResultStr += " self, ";
479 ResultStr += Context->getObjcSelType().getAsString();
480 ResultStr += " _cmd";
481
482 // Method arguments.
483 for (int i = 0; i < OMD->getNumParams(); i++) {
484 ParmVarDecl *PDecl = OMD->getParamDecl(i);
485 ResultStr += ", ";
486 ResultStr += PDecl->getType().getAsString();
487 ResultStr += " ";
488 ResultStr += PDecl->getName();
489 }
490 ResultStr += ")";
491
492}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000493void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
494 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
495 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000496
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000497 if (IMD)
498 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
499 else
500 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000501
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000502 int numMethods = IMD ? IMD->getNumInstanceMethods()
503 : CID->getNumInstanceMethods();
504
505 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000506 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000507 ObjcMethodDecl *OMD;
508 if (IMD)
509 OMD = IMD->getInstanceMethods()[i];
510 else
511 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000512 RewriteObjcMethodDecl(OMD, ResultStr);
513 SourceLocation LocStart = OMD->getLocStart();
514 SourceLocation LocEnd = OMD->getBody()->getLocStart();
515
516 const char *startBuf = SM->getCharacterData(LocStart);
517 const char *endBuf = SM->getCharacterData(LocEnd);
518 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
519 ResultStr.c_str(), ResultStr.size());
520 }
521
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000522 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
523 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000524 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000525 ObjcMethodDecl *OMD;
526 if (IMD)
527 OMD = IMD->getClassMethods()[i];
528 else
529 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000530 RewriteObjcMethodDecl(OMD, ResultStr);
531 SourceLocation LocStart = OMD->getLocStart();
532 SourceLocation LocEnd = OMD->getBody()->getLocStart();
533
534 const char *startBuf = SM->getCharacterData(LocStart);
535 const char *endBuf = SM->getCharacterData(LocEnd);
536 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
537 ResultStr.c_str(), ResultStr.size());
538 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539 if (IMD)
540 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
541 else
542 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000543}
544
Steve Naroffbef11852007-10-26 20:53:56 +0000545void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000546
547 SourceLocation LocStart = ClassDecl->getLocStart();
548 SourceLocation LocEnd = ClassDecl->getLocEnd();
549
550 const char *startBuf = SM->getCharacterData(LocStart);
551 const char *endBuf = SM->getCharacterData(LocEnd);
552
Steve Naroff2feac5e2007-10-30 03:43:13 +0000553 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000554
555 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000556 if (!ObjcForwardDecls.count(ClassDecl)) {
557 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000558 ResultStr += "#ifndef _REWRITER_typedef_";
559 ResultStr += ClassDecl->getName();
560 ResultStr += "\n";
561 ResultStr += "#define _REWRITER_typedef_";
562 ResultStr += ClassDecl->getName();
563 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000564 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000565 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000566 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000567
568 // Mark this typedef as having been generated.
569 ObjcForwardDecls.insert(ClassDecl);
570 }
Steve Narofff908a872007-10-30 02:23:23 +0000571 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
572
Steve Naroff2feac5e2007-10-30 03:43:13 +0000573 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000574 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000575 RewriteProperties(ClassDecl->getNumPropertyDecl(),
576 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000577 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
578 ClassDecl->getInstanceMethods());
579 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
580 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000581
Steve Naroff2feac5e2007-10-30 03:43:13 +0000582 // Lastly, comment out the @end.
583 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000584}
585
Chris Lattnerf04da132007-10-24 17:06:59 +0000586//===----------------------------------------------------------------------===//
587// Function Body / Expression rewriting
588//===----------------------------------------------------------------------===//
589
Steve Narofff3473a72007-11-09 15:20:18 +0000590Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000591 // Otherwise, just rewrite all children.
592 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
593 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000594 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000595 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000596 if (newStmt)
597 *CI = newStmt;
598 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000599
600 // Handle specific things.
601 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
602 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000603
604 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
605 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000606
607 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
608 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000609
Steve Naroff934f2762007-10-24 22:48:43 +0000610 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
611 // Before we rewrite it, put the original message expression in a comment.
612 SourceLocation startLoc = MessExpr->getLocStart();
613 SourceLocation endLoc = MessExpr->getLocEnd();
614
615 const char *startBuf = SM->getCharacterData(startLoc);
616 const char *endBuf = SM->getCharacterData(endLoc);
617
618 std::string messString;
619 messString += "// ";
620 messString.append(startBuf, endBuf-startBuf+1);
621 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000622
Steve Naroff934f2762007-10-24 22:48:43 +0000623 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
624 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
625 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000626 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000627 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000628 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000629
630 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
631 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000632
633 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
634 return RewriteObjcThrowStmt(StmtThrow);
635
Chris Lattnere64b7772007-10-24 16:57:36 +0000636 // Return this stmt unmodified.
637 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000638}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000639
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000640Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000641 // Get the start location and compute the semi location.
642 SourceLocation startLoc = S->getLocStart();
643 const char *startBuf = SM->getCharacterData(startLoc);
644
645 assert((*startBuf == '@') && "bogus @try location");
646
647 std::string buf;
648 // declare a new scope with two variables, _stack and _rethrow.
649 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
650 buf += "int buf[18/*32-bit i386*/];\n";
651 buf += "char *pointers[4];} _stack;\n";
652 buf += "id volatile _rethrow = 0;\n";
653 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000654 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000655
656 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
657
658 startLoc = S->getTryBody()->getLocEnd();
659 startBuf = SM->getCharacterData(startLoc);
660
661 assert((*startBuf == '}') && "bogus @try block");
662
663 SourceLocation lastCurlyLoc = startLoc;
664
665 startLoc = startLoc.getFileLocWithOffset(1);
666 buf = " /* @catch begin */ else {\n";
667 buf += " id _caught = objc_exception_extract(&_stack);\n";
668 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000669 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000670 buf += " _rethrow = objc_exception_extract(&_stack);\n";
671 buf += " else { /* @catch continue */";
672
Chris Lattner28d1fe82007-11-08 04:41:51 +0000673 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000674
675 bool sawIdTypedCatch = false;
676 Stmt *lastCatchBody = 0;
677 ObjcAtCatchStmt *catchList = S->getCatchStmts();
678 while (catchList) {
679 Stmt *catchStmt = catchList->getCatchParamStmt();
680
681 if (catchList == S->getCatchStmts())
682 buf = "if ("; // we are generating code for the first catch clause
683 else
684 buf = "else if (";
685 startLoc = catchList->getLocStart();
686 startBuf = SM->getCharacterData(startLoc);
687
688 assert((*startBuf == '@') && "bogus @catch location");
689
690 const char *lParenLoc = strchr(startBuf, '(');
691
692 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
693 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
694 if (t == Context->getObjcIdType()) {
695 buf += "1) { ";
696 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
697 buf.c_str(), buf.size());
698 sawIdTypedCatch = true;
699 } else if (const PointerType *pType = t->getAsPointerType()) {
700 ObjcInterfaceType *cls; // Should be a pointer to a class.
701
702 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
703 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000704 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000705 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000706 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000707 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
708 buf.c_str(), buf.size());
709 }
710 }
711 // Now rewrite the body...
712 lastCatchBody = catchList->getCatchBody();
713 SourceLocation rParenLoc = catchList->getRParenLoc();
714 SourceLocation bodyLoc = lastCatchBody->getLocStart();
715 const char *bodyBuf = SM->getCharacterData(bodyLoc);
716 const char *rParenBuf = SM->getCharacterData(rParenLoc);
717 assert((*rParenBuf == ')') && "bogus @catch paren location");
718 assert((*bodyBuf == '{') && "bogus @catch body location");
719
720 buf = " = _caught;";
721 // Here we replace ") {" with "= _caught;" (which initializes and
722 // declares the @catch parameter).
723 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
724 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000725 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000726 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000727 }
Steve Naroff75730982007-11-07 04:08:17 +0000728 catchList = catchList->getNextCatchStmt();
729 }
730 // Complete the catch list...
731 if (lastCatchBody) {
732 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
733 const char *bodyBuf = SM->getCharacterData(bodyLoc);
734 assert((*bodyBuf == '}') && "bogus @catch body location");
735 bodyLoc = bodyLoc.getFileLocWithOffset(1);
736 buf = " } } /* @catch end */\n";
737
Chris Lattner28d1fe82007-11-08 04:41:51 +0000738 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000739
740 // Set lastCurlyLoc
741 lastCurlyLoc = lastCatchBody->getLocEnd();
742 }
743 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
744 startLoc = finalStmt->getLocStart();
745 startBuf = SM->getCharacterData(startLoc);
746 assert((*startBuf == '@') && "bogus @finally start");
747
748 buf = "/* @finally */";
749 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
750
751 Stmt *body = finalStmt->getFinallyBody();
752 SourceLocation startLoc = body->getLocStart();
753 SourceLocation endLoc = body->getLocEnd();
754 const char *startBuf = SM->getCharacterData(startLoc);
755 const char *endBuf = SM->getCharacterData(endLoc);
756 assert((*startBuf == '{') && "bogus @finally body location");
757 assert((*endBuf == '}') && "bogus @finally body location");
758
759 startLoc = startLoc.getFileLocWithOffset(1);
760 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000761 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000762 endLoc = endLoc.getFileLocWithOffset(-1);
763 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000764 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000765
766 // Set lastCurlyLoc
767 lastCurlyLoc = body->getLocEnd();
768 }
769 // Now emit the final closing curly brace...
770 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
771 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000772 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000773 return 0;
774}
775
776Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
777 return 0;
778}
779
780Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
781 return 0;
782}
783
Steve Naroff2bd03922007-11-07 15:32:26 +0000784// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
785// the throw expression is typically a message expression that's already
786// been rewritten! (which implies the SourceLocation's are invalid).
787Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
788 // Get the start location and compute the semi location.
789 SourceLocation startLoc = S->getLocStart();
790 const char *startBuf = SM->getCharacterData(startLoc);
791
792 assert((*startBuf == '@') && "bogus @throw location");
793
794 std::string buf;
795 /* void objc_exception_throw(id) __attribute__((noreturn)); */
796 buf = "objc_exception_throw(";
797 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
798 const char *semiBuf = strchr(startBuf, ';');
799 assert((*semiBuf == ';') && "@throw: can't find ';'");
800 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
801 buf = ");";
802 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
803 return 0;
804}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000805
Chris Lattnere64b7772007-10-24 16:57:36 +0000806Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000807 // Create a new string expression.
808 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000809 std::string StrEncoding;
810 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
811 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
812 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000813 SourceLocation(), SourceLocation());
814 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000815 delete Exp;
816 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000817}
818
Steve Naroffb42f8412007-11-05 14:50:49 +0000819Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
820 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
821 // Create a call to sel_registerName("selName").
822 llvm::SmallVector<Expr*, 8> SelExprs;
823 QualType argType = Context->getPointerType(Context->CharTy);
824 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
825 Exp->getSelector().getName().size(),
826 false, argType, SourceLocation(),
827 SourceLocation()));
828 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
829 &SelExprs[0], SelExprs.size());
830 Rewrite.ReplaceStmt(Exp, SelExp);
831 delete Exp;
832 return SelExp;
833}
834
Steve Naroff934f2762007-10-24 22:48:43 +0000835CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
836 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000837 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000838 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000839
840 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000841 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000842
843 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000844 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000845 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
846
847 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000848
Steve Naroff934f2762007-10-24 22:48:43 +0000849 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
850}
851
Steve Naroffd5255f52007-11-01 13:24:47 +0000852static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
853 const char *&startRef, const char *&endRef) {
854 while (startBuf < endBuf) {
855 if (*startBuf == '<')
856 startRef = startBuf; // mark the start.
857 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000858 if (startRef && *startRef == '<') {
859 endRef = startBuf; // mark the end.
860 return true;
861 }
862 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000863 }
864 startBuf++;
865 }
866 return false;
867}
868
869bool RewriteTest::needToScanForQualifiers(QualType T) {
870 // FIXME: we don't currently represent "id <Protocol>" in the type system.
871 if (T == Context->getObjcIdType())
872 return true;
873
874 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000875 Type *pointeeType = pType->getPointeeType().getTypePtr();
876 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
877 return true; // we have "Class <Protocol> *".
878 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000879 return false;
880}
881
882void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
883 const FunctionTypeProto *proto, FunctionDecl *FD) {
884
885 if (needToScanForQualifiers(proto->getResultType())) {
886 // Since types are unique, we need to scan the buffer.
887 SourceLocation Loc = FD->getLocation();
888
889 const char *endBuf = SM->getCharacterData(Loc);
890 const char *startBuf = endBuf;
891 while (*startBuf != ';')
892 startBuf--; // scan backward (from the decl location) for return type.
893 const char *startRef = 0, *endRef = 0;
894 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
895 // Get the locations of the startRef, endRef.
896 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
897 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
898 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000899 Rewrite.InsertText(LessLoc, "/*", 2);
900 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000901 }
902 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000903 // Now check arguments.
904 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
905 if (needToScanForQualifiers(proto->getArgType(i))) {
906 // Since types are unique, we need to scan the buffer.
907 SourceLocation Loc = FD->getLocation();
908
909 const char *startBuf = SM->getCharacterData(Loc);
910 const char *endBuf = startBuf;
911 while (*endBuf != ';')
912 endBuf++; // scan forward (from the decl location) for argument types.
913 const char *startRef = 0, *endRef = 0;
914 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
915 // Get the locations of the startRef, endRef.
916 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
917 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
918 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000919 Rewrite.InsertText(LessLoc, "/*", 2);
920 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000921 }
922 }
923 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000924}
925
Steve Naroff09b266e2007-10-30 23:14:51 +0000926void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
927 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000928 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000929 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000930 return;
931 }
932 // Check for ObjC 'id' and class types that have been adorned with protocol
933 // information (id<p>, C<p>*). The protocol references need to be rewritten!
934 const FunctionType *funcType = FD->getType()->getAsFunctionType();
935 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000936 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
937 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000938}
939
940// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
941void RewriteTest::SynthMsgSendFunctionDecl() {
942 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
943 llvm::SmallVector<QualType, 16> ArgTys;
944 QualType argT = Context->getObjcIdType();
945 assert(!argT.isNull() && "Can't find 'id' type");
946 ArgTys.push_back(argT);
947 argT = Context->getObjcSelType();
948 assert(!argT.isNull() && "Can't find 'SEL' type");
949 ArgTys.push_back(argT);
950 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
951 &ArgTys[0], ArgTys.size(),
952 true /*isVariadic*/);
953 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
954 msgSendIdent, msgSendType,
955 FunctionDecl::Extern, false, 0);
956}
957
958// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
959void RewriteTest::SynthGetClassFunctionDecl() {
960 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
961 llvm::SmallVector<QualType, 16> ArgTys;
962 ArgTys.push_back(Context->getPointerType(
963 Context->CharTy.getQualifiedType(QualType::Const)));
964 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
965 &ArgTys[0], ArgTys.size(),
966 false /*isVariadic*/);
967 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
968 getClassIdent, getClassType,
969 FunctionDecl::Extern, false, 0);
970}
971
Steve Naroff96984642007-11-08 14:30:50 +0000972// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
973void RewriteTest::SynthCFStringFunctionDecl() {
974 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
975 llvm::SmallVector<QualType, 16> ArgTys;
976 ArgTys.push_back(Context->getPointerType(
977 Context->CharTy.getQualifiedType(QualType::Const)));
978 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
979 &ArgTys[0], ArgTys.size(),
980 false /*isVariadic*/);
981 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
982 getClassIdent, getClassType,
983 FunctionDecl::Extern, false, 0);
984}
985
Steve Naroffbeaf2992007-11-03 11:27:19 +0000986Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000987#if 1
988 // This rewrite is specific to GCC, which has builtin support for CFString.
989 if (!CFStringFunctionDecl)
990 SynthCFStringFunctionDecl();
991 // Create a call to __builtin___CFStringMakeConstantString("cstr").
992 llvm::SmallVector<Expr*, 8> StrExpr;
993 StrExpr.push_back(Exp->getString());
994 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
995 &StrExpr[0], StrExpr.size());
996 // cast to NSConstantString *
997 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
998 Rewrite.ReplaceStmt(Exp, cast);
999 delete Exp;
1000 return cast;
1001#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001002 assert(ConstantStringClassReference && "Can't find constant string reference");
1003 llvm::SmallVector<Expr*, 4> InitExprs;
1004
1005 // Synthesize "(Class)&_NSConstantStringClassReference"
1006 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1007 ConstantStringClassReference->getType(),
1008 SourceLocation());
1009 QualType expType = Context->getPointerType(ClsRef->getType());
1010 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1011 expType, SourceLocation());
1012 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1013 SourceLocation());
1014 InitExprs.push_back(cast); // set the 'isa'.
1015 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1016 unsigned IntSize = static_cast<unsigned>(
1017 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1018 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1019 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1020 Exp->getLocStart());
1021 InitExprs.push_back(len); // set "int numBytes".
1022
1023 // struct NSConstantString
1024 QualType CFConstantStrType = Context->getCFConstantStringType();
1025 // (struct NSConstantString) { <exprs from above> }
1026 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1027 &InitExprs[0], InitExprs.size(),
1028 SourceLocation());
1029 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1030 // struct NSConstantString *
1031 expType = Context->getPointerType(StrRep->getType());
1032 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1033 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001034 // cast to NSConstantString *
1035 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001036 Rewrite.ReplaceStmt(Exp, cast);
1037 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001038 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001039#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001040}
1041
Steve Naroff934f2762007-10-24 22:48:43 +00001042Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001043 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001044 if (!MsgSendFunctionDecl)
1045 SynthMsgSendFunctionDecl();
1046 if (!GetClassFunctionDecl)
1047 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001048
1049 // Synthesize a call to objc_msgSend().
1050 llvm::SmallVector<Expr*, 8> MsgExprs;
1051 IdentifierInfo *clsName = Exp->getClassName();
1052
1053 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1054 if (clsName) { // class message.
1055 llvm::SmallVector<Expr*, 8> ClsExprs;
1056 QualType argType = Context->getPointerType(Context->CharTy);
1057 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1058 clsName->getLength(),
1059 false, argType, SourceLocation(),
1060 SourceLocation()));
1061 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1062 &ClsExprs[0], ClsExprs.size());
1063 MsgExprs.push_back(Cls);
1064 } else // instance message.
1065 MsgExprs.push_back(Exp->getReceiver());
1066
Steve Naroffbeaf2992007-11-03 11:27:19 +00001067 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001068 llvm::SmallVector<Expr*, 8> SelExprs;
1069 QualType argType = Context->getPointerType(Context->CharTy);
1070 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1071 Exp->getSelector().getName().size(),
1072 false, argType, SourceLocation(),
1073 SourceLocation()));
1074 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1075 &SelExprs[0], SelExprs.size());
1076 MsgExprs.push_back(SelExp);
1077
1078 // Now push any user supplied arguments.
1079 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1080 MsgExprs.push_back(Exp->getArg(i));
1081 // We've transferred the ownership to MsgExprs. Null out the argument in
1082 // the original expression, since we will delete it below.
1083 Exp->setArg(i, 0);
1084 }
Steve Naroffab972d32007-11-04 22:37:50 +00001085 // Generate the funky cast.
1086 CastExpr *cast;
1087 llvm::SmallVector<QualType, 8> ArgTypes;
1088 QualType returnType;
1089
1090 // Push 'id' and 'SEL', the 2 implicit arguments.
1091 ArgTypes.push_back(Context->getObjcIdType());
1092 ArgTypes.push_back(Context->getObjcSelType());
1093 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1094 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001095 for (int i = 0; i < mDecl->getNumParams(); i++) {
1096 QualType t = mDecl->getParamDecl(i)->getType();
1097 if (t == Context->getObjcClassType())
1098 t = Context->getObjcIdType(); // Convert "Class"->"id"
1099 ArgTypes.push_back(t);
1100 }
Steve Naroffab972d32007-11-04 22:37:50 +00001101 returnType = mDecl->getResultType();
1102 } else {
1103 returnType = Context->getObjcIdType();
1104 }
1105 // Get the type, we will need to reference it in a couple spots.
1106 QualType msgSendType = MsgSendFunctionDecl->getType();
1107
1108 // Create a reference to the objc_msgSend() declaration.
1109 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1110
1111 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1112 // If we don't do this cast, we get the following bizarre warning/note:
1113 // xx.m:13: warning: function called through a non-compatible type
1114 // xx.m:13: note: if this code is reached, the program will abort
1115 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1116 SourceLocation());
1117
1118 // Now do the "normal" pointer to function cast.
1119 QualType castType = Context->getFunctionType(returnType,
1120 &ArgTypes[0], ArgTypes.size(),
1121 false/*FIXME:variadic*/);
1122 castType = Context->getPointerType(castType);
1123 cast = new CastExpr(castType, cast, SourceLocation());
1124
1125 // Don't forget the parens to enforce the proper binding.
1126 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1127
1128 const FunctionType *FT = msgSendType->getAsFunctionType();
1129 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1130 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001131 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001132 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001133
Chris Lattnere64b7772007-10-24 16:57:36 +00001134 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001135 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001136}
1137
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001138/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1139/// an objective-c class with ivars.
1140void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1141 std::string &Result) {
1142 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1143 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001144 // Do not synthesize more than once.
1145 if (ObjcSynthesizedStructs.count(CDecl))
1146 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001147 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1148 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1149 // Do it for the root
1150 SynthesizeObjcInternalStruct(RCDecl, Result);
1151 }
1152
Steve Naroff03300712007-11-12 13:56:41 +00001153 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001154 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001155 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001156 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1157 return;
1158
Steve Naroff04960052007-11-01 17:12:31 +00001159 Result += "\nstruct ";
1160 Result += CDecl->getName();
1161 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1162 Result += " {\n struct ";
1163 Result += RCDecl->getName();
1164 Result += " _";
1165 Result += RCDecl->getName();
1166 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001167 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001168 else
1169 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +00001170
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001171 if (NumIvars > 0) {
1172 SourceLocation LocStart = CDecl->getLocStart();
1173 SourceLocation LocEnd = CDecl->getLocEnd();
1174
1175 const char *startBuf = SM->getCharacterData(LocStart);
1176 const char *endBuf = SM->getCharacterData(LocEnd);
1177 startBuf = strchr(startBuf, '{');
1178 assert((startBuf && endBuf)
1179 && "SynthesizeObjcInternalStruct - malformed @interface");
1180 startBuf++; // past '{'
1181 while (startBuf < endBuf) {
1182 if (*startBuf == '@') {
1183 startBuf = strchr(startBuf, 'p');
1184 // FIXME: presence of @public, etc. inside comment results in
1185 // this transformation as well, which is still correct c-code.
1186 if (!strncmp(startBuf, "public", strlen("public"))) {
1187 startBuf += strlen("public");
1188 Result += "/* @public */";
1189 }
1190 else if (!strncmp(startBuf, "private", strlen("private"))) {
1191 startBuf += strlen("private");
1192 Result += "/* @private */";
1193 }
1194 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1195 startBuf += strlen("protected");
1196 Result += "/* @protected */";
1197 }
1198 }
1199 Result += *startBuf++;
1200 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001201 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001202
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001203 Result += "};\n";
1204 // Mark this struct as having been generated.
1205 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001206 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001207}
1208
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001209// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1210/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001211void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001212 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001213 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001214 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001215 const char *ClassName,
1216 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001217 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001218 if (NumMethods > 0 && !objc_impl_method) {
1219 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001220 SEL _cmd;
1221 char *method_types;
1222 void *_imp;
1223 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001224 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001225 Result += "\nstruct _objc_method {\n";
1226 Result += "\tSEL _cmd;\n";
1227 Result += "\tchar *method_types;\n";
1228 Result += "\tvoid *_imp;\n";
1229 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001230
1231 /* struct _objc_method_list {
1232 struct _objc_method_list *next_method;
1233 int method_count;
1234 struct _objc_method method_list[];
1235 }
1236 */
1237 Result += "\nstruct _objc_method_list {\n";
1238 Result += "\tstruct _objc_method_list *next_method;\n";
1239 Result += "\tint method_count;\n";
1240 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001241 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001242 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001243 // Build _objc_method_list for class's methods if needed
1244 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001245 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001246 Result += prefix;
1247 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1248 Result += "_METHODS_";
1249 Result += ClassName;
1250 Result += " __attribute__ ((section (\"__OBJC, __";
1251 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001252 Result += "_meth\")))= ";
1253 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1254
1255 Result += "\t,{{(SEL)\"";
1256 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001257 std::string MethodTypeString;
1258 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1259 Result += "\", \"";
1260 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001261 Result += "\", ";
1262 Result += MethodInternalNames[Methods[0]];
1263 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001264 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001265 Result += "\t ,{(SEL)\"";
1266 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001267 std::string MethodTypeString;
1268 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1269 Result += "\", \"";
1270 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001271 Result += "\", ";
1272 Result += MethodInternalNames[Methods[i]];
1273 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001274 }
1275 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001276 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001277}
1278
1279/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1280void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1281 int NumProtocols,
1282 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001283 const char *ClassName,
1284 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001285 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001286 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001287 for (int i = 0; i < NumProtocols; i++) {
1288 ObjcProtocolDecl *PDecl = Protocols[i];
1289 // Output struct protocol_methods holder of method selector and type.
1290 if (!objc_protocol_methods &&
1291 (PDecl->getNumInstanceMethods() > 0
1292 || PDecl->getNumClassMethods() > 0)) {
1293 /* struct protocol_methods {
1294 SEL _cmd;
1295 char *method_types;
1296 }
1297 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001298 Result += "\nstruct protocol_methods {\n";
1299 Result += "\tSEL _cmd;\n";
1300 Result += "\tchar *method_types;\n";
1301 Result += "};\n";
1302
1303 /* struct _objc_protocol_method_list {
1304 int protocol_method_count;
1305 struct protocol_methods protocols[];
1306 }
1307 */
1308 Result += "\nstruct _objc_protocol_method_list {\n";
1309 Result += "\tint protocol_method_count;\n";
1310 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001311 objc_protocol_methods = true;
1312 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001313
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001314 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001315 int NumMethods = PDecl->getNumInstanceMethods();
1316 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001317 Result += "\nstatic struct _objc_protocol_method_list "
1318 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1319 Result += PDecl->getName();
1320 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1321 "{\n\t" + utostr(NumMethods) + "\n";
1322
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001323 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001324 Result += "\t,{{(SEL)\"";
1325 Result += Methods[0]->getSelector().getName().c_str();
1326 Result += "\", \"\"}\n";
1327
1328 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001329 Result += "\t ,{(SEL)\"";
1330 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001331 std::string MethodTypeString;
1332 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1333 Result += "\", \"";
1334 Result += MethodTypeString;
1335 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001336 }
1337 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001338 }
1339
1340 // Output class methods declared in this protocol.
1341 NumMethods = PDecl->getNumClassMethods();
1342 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001343 Result += "\nstatic struct _objc_protocol_method_list "
1344 "_OBJC_PROTOCOL_CLASS_METHODS_";
1345 Result += PDecl->getName();
1346 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1347 "{\n\t";
1348 Result += utostr(NumMethods);
1349 Result += "\n";
1350
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001351 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001352 Result += "\t,{{(SEL)\"";
1353 Result += Methods[0]->getSelector().getName().c_str();
1354 Result += "\", \"\"}\n";
1355
1356 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001357 Result += "\t ,{(SEL)\"";
1358 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001359 std::string MethodTypeString;
1360 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1361 Result += "\", \"";
1362 Result += MethodTypeString;
1363 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001364 }
1365 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001366 }
1367 // Output:
1368 /* struct _objc_protocol {
1369 // Objective-C 1.0 extensions
1370 struct _objc_protocol_extension *isa;
1371 char *protocol_name;
1372 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001373 struct _objc_protocol_method_list *instance_methods;
1374 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001375 };
1376 */
1377 static bool objc_protocol = false;
1378 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001379 Result += "\nstruct _objc_protocol {\n";
1380 Result += "\tstruct _objc_protocol_extension *isa;\n";
1381 Result += "\tchar *protocol_name;\n";
1382 Result += "\tstruct _objc_protocol **protocol_list;\n";
1383 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1384 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1385 Result += "};\n";
1386
1387 /* struct _objc_protocol_list {
1388 struct _objc_protocol_list *next;
1389 int protocol_count;
1390 struct _objc_protocol *class_protocols[];
1391 }
1392 */
1393 Result += "\nstruct _objc_protocol_list {\n";
1394 Result += "\tstruct _objc_protocol_list *next;\n";
1395 Result += "\tint protocol_count;\n";
1396 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1397 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001398 objc_protocol = true;
1399 }
1400
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001401 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1402 Result += PDecl->getName();
1403 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1404 "{\n\t0, \"";
1405 Result += PDecl->getName();
1406 Result += "\", 0, ";
1407 if (PDecl->getInstanceMethods() > 0) {
1408 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1409 Result += PDecl->getName();
1410 Result += ", ";
1411 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001412 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001413 Result += "0, ";
1414 if (PDecl->getClassMethods() > 0) {
1415 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1416 Result += PDecl->getName();
1417 Result += "\n";
1418 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001419 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001420 Result += "0\n";
1421 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001422 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001423 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001424 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1425 Result += prefix;
1426 Result += "_PROTOCOLS_";
1427 Result += ClassName;
1428 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1429 "{\n\t0, ";
1430 Result += utostr(NumProtocols);
1431 Result += "\n";
1432
1433 Result += "\t,{&_OBJC_PROTOCOL_";
1434 Result += Protocols[0]->getName();
1435 Result += " \n";
1436
1437 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001438 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001439 Result += "\t ,&_OBJC_PROTOCOL_";
1440 Result += PDecl->getName();
1441 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001442 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001443 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001444 }
1445}
1446
1447/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1448/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001449void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1450 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001451 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1452 // Find category declaration for this implementation.
1453 ObjcCategoryDecl *CDecl;
1454 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1455 CDecl = CDecl->getNextClassCategory())
1456 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1457 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001458
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001459 char *FullCategoryName = (char*)alloca(
1460 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1461 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1462
1463 // Build _objc_method_list for class's instance methods if needed
1464 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1465 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001466 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001467 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001468
1469 // Build _objc_method_list for class's class methods if needed
1470 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1471 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001472 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001473 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001474
1475 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001476 // Null CDecl is case of a category implementation with no category interface
1477 if (CDecl)
1478 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1479 CDecl->getNumReferencedProtocols(),
1480 "CATEGORY",
1481 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001482
1483 /* struct _objc_category {
1484 char *category_name;
1485 char *class_name;
1486 struct _objc_method_list *instance_methods;
1487 struct _objc_method_list *class_methods;
1488 struct _objc_protocol_list *protocols;
1489 // Objective-C 1.0 extensions
1490 uint32_t size; // sizeof (struct _objc_category)
1491 struct _objc_property_list *instance_properties; // category's own
1492 // @property decl.
1493 };
1494 */
1495
1496 static bool objc_category = false;
1497 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001498 Result += "\nstruct _objc_category {\n";
1499 Result += "\tchar *category_name;\n";
1500 Result += "\tchar *class_name;\n";
1501 Result += "\tstruct _objc_method_list *instance_methods;\n";
1502 Result += "\tstruct _objc_method_list *class_methods;\n";
1503 Result += "\tstruct _objc_protocol_list *protocols;\n";
1504 Result += "\tunsigned int size;\n";
1505 Result += "\tstruct _objc_property_list *instance_properties;\n";
1506 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001507 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001508 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001509 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1510 Result += FullCategoryName;
1511 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1512 Result += IDecl->getName();
1513 Result += "\"\n\t, \"";
1514 Result += ClassDecl->getName();
1515 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001516
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001517 if (IDecl->getNumInstanceMethods() > 0) {
1518 Result += "\t, (struct _objc_method_list *)"
1519 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1520 Result += FullCategoryName;
1521 Result += "\n";
1522 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001523 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001524 Result += "\t, 0\n";
1525 if (IDecl->getNumClassMethods() > 0) {
1526 Result += "\t, (struct _objc_method_list *)"
1527 "&_OBJC_CATEGORY_CLASS_METHODS_";
1528 Result += FullCategoryName;
1529 Result += "\n";
1530 }
1531 else
1532 Result += "\t, 0\n";
1533
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001534 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001535 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1536 Result += FullCategoryName;
1537 Result += "\n";
1538 }
1539 else
1540 Result += "\t, 0\n";
1541 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001542}
1543
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001544/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1545/// ivar offset.
1546void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1547 ObjcIvarDecl *ivar,
1548 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001549 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001550 Result += IDecl->getName();
1551 Result += ", ";
1552 Result += ivar->getName();
1553 Result += ")";
1554}
1555
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001556//===----------------------------------------------------------------------===//
1557// Meta Data Emission
1558//===----------------------------------------------------------------------===//
1559
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001560void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1561 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001562 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1563
1564 // Build _objc_ivar_list metadata for classes ivars if needed
1565 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1566 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001567 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001568
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001569 SynthesizeObjcInternalStruct(CDecl, Result);
1570
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001571 if (NumIvars > 0) {
1572 static bool objc_ivar = false;
1573 if (!objc_ivar) {
1574 /* struct _objc_ivar {
1575 char *ivar_name;
1576 char *ivar_type;
1577 int ivar_offset;
1578 };
1579 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001580 Result += "\nstruct _objc_ivar {\n";
1581 Result += "\tchar *ivar_name;\n";
1582 Result += "\tchar *ivar_type;\n";
1583 Result += "\tint ivar_offset;\n";
1584 Result += "};\n";
1585
1586 /* struct _objc_ivar_list {
1587 int ivar_count;
1588 struct _objc_ivar ivar_list[];
1589 };
1590 */
1591 Result += "\nstruct _objc_ivar_list {\n";
1592 Result += "\tint ivar_count;\n";
1593 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001594 objc_ivar = true;
1595 }
1596
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001597 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1598 Result += IDecl->getName();
1599 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1600 "{\n\t";
1601 Result += utostr(NumIvars);
1602 Result += "\n";
1603
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001604 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1605 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001606 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001607 Result += "\t,{{\"";
1608 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001609 Result += "\", \"";
1610 std::string StrEncoding;
1611 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1612 Result += StrEncoding;
1613 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001614 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1615 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001616 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001617 Result += "\t ,{\"";
1618 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001619 Result += "\", \"";
1620 std::string StrEncoding;
1621 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1622 Result += StrEncoding;
1623 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001624 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1625 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001626 }
1627
1628 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001629 }
1630
1631 // Build _objc_method_list for class's instance methods if needed
1632 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1633 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001634 true,
1635 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001636
1637 // Build _objc_method_list for class's class methods if needed
1638 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001639 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001640 false,
1641 "", IDecl->getName(), Result);
1642
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001643 // Protocols referenced in class declaration?
1644 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1645 CDecl->getNumIntfRefProtocols(),
1646 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001647 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001648
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001649
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001650 // Declaration of class/meta-class metadata
1651 /* struct _objc_class {
1652 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001653 const char *super_class_name;
1654 char *name;
1655 long version;
1656 long info;
1657 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001658 struct _objc_ivar_list *ivars;
1659 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001660 struct objc_cache *cache;
1661 struct objc_protocol_list *protocols;
1662 const char *ivar_layout;
1663 struct _objc_class_ext *ext;
1664 };
1665 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001666 static bool objc_class = false;
1667 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001668 Result += "\nstruct _objc_class {\n";
1669 Result += "\tstruct _objc_class *isa;\n";
1670 Result += "\tconst char *super_class_name;\n";
1671 Result += "\tchar *name;\n";
1672 Result += "\tlong version;\n";
1673 Result += "\tlong info;\n";
1674 Result += "\tlong instance_size;\n";
1675 Result += "\tstruct _objc_ivar_list *ivars;\n";
1676 Result += "\tstruct _objc_method_list *methods;\n";
1677 Result += "\tstruct objc_cache *cache;\n";
1678 Result += "\tstruct _objc_protocol_list *protocols;\n";
1679 Result += "\tconst char *ivar_layout;\n";
1680 Result += "\tstruct _objc_class_ext *ext;\n";
1681 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001682 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001683 }
1684
1685 // Meta-class metadata generation.
1686 ObjcInterfaceDecl *RootClass = 0;
1687 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1688 while (SuperClass) {
1689 RootClass = SuperClass;
1690 SuperClass = SuperClass->getSuperClass();
1691 }
1692 SuperClass = CDecl->getSuperClass();
1693
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001694 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1695 Result += CDecl->getName();
1696 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1697 "{\n\t(struct _objc_class *)\"";
1698 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1699 Result += "\"";
1700
1701 if (SuperClass) {
1702 Result += ", \"";
1703 Result += SuperClass->getName();
1704 Result += "\", \"";
1705 Result += CDecl->getName();
1706 Result += "\"";
1707 }
1708 else {
1709 Result += ", 0, \"";
1710 Result += CDecl->getName();
1711 Result += "\"";
1712 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001713 // TODO: 'ivars' field for root class is currently set to 0.
1714 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001715 Result += ", 0,2, sizeof(struct _objc_class), 0";
1716 if (CDecl->getNumClassMethods() > 0) {
1717 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1718 Result += CDecl->getName();
1719 Result += "\n";
1720 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001721 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001722 Result += ", 0\n";
1723 if (CDecl->getNumIntfRefProtocols() > 0) {
1724 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1725 Result += CDecl->getName();
1726 Result += ",0,0\n";
1727 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001728 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001729 Result += "\t,0,0,0,0\n";
1730 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001731
1732 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001733 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1734 Result += CDecl->getName();
1735 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1736 "{\n\t&_OBJC_METACLASS_";
1737 Result += CDecl->getName();
1738 if (SuperClass) {
1739 Result += ", \"";
1740 Result += SuperClass->getName();
1741 Result += "\", \"";
1742 Result += CDecl->getName();
1743 Result += "\"";
1744 }
1745 else {
1746 Result += ", 0, \"";
1747 Result += CDecl->getName();
1748 Result += "\"";
1749 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001750 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001751 Result += ", 0,1";
1752 if (!ObjcSynthesizedStructs.count(CDecl))
1753 Result += ",0";
1754 else {
1755 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001756 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001757 Result += CDecl->getName();
1758 Result += ")";
1759 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001760 if (NumIvars > 0) {
1761 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1762 Result += CDecl->getName();
1763 Result += "\n\t";
1764 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001765 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001766 Result += ",0";
1767 if (IDecl->getNumInstanceMethods() > 0) {
1768 Result += ", &_OBJC_INSTANCE_METHODS_";
1769 Result += CDecl->getName();
1770 Result += ", 0\n\t";
1771 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001772 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001773 Result += ",0,0";
1774 if (CDecl->getNumIntfRefProtocols() > 0) {
1775 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1776 Result += CDecl->getName();
1777 Result += ", 0,0\n";
1778 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001779 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001780 Result += ",0,0,0\n";
1781 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001782}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001783
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001784/// RewriteImplementations - This routine rewrites all method implementations
1785/// and emits meta-data.
1786
1787void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001788 int ClsDefCount = ClassImplementation.size();
1789 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001790
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001791 if (ClsDefCount == 0 && CatDefCount == 0)
1792 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001793 // Rewrite implemented methods
1794 for (int i = 0; i < ClsDefCount; i++)
1795 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001796
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001797 for (int i = 0; i < CatDefCount; i++)
1798 RewriteImplementationDecl(CategoryImplementation[i]);
1799
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001800 // TODO: This is temporary until we decide how to access objc types in a
1801 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001802 Result += "#include <Objc/objc.h>\n";
1803 // This is needed for use of offsetof
1804 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001805
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001806 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001807 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001808 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001809
1810 // For each implemented category, write out all its meta data.
1811 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001812 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001813
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001814 // Write objc_symtab metadata
1815 /*
1816 struct _objc_symtab
1817 {
1818 long sel_ref_cnt;
1819 SEL *refs;
1820 short cls_def_cnt;
1821 short cat_def_cnt;
1822 void *defs[cls_def_cnt + cat_def_cnt];
1823 };
1824 */
1825
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001826 Result += "\nstruct _objc_symtab {\n";
1827 Result += "\tlong sel_ref_cnt;\n";
1828 Result += "\tSEL *refs;\n";
1829 Result += "\tshort cls_def_cnt;\n";
1830 Result += "\tshort cat_def_cnt;\n";
1831 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1832 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001833
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001834 Result += "static struct _objc_symtab "
1835 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1836 Result += "\t0, 0, " + utostr(ClsDefCount)
1837 + ", " + utostr(CatDefCount) + "\n";
1838 for (int i = 0; i < ClsDefCount; i++) {
1839 Result += "\t,&_OBJC_CLASS_";
1840 Result += ClassImplementation[i]->getName();
1841 Result += "\n";
1842 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001843
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001844 for (int i = 0; i < CatDefCount; i++) {
1845 Result += "\t,&_OBJC_CATEGORY_";
1846 Result += CategoryImplementation[i]->getClassInterface()->getName();
1847 Result += "_";
1848 Result += CategoryImplementation[i]->getName();
1849 Result += "\n";
1850 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001851
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001852 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001853
1854 // Write objc_module metadata
1855
1856 /*
1857 struct _objc_module {
1858 long version;
1859 long size;
1860 const char *name;
1861 struct _objc_symtab *symtab;
1862 }
1863 */
1864
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001865 Result += "\nstruct _objc_module {\n";
1866 Result += "\tlong version;\n";
1867 Result += "\tlong size;\n";
1868 Result += "\tconst char *name;\n";
1869 Result += "\tstruct _objc_symtab *symtab;\n";
1870 Result += "};\n\n";
1871 Result += "static struct _objc_module "
1872 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001873 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1874 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001875 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001876
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001877}
Chris Lattner311ff022007-10-16 22:36:42 +00001878