blob: 883482c67e7ddc5151579b6e83c537cc2fef395a [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
136 if (IDecl->getImplDeclNumIvars() > 0 ||
137 CDecl&& CDecl->getIntfDeclNumIvars() > 0) {
138 static bool objc_ivar = false;
139
140 int NumIvars = IDecl->getImplDeclNumIvars() > 0
141 ? IDecl->getImplDeclNumIvars()
142 : CDecl->getIntfDeclNumIvars();
143
144 if (!objc_ivar) {
145 /* struct _objc_ivar {
146 char *ivar_name;
147 char *ivar_type;
148 int ivar_offset;
149 };
150 */
151 printf("\nstruct _objc_ivar {\n");
152 printf("\tchar *ivar_name;\n");
153 printf("\tchar *ivar_type;\n");
154 printf("\tint ivar_offset;\n");
155 printf("};\n");
156 objc_ivar = true;
157 }
158
159 /* struct _objc_ivar_list {
160 int ivar_count;
161 struct _objc_ivar ivar_list[ivar_count];
162 };
163 */
164 printf("\nstatic struct {\n");
165 printf("\tint ivar_count;\n");
166 printf("\tstruct _objc_ivar ivar_list[%d];\n", NumIvars);
167 printf("} _OBJC_INSTANCE_VARIABLES_%s "
168 "__attribute__ ((section (\"__OBJC, __instance_vars\")))= "
169 "{\n\t%d\n",IDecl->getName(),
170 NumIvars);
171 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
172 ? IDecl->getImplDeclIVars()
173 : CDecl->getIntfDeclIvars();
174 for (int i = 0; i < NumIvars; i++)
175 // TODO: 1) ivar names may have to go to another section. 2) encode
176 // ivar_type type of each ivar . 3) compute and add ivar offset.
177 printf("\t,\"%s\", \"\", 0\n", Ivars[i]->getName());
178 printf("};\n");
179 }
180
181}
182
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000183void RewriteTest::WriteObjcMetaData() {
184 int ClsDefCount = ClassImplementation.size();
185 int CatDefCount = CategoryImplementation.size();
186 if (ClsDefCount == 0 && CatDefCount == 0)
187 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000188
189 // For each defined class, write out all its meta data.
190 for (int i = 0; i < ClsDefCount; i++)
191 WriteObjcClassMetaData(ClassImplementation[i]);
192
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000193 // Write objc_symtab metadata
194 /*
195 struct _objc_symtab
196 {
197 long sel_ref_cnt;
198 SEL *refs;
199 short cls_def_cnt;
200 short cat_def_cnt;
201 void *defs[cls_def_cnt + cat_def_cnt];
202 };
203 */
204
205 printf("\nstruct _objc_symtab {\n");
206 printf("\tlong sel_ref_cnt;\n");
207 printf("\tSEL *refs;\n");
208 printf("\tshort cls_def_cnt;\n");
209 printf("\tshort cat_def_cnt;\n");
210 printf("\tvoid *defs[%d];\n", ClsDefCount + CatDefCount);
211 printf("};\n\n");
212
213 printf("static struct _objc_symtab "
214 "_OBJC_SYMBOLS __attribute__ ((section (\"__OBJC, __symbols\")))= {\n");
215 printf("\t0, 0, %d, %d\n", ClsDefCount, CatDefCount);
216 for (int i = 0; i < ClsDefCount; i++)
217 printf("\t,_OBJC_CLASS_%s\n", ClassImplementation[i]->getName());
218
219 for (int i = 0; i < CatDefCount; i++)
220 printf("\t,_OBJC_CATEGORY_%s_%s\n",
221 CategoryImplementation[i]->getClassInterface()->getName(),
222 CategoryImplementation[i]->getName());
223
224 printf("};\n\n");
225
226 // Write objc_module metadata
227
228 /*
229 struct _objc_module {
230 long version;
231 long size;
232 const char *name;
233 struct _objc_symtab *symtab;
234 }
235 */
236
237 printf("\nstruct _objc_module {\n");
238 printf("\tlong version;\n");
239 printf("\tlong size;\n");
240 printf("\tconst char *name;\n");
241 printf("\tstruct _objc_symtab *symtab;");
242 printf("};\n\n");
243 printf("static struct _objc_module "
244 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n");
245 printf("\t%d, %d, \"\", &_OBJC_SYMBOLS\n", OBJC_ABI_VERSION, 16);
246 printf("};\n\n");
247}
Chris Lattner311ff022007-10-16 22:36:42 +0000248
Chris Lattner8a12c272007-10-11 18:38:32 +0000249RewriteTest::~RewriteTest() {
Chris Lattner8a12c272007-10-11 18:38:32 +0000250 // Get the top-level buffer that this corresponds to.
251 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
252 const char *MainBufStart = MainBuf.first;
253 const char *MainBufEnd = MainBuf.second;
254
255 // Loop over the whole file, looking for tabs.
256 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
257 if (*BufPtr != '\t')
258 continue;
259
260 // Okay, we found a tab. This tab will turn into at least one character,
261 // but it depends on which 'virtual column' it is in. Compute that now.
262 unsigned VCol = 0;
263 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
264 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
265 ++VCol;
266
267 // Okay, now that we know the virtual column, we know how many spaces to
268 // insert. We assume 8-character tab-stops.
269 unsigned Spaces = 8-(VCol & 7);
270
271 // Get the location of the tab.
272 SourceLocation TabLoc =
273 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
274
275 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner57c337d2007-10-13 00:46:29 +0000276 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner8a12c272007-10-11 18:38:32 +0000277 }
278
279 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
280 // we are done.
281 if (const RewriteBuffer *RewriteBuf =
282 Rewrite.getRewriteBufferFor(MainFileID)) {
Chris Lattner7c239602007-10-13 00:11:23 +0000283 printf("Changed:\n");
284 std::string S(RewriteBuf->begin(), RewriteBuf->end());
285 printf("%s\n", S.c_str());
Chris Lattner8a12c272007-10-11 18:38:32 +0000286 } else {
287 printf("No changes\n");
288 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000289 // Rewrite Objective-c meta data*
290 WriteObjcMetaData();
Chris Lattner77cd2a02007-10-11 00:43:27 +0000291}