blob: 283f3602346e6826ee331164aa506e728189b4bd [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000037 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000038
39 FunctionDecl *MsgSendFunctionDecl;
40 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000041 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000042 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
Steve Naroffbeaf2992007-11-03 11:27:19 +000044 // ObjC string constant support.
45 FileVarDecl *ConstantStringClassReference;
46 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000047
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000048 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000049 public:
Chris Lattner01c57482007-10-17 22:35:30 +000050 void Initialize(ASTContext &context, unsigned mainFileID) {
51 Context = &context;
52 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000053 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000054 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000055 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000056 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000057 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000058 ConstantStringClassReference = 0;
59 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000060 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000061 // declaring objc_selector outside the parameter list removes a silly
62 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000063 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000064 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000065 "(struct objc_object *, struct objc_selector *, ...);\n"
66 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000067 "(const char *);\n"
68 "extern void objc_exception_throw(struct objc_object *);\n"
69 "extern void objc_exception_try_enter(void *);\n"
70 "extern void objc_exception_try_exit(void *);\n"
71 "extern struct objc_object *objc_exception_extract(void *);\n"
72 "extern int objc_exception_match"
73 "(struct objc_class *, struct objc_object *, ...);\n";
74
Steve Naroffab972d32007-11-04 22:37:50 +000075 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
76 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000077 }
Chris Lattner8a12c272007-10-11 18:38:32 +000078
Chris Lattnerf04da132007-10-24 17:06:59 +000079 // Top Level Driver code.
80 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000081 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000082 ~RewriteTest();
83
84 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000085 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000086 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000087 void RewriteTabs();
88 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000089 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +000090 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000091 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000092 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000093 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +000094 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +000095 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000096 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000097 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000098 void RewriteObjcQualifiedInterfaceTypes(
99 const FunctionTypeProto *proto, FunctionDecl *FD);
100 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +0000101
Chris Lattnerf04da132007-10-24 17:06:59 +0000102 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000103 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000104 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000105 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000106 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000107 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000108 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
109 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
110 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000111 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000112 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
113 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000114 void SynthMsgSendFunctionDecl();
115 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000116 void SynthCFStringFunctionDecl();
117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000119 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
120 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000121
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000122 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
123 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124
Steve Naroff0416fb92007-11-11 17:19:15 +0000125 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000126 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000127 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000128 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000129 const char *ClassName,
130 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000131
132 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
133 int NumProtocols,
134 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000135 const char *ClassName,
136 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000137 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
138 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000139 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
140 ObjcIvarDecl *ivar,
141 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000142 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000143 };
144}
145
Chris Lattner8a12c272007-10-11 18:38:32 +0000146ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000147
Chris Lattnerf04da132007-10-24 17:06:59 +0000148//===----------------------------------------------------------------------===//
149// Top Level Driver Code
150//===----------------------------------------------------------------------===//
151
Chris Lattner8a12c272007-10-11 18:38:32 +0000152void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000153 // Two cases: either the decl could be in the main file, or it could be in a
154 // #included file. If the former, rewrite it now. If the later, check to see
155 // if we rewrote the #include/#import.
156 SourceLocation Loc = D->getLocation();
157 Loc = SM->getLogicalLoc(Loc);
158
159 // If this is for a builtin, ignore it.
160 if (Loc.isInvalid()) return;
161
Steve Naroffebf2b562007-10-23 23:50:29 +0000162 // Look for built-in declarations that we need to refer during the rewrite.
163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000164 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000165 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
166 // declared in <Foundation/NSString.h>
167 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
168 ConstantStringClassReference = FVD;
169 return;
170 }
Steve Naroffbef11852007-10-26 20:53:56 +0000171 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
172 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000173 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
174 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000175 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
176 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000177 } else if (ObjcForwardProtocolDecl *FP =
178 dyn_cast<ObjcForwardProtocolDecl>(D)){
179 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000180 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000181 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000182 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
183 return HandleDeclInMainFile(D);
184
Chris Lattnerf04da132007-10-24 17:06:59 +0000185 // Otherwise, see if there is a #import in the main file that should be
186 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000187 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000188}
189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190/// HandleDeclInMainFile - This is called for each top-level decl defined in the
191/// main file of the input.
192void RewriteTest::HandleDeclInMainFile(Decl *D) {
193 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
194 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000195 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000196
197 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
198 if (Stmt *Body = MD->getBody())
199 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
200 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000201 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
202 ClassImplementation.push_back(CI);
203 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
204 CategoryImplementation.push_back(CI);
205 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
206 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000207 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
208 if (VD->getInit())
209 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
210 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000211 // Nothing yet.
212}
213
214RewriteTest::~RewriteTest() {
215 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000216
217 // Rewrite tabs if we care.
218 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000219
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000220 // Rewrite Objective-c meta data*
221 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000222 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000223
Chris Lattnerf04da132007-10-24 17:06:59 +0000224 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
225 // we are done.
226 if (const RewriteBuffer *RewriteBuf =
227 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000228 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000229 std::string S(RewriteBuf->begin(), RewriteBuf->end());
230 printf("%s\n", S.c_str());
231 } else {
232 printf("No changes\n");
233 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000234 // Emit metadata.
235 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000236}
237
Chris Lattnerf04da132007-10-24 17:06:59 +0000238//===----------------------------------------------------------------------===//
239// Syntactic (non-AST) Rewriting Code
240//===----------------------------------------------------------------------===//
241
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000242void RewriteTest::RewriteInclude(SourceLocation Loc) {
243 // Rip up the #include stack to the main file.
244 SourceLocation IncLoc = Loc, NextLoc = Loc;
245 do {
246 IncLoc = Loc;
247 Loc = SM->getLogicalLoc(NextLoc);
248 NextLoc = SM->getIncludeLoc(Loc);
249 } while (!NextLoc.isInvalid());
250
251 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
252 // IncLoc indicates the header that was included if it is useful.
253 IncLoc = SM->getLogicalLoc(IncLoc);
254 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
255 Loc == LastIncLoc)
256 return;
257 LastIncLoc = Loc;
258
259 unsigned IncCol = SM->getColumnNumber(Loc);
260 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
261
262 // Replace the #import with #include.
263 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
264}
265
Chris Lattnerf04da132007-10-24 17:06:59 +0000266void RewriteTest::RewriteTabs() {
267 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
268 const char *MainBufStart = MainBuf.first;
269 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000270
Chris Lattnerf04da132007-10-24 17:06:59 +0000271 // Loop over the whole file, looking for tabs.
272 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
273 if (*BufPtr != '\t')
274 continue;
275
276 // Okay, we found a tab. This tab will turn into at least one character,
277 // but it depends on which 'virtual column' it is in. Compute that now.
278 unsigned VCol = 0;
279 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
280 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
281 ++VCol;
282
283 // Okay, now that we know the virtual column, we know how many spaces to
284 // insert. We assume 8-character tab-stops.
285 unsigned Spaces = 8-(VCol & 7);
286
287 // Get the location of the tab.
288 SourceLocation TabLoc =
289 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
290
291 // Rewrite the single tab character into a sequence of spaces.
292 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
293 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000294}
295
296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
298 int numDecls = ClassDecl->getNumForwardDecls();
299 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
300
301 // Get the start location and compute the semi location.
302 SourceLocation startLoc = ClassDecl->getLocation();
303 const char *startBuf = SM->getCharacterData(startLoc);
304 const char *semiPtr = strchr(startBuf, ';');
305
306 // Translate to typedef's that forward reference structs with the same name
307 // as the class. As a convenience, we include the original declaration
308 // as a comment.
309 std::string typedefString;
310 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000311 typedefString.append(startBuf, semiPtr-startBuf+1);
312 typedefString += "\n";
313 for (int i = 0; i < numDecls; i++) {
314 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000315 if (ObjcForwardDecls.count(ForwardDecl))
316 continue;
Steve Naroff32174822007-11-09 12:50:28 +0000317 typedefString += "#ifndef _REWRITER_typedef_";
318 typedefString += ForwardDecl->getName();
319 typedefString += "\n";
320 typedefString += "#define _REWRITER_typedef_";
321 typedefString += ForwardDecl->getName();
322 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000323 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000324 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000325 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000326 // Mark this typedef as having been generated.
327 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000328 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000329 }
330
331 // Replace the @class with typedefs corresponding to the classes.
332 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
333 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000334}
335
Steve Naroff71c0a952007-11-13 23:01:27 +0000336void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000337 for (int i = 0; i < nMethods; i++) {
338 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000339 SourceLocation LocStart = Method->getLocStart();
340 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000341
Steve Naroff1d098f62007-11-14 14:34:23 +0000342 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
343 Rewrite.InsertText(LocStart, "/* ", 3);
344 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
345 } else {
346 Rewrite.InsertText(LocStart, "// ", 3);
347 }
Steve Naroff423cb562007-10-30 13:30:57 +0000348 }
349}
350
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000351void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
352{
353 for (int i = 0; i < nProperties; i++) {
354 ObjcPropertyDecl *Property = Properties[i];
355 SourceLocation Loc = Property->getLocation();
356
357 Rewrite.ReplaceText(Loc, 0, "// ", 3);
358
359 // FIXME: handle properties that are declared across multiple lines.
360 }
361}
362
Steve Naroff423cb562007-10-30 13:30:57 +0000363void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
364 SourceLocation LocStart = CatDecl->getLocStart();
365
366 // FIXME: handle category headers that are declared across multiple lines.
367 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
368
Steve Naroff71c0a952007-11-13 23:01:27 +0000369 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
370 CatDecl->getInstanceMethods());
371 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
372 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000373 // Lastly, comment out the @end.
374 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
375}
376
Steve Naroff752d6ef2007-10-30 16:42:30 +0000377void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000378 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
379 const char *MainBufStart = MainBuf.first;
380
Steve Naroff752d6ef2007-10-30 16:42:30 +0000381 SourceLocation LocStart = PDecl->getLocStart();
382
383 // FIXME: handle protocol headers that are declared across multiple lines.
384 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
385
Steve Naroff71c0a952007-11-13 23:01:27 +0000386 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
387 PDecl->getInstanceMethods());
388 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
389 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000390 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000391 SourceLocation LocEnd = PDecl->getAtEndLoc();
392 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffb7fa9922007-11-14 03:37:28 +0000393#if 0
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000394 // Must comment out @optional/@required
395 const char *startBuf = SM->getCharacterData(LocStart);
396 const char *endBuf = SM->getCharacterData(LocEnd);
397 for (const char *p = startBuf; p < endBuf; p++) {
398 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
399 std::string CommentedOptional = "/* @optional */";
400 SourceLocation OptionalLoc = SourceLocation::getFileLoc(MainFileID,
401 p-MainBufStart);
402 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
403 CommentedOptional.c_str(), CommentedOptional.size());
404
405 }
406 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
407 std::string CommentedRequired = "/* @required */";
408 SourceLocation OptionalLoc = SourceLocation::getFileLoc(MainFileID,
409 p-MainBufStart);
410 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
411 CommentedRequired.c_str(), CommentedRequired.size());
412
413 }
414 }
Steve Naroffb7fa9922007-11-14 03:37:28 +0000415#endif
Steve Naroff752d6ef2007-10-30 16:42:30 +0000416}
417
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000418void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
419 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000420 if (LocStart.isInvalid())
421 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000422 // FIXME: handle forward protocol that are declared across multiple lines.
423 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
424}
425
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000426void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
427 std::string &ResultStr) {
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000428 static bool includeObjc = false;
429 if (!includeObjc) {
430 ResultStr += "#include <Objc/objc.h>\n";
431 includeObjc = true;
432 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000433 ResultStr += "\nstatic ";
434 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000435 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000436
437 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000438 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000439
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000440 if (OMD->isInstance())
441 NameStr += "_I_";
442 else
443 NameStr += "_C_";
444
445 NameStr += OMD->getClassInterface()->getName();
446 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000447
448 NamedDecl *MethodContext = OMD->getMethodContext();
449 if (ObjcCategoryImplDecl *CID =
450 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000451 NameStr += CID->getName();
452 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000453 }
454 // Append selector names, replacing ':' with '_'
455 const char *selName = OMD->getSelector().getName().c_str();
456 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000457 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000458 else {
459 std::string selString = OMD->getSelector().getName();
460 int len = selString.size();
461 for (int i = 0; i < len; i++)
462 if (selString[i] == ':')
463 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000464 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000465 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000466 // Remember this name for metadata emission
467 MethodInternalNames[OMD] = NameStr;
468 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000469
470 // Rewrite arguments
471 ResultStr += "(";
472
473 // invisible arguments
474 if (OMD->isInstance()) {
475 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
476 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000477 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
478 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000479 ResultStr += selfTy.getAsString();
480 }
481 else
482 ResultStr += Context->getObjcIdType().getAsString();
483
484 ResultStr += " self, ";
485 ResultStr += Context->getObjcSelType().getAsString();
486 ResultStr += " _cmd";
487
488 // Method arguments.
489 for (int i = 0; i < OMD->getNumParams(); i++) {
490 ParmVarDecl *PDecl = OMD->getParamDecl(i);
491 ResultStr += ", ";
492 ResultStr += PDecl->getType().getAsString();
493 ResultStr += " ";
494 ResultStr += PDecl->getName();
495 }
496 ResultStr += ")";
497
498}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000499void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
500 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
501 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000502
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000503 if (IMD)
504 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
505 else
506 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000507
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000508 int numMethods = IMD ? IMD->getNumInstanceMethods()
509 : CID->getNumInstanceMethods();
510
511 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000512 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000513 ObjcMethodDecl *OMD;
514 if (IMD)
515 OMD = IMD->getInstanceMethods()[i];
516 else
517 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000518 RewriteObjcMethodDecl(OMD, ResultStr);
519 SourceLocation LocStart = OMD->getLocStart();
520 SourceLocation LocEnd = OMD->getBody()->getLocStart();
521
522 const char *startBuf = SM->getCharacterData(LocStart);
523 const char *endBuf = SM->getCharacterData(LocEnd);
524 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
525 ResultStr.c_str(), ResultStr.size());
526 }
527
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000528 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
529 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000530 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000531 ObjcMethodDecl *OMD;
532 if (IMD)
533 OMD = IMD->getClassMethods()[i];
534 else
535 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000536 RewriteObjcMethodDecl(OMD, ResultStr);
537 SourceLocation LocStart = OMD->getLocStart();
538 SourceLocation LocEnd = OMD->getBody()->getLocStart();
539
540 const char *startBuf = SM->getCharacterData(LocStart);
541 const char *endBuf = SM->getCharacterData(LocEnd);
542 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
543 ResultStr.c_str(), ResultStr.size());
544 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000545 if (IMD)
546 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
547 else
548 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000549}
550
Steve Naroffbef11852007-10-26 20:53:56 +0000551void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000552
553 SourceLocation LocStart = ClassDecl->getLocStart();
554 SourceLocation LocEnd = ClassDecl->getLocEnd();
555
556 const char *startBuf = SM->getCharacterData(LocStart);
557 const char *endBuf = SM->getCharacterData(LocEnd);
558
Steve Naroff2feac5e2007-10-30 03:43:13 +0000559 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000560
561 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000562 if (!ObjcForwardDecls.count(ClassDecl)) {
563 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000564 ResultStr += "#ifndef _REWRITER_typedef_";
565 ResultStr += ClassDecl->getName();
566 ResultStr += "\n";
567 ResultStr += "#define _REWRITER_typedef_";
568 ResultStr += ClassDecl->getName();
569 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000570 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000571 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000572 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000573
574 // Mark this typedef as having been generated.
575 ObjcForwardDecls.insert(ClassDecl);
576 }
Steve Narofff908a872007-10-30 02:23:23 +0000577 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
578
Steve Naroff2feac5e2007-10-30 03:43:13 +0000579 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000580 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000581 RewriteProperties(ClassDecl->getNumPropertyDecl(),
582 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000583 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
584 ClassDecl->getInstanceMethods());
585 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
586 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000587
Steve Naroff2feac5e2007-10-30 03:43:13 +0000588 // Lastly, comment out the @end.
589 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000590}
591
Chris Lattnerf04da132007-10-24 17:06:59 +0000592//===----------------------------------------------------------------------===//
593// Function Body / Expression rewriting
594//===----------------------------------------------------------------------===//
595
Steve Narofff3473a72007-11-09 15:20:18 +0000596Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000597 // Otherwise, just rewrite all children.
598 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
599 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000600 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000601 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000602 if (newStmt)
603 *CI = newStmt;
604 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000605
606 // Handle specific things.
607 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
608 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000609
610 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
611 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000612
613 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
614 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000615
Steve Naroff934f2762007-10-24 22:48:43 +0000616 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
617 // Before we rewrite it, put the original message expression in a comment.
618 SourceLocation startLoc = MessExpr->getLocStart();
619 SourceLocation endLoc = MessExpr->getLocEnd();
620
621 const char *startBuf = SM->getCharacterData(startLoc);
622 const char *endBuf = SM->getCharacterData(endLoc);
623
624 std::string messString;
625 messString += "// ";
626 messString.append(startBuf, endBuf-startBuf+1);
627 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000628
Steve Naroff934f2762007-10-24 22:48:43 +0000629 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
630 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
631 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000632 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000633 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000634 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000635
636 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
637 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000638
639 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
640 return RewriteObjcThrowStmt(StmtThrow);
641
Chris Lattnere64b7772007-10-24 16:57:36 +0000642 // Return this stmt unmodified.
643 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000644}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000645
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000646Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000647 // Get the start location and compute the semi location.
648 SourceLocation startLoc = S->getLocStart();
649 const char *startBuf = SM->getCharacterData(startLoc);
650
651 assert((*startBuf == '@') && "bogus @try location");
652
653 std::string buf;
654 // declare a new scope with two variables, _stack and _rethrow.
655 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
656 buf += "int buf[18/*32-bit i386*/];\n";
657 buf += "char *pointers[4];} _stack;\n";
658 buf += "id volatile _rethrow = 0;\n";
659 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000660 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000661
662 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
663
664 startLoc = S->getTryBody()->getLocEnd();
665 startBuf = SM->getCharacterData(startLoc);
666
667 assert((*startBuf == '}') && "bogus @try block");
668
669 SourceLocation lastCurlyLoc = startLoc;
670
671 startLoc = startLoc.getFileLocWithOffset(1);
672 buf = " /* @catch begin */ else {\n";
673 buf += " id _caught = objc_exception_extract(&_stack);\n";
674 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000675 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000676 buf += " _rethrow = objc_exception_extract(&_stack);\n";
677 buf += " else { /* @catch continue */";
678
Chris Lattner28d1fe82007-11-08 04:41:51 +0000679 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000680
681 bool sawIdTypedCatch = false;
682 Stmt *lastCatchBody = 0;
683 ObjcAtCatchStmt *catchList = S->getCatchStmts();
684 while (catchList) {
685 Stmt *catchStmt = catchList->getCatchParamStmt();
686
687 if (catchList == S->getCatchStmts())
688 buf = "if ("; // we are generating code for the first catch clause
689 else
690 buf = "else if (";
691 startLoc = catchList->getLocStart();
692 startBuf = SM->getCharacterData(startLoc);
693
694 assert((*startBuf == '@') && "bogus @catch location");
695
696 const char *lParenLoc = strchr(startBuf, '(');
697
698 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
699 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
700 if (t == Context->getObjcIdType()) {
701 buf += "1) { ";
702 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
703 buf.c_str(), buf.size());
704 sawIdTypedCatch = true;
705 } else if (const PointerType *pType = t->getAsPointerType()) {
706 ObjcInterfaceType *cls; // Should be a pointer to a class.
707
708 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
709 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000710 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000711 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000712 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000713 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
714 buf.c_str(), buf.size());
715 }
716 }
717 // Now rewrite the body...
718 lastCatchBody = catchList->getCatchBody();
719 SourceLocation rParenLoc = catchList->getRParenLoc();
720 SourceLocation bodyLoc = lastCatchBody->getLocStart();
721 const char *bodyBuf = SM->getCharacterData(bodyLoc);
722 const char *rParenBuf = SM->getCharacterData(rParenLoc);
723 assert((*rParenBuf == ')') && "bogus @catch paren location");
724 assert((*bodyBuf == '{') && "bogus @catch body location");
725
726 buf = " = _caught;";
727 // Here we replace ") {" with "= _caught;" (which initializes and
728 // declares the @catch parameter).
729 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
730 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000731 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000732 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000733 }
Steve Naroff75730982007-11-07 04:08:17 +0000734 catchList = catchList->getNextCatchStmt();
735 }
736 // Complete the catch list...
737 if (lastCatchBody) {
738 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
739 const char *bodyBuf = SM->getCharacterData(bodyLoc);
740 assert((*bodyBuf == '}') && "bogus @catch body location");
741 bodyLoc = bodyLoc.getFileLocWithOffset(1);
742 buf = " } } /* @catch end */\n";
743
Chris Lattner28d1fe82007-11-08 04:41:51 +0000744 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000745
746 // Set lastCurlyLoc
747 lastCurlyLoc = lastCatchBody->getLocEnd();
748 }
749 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
750 startLoc = finalStmt->getLocStart();
751 startBuf = SM->getCharacterData(startLoc);
752 assert((*startBuf == '@') && "bogus @finally start");
753
754 buf = "/* @finally */";
755 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
756
757 Stmt *body = finalStmt->getFinallyBody();
758 SourceLocation startLoc = body->getLocStart();
759 SourceLocation endLoc = body->getLocEnd();
760 const char *startBuf = SM->getCharacterData(startLoc);
761 const char *endBuf = SM->getCharacterData(endLoc);
762 assert((*startBuf == '{') && "bogus @finally body location");
763 assert((*endBuf == '}') && "bogus @finally body location");
764
765 startLoc = startLoc.getFileLocWithOffset(1);
766 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000767 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000768 endLoc = endLoc.getFileLocWithOffset(-1);
769 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000770 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000771
772 // Set lastCurlyLoc
773 lastCurlyLoc = body->getLocEnd();
774 }
775 // Now emit the final closing curly brace...
776 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
777 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000778 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000779 return 0;
780}
781
782Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
783 return 0;
784}
785
786Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
787 return 0;
788}
789
Steve Naroff2bd03922007-11-07 15:32:26 +0000790// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
791// the throw expression is typically a message expression that's already
792// been rewritten! (which implies the SourceLocation's are invalid).
793Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
794 // Get the start location and compute the semi location.
795 SourceLocation startLoc = S->getLocStart();
796 const char *startBuf = SM->getCharacterData(startLoc);
797
798 assert((*startBuf == '@') && "bogus @throw location");
799
800 std::string buf;
801 /* void objc_exception_throw(id) __attribute__((noreturn)); */
802 buf = "objc_exception_throw(";
803 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
804 const char *semiBuf = strchr(startBuf, ';');
805 assert((*semiBuf == ';') && "@throw: can't find ';'");
806 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
807 buf = ");";
808 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
809 return 0;
810}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000811
Chris Lattnere64b7772007-10-24 16:57:36 +0000812Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000813 // Create a new string expression.
814 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000815 std::string StrEncoding;
816 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
817 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
818 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000819 SourceLocation(), SourceLocation());
820 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000821 delete Exp;
822 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000823}
824
Steve Naroffb42f8412007-11-05 14:50:49 +0000825Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
826 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
827 // Create a call to sel_registerName("selName").
828 llvm::SmallVector<Expr*, 8> SelExprs;
829 QualType argType = Context->getPointerType(Context->CharTy);
830 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
831 Exp->getSelector().getName().size(),
832 false, argType, SourceLocation(),
833 SourceLocation()));
834 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
835 &SelExprs[0], SelExprs.size());
836 Rewrite.ReplaceStmt(Exp, SelExp);
837 delete Exp;
838 return SelExp;
839}
840
Steve Naroff934f2762007-10-24 22:48:43 +0000841CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
842 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000843 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000844 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000845
846 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000847 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000848
849 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000850 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000851 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
852
853 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000854
Steve Naroff934f2762007-10-24 22:48:43 +0000855 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
856}
857
Steve Naroffd5255f52007-11-01 13:24:47 +0000858static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
859 const char *&startRef, const char *&endRef) {
860 while (startBuf < endBuf) {
861 if (*startBuf == '<')
862 startRef = startBuf; // mark the start.
863 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000864 if (startRef && *startRef == '<') {
865 endRef = startBuf; // mark the end.
866 return true;
867 }
868 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000869 }
870 startBuf++;
871 }
872 return false;
873}
874
875bool RewriteTest::needToScanForQualifiers(QualType T) {
876 // FIXME: we don't currently represent "id <Protocol>" in the type system.
877 if (T == Context->getObjcIdType())
878 return true;
879
880 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000881 Type *pointeeType = pType->getPointeeType().getTypePtr();
882 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
883 return true; // we have "Class <Protocol> *".
884 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000885 return false;
886}
887
888void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
889 const FunctionTypeProto *proto, FunctionDecl *FD) {
890
891 if (needToScanForQualifiers(proto->getResultType())) {
892 // Since types are unique, we need to scan the buffer.
893 SourceLocation Loc = FD->getLocation();
894
895 const char *endBuf = SM->getCharacterData(Loc);
896 const char *startBuf = endBuf;
897 while (*startBuf != ';')
898 startBuf--; // scan backward (from the decl location) for return type.
899 const char *startRef = 0, *endRef = 0;
900 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
901 // Get the locations of the startRef, endRef.
902 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
903 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
904 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000905 Rewrite.InsertText(LessLoc, "/*", 2);
906 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000907 }
908 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000909 // Now check arguments.
910 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
911 if (needToScanForQualifiers(proto->getArgType(i))) {
912 // Since types are unique, we need to scan the buffer.
913 SourceLocation Loc = FD->getLocation();
914
915 const char *startBuf = SM->getCharacterData(Loc);
916 const char *endBuf = startBuf;
917 while (*endBuf != ';')
918 endBuf++; // scan forward (from the decl location) for argument types.
919 const char *startRef = 0, *endRef = 0;
920 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
921 // Get the locations of the startRef, endRef.
922 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
923 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
924 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000925 Rewrite.InsertText(LessLoc, "/*", 2);
926 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000927 }
928 }
929 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000930}
931
Steve Naroff09b266e2007-10-30 23:14:51 +0000932void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
933 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000934 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000935 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000936 return;
937 }
938 // Check for ObjC 'id' and class types that have been adorned with protocol
939 // information (id<p>, C<p>*). The protocol references need to be rewritten!
940 const FunctionType *funcType = FD->getType()->getAsFunctionType();
941 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000942 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
943 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000944}
945
946// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
947void RewriteTest::SynthMsgSendFunctionDecl() {
948 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
949 llvm::SmallVector<QualType, 16> ArgTys;
950 QualType argT = Context->getObjcIdType();
951 assert(!argT.isNull() && "Can't find 'id' type");
952 ArgTys.push_back(argT);
953 argT = Context->getObjcSelType();
954 assert(!argT.isNull() && "Can't find 'SEL' type");
955 ArgTys.push_back(argT);
956 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
957 &ArgTys[0], ArgTys.size(),
958 true /*isVariadic*/);
959 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
960 msgSendIdent, msgSendType,
961 FunctionDecl::Extern, false, 0);
962}
963
964// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
965void RewriteTest::SynthGetClassFunctionDecl() {
966 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
967 llvm::SmallVector<QualType, 16> ArgTys;
968 ArgTys.push_back(Context->getPointerType(
969 Context->CharTy.getQualifiedType(QualType::Const)));
970 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
971 &ArgTys[0], ArgTys.size(),
972 false /*isVariadic*/);
973 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
974 getClassIdent, getClassType,
975 FunctionDecl::Extern, false, 0);
976}
977
Steve Naroff96984642007-11-08 14:30:50 +0000978// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
979void RewriteTest::SynthCFStringFunctionDecl() {
980 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
981 llvm::SmallVector<QualType, 16> ArgTys;
982 ArgTys.push_back(Context->getPointerType(
983 Context->CharTy.getQualifiedType(QualType::Const)));
984 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
985 &ArgTys[0], ArgTys.size(),
986 false /*isVariadic*/);
987 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
988 getClassIdent, getClassType,
989 FunctionDecl::Extern, false, 0);
990}
991
Steve Naroffbeaf2992007-11-03 11:27:19 +0000992Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000993#if 1
994 // This rewrite is specific to GCC, which has builtin support for CFString.
995 if (!CFStringFunctionDecl)
996 SynthCFStringFunctionDecl();
997 // Create a call to __builtin___CFStringMakeConstantString("cstr").
998 llvm::SmallVector<Expr*, 8> StrExpr;
999 StrExpr.push_back(Exp->getString());
1000 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1001 &StrExpr[0], StrExpr.size());
1002 // cast to NSConstantString *
1003 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1004 Rewrite.ReplaceStmt(Exp, cast);
1005 delete Exp;
1006 return cast;
1007#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001008 assert(ConstantStringClassReference && "Can't find constant string reference");
1009 llvm::SmallVector<Expr*, 4> InitExprs;
1010
1011 // Synthesize "(Class)&_NSConstantStringClassReference"
1012 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1013 ConstantStringClassReference->getType(),
1014 SourceLocation());
1015 QualType expType = Context->getPointerType(ClsRef->getType());
1016 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1017 expType, SourceLocation());
1018 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1019 SourceLocation());
1020 InitExprs.push_back(cast); // set the 'isa'.
1021 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1022 unsigned IntSize = static_cast<unsigned>(
1023 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1024 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1025 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1026 Exp->getLocStart());
1027 InitExprs.push_back(len); // set "int numBytes".
1028
1029 // struct NSConstantString
1030 QualType CFConstantStrType = Context->getCFConstantStringType();
1031 // (struct NSConstantString) { <exprs from above> }
1032 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1033 &InitExprs[0], InitExprs.size(),
1034 SourceLocation());
1035 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1036 // struct NSConstantString *
1037 expType = Context->getPointerType(StrRep->getType());
1038 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1039 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001040 // cast to NSConstantString *
1041 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001042 Rewrite.ReplaceStmt(Exp, cast);
1043 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001044 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001045#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001046}
1047
Steve Naroff934f2762007-10-24 22:48:43 +00001048Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001049 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001050 if (!MsgSendFunctionDecl)
1051 SynthMsgSendFunctionDecl();
1052 if (!GetClassFunctionDecl)
1053 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001054
1055 // Synthesize a call to objc_msgSend().
1056 llvm::SmallVector<Expr*, 8> MsgExprs;
1057 IdentifierInfo *clsName = Exp->getClassName();
1058
1059 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1060 if (clsName) { // class message.
1061 llvm::SmallVector<Expr*, 8> ClsExprs;
1062 QualType argType = Context->getPointerType(Context->CharTy);
1063 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1064 clsName->getLength(),
1065 false, argType, SourceLocation(),
1066 SourceLocation()));
1067 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1068 &ClsExprs[0], ClsExprs.size());
1069 MsgExprs.push_back(Cls);
1070 } else // instance message.
1071 MsgExprs.push_back(Exp->getReceiver());
1072
Steve Naroffbeaf2992007-11-03 11:27:19 +00001073 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001074 llvm::SmallVector<Expr*, 8> SelExprs;
1075 QualType argType = Context->getPointerType(Context->CharTy);
1076 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1077 Exp->getSelector().getName().size(),
1078 false, argType, SourceLocation(),
1079 SourceLocation()));
1080 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1081 &SelExprs[0], SelExprs.size());
1082 MsgExprs.push_back(SelExp);
1083
1084 // Now push any user supplied arguments.
1085 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1086 MsgExprs.push_back(Exp->getArg(i));
1087 // We've transferred the ownership to MsgExprs. Null out the argument in
1088 // the original expression, since we will delete it below.
1089 Exp->setArg(i, 0);
1090 }
Steve Naroffab972d32007-11-04 22:37:50 +00001091 // Generate the funky cast.
1092 CastExpr *cast;
1093 llvm::SmallVector<QualType, 8> ArgTypes;
1094 QualType returnType;
1095
1096 // Push 'id' and 'SEL', the 2 implicit arguments.
1097 ArgTypes.push_back(Context->getObjcIdType());
1098 ArgTypes.push_back(Context->getObjcSelType());
1099 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1100 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001101 for (int i = 0; i < mDecl->getNumParams(); i++) {
1102 QualType t = mDecl->getParamDecl(i)->getType();
1103 if (t == Context->getObjcClassType())
1104 t = Context->getObjcIdType(); // Convert "Class"->"id"
1105 ArgTypes.push_back(t);
1106 }
Steve Naroffab972d32007-11-04 22:37:50 +00001107 returnType = mDecl->getResultType();
1108 } else {
1109 returnType = Context->getObjcIdType();
1110 }
1111 // Get the type, we will need to reference it in a couple spots.
1112 QualType msgSendType = MsgSendFunctionDecl->getType();
1113
1114 // Create a reference to the objc_msgSend() declaration.
1115 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1116
1117 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1118 // If we don't do this cast, we get the following bizarre warning/note:
1119 // xx.m:13: warning: function called through a non-compatible type
1120 // xx.m:13: note: if this code is reached, the program will abort
1121 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1122 SourceLocation());
1123
1124 // Now do the "normal" pointer to function cast.
1125 QualType castType = Context->getFunctionType(returnType,
1126 &ArgTypes[0], ArgTypes.size(),
1127 false/*FIXME:variadic*/);
1128 castType = Context->getPointerType(castType);
1129 cast = new CastExpr(castType, cast, SourceLocation());
1130
1131 // Don't forget the parens to enforce the proper binding.
1132 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1133
1134 const FunctionType *FT = msgSendType->getAsFunctionType();
1135 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1136 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001137 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001138 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001139
Chris Lattnere64b7772007-10-24 16:57:36 +00001140 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001141 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001142}
1143
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001144/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1145/// an objective-c class with ivars.
1146void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1147 std::string &Result) {
1148 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1149 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001150 // Do not synthesize more than once.
1151 if (ObjcSynthesizedStructs.count(CDecl))
1152 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001153 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1154 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1155 // Do it for the root
1156 SynthesizeObjcInternalStruct(RCDecl, Result);
1157 }
1158
Steve Naroff03300712007-11-12 13:56:41 +00001159 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001160 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001161 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001162 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1163 return;
1164
Steve Naroff04960052007-11-01 17:12:31 +00001165 Result += "\nstruct ";
1166 Result += CDecl->getName();
1167 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1168 Result += " {\n struct ";
1169 Result += RCDecl->getName();
1170 Result += " _";
1171 Result += RCDecl->getName();
1172 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001173 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001174 else
1175 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +00001176
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001177 if (NumIvars > 0) {
1178 SourceLocation LocStart = CDecl->getLocStart();
1179 SourceLocation LocEnd = CDecl->getLocEnd();
1180
1181 const char *startBuf = SM->getCharacterData(LocStart);
1182 const char *endBuf = SM->getCharacterData(LocEnd);
1183 startBuf = strchr(startBuf, '{');
1184 assert((startBuf && endBuf)
1185 && "SynthesizeObjcInternalStruct - malformed @interface");
1186 startBuf++; // past '{'
1187 while (startBuf < endBuf) {
1188 if (*startBuf == '@') {
1189 startBuf = strchr(startBuf, 'p');
1190 // FIXME: presence of @public, etc. inside comment results in
1191 // this transformation as well, which is still correct c-code.
1192 if (!strncmp(startBuf, "public", strlen("public"))) {
1193 startBuf += strlen("public");
1194 Result += "/* @public */";
1195 }
1196 else if (!strncmp(startBuf, "private", strlen("private"))) {
1197 startBuf += strlen("private");
1198 Result += "/* @private */";
1199 }
1200 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1201 startBuf += strlen("protected");
1202 Result += "/* @protected */";
1203 }
1204 }
1205 Result += *startBuf++;
1206 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001207 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001208
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001209 Result += "};\n";
1210 // Mark this struct as having been generated.
1211 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001212 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001213}
1214
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001215// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1216/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001217void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001218 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001219 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001220 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001221 const char *ClassName,
1222 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001223 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001224 if (NumMethods > 0 && !objc_impl_method) {
1225 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001226 SEL _cmd;
1227 char *method_types;
1228 void *_imp;
1229 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001230 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001231 Result += "\nstruct _objc_method {\n";
1232 Result += "\tSEL _cmd;\n";
1233 Result += "\tchar *method_types;\n";
1234 Result += "\tvoid *_imp;\n";
1235 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001236
1237 /* struct _objc_method_list {
1238 struct _objc_method_list *next_method;
1239 int method_count;
1240 struct _objc_method method_list[];
1241 }
1242 */
1243 Result += "\nstruct _objc_method_list {\n";
1244 Result += "\tstruct _objc_method_list *next_method;\n";
1245 Result += "\tint method_count;\n";
1246 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001247 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001248 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001249 // Build _objc_method_list for class's methods if needed
1250 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001251 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001252 Result += prefix;
1253 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1254 Result += "_METHODS_";
1255 Result += ClassName;
1256 Result += " __attribute__ ((section (\"__OBJC, __";
1257 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001258 Result += "_meth\")))= ";
1259 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1260
1261 Result += "\t,{{(SEL)\"";
1262 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001263 std::string MethodTypeString;
1264 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1265 Result += "\", \"";
1266 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001267 Result += "\", ";
1268 Result += MethodInternalNames[Methods[0]];
1269 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001270 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001271 Result += "\t ,{(SEL)\"";
1272 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001273 std::string MethodTypeString;
1274 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1275 Result += "\", \"";
1276 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001277 Result += "\", ";
1278 Result += MethodInternalNames[Methods[i]];
1279 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001280 }
1281 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001282 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001283}
1284
1285/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1286void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1287 int NumProtocols,
1288 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001289 const char *ClassName,
1290 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001291 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001292 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001293 for (int i = 0; i < NumProtocols; i++) {
1294 ObjcProtocolDecl *PDecl = Protocols[i];
1295 // Output struct protocol_methods holder of method selector and type.
1296 if (!objc_protocol_methods &&
1297 (PDecl->getNumInstanceMethods() > 0
1298 || PDecl->getNumClassMethods() > 0)) {
1299 /* struct protocol_methods {
1300 SEL _cmd;
1301 char *method_types;
1302 }
1303 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001304 Result += "\nstruct protocol_methods {\n";
1305 Result += "\tSEL _cmd;\n";
1306 Result += "\tchar *method_types;\n";
1307 Result += "};\n";
1308
1309 /* struct _objc_protocol_method_list {
1310 int protocol_method_count;
1311 struct protocol_methods protocols[];
1312 }
1313 */
1314 Result += "\nstruct _objc_protocol_method_list {\n";
1315 Result += "\tint protocol_method_count;\n";
1316 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001317 objc_protocol_methods = true;
1318 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001319
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001320 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001321 int NumMethods = PDecl->getNumInstanceMethods();
1322 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001323 Result += "\nstatic struct _objc_protocol_method_list "
1324 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1325 Result += PDecl->getName();
1326 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1327 "{\n\t" + utostr(NumMethods) + "\n";
1328
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001329 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001330 Result += "\t,{{(SEL)\"";
1331 Result += Methods[0]->getSelector().getName().c_str();
1332 Result += "\", \"\"}\n";
1333
1334 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001335 Result += "\t ,{(SEL)\"";
1336 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001337 std::string MethodTypeString;
1338 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1339 Result += "\", \"";
1340 Result += MethodTypeString;
1341 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001342 }
1343 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001344 }
1345
1346 // Output class methods declared in this protocol.
1347 NumMethods = PDecl->getNumClassMethods();
1348 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001349 Result += "\nstatic struct _objc_protocol_method_list "
1350 "_OBJC_PROTOCOL_CLASS_METHODS_";
1351 Result += PDecl->getName();
1352 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1353 "{\n\t";
1354 Result += utostr(NumMethods);
1355 Result += "\n";
1356
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001357 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001358 Result += "\t,{{(SEL)\"";
1359 Result += Methods[0]->getSelector().getName().c_str();
1360 Result += "\", \"\"}\n";
1361
1362 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001363 Result += "\t ,{(SEL)\"";
1364 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001365 std::string MethodTypeString;
1366 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1367 Result += "\", \"";
1368 Result += MethodTypeString;
1369 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001370 }
1371 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001372 }
1373 // Output:
1374 /* struct _objc_protocol {
1375 // Objective-C 1.0 extensions
1376 struct _objc_protocol_extension *isa;
1377 char *protocol_name;
1378 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001379 struct _objc_protocol_method_list *instance_methods;
1380 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001381 };
1382 */
1383 static bool objc_protocol = false;
1384 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001385 Result += "\nstruct _objc_protocol {\n";
1386 Result += "\tstruct _objc_protocol_extension *isa;\n";
1387 Result += "\tchar *protocol_name;\n";
1388 Result += "\tstruct _objc_protocol **protocol_list;\n";
1389 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1390 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1391 Result += "};\n";
1392
1393 /* struct _objc_protocol_list {
1394 struct _objc_protocol_list *next;
1395 int protocol_count;
1396 struct _objc_protocol *class_protocols[];
1397 }
1398 */
1399 Result += "\nstruct _objc_protocol_list {\n";
1400 Result += "\tstruct _objc_protocol_list *next;\n";
1401 Result += "\tint protocol_count;\n";
1402 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1403 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001404 objc_protocol = true;
1405 }
1406
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001407 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1408 Result += PDecl->getName();
1409 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1410 "{\n\t0, \"";
1411 Result += PDecl->getName();
1412 Result += "\", 0, ";
1413 if (PDecl->getInstanceMethods() > 0) {
1414 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1415 Result += PDecl->getName();
1416 Result += ", ";
1417 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001418 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001419 Result += "0, ";
1420 if (PDecl->getClassMethods() > 0) {
1421 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1422 Result += PDecl->getName();
1423 Result += "\n";
1424 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001425 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001426 Result += "0\n";
1427 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001428 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001429 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001430 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1431 Result += prefix;
1432 Result += "_PROTOCOLS_";
1433 Result += ClassName;
1434 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1435 "{\n\t0, ";
1436 Result += utostr(NumProtocols);
1437 Result += "\n";
1438
1439 Result += "\t,{&_OBJC_PROTOCOL_";
1440 Result += Protocols[0]->getName();
1441 Result += " \n";
1442
1443 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001444 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001445 Result += "\t ,&_OBJC_PROTOCOL_";
1446 Result += PDecl->getName();
1447 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001448 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001449 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001450 }
1451}
1452
1453/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1454/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001455void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1456 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001457 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1458 // Find category declaration for this implementation.
1459 ObjcCategoryDecl *CDecl;
1460 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1461 CDecl = CDecl->getNextClassCategory())
1462 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1463 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001464
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001465 char *FullCategoryName = (char*)alloca(
1466 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1467 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1468
1469 // Build _objc_method_list for class's instance methods if needed
1470 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1471 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001472 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001473 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001474
1475 // Build _objc_method_list for class's class methods if needed
1476 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1477 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001478 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001479 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001480
1481 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001482 // Null CDecl is case of a category implementation with no category interface
1483 if (CDecl)
1484 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1485 CDecl->getNumReferencedProtocols(),
1486 "CATEGORY",
1487 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001488
1489 /* struct _objc_category {
1490 char *category_name;
1491 char *class_name;
1492 struct _objc_method_list *instance_methods;
1493 struct _objc_method_list *class_methods;
1494 struct _objc_protocol_list *protocols;
1495 // Objective-C 1.0 extensions
1496 uint32_t size; // sizeof (struct _objc_category)
1497 struct _objc_property_list *instance_properties; // category's own
1498 // @property decl.
1499 };
1500 */
1501
1502 static bool objc_category = false;
1503 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001504 Result += "\nstruct _objc_category {\n";
1505 Result += "\tchar *category_name;\n";
1506 Result += "\tchar *class_name;\n";
1507 Result += "\tstruct _objc_method_list *instance_methods;\n";
1508 Result += "\tstruct _objc_method_list *class_methods;\n";
1509 Result += "\tstruct _objc_protocol_list *protocols;\n";
1510 Result += "\tunsigned int size;\n";
1511 Result += "\tstruct _objc_property_list *instance_properties;\n";
1512 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001513 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001514 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001515 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1516 Result += FullCategoryName;
1517 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1518 Result += IDecl->getName();
1519 Result += "\"\n\t, \"";
1520 Result += ClassDecl->getName();
1521 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001522
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001523 if (IDecl->getNumInstanceMethods() > 0) {
1524 Result += "\t, (struct _objc_method_list *)"
1525 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1526 Result += FullCategoryName;
1527 Result += "\n";
1528 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001529 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001530 Result += "\t, 0\n";
1531 if (IDecl->getNumClassMethods() > 0) {
1532 Result += "\t, (struct _objc_method_list *)"
1533 "&_OBJC_CATEGORY_CLASS_METHODS_";
1534 Result += FullCategoryName;
1535 Result += "\n";
1536 }
1537 else
1538 Result += "\t, 0\n";
1539
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001540 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001541 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1542 Result += FullCategoryName;
1543 Result += "\n";
1544 }
1545 else
1546 Result += "\t, 0\n";
1547 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001548}
1549
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001550/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1551/// ivar offset.
1552void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1553 ObjcIvarDecl *ivar,
1554 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001555 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001556 Result += IDecl->getName();
1557 Result += ", ";
1558 Result += ivar->getName();
1559 Result += ")";
1560}
1561
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001562//===----------------------------------------------------------------------===//
1563// Meta Data Emission
1564//===----------------------------------------------------------------------===//
1565
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001566void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1567 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001568 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1569
1570 // Build _objc_ivar_list metadata for classes ivars if needed
1571 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1572 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001573 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001574
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001575 SynthesizeObjcInternalStruct(CDecl, Result);
1576
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001577 if (NumIvars > 0) {
1578 static bool objc_ivar = false;
1579 if (!objc_ivar) {
1580 /* struct _objc_ivar {
1581 char *ivar_name;
1582 char *ivar_type;
1583 int ivar_offset;
1584 };
1585 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001586 Result += "\nstruct _objc_ivar {\n";
1587 Result += "\tchar *ivar_name;\n";
1588 Result += "\tchar *ivar_type;\n";
1589 Result += "\tint ivar_offset;\n";
1590 Result += "};\n";
1591
1592 /* struct _objc_ivar_list {
1593 int ivar_count;
1594 struct _objc_ivar ivar_list[];
1595 };
1596 */
1597 Result += "\nstruct _objc_ivar_list {\n";
1598 Result += "\tint ivar_count;\n";
1599 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001600 objc_ivar = true;
1601 }
1602
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001603 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1604 Result += IDecl->getName();
1605 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1606 "{\n\t";
1607 Result += utostr(NumIvars);
1608 Result += "\n";
1609
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001610 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1611 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001612 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001613 Result += "\t,{{\"";
1614 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001615 Result += "\", \"";
1616 std::string StrEncoding;
1617 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1618 Result += StrEncoding;
1619 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001620 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1621 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001622 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001623 Result += "\t ,{\"";
1624 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001625 Result += "\", \"";
1626 std::string StrEncoding;
1627 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1628 Result += StrEncoding;
1629 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001630 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1631 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001632 }
1633
1634 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001635 }
1636
1637 // Build _objc_method_list for class's instance methods if needed
1638 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1639 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001640 true,
1641 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001642
1643 // Build _objc_method_list for class's class methods if needed
1644 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001645 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001646 false,
1647 "", IDecl->getName(), Result);
1648
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001649 // Protocols referenced in class declaration?
1650 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1651 CDecl->getNumIntfRefProtocols(),
1652 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001653 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001654
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001655
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001656 // Declaration of class/meta-class metadata
1657 /* struct _objc_class {
1658 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001659 const char *super_class_name;
1660 char *name;
1661 long version;
1662 long info;
1663 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001664 struct _objc_ivar_list *ivars;
1665 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001666 struct objc_cache *cache;
1667 struct objc_protocol_list *protocols;
1668 const char *ivar_layout;
1669 struct _objc_class_ext *ext;
1670 };
1671 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001672 static bool objc_class = false;
1673 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001674 Result += "\nstruct _objc_class {\n";
1675 Result += "\tstruct _objc_class *isa;\n";
1676 Result += "\tconst char *super_class_name;\n";
1677 Result += "\tchar *name;\n";
1678 Result += "\tlong version;\n";
1679 Result += "\tlong info;\n";
1680 Result += "\tlong instance_size;\n";
1681 Result += "\tstruct _objc_ivar_list *ivars;\n";
1682 Result += "\tstruct _objc_method_list *methods;\n";
1683 Result += "\tstruct objc_cache *cache;\n";
1684 Result += "\tstruct _objc_protocol_list *protocols;\n";
1685 Result += "\tconst char *ivar_layout;\n";
1686 Result += "\tstruct _objc_class_ext *ext;\n";
1687 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001688 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001689 }
1690
1691 // Meta-class metadata generation.
1692 ObjcInterfaceDecl *RootClass = 0;
1693 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1694 while (SuperClass) {
1695 RootClass = SuperClass;
1696 SuperClass = SuperClass->getSuperClass();
1697 }
1698 SuperClass = CDecl->getSuperClass();
1699
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001700 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1701 Result += CDecl->getName();
1702 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1703 "{\n\t(struct _objc_class *)\"";
1704 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1705 Result += "\"";
1706
1707 if (SuperClass) {
1708 Result += ", \"";
1709 Result += SuperClass->getName();
1710 Result += "\", \"";
1711 Result += CDecl->getName();
1712 Result += "\"";
1713 }
1714 else {
1715 Result += ", 0, \"";
1716 Result += CDecl->getName();
1717 Result += "\"";
1718 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001719 // TODO: 'ivars' field for root class is currently set to 0.
1720 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001721 Result += ", 0,2, sizeof(struct _objc_class), 0";
1722 if (CDecl->getNumClassMethods() > 0) {
1723 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1724 Result += CDecl->getName();
1725 Result += "\n";
1726 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001727 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001728 Result += ", 0\n";
1729 if (CDecl->getNumIntfRefProtocols() > 0) {
1730 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1731 Result += CDecl->getName();
1732 Result += ",0,0\n";
1733 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001734 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001735 Result += "\t,0,0,0,0\n";
1736 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001737
1738 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001739 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1740 Result += CDecl->getName();
1741 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1742 "{\n\t&_OBJC_METACLASS_";
1743 Result += CDecl->getName();
1744 if (SuperClass) {
1745 Result += ", \"";
1746 Result += SuperClass->getName();
1747 Result += "\", \"";
1748 Result += CDecl->getName();
1749 Result += "\"";
1750 }
1751 else {
1752 Result += ", 0, \"";
1753 Result += CDecl->getName();
1754 Result += "\"";
1755 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001756 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001757 Result += ", 0,1";
1758 if (!ObjcSynthesizedStructs.count(CDecl))
1759 Result += ",0";
1760 else {
1761 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001762 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001763 Result += CDecl->getName();
1764 Result += ")";
1765 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001766 if (NumIvars > 0) {
1767 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1768 Result += CDecl->getName();
1769 Result += "\n\t";
1770 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001771 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001772 Result += ",0";
1773 if (IDecl->getNumInstanceMethods() > 0) {
1774 Result += ", &_OBJC_INSTANCE_METHODS_";
1775 Result += CDecl->getName();
1776 Result += ", 0\n\t";
1777 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001778 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001779 Result += ",0,0";
1780 if (CDecl->getNumIntfRefProtocols() > 0) {
1781 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1782 Result += CDecl->getName();
1783 Result += ", 0,0\n";
1784 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001785 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001786 Result += ",0,0,0\n";
1787 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001788}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001789
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001790/// RewriteImplementations - This routine rewrites all method implementations
1791/// and emits meta-data.
1792
1793void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001794 int ClsDefCount = ClassImplementation.size();
1795 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001796
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001797 if (ClsDefCount == 0 && CatDefCount == 0)
1798 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001799 // Rewrite implemented methods
1800 for (int i = 0; i < ClsDefCount; i++)
1801 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001802
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001803 for (int i = 0; i < CatDefCount; i++)
1804 RewriteImplementationDecl(CategoryImplementation[i]);
1805
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001806 // TODO: This is temporary until we decide how to access objc types in a
1807 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001808 Result += "#include <Objc/objc.h>\n";
1809 // This is needed for use of offsetof
1810 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001811
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001812 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001813 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001814 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001815
1816 // For each implemented category, write out all its meta data.
1817 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001818 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001819
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001820 // Write objc_symtab metadata
1821 /*
1822 struct _objc_symtab
1823 {
1824 long sel_ref_cnt;
1825 SEL *refs;
1826 short cls_def_cnt;
1827 short cat_def_cnt;
1828 void *defs[cls_def_cnt + cat_def_cnt];
1829 };
1830 */
1831
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001832 Result += "\nstruct _objc_symtab {\n";
1833 Result += "\tlong sel_ref_cnt;\n";
1834 Result += "\tSEL *refs;\n";
1835 Result += "\tshort cls_def_cnt;\n";
1836 Result += "\tshort cat_def_cnt;\n";
1837 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1838 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001839
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001840 Result += "static struct _objc_symtab "
1841 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1842 Result += "\t0, 0, " + utostr(ClsDefCount)
1843 + ", " + utostr(CatDefCount) + "\n";
1844 for (int i = 0; i < ClsDefCount; i++) {
1845 Result += "\t,&_OBJC_CLASS_";
1846 Result += ClassImplementation[i]->getName();
1847 Result += "\n";
1848 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001849
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001850 for (int i = 0; i < CatDefCount; i++) {
1851 Result += "\t,&_OBJC_CATEGORY_";
1852 Result += CategoryImplementation[i]->getClassInterface()->getName();
1853 Result += "_";
1854 Result += CategoryImplementation[i]->getName();
1855 Result += "\n";
1856 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001857
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001858 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001859
1860 // Write objc_module metadata
1861
1862 /*
1863 struct _objc_module {
1864 long version;
1865 long size;
1866 const char *name;
1867 struct _objc_symtab *symtab;
1868 }
1869 */
1870
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001871 Result += "\nstruct _objc_module {\n";
1872 Result += "\tlong version;\n";
1873 Result += "\tlong size;\n";
1874 Result += "\tconst char *name;\n";
1875 Result += "\tstruct _objc_symtab *symtab;\n";
1876 Result += "};\n\n";
1877 Result += "static struct _objc_module "
1878 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001879 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1880 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001881 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001882
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001883}
Chris Lattner311ff022007-10-16 22:36:42 +00001884