blob: 0f6c9741cdb8aba9fc2fb8da09798364ff6cbed4 [file] [log] [blame]
Chris Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff1ccf4632007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000023using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000025
Chris Lattnerb429ae42007-10-11 00:43:27 +000026namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner74db1682007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000037 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000038
39 FunctionDecl *MsgSendFunctionDecl;
40 FunctionDecl *GetClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000041 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000042 FunctionDecl *CFStringFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000043
Steve Naroff0add5d22007-11-03 11:27:19 +000044 // ObjC string constant support.
45 FileVarDecl *ConstantStringClassReference;
46 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000047
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000048 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000049 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000050 void Initialize(ASTContext &context, unsigned mainFileID) {
51 Context = &context;
52 SM = &Context->SourceMgr;
Chris Lattner569faa62007-10-11 18:38:32 +000053 MainFileID = mainFileID;
Steve Naroffe9780582007-10-23 23:50:29 +000054 MsgSendFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000055 GetClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000056 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000057 CFStringFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000058 ConstantStringClassReference = 0;
59 NSStringRecord = 0;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000060 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Narofffcab7932007-11-05 14:55:35 +000061 // declaring objc_selector outside the parameter list removes a silly
62 // scope related warning...
Steve Naroffd3287d82007-11-07 18:43:40 +000063 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Narofffcab7932007-11-05 14:55:35 +000064 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +000065 "(struct objc_object *, struct objc_selector *, ...);\n"
66 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +000067 "(const char *);\n"
68 "extern void objc_exception_throw(struct objc_object *);\n"
69 "extern void objc_exception_try_enter(void *);\n"
70 "extern void objc_exception_try_exit(void *);\n"
71 "extern struct objc_object *objc_exception_extract(void *);\n"
72 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +000073 "(struct objc_class *, struct objc_object *, ...);\n"
74 "#include <Objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +000075
Steve Naroff0744c472007-11-04 22:37:50 +000076 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
77 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +000078 }
Chris Lattner569faa62007-10-11 18:38:32 +000079
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000080 // Top Level Driver code.
81 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000082 void HandleDeclInMainFile(Decl *D);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000083 ~RewriteTest();
84
85 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +000086 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +000087 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000088 void RewriteTabs();
89 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +000090 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +000091 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +000092 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +000093 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +000094 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +000095 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +000096 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +000097 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +000098 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +000099 void RewriteObjcQualifiedInterfaceTypes(
100 const FunctionTypeProto *proto, FunctionDecl *FD);
101 bool needToScanForQualifiers(QualType T);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000102
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000103 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000104 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000105 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff296b74f2007-11-05 14:50:49 +0000106 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000107 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000108 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000109 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
110 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
111 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000112 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000113 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
114 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000115 void SynthMsgSendFunctionDecl();
116 void SynthGetClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000117 void SynthCFStringFunctionDecl();
118
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000119 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000120 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
121 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000122
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000123 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
124 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000125
Steve Naroffb82c50f2007-11-11 17:19:15 +0000126 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000127 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000128 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000129 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000130 const char *ClassName,
131 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000132
133 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
134 int NumProtocols,
135 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000136 const char *ClassName,
137 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000138 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
139 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000140 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
141 ObjcIvarDecl *ivar,
142 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000143 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000144 };
145}
146
Chris Lattner569faa62007-10-11 18:38:32 +0000147ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000148
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000149//===----------------------------------------------------------------------===//
150// Top Level Driver Code
151//===----------------------------------------------------------------------===//
152
Chris Lattner569faa62007-10-11 18:38:32 +0000153void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000154 // Two cases: either the decl could be in the main file, or it could be in a
155 // #included file. If the former, rewrite it now. If the later, check to see
156 // if we rewrote the #include/#import.
157 SourceLocation Loc = D->getLocation();
158 Loc = SM->getLogicalLoc(Loc);
159
160 // If this is for a builtin, ignore it.
161 if (Loc.isInvalid()) return;
162
Steve Naroffe9780582007-10-23 23:50:29 +0000163 // Look for built-in declarations that we need to refer during the rewrite.
164 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000165 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000166 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
167 // declared in <Foundation/NSString.h>
168 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
169 ConstantStringClassReference = FVD;
170 return;
171 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000172 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
173 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000174 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
175 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000176 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
177 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000178 } else if (ObjcForwardProtocolDecl *FP =
179 dyn_cast<ObjcForwardProtocolDecl>(D)){
180 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000181 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000182 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000183 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
184 return HandleDeclInMainFile(D);
185
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000186 // Otherwise, see if there is a #import in the main file that should be
187 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000188 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000189}
190
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000191/// HandleDeclInMainFile - This is called for each top-level decl defined in the
192/// main file of the input.
193void RewriteTest::HandleDeclInMainFile(Decl *D) {
194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
195 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000196 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000197
198 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
199 if (Stmt *Body = MD->getBody())
200 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
201 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000202 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
203 ClassImplementation.push_back(CI);
204 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
205 CategoryImplementation.push_back(CI);
206 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
207 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000208 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
209 if (VD->getInit())
210 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
211 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000212 // Nothing yet.
213}
214
215RewriteTest::~RewriteTest() {
216 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000217
218 // Rewrite tabs if we care.
219 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000220
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000221 // Rewrite Objective-c meta data*
222 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000223 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000224
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000225 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
226 // we are done.
227 if (const RewriteBuffer *RewriteBuf =
228 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000229 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000230 std::string S(RewriteBuf->begin(), RewriteBuf->end());
231 printf("%s\n", S.c_str());
232 } else {
233 printf("No changes\n");
234 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000235 // Emit metadata.
236 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000237}
238
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000239//===----------------------------------------------------------------------===//
240// Syntactic (non-AST) Rewriting Code
241//===----------------------------------------------------------------------===//
242
Chris Lattner74db1682007-10-16 21:07:07 +0000243void RewriteTest::RewriteInclude(SourceLocation Loc) {
244 // Rip up the #include stack to the main file.
245 SourceLocation IncLoc = Loc, NextLoc = Loc;
246 do {
247 IncLoc = Loc;
248 Loc = SM->getLogicalLoc(NextLoc);
249 NextLoc = SM->getIncludeLoc(Loc);
250 } while (!NextLoc.isInvalid());
251
252 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
253 // IncLoc indicates the header that was included if it is useful.
254 IncLoc = SM->getLogicalLoc(IncLoc);
255 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
256 Loc == LastIncLoc)
257 return;
258 LastIncLoc = Loc;
259
260 unsigned IncCol = SM->getColumnNumber(Loc);
261 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
262
263 // Replace the #import with #include.
264 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
265}
266
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000267void RewriteTest::RewriteTabs() {
268 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
269 const char *MainBufStart = MainBuf.first;
270 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000271
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000272 // Loop over the whole file, looking for tabs.
273 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
274 if (*BufPtr != '\t')
275 continue;
276
277 // Okay, we found a tab. This tab will turn into at least one character,
278 // but it depends on which 'virtual column' it is in. Compute that now.
279 unsigned VCol = 0;
280 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
281 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
282 ++VCol;
283
284 // Okay, now that we know the virtual column, we know how many spaces to
285 // insert. We assume 8-character tab-stops.
286 unsigned Spaces = 8-(VCol & 7);
287
288 // Get the location of the tab.
289 SourceLocation TabLoc =
290 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
291
292 // Rewrite the single tab character into a sequence of spaces.
293 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
294 }
Chris Lattner569faa62007-10-11 18:38:32 +0000295}
296
297
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000298void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
299 int numDecls = ClassDecl->getNumForwardDecls();
300 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
301
302 // Get the start location and compute the semi location.
303 SourceLocation startLoc = ClassDecl->getLocation();
304 const char *startBuf = SM->getCharacterData(startLoc);
305 const char *semiPtr = strchr(startBuf, ';');
306
307 // Translate to typedef's that forward reference structs with the same name
308 // as the class. As a convenience, we include the original declaration
309 // as a comment.
310 std::string typedefString;
311 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000312 typedefString.append(startBuf, semiPtr-startBuf+1);
313 typedefString += "\n";
314 for (int i = 0; i < numDecls; i++) {
315 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000316 typedefString += "#ifndef _REWRITER_typedef_";
317 typedefString += ForwardDecl->getName();
318 typedefString += "\n";
319 typedefString += "#define _REWRITER_typedef_";
320 typedefString += ForwardDecl->getName();
321 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000322 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000323 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000324 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000325 }
326
327 // Replace the @class with typedefs corresponding to the classes.
328 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
329 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000330}
331
Steve Naroff18c83382007-11-13 23:01:27 +0000332void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000333 for (int i = 0; i < nMethods; i++) {
334 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000335 SourceLocation LocStart = Method->getLocStart();
336 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000337
Steve Narofffbfb46d2007-11-14 14:34:23 +0000338 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
339 Rewrite.InsertText(LocStart, "/* ", 3);
340 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
341 } else {
342 Rewrite.InsertText(LocStart, "// ", 3);
343 }
Steve Naroff667f1682007-10-30 13:30:57 +0000344 }
345}
346
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000347void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
348{
349 for (int i = 0; i < nProperties; i++) {
350 ObjcPropertyDecl *Property = Properties[i];
351 SourceLocation Loc = Property->getLocation();
352
353 Rewrite.ReplaceText(Loc, 0, "// ", 3);
354
355 // FIXME: handle properties that are declared across multiple lines.
356 }
357}
358
Steve Naroff667f1682007-10-30 13:30:57 +0000359void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
360 SourceLocation LocStart = CatDecl->getLocStart();
361
362 // FIXME: handle category headers that are declared across multiple lines.
363 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
364
Steve Naroff18c83382007-11-13 23:01:27 +0000365 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
366 CatDecl->getInstanceMethods());
367 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
368 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000369 // Lastly, comment out the @end.
370 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
371}
372
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000373void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000374 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000375
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000376 SourceLocation LocStart = PDecl->getLocStart();
377
378 // FIXME: handle protocol headers that are declared across multiple lines.
379 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
380
Steve Naroff18c83382007-11-13 23:01:27 +0000381 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
382 PDecl->getInstanceMethods());
383 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
384 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000385 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000386 SourceLocation LocEnd = PDecl->getAtEndLoc();
387 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000388
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000389 // Must comment out @optional/@required
390 const char *startBuf = SM->getCharacterData(LocStart);
391 const char *endBuf = SM->getCharacterData(LocEnd);
392 for (const char *p = startBuf; p < endBuf; p++) {
393 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
394 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000395 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000396 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
397 CommentedOptional.c_str(), CommentedOptional.size());
398
399 }
400 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
401 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000402 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000403 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
404 CommentedRequired.c_str(), CommentedRequired.size());
405
406 }
407 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000408}
409
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000410void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
411 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000412 if (LocStart.isInvalid())
413 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000414 // FIXME: handle forward protocol that are declared across multiple lines.
415 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
416}
417
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000418void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
419 std::string &ResultStr) {
420 ResultStr += "\nstatic ";
421 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000422 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000423
424 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000425 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000426
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000427 if (OMD->isInstance())
428 NameStr += "_I_";
429 else
430 NameStr += "_C_";
431
432 NameStr += OMD->getClassInterface()->getName();
433 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000434
435 NamedDecl *MethodContext = OMD->getMethodContext();
436 if (ObjcCategoryImplDecl *CID =
437 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000438 NameStr += CID->getName();
439 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000440 }
441 // Append selector names, replacing ':' with '_'
442 const char *selName = OMD->getSelector().getName().c_str();
443 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000444 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000445 else {
446 std::string selString = OMD->getSelector().getName();
447 int len = selString.size();
448 for (int i = 0; i < len; i++)
449 if (selString[i] == ':')
450 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000451 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000452 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000453 // Remember this name for metadata emission
454 MethodInternalNames[OMD] = NameStr;
455 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000456
457 // Rewrite arguments
458 ResultStr += "(";
459
460 // invisible arguments
461 if (OMD->isInstance()) {
462 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
463 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000464 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
465 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000466 ResultStr += selfTy.getAsString();
467 }
468 else
469 ResultStr += Context->getObjcIdType().getAsString();
470
471 ResultStr += " self, ";
472 ResultStr += Context->getObjcSelType().getAsString();
473 ResultStr += " _cmd";
474
475 // Method arguments.
476 for (int i = 0; i < OMD->getNumParams(); i++) {
477 ParmVarDecl *PDecl = OMD->getParamDecl(i);
478 ResultStr += ", ";
479 ResultStr += PDecl->getType().getAsString();
480 ResultStr += " ";
481 ResultStr += PDecl->getName();
482 }
483 ResultStr += ")";
484
485}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000486void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
487 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
488 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000489
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000490 if (IMD)
491 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
492 else
493 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000494
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000495 int numMethods = IMD ? IMD->getNumInstanceMethods()
496 : CID->getNumInstanceMethods();
497
498 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000499 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000500 ObjcMethodDecl *OMD;
501 if (IMD)
502 OMD = IMD->getInstanceMethods()[i];
503 else
504 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000505 RewriteObjcMethodDecl(OMD, ResultStr);
506 SourceLocation LocStart = OMD->getLocStart();
507 SourceLocation LocEnd = OMD->getBody()->getLocStart();
508
509 const char *startBuf = SM->getCharacterData(LocStart);
510 const char *endBuf = SM->getCharacterData(LocEnd);
511 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
512 ResultStr.c_str(), ResultStr.size());
513 }
514
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000515 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
516 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000517 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000518 ObjcMethodDecl *OMD;
519 if (IMD)
520 OMD = IMD->getClassMethods()[i];
521 else
522 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000523 RewriteObjcMethodDecl(OMD, ResultStr);
524 SourceLocation LocStart = OMD->getLocStart();
525 SourceLocation LocEnd = OMD->getBody()->getLocStart();
526
527 const char *startBuf = SM->getCharacterData(LocStart);
528 const char *endBuf = SM->getCharacterData(LocEnd);
529 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
530 ResultStr.c_str(), ResultStr.size());
531 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000532 if (IMD)
533 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
534 else
535 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000536}
537
Steve Naroff3774dd92007-10-26 20:53:56 +0000538void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000539 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000540 if (!ObjcForwardDecls.count(ClassDecl)) {
541 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000542 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000543 ResultStr += ClassDecl->getName();
544 ResultStr += "\n";
545 ResultStr += "#define _REWRITER_typedef_";
546 ResultStr += ClassDecl->getName();
547 ResultStr += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000548 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000549 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000550 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000551
552 // Mark this typedef as having been generated.
553 ObjcForwardDecls.insert(ClassDecl);
554 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000555 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
556
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000557 RewriteProperties(ClassDecl->getNumPropertyDecl(),
558 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000559 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
560 ClassDecl->getInstanceMethods());
561 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
562 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000563
Steve Naroff1ccf4632007-10-30 03:43:13 +0000564 // Lastly, comment out the @end.
565 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000566}
567
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000568//===----------------------------------------------------------------------===//
569// Function Body / Expression rewriting
570//===----------------------------------------------------------------------===//
571
Steve Naroff334fbc22007-11-09 15:20:18 +0000572Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000573 // Otherwise, just rewrite all children.
574 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
575 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000576 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000577 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000578 if (newStmt)
579 *CI = newStmt;
580 }
Steve Naroffe9780582007-10-23 23:50:29 +0000581
582 // Handle specific things.
583 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
584 return RewriteAtEncode(AtEncode);
Steve Naroff296b74f2007-11-05 14:50:49 +0000585
586 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
587 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000588
589 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
590 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000591
Steve Naroff71226032007-10-24 22:48:43 +0000592 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
593 // Before we rewrite it, put the original message expression in a comment.
594 SourceLocation startLoc = MessExpr->getLocStart();
595 SourceLocation endLoc = MessExpr->getLocEnd();
596
597 const char *startBuf = SM->getCharacterData(startLoc);
598 const char *endBuf = SM->getCharacterData(endLoc);
599
600 std::string messString;
601 messString += "// ";
602 messString.append(startBuf, endBuf-startBuf+1);
603 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000604
Steve Naroff71226032007-10-24 22:48:43 +0000605 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
606 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
607 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000608 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000609 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000610 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000611
612 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
613 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000614
615 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
616 return RewriteObjcThrowStmt(StmtThrow);
617
Chris Lattner0021f452007-10-24 16:57:36 +0000618 // Return this stmt unmodified.
619 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000620}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000621
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000622Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000623 // Get the start location and compute the semi location.
624 SourceLocation startLoc = S->getLocStart();
625 const char *startBuf = SM->getCharacterData(startLoc);
626
627 assert((*startBuf == '@') && "bogus @try location");
628
629 std::string buf;
630 // declare a new scope with two variables, _stack and _rethrow.
631 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
632 buf += "int buf[18/*32-bit i386*/];\n";
633 buf += "char *pointers[4];} _stack;\n";
634 buf += "id volatile _rethrow = 0;\n";
635 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000636 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000637
638 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
639
640 startLoc = S->getTryBody()->getLocEnd();
641 startBuf = SM->getCharacterData(startLoc);
642
643 assert((*startBuf == '}') && "bogus @try block");
644
645 SourceLocation lastCurlyLoc = startLoc;
646
647 startLoc = startLoc.getFileLocWithOffset(1);
648 buf = " /* @catch begin */ else {\n";
649 buf += " id _caught = objc_exception_extract(&_stack);\n";
650 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000651 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000652 buf += " _rethrow = objc_exception_extract(&_stack);\n";
653 buf += " else { /* @catch continue */";
654
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000655 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000656
657 bool sawIdTypedCatch = false;
658 Stmt *lastCatchBody = 0;
659 ObjcAtCatchStmt *catchList = S->getCatchStmts();
660 while (catchList) {
661 Stmt *catchStmt = catchList->getCatchParamStmt();
662
663 if (catchList == S->getCatchStmts())
664 buf = "if ("; // we are generating code for the first catch clause
665 else
666 buf = "else if (";
667 startLoc = catchList->getLocStart();
668 startBuf = SM->getCharacterData(startLoc);
669
670 assert((*startBuf == '@') && "bogus @catch location");
671
672 const char *lParenLoc = strchr(startBuf, '(');
673
674 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
675 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
676 if (t == Context->getObjcIdType()) {
677 buf += "1) { ";
678 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
679 buf.c_str(), buf.size());
680 sawIdTypedCatch = true;
681 } else if (const PointerType *pType = t->getAsPointerType()) {
682 ObjcInterfaceType *cls; // Should be a pointer to a class.
683
684 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
685 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000686 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000687 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000688 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000689 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
690 buf.c_str(), buf.size());
691 }
692 }
693 // Now rewrite the body...
694 lastCatchBody = catchList->getCatchBody();
695 SourceLocation rParenLoc = catchList->getRParenLoc();
696 SourceLocation bodyLoc = lastCatchBody->getLocStart();
697 const char *bodyBuf = SM->getCharacterData(bodyLoc);
698 const char *rParenBuf = SM->getCharacterData(rParenLoc);
699 assert((*rParenBuf == ')') && "bogus @catch paren location");
700 assert((*bodyBuf == '{') && "bogus @catch body location");
701
702 buf = " = _caught;";
703 // Here we replace ") {" with "= _caught;" (which initializes and
704 // declares the @catch parameter).
705 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
706 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000707 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000708 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000709 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000710 catchList = catchList->getNextCatchStmt();
711 }
712 // Complete the catch list...
713 if (lastCatchBody) {
714 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
715 const char *bodyBuf = SM->getCharacterData(bodyLoc);
716 assert((*bodyBuf == '}') && "bogus @catch body location");
717 bodyLoc = bodyLoc.getFileLocWithOffset(1);
718 buf = " } } /* @catch end */\n";
719
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000720 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000721
722 // Set lastCurlyLoc
723 lastCurlyLoc = lastCatchBody->getLocEnd();
724 }
725 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
726 startLoc = finalStmt->getLocStart();
727 startBuf = SM->getCharacterData(startLoc);
728 assert((*startBuf == '@') && "bogus @finally start");
729
730 buf = "/* @finally */";
731 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
732
733 Stmt *body = finalStmt->getFinallyBody();
734 SourceLocation startLoc = body->getLocStart();
735 SourceLocation endLoc = body->getLocEnd();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *endBuf = SM->getCharacterData(endLoc);
738 assert((*startBuf == '{') && "bogus @finally body location");
739 assert((*endBuf == '}') && "bogus @finally body location");
740
741 startLoc = startLoc.getFileLocWithOffset(1);
742 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000743 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000744 endLoc = endLoc.getFileLocWithOffset(-1);
745 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000746 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000747
748 // Set lastCurlyLoc
749 lastCurlyLoc = body->getLocEnd();
750 }
751 // Now emit the final closing curly brace...
752 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
753 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000754 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000755 return 0;
756}
757
758Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
759 return 0;
760}
761
762Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
763 return 0;
764}
765
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000766// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
767// the throw expression is typically a message expression that's already
768// been rewritten! (which implies the SourceLocation's are invalid).
769Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
770 // Get the start location and compute the semi location.
771 SourceLocation startLoc = S->getLocStart();
772 const char *startBuf = SM->getCharacterData(startLoc);
773
774 assert((*startBuf == '@') && "bogus @throw location");
775
776 std::string buf;
777 /* void objc_exception_throw(id) __attribute__((noreturn)); */
778 buf = "objc_exception_throw(";
779 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
780 const char *semiBuf = strchr(startBuf, ';');
781 assert((*semiBuf == ';') && "@throw: can't find ';'");
782 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
783 buf = ");";
784 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
785 return 0;
786}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000787
Chris Lattner0021f452007-10-24 16:57:36 +0000788Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000789 // Create a new string expression.
790 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000791 std::string StrEncoding;
792 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
793 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
794 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000795 SourceLocation(), SourceLocation());
796 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000797 delete Exp;
798 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000799}
800
Steve Naroff296b74f2007-11-05 14:50:49 +0000801Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
802 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
803 // Create a call to sel_registerName("selName").
804 llvm::SmallVector<Expr*, 8> SelExprs;
805 QualType argType = Context->getPointerType(Context->CharTy);
806 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
807 Exp->getSelector().getName().size(),
808 false, argType, SourceLocation(),
809 SourceLocation()));
810 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
811 &SelExprs[0], SelExprs.size());
812 Rewrite.ReplaceStmt(Exp, SelExp);
813 delete Exp;
814 return SelExp;
815}
816
Steve Naroff71226032007-10-24 22:48:43 +0000817CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
818 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000819 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000820 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000821
822 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000823 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000824
825 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000826 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000827 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
828
829 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000830
Steve Naroff71226032007-10-24 22:48:43 +0000831 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
832}
833
Steve Naroffc8a92d12007-11-01 13:24:47 +0000834static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
835 const char *&startRef, const char *&endRef) {
836 while (startBuf < endBuf) {
837 if (*startBuf == '<')
838 startRef = startBuf; // mark the start.
839 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000840 if (startRef && *startRef == '<') {
841 endRef = startBuf; // mark the end.
842 return true;
843 }
844 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000845 }
846 startBuf++;
847 }
848 return false;
849}
850
851bool RewriteTest::needToScanForQualifiers(QualType T) {
852 // FIXME: we don't currently represent "id <Protocol>" in the type system.
853 if (T == Context->getObjcIdType())
854 return true;
855
856 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000857 Type *pointeeType = pType->getPointeeType().getTypePtr();
858 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
859 return true; // we have "Class <Protocol> *".
860 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000861 return false;
862}
863
864void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
865 const FunctionTypeProto *proto, FunctionDecl *FD) {
866
867 if (needToScanForQualifiers(proto->getResultType())) {
868 // Since types are unique, we need to scan the buffer.
869 SourceLocation Loc = FD->getLocation();
870
871 const char *endBuf = SM->getCharacterData(Loc);
872 const char *startBuf = endBuf;
873 while (*startBuf != ';')
874 startBuf--; // scan backward (from the decl location) for return type.
875 const char *startRef = 0, *endRef = 0;
876 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
877 // Get the locations of the startRef, endRef.
878 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
879 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
880 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000881 Rewrite.InsertText(LessLoc, "/*", 2);
882 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000883 }
884 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000885 // Now check arguments.
886 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
887 if (needToScanForQualifiers(proto->getArgType(i))) {
888 // Since types are unique, we need to scan the buffer.
889 SourceLocation Loc = FD->getLocation();
890
891 const char *startBuf = SM->getCharacterData(Loc);
892 const char *endBuf = startBuf;
893 while (*endBuf != ';')
894 endBuf++; // scan forward (from the decl location) for argument types.
895 const char *startRef = 0, *endRef = 0;
896 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
897 // Get the locations of the startRef, endRef.
898 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
899 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
900 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000901 Rewrite.InsertText(LessLoc, "/*", 2);
902 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000903 }
904 }
905 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000906}
907
Steve Naroff02a82aa2007-10-30 23:14:51 +0000908void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
909 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000910 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000911 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000912 return;
913 }
914 // Check for ObjC 'id' and class types that have been adorned with protocol
915 // information (id<p>, C<p>*). The protocol references need to be rewritten!
916 const FunctionType *funcType = FD->getType()->getAsFunctionType();
917 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000918 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
919 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000920}
921
922// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
923void RewriteTest::SynthMsgSendFunctionDecl() {
924 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
925 llvm::SmallVector<QualType, 16> ArgTys;
926 QualType argT = Context->getObjcIdType();
927 assert(!argT.isNull() && "Can't find 'id' type");
928 ArgTys.push_back(argT);
929 argT = Context->getObjcSelType();
930 assert(!argT.isNull() && "Can't find 'SEL' type");
931 ArgTys.push_back(argT);
932 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
933 &ArgTys[0], ArgTys.size(),
934 true /*isVariadic*/);
935 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
936 msgSendIdent, msgSendType,
937 FunctionDecl::Extern, false, 0);
938}
939
940// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
941void RewriteTest::SynthGetClassFunctionDecl() {
942 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
943 llvm::SmallVector<QualType, 16> ArgTys;
944 ArgTys.push_back(Context->getPointerType(
945 Context->CharTy.getQualifiedType(QualType::Const)));
946 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
947 &ArgTys[0], ArgTys.size(),
948 false /*isVariadic*/);
949 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
950 getClassIdent, getClassType,
951 FunctionDecl::Extern, false, 0);
952}
953
Steve Naroffabb96362007-11-08 14:30:50 +0000954// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
955void RewriteTest::SynthCFStringFunctionDecl() {
956 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
957 llvm::SmallVector<QualType, 16> ArgTys;
958 ArgTys.push_back(Context->getPointerType(
959 Context->CharTy.getQualifiedType(QualType::Const)));
960 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
961 &ArgTys[0], ArgTys.size(),
962 false /*isVariadic*/);
963 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
964 getClassIdent, getClassType,
965 FunctionDecl::Extern, false, 0);
966}
967
Steve Naroff0add5d22007-11-03 11:27:19 +0000968Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +0000969#if 1
970 // This rewrite is specific to GCC, which has builtin support for CFString.
971 if (!CFStringFunctionDecl)
972 SynthCFStringFunctionDecl();
973 // Create a call to __builtin___CFStringMakeConstantString("cstr").
974 llvm::SmallVector<Expr*, 8> StrExpr;
975 StrExpr.push_back(Exp->getString());
976 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
977 &StrExpr[0], StrExpr.size());
978 // cast to NSConstantString *
979 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
980 Rewrite.ReplaceStmt(Exp, cast);
981 delete Exp;
982 return cast;
983#else
Steve Naroff0add5d22007-11-03 11:27:19 +0000984 assert(ConstantStringClassReference && "Can't find constant string reference");
985 llvm::SmallVector<Expr*, 4> InitExprs;
986
987 // Synthesize "(Class)&_NSConstantStringClassReference"
988 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
989 ConstantStringClassReference->getType(),
990 SourceLocation());
991 QualType expType = Context->getPointerType(ClsRef->getType());
992 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
993 expType, SourceLocation());
994 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
995 SourceLocation());
996 InitExprs.push_back(cast); // set the 'isa'.
997 InitExprs.push_back(Exp->getString()); // set "char *bytes".
998 unsigned IntSize = static_cast<unsigned>(
999 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1000 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1001 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1002 Exp->getLocStart());
1003 InitExprs.push_back(len); // set "int numBytes".
1004
1005 // struct NSConstantString
1006 QualType CFConstantStrType = Context->getCFConstantStringType();
1007 // (struct NSConstantString) { <exprs from above> }
1008 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1009 &InitExprs[0], InitExprs.size(),
1010 SourceLocation());
1011 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1012 // struct NSConstantString *
1013 expType = Context->getPointerType(StrRep->getType());
1014 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1015 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001016 // cast to NSConstantString *
1017 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001018 Rewrite.ReplaceStmt(Exp, cast);
1019 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001020 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001021#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001022}
1023
Steve Naroff71226032007-10-24 22:48:43 +00001024Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +00001025 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +00001026 if (!MsgSendFunctionDecl)
1027 SynthMsgSendFunctionDecl();
1028 if (!GetClassFunctionDecl)
1029 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +00001030
1031 // Synthesize a call to objc_msgSend().
1032 llvm::SmallVector<Expr*, 8> MsgExprs;
1033 IdentifierInfo *clsName = Exp->getClassName();
1034
1035 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1036 if (clsName) { // class message.
1037 llvm::SmallVector<Expr*, 8> ClsExprs;
1038 QualType argType = Context->getPointerType(Context->CharTy);
1039 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1040 clsName->getLength(),
1041 false, argType, SourceLocation(),
1042 SourceLocation()));
1043 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1044 &ClsExprs[0], ClsExprs.size());
1045 MsgExprs.push_back(Cls);
Steve Naroff885e2122007-11-14 23:54:14 +00001046 } else { // instance message.
1047 Expr *recExpr = Exp->getReceiver();
Steve Naroff71226032007-10-24 22:48:43 +00001048
Steve Naroff26eb0812007-11-15 00:00:21 +00001049 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
Steve Naroff885e2122007-11-14 23:54:14 +00001050 MsgExprs.push_back(recExpr);
1051 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001052 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001053 llvm::SmallVector<Expr*, 8> SelExprs;
1054 QualType argType = Context->getPointerType(Context->CharTy);
1055 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1056 Exp->getSelector().getName().size(),
1057 false, argType, SourceLocation(),
1058 SourceLocation()));
1059 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1060 &SelExprs[0], SelExprs.size());
1061 MsgExprs.push_back(SelExp);
1062
1063 // Now push any user supplied arguments.
1064 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001065 Expr *userExpr = Exp->getArg(i);
1066#if 0
1067 // Make sure we cast "self" to "id".
1068 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(userExpr)) {
1069 if (!strcmp(DRE->getDecl()->getName(), "self"))
1070 userExpr = new CastExpr(Context->getObjcIdType(), userExpr,
1071 SourceLocation());
1072 }
1073#endif
1074 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001075 // We've transferred the ownership to MsgExprs. Null out the argument in
1076 // the original expression, since we will delete it below.
1077 Exp->setArg(i, 0);
1078 }
Steve Naroff0744c472007-11-04 22:37:50 +00001079 // Generate the funky cast.
1080 CastExpr *cast;
1081 llvm::SmallVector<QualType, 8> ArgTypes;
1082 QualType returnType;
1083
1084 // Push 'id' and 'SEL', the 2 implicit arguments.
1085 ArgTypes.push_back(Context->getObjcIdType());
1086 ArgTypes.push_back(Context->getObjcSelType());
1087 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1088 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001089 for (int i = 0; i < mDecl->getNumParams(); i++) {
1090 QualType t = mDecl->getParamDecl(i)->getType();
1091 if (t == Context->getObjcClassType())
1092 t = Context->getObjcIdType(); // Convert "Class"->"id"
1093 ArgTypes.push_back(t);
1094 }
Steve Naroff0744c472007-11-04 22:37:50 +00001095 returnType = mDecl->getResultType();
1096 } else {
1097 returnType = Context->getObjcIdType();
1098 }
1099 // Get the type, we will need to reference it in a couple spots.
1100 QualType msgSendType = MsgSendFunctionDecl->getType();
1101
1102 // Create a reference to the objc_msgSend() declaration.
1103 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1104
1105 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1106 // If we don't do this cast, we get the following bizarre warning/note:
1107 // xx.m:13: warning: function called through a non-compatible type
1108 // xx.m:13: note: if this code is reached, the program will abort
1109 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1110 SourceLocation());
1111
1112 // Now do the "normal" pointer to function cast.
1113 QualType castType = Context->getFunctionType(returnType,
1114 &ArgTypes[0], ArgTypes.size(),
1115 false/*FIXME:variadic*/);
1116 castType = Context->getPointerType(castType);
1117 cast = new CastExpr(castType, cast, SourceLocation());
1118
1119 // Don't forget the parens to enforce the proper binding.
1120 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1121
1122 const FunctionType *FT = msgSendType->getAsFunctionType();
1123 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1124 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001125 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001126 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001127
Chris Lattner0021f452007-10-24 16:57:36 +00001128 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001129 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001130}
1131
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001132/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1133/// an objective-c class with ivars.
1134void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1135 std::string &Result) {
1136 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1137 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001138 // Do not synthesize more than once.
1139 if (ObjcSynthesizedStructs.count(CDecl))
1140 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001141 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1142 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1143 // Do it for the root
1144 SynthesizeObjcInternalStruct(RCDecl, Result);
1145 }
1146
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001147 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001148 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +00001149 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001150 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1151 return;
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001152 // FIXME: This has potential of causing problem. If
1153 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001154 Result += "\nstruct ";
1155 Result += CDecl->getName();
1156
1157 SourceLocation LocStart = CDecl->getLocStart();
1158 SourceLocation LocEnd = CDecl->getLocEnd();
1159
1160 const char *startBuf = SM->getCharacterData(LocStart);
1161 const char *endBuf = SM->getCharacterData(LocEnd);
1162
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001163 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001164 const char *cursor = strchr(startBuf, '{');
1165 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001166 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001167
1168 // rewrite the original header *without* disturbing the '{'
1169 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1170 Result.c_str(), Result.size());
1171 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1172 Result = "\n struct ";
1173 Result += RCDecl->getName();
1174 Result += " _";
1175 Result += RCDecl->getName();
1176 Result += ";\n";
1177
1178 // insert the super class structure definition.
1179 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1180 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1181 }
1182 cursor++; // past '{'
1183
1184 // Now comment out any visibility specifiers.
1185 while (cursor < endBuf) {
1186 if (*cursor == '@') {
1187 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001188 // Skip whitespace.
1189 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1190 /*scan*/;
1191
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001192 // FIXME: presence of @public, etc. inside comment results in
1193 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001194 if (!strncmp(cursor, "public", strlen("public")) ||
1195 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001196 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001197 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001198 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001199 // FIXME: If there are cases where '<' is used in ivar declaration part
1200 // of user code, then scan the ivar list and use needToScanForQualifiers
1201 // for type checking.
1202 else if (*cursor == '<') {
1203 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1204 Rewrite.InsertText(atLoc, "/* ", 3);
1205 cursor = strchr(cursor, '>');
1206 cursor++;
1207 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1208 Rewrite.InsertText(atLoc, " */", 3);
1209 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001210 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001211 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001212 // Don't forget to add a ';'!!
1213 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1214 } else { // we don't have any instance variables - insert super struct.
1215 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1216 Result += " {\n struct ";
1217 Result += RCDecl->getName();
1218 Result += " _";
1219 Result += RCDecl->getName();
1220 Result += ";\n};\n";
1221 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1222 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001223 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001224 // Mark this struct as having been generated.
1225 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001226 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001227}
1228
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001229// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1230/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001231void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001232 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001233 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001234 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001235 const char *ClassName,
1236 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001237 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001238 if (NumMethods > 0 && !objc_impl_method) {
1239 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001240 SEL _cmd;
1241 char *method_types;
1242 void *_imp;
1243 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001244 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001245 Result += "\nstruct _objc_method {\n";
1246 Result += "\tSEL _cmd;\n";
1247 Result += "\tchar *method_types;\n";
1248 Result += "\tvoid *_imp;\n";
1249 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001250
1251 /* struct _objc_method_list {
1252 struct _objc_method_list *next_method;
1253 int method_count;
1254 struct _objc_method method_list[];
1255 }
1256 */
1257 Result += "\nstruct _objc_method_list {\n";
1258 Result += "\tstruct _objc_method_list *next_method;\n";
1259 Result += "\tint method_count;\n";
1260 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001261 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001262 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001263 // Build _objc_method_list for class's methods if needed
1264 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001265 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001266 Result += prefix;
1267 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1268 Result += "_METHODS_";
1269 Result += ClassName;
1270 Result += " __attribute__ ((section (\"__OBJC, __";
1271 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001272 Result += "_meth\")))= ";
1273 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1274
1275 Result += "\t,{{(SEL)\"";
1276 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001277 std::string MethodTypeString;
1278 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1279 Result += "\", \"";
1280 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001281 Result += "\", ";
1282 Result += MethodInternalNames[Methods[0]];
1283 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001284 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001285 Result += "\t ,{(SEL)\"";
1286 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001287 std::string MethodTypeString;
1288 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1289 Result += "\", \"";
1290 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001291 Result += "\", ";
1292 Result += MethodInternalNames[Methods[i]];
1293 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001294 }
1295 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001296 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001297}
1298
1299/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1300void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1301 int NumProtocols,
1302 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001303 const char *ClassName,
1304 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001305 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001306 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001307 for (int i = 0; i < NumProtocols; i++) {
1308 ObjcProtocolDecl *PDecl = Protocols[i];
1309 // Output struct protocol_methods holder of method selector and type.
1310 if (!objc_protocol_methods &&
1311 (PDecl->getNumInstanceMethods() > 0
1312 || PDecl->getNumClassMethods() > 0)) {
1313 /* struct protocol_methods {
1314 SEL _cmd;
1315 char *method_types;
1316 }
1317 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001318 Result += "\nstruct protocol_methods {\n";
1319 Result += "\tSEL _cmd;\n";
1320 Result += "\tchar *method_types;\n";
1321 Result += "};\n";
1322
1323 /* struct _objc_protocol_method_list {
1324 int protocol_method_count;
1325 struct protocol_methods protocols[];
1326 }
1327 */
1328 Result += "\nstruct _objc_protocol_method_list {\n";
1329 Result += "\tint protocol_method_count;\n";
1330 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001331 objc_protocol_methods = true;
1332 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001333
Fariborz Jahanian04455192007-10-22 21:41:37 +00001334 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001335 int NumMethods = PDecl->getNumInstanceMethods();
1336 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001337 Result += "\nstatic struct _objc_protocol_method_list "
1338 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1339 Result += PDecl->getName();
1340 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1341 "{\n\t" + utostr(NumMethods) + "\n";
1342
Fariborz Jahanian04455192007-10-22 21:41:37 +00001343 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001344 Result += "\t,{{(SEL)\"";
1345 Result += Methods[0]->getSelector().getName().c_str();
1346 Result += "\", \"\"}\n";
1347
1348 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001349 Result += "\t ,{(SEL)\"";
1350 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001351 std::string MethodTypeString;
1352 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1353 Result += "\", \"";
1354 Result += MethodTypeString;
1355 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001356 }
1357 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001358 }
1359
1360 // Output class methods declared in this protocol.
1361 NumMethods = PDecl->getNumClassMethods();
1362 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001363 Result += "\nstatic struct _objc_protocol_method_list "
1364 "_OBJC_PROTOCOL_CLASS_METHODS_";
1365 Result += PDecl->getName();
1366 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1367 "{\n\t";
1368 Result += utostr(NumMethods);
1369 Result += "\n";
1370
Fariborz Jahanian04455192007-10-22 21:41:37 +00001371 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001372 Result += "\t,{{(SEL)\"";
1373 Result += Methods[0]->getSelector().getName().c_str();
1374 Result += "\", \"\"}\n";
1375
1376 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001377 Result += "\t ,{(SEL)\"";
1378 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001379 std::string MethodTypeString;
1380 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1381 Result += "\", \"";
1382 Result += MethodTypeString;
1383 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001384 }
1385 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001386 }
1387 // Output:
1388 /* struct _objc_protocol {
1389 // Objective-C 1.0 extensions
1390 struct _objc_protocol_extension *isa;
1391 char *protocol_name;
1392 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001393 struct _objc_protocol_method_list *instance_methods;
1394 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001395 };
1396 */
1397 static bool objc_protocol = false;
1398 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001399 Result += "\nstruct _objc_protocol {\n";
1400 Result += "\tstruct _objc_protocol_extension *isa;\n";
1401 Result += "\tchar *protocol_name;\n";
1402 Result += "\tstruct _objc_protocol **protocol_list;\n";
1403 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1404 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1405 Result += "};\n";
1406
1407 /* struct _objc_protocol_list {
1408 struct _objc_protocol_list *next;
1409 int protocol_count;
1410 struct _objc_protocol *class_protocols[];
1411 }
1412 */
1413 Result += "\nstruct _objc_protocol_list {\n";
1414 Result += "\tstruct _objc_protocol_list *next;\n";
1415 Result += "\tint protocol_count;\n";
1416 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1417 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001418 objc_protocol = true;
1419 }
1420
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001421 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1422 Result += PDecl->getName();
1423 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1424 "{\n\t0, \"";
1425 Result += PDecl->getName();
1426 Result += "\", 0, ";
1427 if (PDecl->getInstanceMethods() > 0) {
1428 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1429 Result += PDecl->getName();
1430 Result += ", ";
1431 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001432 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001433 Result += "0, ";
1434 if (PDecl->getClassMethods() > 0) {
1435 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1436 Result += PDecl->getName();
1437 Result += "\n";
1438 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001439 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001440 Result += "0\n";
1441 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001442 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001443 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001444 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1445 Result += prefix;
1446 Result += "_PROTOCOLS_";
1447 Result += ClassName;
1448 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1449 "{\n\t0, ";
1450 Result += utostr(NumProtocols);
1451 Result += "\n";
1452
1453 Result += "\t,{&_OBJC_PROTOCOL_";
1454 Result += Protocols[0]->getName();
1455 Result += " \n";
1456
1457 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001458 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001459 Result += "\t ,&_OBJC_PROTOCOL_";
1460 Result += PDecl->getName();
1461 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001462 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001463 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001464 }
1465}
1466
1467/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1468/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001469void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1470 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001471 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1472 // Find category declaration for this implementation.
1473 ObjcCategoryDecl *CDecl;
1474 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1475 CDecl = CDecl->getNextClassCategory())
1476 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1477 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001478
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001479 char *FullCategoryName = (char*)alloca(
1480 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1481 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1482
1483 // Build _objc_method_list for class's instance methods if needed
1484 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1485 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001486 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001487 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001488
1489 // Build _objc_method_list for class's class methods if needed
1490 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1491 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001492 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001493 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001494
1495 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001496 // Null CDecl is case of a category implementation with no category interface
1497 if (CDecl)
1498 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1499 CDecl->getNumReferencedProtocols(),
1500 "CATEGORY",
1501 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001502
1503 /* struct _objc_category {
1504 char *category_name;
1505 char *class_name;
1506 struct _objc_method_list *instance_methods;
1507 struct _objc_method_list *class_methods;
1508 struct _objc_protocol_list *protocols;
1509 // Objective-C 1.0 extensions
1510 uint32_t size; // sizeof (struct _objc_category)
1511 struct _objc_property_list *instance_properties; // category's own
1512 // @property decl.
1513 };
1514 */
1515
1516 static bool objc_category = false;
1517 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001518 Result += "\nstruct _objc_category {\n";
1519 Result += "\tchar *category_name;\n";
1520 Result += "\tchar *class_name;\n";
1521 Result += "\tstruct _objc_method_list *instance_methods;\n";
1522 Result += "\tstruct _objc_method_list *class_methods;\n";
1523 Result += "\tstruct _objc_protocol_list *protocols;\n";
1524 Result += "\tunsigned int size;\n";
1525 Result += "\tstruct _objc_property_list *instance_properties;\n";
1526 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001527 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001528 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001529 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1530 Result += FullCategoryName;
1531 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1532 Result += IDecl->getName();
1533 Result += "\"\n\t, \"";
1534 Result += ClassDecl->getName();
1535 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001536
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001537 if (IDecl->getNumInstanceMethods() > 0) {
1538 Result += "\t, (struct _objc_method_list *)"
1539 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1540 Result += FullCategoryName;
1541 Result += "\n";
1542 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001543 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001544 Result += "\t, 0\n";
1545 if (IDecl->getNumClassMethods() > 0) {
1546 Result += "\t, (struct _objc_method_list *)"
1547 "&_OBJC_CATEGORY_CLASS_METHODS_";
1548 Result += FullCategoryName;
1549 Result += "\n";
1550 }
1551 else
1552 Result += "\t, 0\n";
1553
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001554 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001555 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1556 Result += FullCategoryName;
1557 Result += "\n";
1558 }
1559 else
1560 Result += "\t, 0\n";
1561 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001562}
1563
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001564/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1565/// ivar offset.
1566void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1567 ObjcIvarDecl *ivar,
1568 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001569 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001570 Result += IDecl->getName();
1571 Result += ", ";
1572 Result += ivar->getName();
1573 Result += ")";
1574}
1575
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001576//===----------------------------------------------------------------------===//
1577// Meta Data Emission
1578//===----------------------------------------------------------------------===//
1579
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001580void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1581 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001582 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1583
1584 // Build _objc_ivar_list metadata for classes ivars if needed
1585 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1586 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001587 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001588
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001589 SynthesizeObjcInternalStruct(CDecl, Result);
1590
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001591 if (NumIvars > 0) {
1592 static bool objc_ivar = false;
1593 if (!objc_ivar) {
1594 /* struct _objc_ivar {
1595 char *ivar_name;
1596 char *ivar_type;
1597 int ivar_offset;
1598 };
1599 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001600 Result += "\nstruct _objc_ivar {\n";
1601 Result += "\tchar *ivar_name;\n";
1602 Result += "\tchar *ivar_type;\n";
1603 Result += "\tint ivar_offset;\n";
1604 Result += "};\n";
1605
1606 /* struct _objc_ivar_list {
1607 int ivar_count;
1608 struct _objc_ivar ivar_list[];
1609 };
1610 */
1611 Result += "\nstruct _objc_ivar_list {\n";
1612 Result += "\tint ivar_count;\n";
1613 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001614 objc_ivar = true;
1615 }
1616
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001617 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1618 Result += IDecl->getName();
1619 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1620 "{\n\t";
1621 Result += utostr(NumIvars);
1622 Result += "\n";
1623
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001624 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1625 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001626 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001627 Result += "\t,{{\"";
1628 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001629 Result += "\", \"";
1630 std::string StrEncoding;
1631 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1632 Result += StrEncoding;
1633 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001634 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1635 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001636 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001637 Result += "\t ,{\"";
1638 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001639 Result += "\", \"";
1640 std::string StrEncoding;
1641 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1642 Result += StrEncoding;
1643 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001644 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1645 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001646 }
1647
1648 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001649 }
1650
1651 // Build _objc_method_list for class's instance methods if needed
1652 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1653 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001654 true,
1655 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001656
1657 // Build _objc_method_list for class's class methods if needed
1658 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001659 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001660 false,
1661 "", IDecl->getName(), Result);
1662
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001663 // Protocols referenced in class declaration?
1664 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1665 CDecl->getNumIntfRefProtocols(),
1666 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001667 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001668
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001669
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001670 // Declaration of class/meta-class metadata
1671 /* struct _objc_class {
1672 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001673 const char *super_class_name;
1674 char *name;
1675 long version;
1676 long info;
1677 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001678 struct _objc_ivar_list *ivars;
1679 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001680 struct objc_cache *cache;
1681 struct objc_protocol_list *protocols;
1682 const char *ivar_layout;
1683 struct _objc_class_ext *ext;
1684 };
1685 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001686 static bool objc_class = false;
1687 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001688 Result += "\nstruct _objc_class {\n";
1689 Result += "\tstruct _objc_class *isa;\n";
1690 Result += "\tconst char *super_class_name;\n";
1691 Result += "\tchar *name;\n";
1692 Result += "\tlong version;\n";
1693 Result += "\tlong info;\n";
1694 Result += "\tlong instance_size;\n";
1695 Result += "\tstruct _objc_ivar_list *ivars;\n";
1696 Result += "\tstruct _objc_method_list *methods;\n";
1697 Result += "\tstruct objc_cache *cache;\n";
1698 Result += "\tstruct _objc_protocol_list *protocols;\n";
1699 Result += "\tconst char *ivar_layout;\n";
1700 Result += "\tstruct _objc_class_ext *ext;\n";
1701 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001702 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001703 }
1704
1705 // Meta-class metadata generation.
1706 ObjcInterfaceDecl *RootClass = 0;
1707 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1708 while (SuperClass) {
1709 RootClass = SuperClass;
1710 SuperClass = SuperClass->getSuperClass();
1711 }
1712 SuperClass = CDecl->getSuperClass();
1713
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001714 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1715 Result += CDecl->getName();
1716 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1717 "{\n\t(struct _objc_class *)\"";
1718 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1719 Result += "\"";
1720
1721 if (SuperClass) {
1722 Result += ", \"";
1723 Result += SuperClass->getName();
1724 Result += "\", \"";
1725 Result += CDecl->getName();
1726 Result += "\"";
1727 }
1728 else {
1729 Result += ", 0, \"";
1730 Result += CDecl->getName();
1731 Result += "\"";
1732 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001733 // TODO: 'ivars' field for root class is currently set to 0.
1734 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001735 Result += ", 0,2, sizeof(struct _objc_class), 0";
1736 if (CDecl->getNumClassMethods() > 0) {
1737 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1738 Result += CDecl->getName();
1739 Result += "\n";
1740 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001741 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001742 Result += ", 0\n";
1743 if (CDecl->getNumIntfRefProtocols() > 0) {
1744 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1745 Result += CDecl->getName();
1746 Result += ",0,0\n";
1747 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001748 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001749 Result += "\t,0,0,0,0\n";
1750 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001751
1752 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001753 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1754 Result += CDecl->getName();
1755 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1756 "{\n\t&_OBJC_METACLASS_";
1757 Result += CDecl->getName();
1758 if (SuperClass) {
1759 Result += ", \"";
1760 Result += SuperClass->getName();
1761 Result += "\", \"";
1762 Result += CDecl->getName();
1763 Result += "\"";
1764 }
1765 else {
1766 Result += ", 0, \"";
1767 Result += CDecl->getName();
1768 Result += "\"";
1769 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001770 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001771 Result += ", 0,1";
1772 if (!ObjcSynthesizedStructs.count(CDecl))
1773 Result += ",0";
1774 else {
1775 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001776 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001777 Result += CDecl->getName();
1778 Result += ")";
1779 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001780 if (NumIvars > 0) {
1781 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1782 Result += CDecl->getName();
1783 Result += "\n\t";
1784 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001785 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001786 Result += ",0";
1787 if (IDecl->getNumInstanceMethods() > 0) {
1788 Result += ", &_OBJC_INSTANCE_METHODS_";
1789 Result += CDecl->getName();
1790 Result += ", 0\n\t";
1791 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001792 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001793 Result += ",0,0";
1794 if (CDecl->getNumIntfRefProtocols() > 0) {
1795 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1796 Result += CDecl->getName();
1797 Result += ", 0,0\n";
1798 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001799 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001800 Result += ",0,0,0\n";
1801 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001802}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001803
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001804/// RewriteImplementations - This routine rewrites all method implementations
1805/// and emits meta-data.
1806
1807void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001808 int ClsDefCount = ClassImplementation.size();
1809 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001810
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001811 if (ClsDefCount == 0 && CatDefCount == 0)
1812 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001813 // Rewrite implemented methods
1814 for (int i = 0; i < ClsDefCount; i++)
1815 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001816
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001817 for (int i = 0; i < CatDefCount; i++)
1818 RewriteImplementationDecl(CategoryImplementation[i]);
1819
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001820 // This is needed for use of offsetof
1821 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001822
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001823 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001824 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001825 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001826
1827 // For each implemented category, write out all its meta data.
1828 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001829 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001830
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001831 // Write objc_symtab metadata
1832 /*
1833 struct _objc_symtab
1834 {
1835 long sel_ref_cnt;
1836 SEL *refs;
1837 short cls_def_cnt;
1838 short cat_def_cnt;
1839 void *defs[cls_def_cnt + cat_def_cnt];
1840 };
1841 */
1842
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001843 Result += "\nstruct _objc_symtab {\n";
1844 Result += "\tlong sel_ref_cnt;\n";
1845 Result += "\tSEL *refs;\n";
1846 Result += "\tshort cls_def_cnt;\n";
1847 Result += "\tshort cat_def_cnt;\n";
1848 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1849 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001850
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001851 Result += "static struct _objc_symtab "
1852 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1853 Result += "\t0, 0, " + utostr(ClsDefCount)
1854 + ", " + utostr(CatDefCount) + "\n";
1855 for (int i = 0; i < ClsDefCount; i++) {
1856 Result += "\t,&_OBJC_CLASS_";
1857 Result += ClassImplementation[i]->getName();
1858 Result += "\n";
1859 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001860
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001861 for (int i = 0; i < CatDefCount; i++) {
1862 Result += "\t,&_OBJC_CATEGORY_";
1863 Result += CategoryImplementation[i]->getClassInterface()->getName();
1864 Result += "_";
1865 Result += CategoryImplementation[i]->getName();
1866 Result += "\n";
1867 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001868
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001869 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001870
1871 // Write objc_module metadata
1872
1873 /*
1874 struct _objc_module {
1875 long version;
1876 long size;
1877 const char *name;
1878 struct _objc_symtab *symtab;
1879 }
1880 */
1881
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001882 Result += "\nstruct _objc_module {\n";
1883 Result += "\tlong version;\n";
1884 Result += "\tlong size;\n";
1885 Result += "\tconst char *name;\n";
1886 Result += "\tstruct _objc_symtab *symtab;\n";
1887 Result += "};\n\n";
1888 Result += "static struct _objc_module "
1889 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001890 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1891 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001892 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00001893
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001894}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001895