blob: c5c851b4ec0119c859730be96b9fbb0470784d83 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000037 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000038
39 FunctionDecl *MsgSendFunctionDecl;
40 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000041 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000042 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
Steve Naroffbeaf2992007-11-03 11:27:19 +000044 // ObjC string constant support.
45 FileVarDecl *ConstantStringClassReference;
46 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000047
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000048 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000049 public:
Chris Lattner01c57482007-10-17 22:35:30 +000050 void Initialize(ASTContext &context, unsigned mainFileID) {
51 Context = &context;
52 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000053 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000054 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000055 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000056 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000057 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000058 ConstantStringClassReference = 0;
59 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000060 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000061 // declaring objc_selector outside the parameter list removes a silly
62 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000063 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000064 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000065 "(struct objc_object *, struct objc_selector *, ...);\n"
66 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000067 "(const char *);\n"
68 "extern void objc_exception_throw(struct objc_object *);\n"
69 "extern void objc_exception_try_enter(void *);\n"
70 "extern void objc_exception_try_exit(void *);\n"
71 "extern struct objc_object *objc_exception_extract(void *);\n"
72 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +000073 "(struct objc_class *, struct objc_object *, ...);\n"
74 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +000075
Steve Naroffab972d32007-11-04 22:37:50 +000076 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
77 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000078 }
Chris Lattner8a12c272007-10-11 18:38:32 +000079
Chris Lattnerf04da132007-10-24 17:06:59 +000080 // Top Level Driver code.
81 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000082 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000083 ~RewriteTest();
84
85 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000086 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000087 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000088 void RewriteTabs();
89 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000090 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +000091 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000092 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000093 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000094 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +000095 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +000096 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000097 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000098 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000099 void RewriteObjcQualifiedInterfaceTypes(
100 const FunctionTypeProto *proto, FunctionDecl *FD);
101 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +0000102
Chris Lattnerf04da132007-10-24 17:06:59 +0000103 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000104 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000105 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000106 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000107 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000108 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000109 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
110 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
111 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000112 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000113 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
114 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000115 void SynthMsgSendFunctionDecl();
116 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000117 void SynthCFStringFunctionDecl();
118
Chris Lattnerf04da132007-10-24 17:06:59 +0000119 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
121 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000122
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000123 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
124 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000125
Steve Naroff0416fb92007-11-11 17:19:15 +0000126 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000127 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000128 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000129 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000130 const char *ClassName,
131 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000132
133 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
134 int NumProtocols,
135 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000136 const char *ClassName,
137 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000138 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
139 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000140 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
141 ObjcIvarDecl *ivar,
142 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000143 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000144 };
145}
146
Chris Lattner8a12c272007-10-11 18:38:32 +0000147ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000148
Chris Lattnerf04da132007-10-24 17:06:59 +0000149//===----------------------------------------------------------------------===//
150// Top Level Driver Code
151//===----------------------------------------------------------------------===//
152
Chris Lattner8a12c272007-10-11 18:38:32 +0000153void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000154 // Two cases: either the decl could be in the main file, or it could be in a
155 // #included file. If the former, rewrite it now. If the later, check to see
156 // if we rewrote the #include/#import.
157 SourceLocation Loc = D->getLocation();
158 Loc = SM->getLogicalLoc(Loc);
159
160 // If this is for a builtin, ignore it.
161 if (Loc.isInvalid()) return;
162
Steve Naroffebf2b562007-10-23 23:50:29 +0000163 // Look for built-in declarations that we need to refer during the rewrite.
164 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000165 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000166 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
167 // declared in <Foundation/NSString.h>
168 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
169 ConstantStringClassReference = FVD;
170 return;
171 }
Steve Naroffbef11852007-10-26 20:53:56 +0000172 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
173 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000174 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
175 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000176 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
177 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000178 } else if (ObjcForwardProtocolDecl *FP =
179 dyn_cast<ObjcForwardProtocolDecl>(D)){
180 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000181 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000182 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000183 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
184 return HandleDeclInMainFile(D);
185
Chris Lattnerf04da132007-10-24 17:06:59 +0000186 // Otherwise, see if there is a #import in the main file that should be
187 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000188 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000189}
190
Chris Lattnerf04da132007-10-24 17:06:59 +0000191/// HandleDeclInMainFile - This is called for each top-level decl defined in the
192/// main file of the input.
193void RewriteTest::HandleDeclInMainFile(Decl *D) {
194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
195 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000196 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000197
198 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
199 if (Stmt *Body = MD->getBody())
200 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
201 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000202 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
203 ClassImplementation.push_back(CI);
204 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
205 CategoryImplementation.push_back(CI);
206 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
207 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000208 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
209 if (VD->getInit())
210 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
211 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000212 // Nothing yet.
213}
214
215RewriteTest::~RewriteTest() {
216 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000217
218 // Rewrite tabs if we care.
219 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000220
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000221 // Rewrite Objective-c meta data*
222 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000223 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000224
Chris Lattnerf04da132007-10-24 17:06:59 +0000225 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
226 // we are done.
227 if (const RewriteBuffer *RewriteBuf =
228 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000229 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000230 std::string S(RewriteBuf->begin(), RewriteBuf->end());
231 printf("%s\n", S.c_str());
232 } else {
233 printf("No changes\n");
234 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000235 // Emit metadata.
236 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000237}
238
Chris Lattnerf04da132007-10-24 17:06:59 +0000239//===----------------------------------------------------------------------===//
240// Syntactic (non-AST) Rewriting Code
241//===----------------------------------------------------------------------===//
242
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000243void RewriteTest::RewriteInclude(SourceLocation Loc) {
244 // Rip up the #include stack to the main file.
245 SourceLocation IncLoc = Loc, NextLoc = Loc;
246 do {
247 IncLoc = Loc;
248 Loc = SM->getLogicalLoc(NextLoc);
249 NextLoc = SM->getIncludeLoc(Loc);
250 } while (!NextLoc.isInvalid());
251
252 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
253 // IncLoc indicates the header that was included if it is useful.
254 IncLoc = SM->getLogicalLoc(IncLoc);
255 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
256 Loc == LastIncLoc)
257 return;
258 LastIncLoc = Loc;
259
260 unsigned IncCol = SM->getColumnNumber(Loc);
261 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
262
263 // Replace the #import with #include.
264 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
265}
266
Chris Lattnerf04da132007-10-24 17:06:59 +0000267void RewriteTest::RewriteTabs() {
268 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
269 const char *MainBufStart = MainBuf.first;
270 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000271
Chris Lattnerf04da132007-10-24 17:06:59 +0000272 // Loop over the whole file, looking for tabs.
273 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
274 if (*BufPtr != '\t')
275 continue;
276
277 // Okay, we found a tab. This tab will turn into at least one character,
278 // but it depends on which 'virtual column' it is in. Compute that now.
279 unsigned VCol = 0;
280 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
281 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
282 ++VCol;
283
284 // Okay, now that we know the virtual column, we know how many spaces to
285 // insert. We assume 8-character tab-stops.
286 unsigned Spaces = 8-(VCol & 7);
287
288 // Get the location of the tab.
289 SourceLocation TabLoc =
290 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
291
292 // Rewrite the single tab character into a sequence of spaces.
293 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
294 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000295}
296
297
Chris Lattnerf04da132007-10-24 17:06:59 +0000298void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
299 int numDecls = ClassDecl->getNumForwardDecls();
300 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
301
302 // Get the start location and compute the semi location.
303 SourceLocation startLoc = ClassDecl->getLocation();
304 const char *startBuf = SM->getCharacterData(startLoc);
305 const char *semiPtr = strchr(startBuf, ';');
306
307 // Translate to typedef's that forward reference structs with the same name
308 // as the class. As a convenience, we include the original declaration
309 // as a comment.
310 std::string typedefString;
311 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000312 typedefString.append(startBuf, semiPtr-startBuf+1);
313 typedefString += "\n";
314 for (int i = 0; i < numDecls; i++) {
315 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-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 Naroff352336b2007-11-05 14:36:37 +0000322 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000323 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000324 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-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 Lattnerf04da132007-10-24 17:06:59 +0000330}
331
Steve Naroff71c0a952007-11-13 23:01:27 +0000332void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000333 for (int i = 0; i < nMethods; i++) {
334 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000335 SourceLocation LocStart = Method->getLocStart();
336 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000337
Steve Naroff1d098f62007-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 Naroff423cb562007-10-30 13:30:57 +0000344 }
345}
346
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000347void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
348{
349 for (int i = 0; i < nProperties; i++) {
350 ObjcPropertyDecl *Property = Properties[i];
351 SourceLocation Loc = Property->getLocation();
352
353 Rewrite.ReplaceText(Loc, 0, "// ", 3);
354
355 // FIXME: handle properties that are declared across multiple lines.
356 }
357}
358
Steve Naroff423cb562007-10-30 13:30:57 +0000359void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
360 SourceLocation LocStart = CatDecl->getLocStart();
361
362 // FIXME: handle category headers that are declared across multiple lines.
363 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
364
Steve Naroff71c0a952007-11-13 23:01:27 +0000365 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
366 CatDecl->getInstanceMethods());
367 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
368 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000369 // Lastly, comment out the @end.
370 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
371}
372
Steve Naroff752d6ef2007-10-30 16:42:30 +0000373void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000374 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000375
Steve Naroff752d6ef2007-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 Naroff71c0a952007-11-13 23:01:27 +0000381 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
382 PDecl->getInstanceMethods());
383 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
384 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000385 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000386 SourceLocation LocEnd = PDecl->getAtEndLoc();
387 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000388
Fariborz Jahanianb82b3ea2007-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 Naroff8cc764c2007-11-14 15:03:57 +0000395 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-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 Naroff8cc764c2007-11-14 15:03:57 +0000402 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000403 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
404 CommentedRequired.c_str(), CommentedRequired.size());
405
406 }
407 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000408}
409
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000410void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
411 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000412 if (LocStart.isInvalid())
413 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000418void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
419 std::string &ResultStr) {
420 ResultStr += "\nstatic ";
421 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000422 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000423
424 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000425 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000426
Fariborz Jahanianb7908b52007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000434
435 NamedDecl *MethodContext = OMD->getMethodContext();
436 if (ObjcCategoryImplDecl *CID =
437 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000438 NameStr += CID->getName();
439 NameStr += "_";
Fariborz Jahanian48a0b6a2007-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 Jahanianb7908b52007-11-13 21:02:00 +0000444 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-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 Jahanianb7908b52007-11-13 21:02:00 +0000451 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000452 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000453 // Remember this name for metadata emission
454 MethodInternalNames[OMD] = NameStr;
455 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-11-13 20:04:28 +0000464 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
465 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-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 Jahanian48a0b6a2007-11-13 18:44:14 +0000489
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000490 if (IMD)
491 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
492 else
493 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000494
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000495 int numMethods = IMD ? IMD->getNumInstanceMethods()
496 : CID->getNumInstanceMethods();
497
498 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000499 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000500 ObjcMethodDecl *OMD;
501 if (IMD)
502 OMD = IMD->getInstanceMethods()[i];
503 else
504 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-11-13 20:04:28 +0000515 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
516 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000517 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000518 ObjcMethodDecl *OMD;
519 if (IMD)
520 OMD = IMD->getClassMethods()[i];
521 else
522 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-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 Jahanian66d6b292007-11-13 20:04:28 +0000532 if (IMD)
533 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
534 else
535 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000536}
537
Steve Naroffbef11852007-10-26 20:53:56 +0000538void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000539 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000540 if (!ObjcForwardDecls.count(ClassDecl)) {
541 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000542 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-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 Naroff352336b2007-11-05 14:36:37 +0000548 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000549 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000550 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000551
552 // Mark this typedef as having been generated.
553 ObjcForwardDecls.insert(ClassDecl);
554 }
Steve Narofff908a872007-10-30 02:23:23 +0000555 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
556
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000557 RewriteProperties(ClassDecl->getNumPropertyDecl(),
558 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000559 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
560 ClassDecl->getInstanceMethods());
561 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
562 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000563
Steve Naroff2feac5e2007-10-30 03:43:13 +0000564 // Lastly, comment out the @end.
565 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000566}
567
Chris Lattnerf04da132007-10-24 17:06:59 +0000568//===----------------------------------------------------------------------===//
569// Function Body / Expression rewriting
570//===----------------------------------------------------------------------===//
571
Steve Narofff3473a72007-11-09 15:20:18 +0000572Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-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 Naroff75730982007-11-07 04:08:17 +0000576 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000577 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000578 if (newStmt)
579 *CI = newStmt;
580 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000581
582 // Handle specific things.
583 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
584 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000585
586 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
587 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000588
589 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
590 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000591
Steve Naroff934f2762007-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 Naroffbef11852007-10-26 20:53:56 +0000604
Steve Naroff934f2762007-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 Naroff752d6ef2007-10-30 16:42:30 +0000608 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000609 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000610 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000611
612 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
613 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000614
615 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
616 return RewriteObjcThrowStmt(StmtThrow);
617
Chris Lattnere64b7772007-10-24 16:57:36 +0000618 // Return this stmt unmodified.
619 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000620}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000621
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000622Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-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 Naroff21867b12007-11-07 18:43:40 +0000636 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-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 Naroff21867b12007-11-07 18:43:40 +0000651 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000652 buf += " _rethrow = objc_exception_extract(&_stack);\n";
653 buf += " else { /* @catch continue */";
654
Chris Lattner28d1fe82007-11-08 04:41:51 +0000655 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-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 Naroff21867b12007-11-07 18:43:40 +0000686 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000687 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000688 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-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 Naroff2bd03922007-11-07 15:32:26 +0000707 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000708 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000709 }
Steve Naroff75730982007-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 Lattner28d1fe82007-11-08 04:41:51 +0000720 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-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 Lattner28d1fe82007-11-08 04:41:51 +0000743 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000744 endLoc = endLoc.getFileLocWithOffset(-1);
745 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000746 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-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 Lattner28d1fe82007-11-08 04:41:51 +0000754 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-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 Naroff2bd03922007-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 Jahanian909f02a2007-11-05 17:47:33 +0000787
Chris Lattnere64b7772007-10-24 16:57:36 +0000788Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000789 // Create a new string expression.
790 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-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 Lattner01c57482007-10-17 22:35:30 +0000795 SourceLocation(), SourceLocation());
796 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000797 delete Exp;
798 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000799}
800
Steve Naroffb42f8412007-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 Naroff934f2762007-10-24 22:48:43 +0000817CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
818 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000819 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000820 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000821
822 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000823 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000824
825 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000826 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000827 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
828
829 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000830
Steve Naroff934f2762007-10-24 22:48:43 +0000831 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
832}
833
Steve Naroffd5255f52007-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 Naroff32174822007-11-09 12:50:28 +0000840 if (startRef && *startRef == '<') {
841 endRef = startBuf; // mark the end.
842 return true;
843 }
844 return false;
Steve Naroffd5255f52007-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 Naroff9165ad32007-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 Naroffd5255f52007-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 Lattner28d1fe82007-11-08 04:41:51 +0000881 Rewrite.InsertText(LessLoc, "/*", 2);
882 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000883 }
884 }
Steve Naroffd5255f52007-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 Lattner28d1fe82007-11-08 04:41:51 +0000901 Rewrite.InsertText(LessLoc, "/*", 2);
902 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000903 }
904 }
905 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000906}
907
Steve Naroff09b266e2007-10-30 23:14:51 +0000908void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
909 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000910 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000911 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-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 Naroffd5255f52007-11-01 13:24:47 +0000918 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
919 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-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 Naroff96984642007-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 Naroffbeaf2992007-11-03 11:27:19 +0000968Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-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 Naroffbeaf2992007-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 Naroff352336b2007-11-05 14:36:37 +00001016 // cast to NSConstantString *
1017 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001018 Rewrite.ReplaceStmt(Exp, cast);
1019 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001020 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001021#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001022}
1023
Steve Naroff934f2762007-10-24 22:48:43 +00001024Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001025 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001026 if (!MsgSendFunctionDecl)
1027 SynthMsgSendFunctionDecl();
1028 if (!GetClassFunctionDecl)
1029 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-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 Naroff6568d4d2007-11-14 23:54:14 +00001046 } else { // instance message.
1047 Expr *recExpr = Exp->getReceiver();
Steve Naroff934f2762007-10-24 22:48:43 +00001048
Steve Naroff6568d4d2007-11-14 23:54:14 +00001049 // Make sure we cast "self" to "id".
1050 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(recExpr)) {
1051 if (!strcmp(DRE->getDecl()->getName(), "self"))
1052 recExpr = new CastExpr(Context->getObjcIdType(), recExpr,
1053 SourceLocation());
1054 }
1055 MsgExprs.push_back(recExpr);
1056 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001057 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001058 llvm::SmallVector<Expr*, 8> SelExprs;
1059 QualType argType = Context->getPointerType(Context->CharTy);
1060 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1061 Exp->getSelector().getName().size(),
1062 false, argType, SourceLocation(),
1063 SourceLocation()));
1064 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1065 &SelExprs[0], SelExprs.size());
1066 MsgExprs.push_back(SelExp);
1067
1068 // Now push any user supplied arguments.
1069 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001070 Expr *userExpr = Exp->getArg(i);
1071#if 0
1072 // Make sure we cast "self" to "id".
1073 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(userExpr)) {
1074 if (!strcmp(DRE->getDecl()->getName(), "self"))
1075 userExpr = new CastExpr(Context->getObjcIdType(), userExpr,
1076 SourceLocation());
1077 }
1078#endif
1079 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001080 // We've transferred the ownership to MsgExprs. Null out the argument in
1081 // the original expression, since we will delete it below.
1082 Exp->setArg(i, 0);
1083 }
Steve Naroffab972d32007-11-04 22:37:50 +00001084 // Generate the funky cast.
1085 CastExpr *cast;
1086 llvm::SmallVector<QualType, 8> ArgTypes;
1087 QualType returnType;
1088
1089 // Push 'id' and 'SEL', the 2 implicit arguments.
1090 ArgTypes.push_back(Context->getObjcIdType());
1091 ArgTypes.push_back(Context->getObjcSelType());
1092 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1093 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001094 for (int i = 0; i < mDecl->getNumParams(); i++) {
1095 QualType t = mDecl->getParamDecl(i)->getType();
1096 if (t == Context->getObjcClassType())
1097 t = Context->getObjcIdType(); // Convert "Class"->"id"
1098 ArgTypes.push_back(t);
1099 }
Steve Naroffab972d32007-11-04 22:37:50 +00001100 returnType = mDecl->getResultType();
1101 } else {
1102 returnType = Context->getObjcIdType();
1103 }
1104 // Get the type, we will need to reference it in a couple spots.
1105 QualType msgSendType = MsgSendFunctionDecl->getType();
1106
1107 // Create a reference to the objc_msgSend() declaration.
1108 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1109
1110 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1111 // If we don't do this cast, we get the following bizarre warning/note:
1112 // xx.m:13: warning: function called through a non-compatible type
1113 // xx.m:13: note: if this code is reached, the program will abort
1114 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1115 SourceLocation());
1116
1117 // Now do the "normal" pointer to function cast.
1118 QualType castType = Context->getFunctionType(returnType,
1119 &ArgTypes[0], ArgTypes.size(),
1120 false/*FIXME:variadic*/);
1121 castType = Context->getPointerType(castType);
1122 cast = new CastExpr(castType, cast, SourceLocation());
1123
1124 // Don't forget the parens to enforce the proper binding.
1125 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1126
1127 const FunctionType *FT = msgSendType->getAsFunctionType();
1128 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1129 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001130 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001131 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001132
Chris Lattnere64b7772007-10-24 16:57:36 +00001133 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001134 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001135}
1136
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001137/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1138/// an objective-c class with ivars.
1139void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1140 std::string &Result) {
1141 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1142 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001143 // Do not synthesize more than once.
1144 if (ObjcSynthesizedStructs.count(CDecl))
1145 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001146 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1147 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1148 // Do it for the root
1149 SynthesizeObjcInternalStruct(RCDecl, Result);
1150 }
1151
Steve Naroff03300712007-11-12 13:56:41 +00001152 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001153 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001154 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001155 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1156 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001157 // FIXME: This has potential of causing problem. If
1158 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001159 Result += "\nstruct ";
1160 Result += CDecl->getName();
1161
1162 SourceLocation LocStart = CDecl->getLocStart();
1163 SourceLocation LocEnd = CDecl->getLocEnd();
1164
1165 const char *startBuf = SM->getCharacterData(LocStart);
1166 const char *endBuf = SM->getCharacterData(LocEnd);
1167
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001168 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001169 const char *cursor = strchr(startBuf, '{');
1170 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001171 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001172
1173 // rewrite the original header *without* disturbing the '{'
1174 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1175 Result.c_str(), Result.size());
1176 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1177 Result = "\n struct ";
1178 Result += RCDecl->getName();
1179 Result += " _";
1180 Result += RCDecl->getName();
1181 Result += ";\n";
1182
1183 // insert the super class structure definition.
1184 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1185 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1186 }
1187 cursor++; // past '{'
1188
1189 // Now comment out any visibility specifiers.
1190 while (cursor < endBuf) {
1191 if (*cursor == '@') {
1192 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001193 // Skip whitespace.
1194 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1195 /*scan*/;
1196
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001197 // FIXME: presence of @public, etc. inside comment results in
1198 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001199 if (!strncmp(cursor, "public", strlen("public")) ||
1200 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001201 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001202 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001203 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001204 // FIXME: If there are cases where '<' is used in ivar declaration part
1205 // of user code, then scan the ivar list and use needToScanForQualifiers
1206 // for type checking.
1207 else if (*cursor == '<') {
1208 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1209 Rewrite.InsertText(atLoc, "/* ", 3);
1210 cursor = strchr(cursor, '>');
1211 cursor++;
1212 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1213 Rewrite.InsertText(atLoc, " */", 3);
1214 }
Steve Narofffea763e82007-11-14 19:25:57 +00001215 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001216 }
Steve Narofffea763e82007-11-14 19:25:57 +00001217 // Don't forget to add a ';'!!
1218 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1219 } else { // we don't have any instance variables - insert super struct.
1220 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1221 Result += " {\n struct ";
1222 Result += RCDecl->getName();
1223 Result += " _";
1224 Result += RCDecl->getName();
1225 Result += ";\n};\n";
1226 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1227 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001228 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001229 // Mark this struct as having been generated.
1230 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001231 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001232}
1233
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001234// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1235/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001236void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001237 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001238 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001239 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001240 const char *ClassName,
1241 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001242 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001243 if (NumMethods > 0 && !objc_impl_method) {
1244 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001245 SEL _cmd;
1246 char *method_types;
1247 void *_imp;
1248 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001249 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001250 Result += "\nstruct _objc_method {\n";
1251 Result += "\tSEL _cmd;\n";
1252 Result += "\tchar *method_types;\n";
1253 Result += "\tvoid *_imp;\n";
1254 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001255
1256 /* struct _objc_method_list {
1257 struct _objc_method_list *next_method;
1258 int method_count;
1259 struct _objc_method method_list[];
1260 }
1261 */
1262 Result += "\nstruct _objc_method_list {\n";
1263 Result += "\tstruct _objc_method_list *next_method;\n";
1264 Result += "\tint method_count;\n";
1265 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001266 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001267 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001268 // Build _objc_method_list for class's methods if needed
1269 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001270 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001271 Result += prefix;
1272 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1273 Result += "_METHODS_";
1274 Result += ClassName;
1275 Result += " __attribute__ ((section (\"__OBJC, __";
1276 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001277 Result += "_meth\")))= ";
1278 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1279
1280 Result += "\t,{{(SEL)\"";
1281 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001282 std::string MethodTypeString;
1283 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1284 Result += "\", \"";
1285 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001286 Result += "\", ";
1287 Result += MethodInternalNames[Methods[0]];
1288 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001289 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001290 Result += "\t ,{(SEL)\"";
1291 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001292 std::string MethodTypeString;
1293 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1294 Result += "\", \"";
1295 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001296 Result += "\", ";
1297 Result += MethodInternalNames[Methods[i]];
1298 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001299 }
1300 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001301 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001302}
1303
1304/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1305void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1306 int NumProtocols,
1307 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001308 const char *ClassName,
1309 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001310 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001311 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001312 for (int i = 0; i < NumProtocols; i++) {
1313 ObjcProtocolDecl *PDecl = Protocols[i];
1314 // Output struct protocol_methods holder of method selector and type.
1315 if (!objc_protocol_methods &&
1316 (PDecl->getNumInstanceMethods() > 0
1317 || PDecl->getNumClassMethods() > 0)) {
1318 /* struct protocol_methods {
1319 SEL _cmd;
1320 char *method_types;
1321 }
1322 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001323 Result += "\nstruct protocol_methods {\n";
1324 Result += "\tSEL _cmd;\n";
1325 Result += "\tchar *method_types;\n";
1326 Result += "};\n";
1327
1328 /* struct _objc_protocol_method_list {
1329 int protocol_method_count;
1330 struct protocol_methods protocols[];
1331 }
1332 */
1333 Result += "\nstruct _objc_protocol_method_list {\n";
1334 Result += "\tint protocol_method_count;\n";
1335 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001336 objc_protocol_methods = true;
1337 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001338
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001339 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001340 int NumMethods = PDecl->getNumInstanceMethods();
1341 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001342 Result += "\nstatic struct _objc_protocol_method_list "
1343 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1344 Result += PDecl->getName();
1345 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1346 "{\n\t" + utostr(NumMethods) + "\n";
1347
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001348 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001349 Result += "\t,{{(SEL)\"";
1350 Result += Methods[0]->getSelector().getName().c_str();
1351 Result += "\", \"\"}\n";
1352
1353 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001354 Result += "\t ,{(SEL)\"";
1355 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001356 std::string MethodTypeString;
1357 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1358 Result += "\", \"";
1359 Result += MethodTypeString;
1360 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001361 }
1362 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001363 }
1364
1365 // Output class methods declared in this protocol.
1366 NumMethods = PDecl->getNumClassMethods();
1367 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001368 Result += "\nstatic struct _objc_protocol_method_list "
1369 "_OBJC_PROTOCOL_CLASS_METHODS_";
1370 Result += PDecl->getName();
1371 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1372 "{\n\t";
1373 Result += utostr(NumMethods);
1374 Result += "\n";
1375
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001376 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001377 Result += "\t,{{(SEL)\"";
1378 Result += Methods[0]->getSelector().getName().c_str();
1379 Result += "\", \"\"}\n";
1380
1381 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001382 Result += "\t ,{(SEL)\"";
1383 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001384 std::string MethodTypeString;
1385 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1386 Result += "\", \"";
1387 Result += MethodTypeString;
1388 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001389 }
1390 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001391 }
1392 // Output:
1393 /* struct _objc_protocol {
1394 // Objective-C 1.0 extensions
1395 struct _objc_protocol_extension *isa;
1396 char *protocol_name;
1397 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001398 struct _objc_protocol_method_list *instance_methods;
1399 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001400 };
1401 */
1402 static bool objc_protocol = false;
1403 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001404 Result += "\nstruct _objc_protocol {\n";
1405 Result += "\tstruct _objc_protocol_extension *isa;\n";
1406 Result += "\tchar *protocol_name;\n";
1407 Result += "\tstruct _objc_protocol **protocol_list;\n";
1408 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1409 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1410 Result += "};\n";
1411
1412 /* struct _objc_protocol_list {
1413 struct _objc_protocol_list *next;
1414 int protocol_count;
1415 struct _objc_protocol *class_protocols[];
1416 }
1417 */
1418 Result += "\nstruct _objc_protocol_list {\n";
1419 Result += "\tstruct _objc_protocol_list *next;\n";
1420 Result += "\tint protocol_count;\n";
1421 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1422 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001423 objc_protocol = true;
1424 }
1425
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001426 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1427 Result += PDecl->getName();
1428 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1429 "{\n\t0, \"";
1430 Result += PDecl->getName();
1431 Result += "\", 0, ";
1432 if (PDecl->getInstanceMethods() > 0) {
1433 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1434 Result += PDecl->getName();
1435 Result += ", ";
1436 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001437 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001438 Result += "0, ";
1439 if (PDecl->getClassMethods() > 0) {
1440 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1441 Result += PDecl->getName();
1442 Result += "\n";
1443 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001444 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001445 Result += "0\n";
1446 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001447 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001448 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001449 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1450 Result += prefix;
1451 Result += "_PROTOCOLS_";
1452 Result += ClassName;
1453 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1454 "{\n\t0, ";
1455 Result += utostr(NumProtocols);
1456 Result += "\n";
1457
1458 Result += "\t,{&_OBJC_PROTOCOL_";
1459 Result += Protocols[0]->getName();
1460 Result += " \n";
1461
1462 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001463 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001464 Result += "\t ,&_OBJC_PROTOCOL_";
1465 Result += PDecl->getName();
1466 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001467 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001468 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001469 }
1470}
1471
1472/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1473/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001474void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1475 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001476 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1477 // Find category declaration for this implementation.
1478 ObjcCategoryDecl *CDecl;
1479 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1480 CDecl = CDecl->getNextClassCategory())
1481 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1482 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001483
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001484 char *FullCategoryName = (char*)alloca(
1485 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1486 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1487
1488 // Build _objc_method_list for class's instance methods if needed
1489 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1490 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001491 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001492 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001493
1494 // Build _objc_method_list for class's class methods if needed
1495 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1496 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001497 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001498 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001499
1500 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001501 // Null CDecl is case of a category implementation with no category interface
1502 if (CDecl)
1503 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1504 CDecl->getNumReferencedProtocols(),
1505 "CATEGORY",
1506 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001507
1508 /* struct _objc_category {
1509 char *category_name;
1510 char *class_name;
1511 struct _objc_method_list *instance_methods;
1512 struct _objc_method_list *class_methods;
1513 struct _objc_protocol_list *protocols;
1514 // Objective-C 1.0 extensions
1515 uint32_t size; // sizeof (struct _objc_category)
1516 struct _objc_property_list *instance_properties; // category's own
1517 // @property decl.
1518 };
1519 */
1520
1521 static bool objc_category = false;
1522 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001523 Result += "\nstruct _objc_category {\n";
1524 Result += "\tchar *category_name;\n";
1525 Result += "\tchar *class_name;\n";
1526 Result += "\tstruct _objc_method_list *instance_methods;\n";
1527 Result += "\tstruct _objc_method_list *class_methods;\n";
1528 Result += "\tstruct _objc_protocol_list *protocols;\n";
1529 Result += "\tunsigned int size;\n";
1530 Result += "\tstruct _objc_property_list *instance_properties;\n";
1531 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001532 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001533 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001534 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1535 Result += FullCategoryName;
1536 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1537 Result += IDecl->getName();
1538 Result += "\"\n\t, \"";
1539 Result += ClassDecl->getName();
1540 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001541
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001542 if (IDecl->getNumInstanceMethods() > 0) {
1543 Result += "\t, (struct _objc_method_list *)"
1544 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1545 Result += FullCategoryName;
1546 Result += "\n";
1547 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001548 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001549 Result += "\t, 0\n";
1550 if (IDecl->getNumClassMethods() > 0) {
1551 Result += "\t, (struct _objc_method_list *)"
1552 "&_OBJC_CATEGORY_CLASS_METHODS_";
1553 Result += FullCategoryName;
1554 Result += "\n";
1555 }
1556 else
1557 Result += "\t, 0\n";
1558
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001559 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001560 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1561 Result += FullCategoryName;
1562 Result += "\n";
1563 }
1564 else
1565 Result += "\t, 0\n";
1566 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001567}
1568
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001569/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1570/// ivar offset.
1571void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1572 ObjcIvarDecl *ivar,
1573 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001574 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001575 Result += IDecl->getName();
1576 Result += ", ";
1577 Result += ivar->getName();
1578 Result += ")";
1579}
1580
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001581//===----------------------------------------------------------------------===//
1582// Meta Data Emission
1583//===----------------------------------------------------------------------===//
1584
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001585void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1586 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001587 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1588
1589 // Build _objc_ivar_list metadata for classes ivars if needed
1590 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1591 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001592 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001593
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001594 SynthesizeObjcInternalStruct(CDecl, Result);
1595
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001596 if (NumIvars > 0) {
1597 static bool objc_ivar = false;
1598 if (!objc_ivar) {
1599 /* struct _objc_ivar {
1600 char *ivar_name;
1601 char *ivar_type;
1602 int ivar_offset;
1603 };
1604 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001605 Result += "\nstruct _objc_ivar {\n";
1606 Result += "\tchar *ivar_name;\n";
1607 Result += "\tchar *ivar_type;\n";
1608 Result += "\tint ivar_offset;\n";
1609 Result += "};\n";
1610
1611 /* struct _objc_ivar_list {
1612 int ivar_count;
1613 struct _objc_ivar ivar_list[];
1614 };
1615 */
1616 Result += "\nstruct _objc_ivar_list {\n";
1617 Result += "\tint ivar_count;\n";
1618 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001619 objc_ivar = true;
1620 }
1621
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001622 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1623 Result += IDecl->getName();
1624 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1625 "{\n\t";
1626 Result += utostr(NumIvars);
1627 Result += "\n";
1628
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001629 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1630 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001631 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001632 Result += "\t,{{\"";
1633 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001634 Result += "\", \"";
1635 std::string StrEncoding;
1636 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1637 Result += StrEncoding;
1638 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001639 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1640 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001641 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001642 Result += "\t ,{\"";
1643 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001644 Result += "\", \"";
1645 std::string StrEncoding;
1646 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1647 Result += StrEncoding;
1648 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001649 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1650 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001651 }
1652
1653 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001654 }
1655
1656 // Build _objc_method_list for class's instance methods if needed
1657 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1658 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001659 true,
1660 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001661
1662 // Build _objc_method_list for class's class methods if needed
1663 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001664 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001665 false,
1666 "", IDecl->getName(), Result);
1667
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001668 // Protocols referenced in class declaration?
1669 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1670 CDecl->getNumIntfRefProtocols(),
1671 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001672 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001673
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001674
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001675 // Declaration of class/meta-class metadata
1676 /* struct _objc_class {
1677 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001678 const char *super_class_name;
1679 char *name;
1680 long version;
1681 long info;
1682 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001683 struct _objc_ivar_list *ivars;
1684 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001685 struct objc_cache *cache;
1686 struct objc_protocol_list *protocols;
1687 const char *ivar_layout;
1688 struct _objc_class_ext *ext;
1689 };
1690 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001691 static bool objc_class = false;
1692 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001693 Result += "\nstruct _objc_class {\n";
1694 Result += "\tstruct _objc_class *isa;\n";
1695 Result += "\tconst char *super_class_name;\n";
1696 Result += "\tchar *name;\n";
1697 Result += "\tlong version;\n";
1698 Result += "\tlong info;\n";
1699 Result += "\tlong instance_size;\n";
1700 Result += "\tstruct _objc_ivar_list *ivars;\n";
1701 Result += "\tstruct _objc_method_list *methods;\n";
1702 Result += "\tstruct objc_cache *cache;\n";
1703 Result += "\tstruct _objc_protocol_list *protocols;\n";
1704 Result += "\tconst char *ivar_layout;\n";
1705 Result += "\tstruct _objc_class_ext *ext;\n";
1706 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001707 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001708 }
1709
1710 // Meta-class metadata generation.
1711 ObjcInterfaceDecl *RootClass = 0;
1712 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1713 while (SuperClass) {
1714 RootClass = SuperClass;
1715 SuperClass = SuperClass->getSuperClass();
1716 }
1717 SuperClass = CDecl->getSuperClass();
1718
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001719 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1720 Result += CDecl->getName();
1721 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1722 "{\n\t(struct _objc_class *)\"";
1723 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1724 Result += "\"";
1725
1726 if (SuperClass) {
1727 Result += ", \"";
1728 Result += SuperClass->getName();
1729 Result += "\", \"";
1730 Result += CDecl->getName();
1731 Result += "\"";
1732 }
1733 else {
1734 Result += ", 0, \"";
1735 Result += CDecl->getName();
1736 Result += "\"";
1737 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001738 // TODO: 'ivars' field for root class is currently set to 0.
1739 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001740 Result += ", 0,2, sizeof(struct _objc_class), 0";
1741 if (CDecl->getNumClassMethods() > 0) {
1742 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1743 Result += CDecl->getName();
1744 Result += "\n";
1745 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001746 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001747 Result += ", 0\n";
1748 if (CDecl->getNumIntfRefProtocols() > 0) {
1749 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1750 Result += CDecl->getName();
1751 Result += ",0,0\n";
1752 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001753 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001754 Result += "\t,0,0,0,0\n";
1755 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001756
1757 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001758 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1759 Result += CDecl->getName();
1760 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1761 "{\n\t&_OBJC_METACLASS_";
1762 Result += CDecl->getName();
1763 if (SuperClass) {
1764 Result += ", \"";
1765 Result += SuperClass->getName();
1766 Result += "\", \"";
1767 Result += CDecl->getName();
1768 Result += "\"";
1769 }
1770 else {
1771 Result += ", 0, \"";
1772 Result += CDecl->getName();
1773 Result += "\"";
1774 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001775 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001776 Result += ", 0,1";
1777 if (!ObjcSynthesizedStructs.count(CDecl))
1778 Result += ",0";
1779 else {
1780 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001781 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001782 Result += CDecl->getName();
1783 Result += ")";
1784 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001785 if (NumIvars > 0) {
1786 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1787 Result += CDecl->getName();
1788 Result += "\n\t";
1789 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001790 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001791 Result += ",0";
1792 if (IDecl->getNumInstanceMethods() > 0) {
1793 Result += ", &_OBJC_INSTANCE_METHODS_";
1794 Result += CDecl->getName();
1795 Result += ", 0\n\t";
1796 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001797 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001798 Result += ",0,0";
1799 if (CDecl->getNumIntfRefProtocols() > 0) {
1800 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1801 Result += CDecl->getName();
1802 Result += ", 0,0\n";
1803 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001804 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001805 Result += ",0,0,0\n";
1806 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001807}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001808
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001809/// RewriteImplementations - This routine rewrites all method implementations
1810/// and emits meta-data.
1811
1812void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001813 int ClsDefCount = ClassImplementation.size();
1814 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001815
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001816 if (ClsDefCount == 0 && CatDefCount == 0)
1817 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001818 // Rewrite implemented methods
1819 for (int i = 0; i < ClsDefCount; i++)
1820 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001821
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001822 for (int i = 0; i < CatDefCount; i++)
1823 RewriteImplementationDecl(CategoryImplementation[i]);
1824
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001825 // This is needed for use of offsetof
1826 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001827
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001828 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001829 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001830 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001831
1832 // For each implemented category, write out all its meta data.
1833 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001834 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001835
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001836 // Write objc_symtab metadata
1837 /*
1838 struct _objc_symtab
1839 {
1840 long sel_ref_cnt;
1841 SEL *refs;
1842 short cls_def_cnt;
1843 short cat_def_cnt;
1844 void *defs[cls_def_cnt + cat_def_cnt];
1845 };
1846 */
1847
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001848 Result += "\nstruct _objc_symtab {\n";
1849 Result += "\tlong sel_ref_cnt;\n";
1850 Result += "\tSEL *refs;\n";
1851 Result += "\tshort cls_def_cnt;\n";
1852 Result += "\tshort cat_def_cnt;\n";
1853 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1854 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001855
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001856 Result += "static struct _objc_symtab "
1857 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1858 Result += "\t0, 0, " + utostr(ClsDefCount)
1859 + ", " + utostr(CatDefCount) + "\n";
1860 for (int i = 0; i < ClsDefCount; i++) {
1861 Result += "\t,&_OBJC_CLASS_";
1862 Result += ClassImplementation[i]->getName();
1863 Result += "\n";
1864 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001865
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001866 for (int i = 0; i < CatDefCount; i++) {
1867 Result += "\t,&_OBJC_CATEGORY_";
1868 Result += CategoryImplementation[i]->getClassInterface()->getName();
1869 Result += "_";
1870 Result += CategoryImplementation[i]->getName();
1871 Result += "\n";
1872 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001873
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001874 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001875
1876 // Write objc_module metadata
1877
1878 /*
1879 struct _objc_module {
1880 long version;
1881 long size;
1882 const char *name;
1883 struct _objc_symtab *symtab;
1884 }
1885 */
1886
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001887 Result += "\nstruct _objc_module {\n";
1888 Result += "\tlong version;\n";
1889 Result += "\tlong size;\n";
1890 Result += "\tconst char *name;\n";
1891 Result += "\tstruct _objc_symtab *symtab;\n";
1892 Result += "};\n\n";
1893 Result += "static struct _objc_module "
1894 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001895 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1896 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001897 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001898
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001899}
Chris Lattner311ff022007-10-16 22:36:42 +00001900