blob: 69739f5c517077f997b9449ad5d08ba871142872 [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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000019using namespace clang;
20
21
22namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000023 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000024 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000025 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000026 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000027 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000029 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
30 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
31 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032 public:
Chris Lattner01c57482007-10-17 22:35:30 +000033 void Initialize(ASTContext &context, unsigned mainFileID) {
34 Context = &context;
35 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000036 MainFileID = mainFileID;
Chris Lattner01c57482007-10-17 22:35:30 +000037 Rewrite.setSourceMgr(Context->SourceMgr);
Chris Lattner77cd2a02007-10-11 00:43:27 +000038 }
39
40 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner8a12c272007-10-11 18:38:32 +000041
Chris Lattner2c64b7b2007-10-16 21:07:07 +000042 void HandleDeclInMainFile(Decl *D);
43 void RewriteInclude(SourceLocation Loc);
Chris Lattner311ff022007-10-16 22:36:42 +000044
45 void RewriteFunctionBody(Stmt *S);
46 void RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000047
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +000048 void WriteObjcClassMetaData(ObjcImplementationDecl *IDecl);
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000049 void WriteObjcMetaData();
50
Chris Lattner8a12c272007-10-11 18:38:32 +000051 ~RewriteTest();
Chris Lattner77cd2a02007-10-11 00:43:27 +000052 };
53}
54
Chris Lattner8a12c272007-10-11 18:38:32 +000055ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +000056
Chris Lattner8a12c272007-10-11 18:38:32 +000057void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000058 // Two cases: either the decl could be in the main file, or it could be in a
59 // #included file. If the former, rewrite it now. If the later, check to see
60 // if we rewrote the #include/#import.
61 SourceLocation Loc = D->getLocation();
62 Loc = SM->getLogicalLoc(Loc);
63
64 // If this is for a builtin, ignore it.
65 if (Loc.isInvalid()) return;
66
67 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
68 return HandleDeclInMainFile(D);
69
70 RewriteInclude(Loc);
71}
72
73void RewriteTest::RewriteInclude(SourceLocation Loc) {
74 // Rip up the #include stack to the main file.
75 SourceLocation IncLoc = Loc, NextLoc = Loc;
76 do {
77 IncLoc = Loc;
78 Loc = SM->getLogicalLoc(NextLoc);
79 NextLoc = SM->getIncludeLoc(Loc);
80 } while (!NextLoc.isInvalid());
81
82 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
83 // IncLoc indicates the header that was included if it is useful.
84 IncLoc = SM->getLogicalLoc(IncLoc);
85 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
86 Loc == LastIncLoc)
87 return;
88 LastIncLoc = Loc;
89
90 unsigned IncCol = SM->getColumnNumber(Loc);
91 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
92
93 // Replace the #import with #include.
94 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
95}
96
97/// HandleDeclInMainFile - This is called for each top-level decl defined in the
98/// main file of the input.
99void RewriteTest::HandleDeclInMainFile(Decl *D) {
Chris Lattner311ff022007-10-16 22:36:42 +0000100 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
101 if (Stmt *Body = FD->getBody())
102 RewriteFunctionBody(Body);
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000103
104 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
105 ClassImplementation.push_back(CI);
106 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
107 CategoryImplementation.push_back(CI);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000108 // Nothing yet.
Chris Lattner8a12c272007-10-11 18:38:32 +0000109}
110
111
Chris Lattner311ff022007-10-16 22:36:42 +0000112void RewriteTest::RewriteFunctionBody(Stmt *S) {
113 // Handle specific things.
114 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
115 return RewriteAtEncode(AtEncode);
116
117 // Otherwise, just rewrite all children.
118 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
119 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000120 if (*CI)
121 RewriteFunctionBody(*CI);
Chris Lattner311ff022007-10-16 22:36:42 +0000122}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000123
Chris Lattner311ff022007-10-16 22:36:42 +0000124void RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000125 // Create a new string expression.
126 QualType StrType = Context->getPointerType(Context->CharTy);
127 Expr *Replacement = new StringLiteral("foo", 3, false, StrType,
128 SourceLocation(), SourceLocation());
129 Rewrite.ReplaceStmt(Exp, Replacement);
130 delete Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000131}
132
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000133void RewriteTest::WriteObjcClassMetaData(ObjcImplementationDecl *IDecl) {
134 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
135
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000136 // Build _objc_ivar_list metadata for classes ivars if needed
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000137 if (IDecl->getImplDeclNumIvars() > 0 ||
138 CDecl&& CDecl->getIntfDeclNumIvars() > 0) {
139 static bool objc_ivar = false;
140
141 int NumIvars = IDecl->getImplDeclNumIvars() > 0
142 ? IDecl->getImplDeclNumIvars()
143 : CDecl->getIntfDeclNumIvars();
144
145 if (!objc_ivar) {
146 /* struct _objc_ivar {
147 char *ivar_name;
148 char *ivar_type;
149 int ivar_offset;
150 };
151 */
152 printf("\nstruct _objc_ivar {\n");
153 printf("\tchar *ivar_name;\n");
154 printf("\tchar *ivar_type;\n");
155 printf("\tint ivar_offset;\n");
156 printf("};\n");
157 objc_ivar = true;
158 }
159
160 /* struct _objc_ivar_list {
161 int ivar_count;
162 struct _objc_ivar ivar_list[ivar_count];
163 };
164 */
165 printf("\nstatic struct {\n");
166 printf("\tint ivar_count;\n");
167 printf("\tstruct _objc_ivar ivar_list[%d];\n", NumIvars);
168 printf("} _OBJC_INSTANCE_VARIABLES_%s "
169 "__attribute__ ((section (\"__OBJC, __instance_vars\")))= "
170 "{\n\t%d\n",IDecl->getName(),
171 NumIvars);
172 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
173 ? IDecl->getImplDeclIVars()
174 : CDecl->getIntfDeclIvars();
175 for (int i = 0; i < NumIvars; i++)
176 // TODO: 1) ivar names may have to go to another section. 2) encode
177 // ivar_type type of each ivar . 3) compute and add ivar offset.
178 printf("\t,\"%s\", \"\", 0\n", Ivars[i]->getName());
179 printf("};\n");
180 }
181
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000182 // Build _objc_method_list for class's instance methods if needed
183 if (IDecl->getNumInstanceMethods() > 0) {
184 int NumMethods = IDecl->getNumInstanceMethods();
185 static bool objc_method = false;
186 if (!objc_method) {
187 /* struct _objc_method {
188 SEL _cmd;
189 char *method_types;
190 void *_imp;
191 }
192 */
193 printf("\nstruct _objc_method {\n");
194 printf("\tSEL _cmd;\n");
195 printf("\tchar *method_types;\n");
196 printf("\tvoid *_imp;\n");
197 printf("};\n");
198 objc_method = true;
199 }
200 /* struct _objc_method_list {
201 struct objc_method_list *next_method;
202 int method_count;
203 struct _objc_method method_list[method_count];
204 }
205 */
206 printf("\nstatic struct {\n");
207 printf("\tstruct objc_method_list *next_method;\n");
208 printf("\tint method_count;\n");
209 printf("\tstruct _objc_method method_list[%d];\n", NumMethods);
210 printf("} _OBJC_INSTANCE_METHODS_%s "
211 "__attribute__ ((section (\"__OBJC, __inst_meth\")))= "
212 "{\n\t0, %d\n", IDecl->getName(), NumMethods);
213 ObjcMethodDecl **Methods = IDecl->getInstanceMethods();
214 for (int i = 0; i < NumMethods; i++)
215 // TODO: 1) method selector name may hav to go into their own section
216 // 2) encode method types for use here (which may have to go into
217 // __meth_var_types section, 3) Need method address as 3rd initializer.
218 printf("\t,(SEL)\"%s\", \"\", 0\n",
219 Methods[i]->getSelector().getName().c_str());
220 printf("};\n");
221 }
222
223
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000224}
225
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000226void RewriteTest::WriteObjcMetaData() {
227 int ClsDefCount = ClassImplementation.size();
228 int CatDefCount = CategoryImplementation.size();
229 if (ClsDefCount == 0 && CatDefCount == 0)
230 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000231
232 // For each defined class, write out all its meta data.
233 for (int i = 0; i < ClsDefCount; i++)
234 WriteObjcClassMetaData(ClassImplementation[i]);
235
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000236 // Write objc_symtab metadata
237 /*
238 struct _objc_symtab
239 {
240 long sel_ref_cnt;
241 SEL *refs;
242 short cls_def_cnt;
243 short cat_def_cnt;
244 void *defs[cls_def_cnt + cat_def_cnt];
245 };
246 */
247
248 printf("\nstruct _objc_symtab {\n");
249 printf("\tlong sel_ref_cnt;\n");
250 printf("\tSEL *refs;\n");
251 printf("\tshort cls_def_cnt;\n");
252 printf("\tshort cat_def_cnt;\n");
253 printf("\tvoid *defs[%d];\n", ClsDefCount + CatDefCount);
254 printf("};\n\n");
255
256 printf("static struct _objc_symtab "
257 "_OBJC_SYMBOLS __attribute__ ((section (\"__OBJC, __symbols\")))= {\n");
258 printf("\t0, 0, %d, %d\n", ClsDefCount, CatDefCount);
259 for (int i = 0; i < ClsDefCount; i++)
260 printf("\t,_OBJC_CLASS_%s\n", ClassImplementation[i]->getName());
261
262 for (int i = 0; i < CatDefCount; i++)
263 printf("\t,_OBJC_CATEGORY_%s_%s\n",
264 CategoryImplementation[i]->getClassInterface()->getName(),
265 CategoryImplementation[i]->getName());
266
267 printf("};\n\n");
268
269 // Write objc_module metadata
270
271 /*
272 struct _objc_module {
273 long version;
274 long size;
275 const char *name;
276 struct _objc_symtab *symtab;
277 }
278 */
279
280 printf("\nstruct _objc_module {\n");
281 printf("\tlong version;\n");
282 printf("\tlong size;\n");
283 printf("\tconst char *name;\n");
284 printf("\tstruct _objc_symtab *symtab;");
285 printf("};\n\n");
286 printf("static struct _objc_module "
287 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n");
288 printf("\t%d, %d, \"\", &_OBJC_SYMBOLS\n", OBJC_ABI_VERSION, 16);
289 printf("};\n\n");
290}
Chris Lattner311ff022007-10-16 22:36:42 +0000291
Chris Lattner8a12c272007-10-11 18:38:32 +0000292RewriteTest::~RewriteTest() {
Chris Lattner8a12c272007-10-11 18:38:32 +0000293 // Get the top-level buffer that this corresponds to.
294 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
295 const char *MainBufStart = MainBuf.first;
296 const char *MainBufEnd = MainBuf.second;
297
298 // Loop over the whole file, looking for tabs.
299 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
300 if (*BufPtr != '\t')
301 continue;
302
303 // Okay, we found a tab. This tab will turn into at least one character,
304 // but it depends on which 'virtual column' it is in. Compute that now.
305 unsigned VCol = 0;
306 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
307 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
308 ++VCol;
309
310 // Okay, now that we know the virtual column, we know how many spaces to
311 // insert. We assume 8-character tab-stops.
312 unsigned Spaces = 8-(VCol & 7);
313
314 // Get the location of the tab.
315 SourceLocation TabLoc =
316 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
317
318 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner57c337d2007-10-13 00:46:29 +0000319 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner8a12c272007-10-11 18:38:32 +0000320 }
321
322 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
323 // we are done.
324 if (const RewriteBuffer *RewriteBuf =
325 Rewrite.getRewriteBufferFor(MainFileID)) {
Chris Lattner7c239602007-10-13 00:11:23 +0000326 printf("Changed:\n");
327 std::string S(RewriteBuf->begin(), RewriteBuf->end());
328 printf("%s\n", S.c_str());
Chris Lattner8a12c272007-10-11 18:38:32 +0000329 } else {
330 printf("No changes\n");
331 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000332 // Rewrite Objective-c meta data*
333 WriteObjcMetaData();
Chris Lattner77cd2a02007-10-11 00:43:27 +0000334}