blob: 3a007f3e71fed17e9e758c3c1a806200c54a16aa [file] [log] [blame]
Chris Lattner57629372007-09-15 22:21:22 +00001//===--- Rewriter.cpp - Code rewriting interface --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Rewriter class, which is used for code
11// transformations.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Rewrite/Rewriter.h"
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000016#include "clang/AST/Stmt.h"
Chris Lattner93e2a4e2007-10-17 21:23:07 +000017#include "clang/Lex/Lexer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000019#include <sstream>
Chris Lattner57629372007-09-15 22:21:22 +000020using namespace clang;
21
Chris Lattner3cfe3d32007-10-13 00:11:23 +000022/// getMappedOffset - Given an offset into the original SourceBuffer that this
23/// RewriteBuffer is based on, map it into the offset space of the
24/// RewriteBuffer.
25unsigned RewriteBuffer::getMappedOffset(unsigned OrigOffset,
26 bool AfterInserts) const {
27 unsigned ResultOffset = OrigOffset;
28 unsigned DeltaIdx = 0;
29
30 // Move past any deltas that are relevant.
31 // FIXME: binary search.
32 for (; DeltaIdx != Deltas.size() &&
Chris Lattnerf5e7f842007-10-13 00:17:04 +000033 Deltas[DeltaIdx].FileLoc < OrigOffset; ++DeltaIdx)
Chris Lattner3cfe3d32007-10-13 00:11:23 +000034 ResultOffset += Deltas[DeltaIdx].Delta;
35
36 if (AfterInserts && DeltaIdx != Deltas.size() &&
37 OrigOffset == Deltas[DeltaIdx].FileLoc)
38 ResultOffset += Deltas[DeltaIdx].Delta;
39 return ResultOffset;
40}
41
42/// AddDelta - When a change is made that shifts around the text buffer, this
43/// method is used to record that info.
44void RewriteBuffer::AddDelta(unsigned OrigOffset, int Change) {
45 assert(Change != 0 && "Not changing anything");
46 unsigned DeltaIdx = 0;
47
48 // Skip over any unrelated deltas.
49 for (; DeltaIdx != Deltas.size() &&
Chris Lattnerf5e7f842007-10-13 00:17:04 +000050 Deltas[DeltaIdx].FileLoc < OrigOffset; ++DeltaIdx)
Chris Lattner3cfe3d32007-10-13 00:11:23 +000051 ;
52
53 // If there is no a delta for this offset, insert a new delta record.
54 if (DeltaIdx == Deltas.size() || OrigOffset != Deltas[DeltaIdx].FileLoc) {
55 // If this is a removal, check to see if this can be folded into
56 // a delta at the end of the deletion. For example, if we have:
57 // ABCXDEF (X inserted after C) and delete C, we want to end up with no
58 // delta because X basically replaced C.
59 if (Change < 0 && DeltaIdx != Deltas.size() &&
60 OrigOffset-Change == Deltas[DeltaIdx].FileLoc) {
61 // Adjust the start of the delta to be the start of the deleted region.
62 Deltas[DeltaIdx].FileLoc += Change;
63 Deltas[DeltaIdx].Delta += Change;
64
65 // If the delta becomes a noop, remove it.
66 if (Deltas[DeltaIdx].Delta == 0)
67 Deltas.erase(Deltas.begin()+DeltaIdx);
68 return;
69 }
70
71 // Otherwise, create an entry and return.
72 Deltas.insert(Deltas.begin()+DeltaIdx,
73 SourceDelta::get(OrigOffset, Change));
74 return;
75 }
76
77 // Otherwise, we found a delta record at this offset, adjust it.
78 Deltas[DeltaIdx].Delta += Change;
79
80 // If it is now dead, remove it.
Fariborz Jahanian07cf2e02007-11-06 23:06:16 +000081 if (Deltas[DeltaIdx].Delta == 0)
Chris Lattner3cfe3d32007-10-13 00:11:23 +000082 Deltas.erase(Deltas.begin()+DeltaIdx);
83}
84
Chris Lattner57629372007-09-15 22:21:22 +000085
86void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size) {
Chris Lattner3cfe3d32007-10-13 00:11:23 +000087 // Nothing to remove, exit early.
88 if (Size == 0) return;
89
90 unsigned RealOffset = getMappedOffset(OrigOffset, true);
91 assert(RealOffset+Size < Buffer.size() && "Invalid location");
92
93 // Remove the dead characters.
94 Buffer.erase(Buffer.begin()+RealOffset, Buffer.begin()+RealOffset+Size);
95
96 // Add a delta so that future changes are offset correctly.
97 AddDelta(OrigOffset, -Size);
Chris Lattner57629372007-09-15 22:21:22 +000098}
99
100void RewriteBuffer::InsertText(unsigned OrigOffset,
101 const char *StrData, unsigned StrLen) {
Chris Lattnercea0bcc2007-10-13 00:21:23 +0000102 // Nothing to insert, exit early.
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000103 if (StrLen == 0) return;
Chris Lattnercea0bcc2007-10-13 00:21:23 +0000104
105 unsigned RealOffset = getMappedOffset(OrigOffset, true);
106 assert(RealOffset <= Buffer.size() && "Invalid location");
107
Chris Lattnerd119a842007-11-08 04:41:04 +0000108 // Insert the new characters.
Chris Lattnercea0bcc2007-10-13 00:21:23 +0000109 Buffer.insert(Buffer.begin()+RealOffset, StrData, StrData+StrLen);
110
111 // Add a delta so that future changes are offset correctly.
112 AddDelta(OrigOffset, StrLen);
Chris Lattner57629372007-09-15 22:21:22 +0000113}
Chris Lattner569faa62007-10-11 18:38:32 +0000114
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000115/// ReplaceText - This method replaces a range of characters in the input
116/// buffer with a new string. This is effectively a combined "remove/insert"
117/// operation.
118void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
119 const char *NewStr, unsigned NewLength) {
Chris Lattnerb57cd002007-11-08 04:09:59 +0000120 unsigned RealOffset = getMappedOffset(OrigOffset, true);
Chris Lattnere471a3b2007-10-13 00:46:29 +0000121 assert(RealOffset+OrigLength <= Buffer.size() && "Invalid location");
122
Chris Lattner9c752232007-11-08 07:35:14 +0000123 Buffer.erase(Buffer.begin()+RealOffset, Buffer.begin()+RealOffset+OrigLength);
124 Buffer.insert(Buffer.begin()+RealOffset, NewStr, NewStr+NewLength);
125 AddDelta(OrigOffset, NewLength-OrigLength);
126 return;
127
Chris Lattnere471a3b2007-10-13 00:46:29 +0000128 // Overwrite the common piece.
Chris Lattnerd119a842007-11-08 04:41:04 +0000129 unsigned CommonLength = std::min(OrigLength, NewLength);
130 std::copy(NewStr, NewStr+CommonLength, Buffer.begin()+RealOffset);
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000131
Chris Lattnere471a3b2007-10-13 00:46:29 +0000132 // If replacing without shifting around, just overwrite the text.
133 if (OrigLength == NewLength)
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000134 return;
Chris Lattnere471a3b2007-10-13 00:46:29 +0000135
136 // If inserting more than existed before, this is like an insertion.
137 if (NewLength > OrigLength) {
138 Buffer.insert(Buffer.begin()+RealOffset+OrigLength,
139 NewStr+OrigLength, NewStr+NewLength);
140 } else {
141 // If insertion less than existed before, this is like a removal.
142 Buffer.erase(Buffer.begin()+RealOffset+NewLength,
143 Buffer.begin()+RealOffset+OrigLength);
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000144 }
Chris Lattnere471a3b2007-10-13 00:46:29 +0000145 AddDelta(OrigOffset, NewLength-OrigLength);
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000146}
Chris Lattner569faa62007-10-11 18:38:32 +0000147
148
149//===----------------------------------------------------------------------===//
150// Rewriter class
151//===----------------------------------------------------------------------===//
152
Chris Lattner6fe8b272007-10-16 22:36:42 +0000153/// getRangeSize - Return the size in bytes of the specified range if they
154/// are in the same file. If not, this returns -1.
155int Rewriter::getRangeSize(SourceRange Range) const {
156 if (!isRewritable(Range.getBegin()) ||
157 !isRewritable(Range.getEnd())) return -1;
158
159 unsigned StartOff, StartFileID;
160 unsigned EndOff , EndFileID;
161
162 StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
163 EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
164
165 if (StartFileID != EndFileID)
166 return -1;
167
Chris Lattnerbc68f692007-10-25 17:18:59 +0000168 // If edits have been made to this buffer, the delta between the range may
169 // have changed.
Chris Lattnera8a73682007-10-25 17:17:34 +0000170 std::map<unsigned, RewriteBuffer>::const_iterator I =
171 RewriteBuffers.find(StartFileID);
Chris Lattnerbc68f692007-10-25 17:18:59 +0000172 if (I != RewriteBuffers.end()) {
Chris Lattnera8a73682007-10-25 17:17:34 +0000173 const RewriteBuffer &RB = I->second;
Chris Lattnerbc68f692007-10-25 17:18:59 +0000174 EndOff = RB.getMappedOffset(EndOff, true);
175 StartOff = RB.getMappedOffset(StartOff);
Chris Lattnera8a73682007-10-25 17:17:34 +0000176 }
177
178
Chris Lattner93e2a4e2007-10-17 21:23:07 +0000179 // Adjust the end offset to the end of the last token, instead of being the
180 // start of the last token.
Chris Lattnerbc68f692007-10-25 17:18:59 +0000181 EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr);
Chris Lattner93e2a4e2007-10-17 21:23:07 +0000182
Chris Lattnerbc68f692007-10-25 17:18:59 +0000183 return EndOff-StartOff;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000184}
185
186
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000187unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
188 unsigned &FileID) const {
Chris Lattner74db1682007-10-16 21:07:07 +0000189 std::pair<unsigned,unsigned> V = SourceMgr->getDecomposedFileLoc(Loc);
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000190 FileID = V.first;
191 return V.second;
192}
193
194
Chris Lattner569faa62007-10-11 18:38:32 +0000195/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
196///
197RewriteBuffer &Rewriter::getEditBuffer(unsigned FileID) {
198 std::map<unsigned, RewriteBuffer>::iterator I =
199 RewriteBuffers.lower_bound(FileID);
200 if (I != RewriteBuffers.end() && I->first == FileID)
201 return I->second;
202 I = RewriteBuffers.insert(I, std::make_pair(FileID, RewriteBuffer()));
203
Chris Lattner74db1682007-10-16 21:07:07 +0000204 std::pair<const char*, const char*> MB = SourceMgr->getBufferData(FileID);
Chris Lattner569faa62007-10-11 18:38:32 +0000205 I->second.Initialize(MB.first, MB.second);
206
207 return I->second;
208}
209
Chris Lattner532e5742007-11-02 17:26:47 +0000210/// InsertText - Insert the specified string at the specified location in the
211/// original buffer. This method is only valid on rewritable source
212/// locations.
213void Rewriter::InsertText(SourceLocation Loc,
214 const char *StrData, unsigned StrLen) {
215 unsigned FileID;
216 unsigned StartOffs = getLocationOffsetAndFileID(Loc, FileID);
217 getEditBuffer(FileID).InsertText(StartOffs, StrData, StrLen);
218}
219
Chris Lattnercfd61c82007-10-16 22:51:17 +0000220/// RemoveText - Remove the specified text region. This method is only valid
221/// on a rewritable source location.
222void Rewriter::RemoveText(SourceLocation Start, unsigned Length) {
223 unsigned FileID;
224 unsigned StartOffs = getLocationOffsetAndFileID(Start, FileID);
225 getEditBuffer(FileID).RemoveText(StartOffs, Length);
226}
Chris Lattner569faa62007-10-11 18:38:32 +0000227
Chris Lattnercfd61c82007-10-16 22:51:17 +0000228/// ReplaceText - This method replaces a range of characters in the input
229/// buffer with a new string. This is effectively a combined "remove/insert"
230/// operation.
Chris Lattner569faa62007-10-11 18:38:32 +0000231void Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
232 const char *NewStr, unsigned NewLength) {
233 assert(isRewritable(Start) && "Not a rewritable location!");
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000234 unsigned StartFileID;
235 unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
Chris Lattner569faa62007-10-11 18:38:32 +0000236
Chris Lattner3cfe3d32007-10-13 00:11:23 +0000237 getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength,
238 NewStr, NewLength);
Chris Lattner569faa62007-10-11 18:38:32 +0000239}
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000240
241/// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty
242/// printer to generate the replacement code. This returns true if the input
243/// could not be rewritten, or false if successful.
244bool Rewriter::ReplaceStmt(Stmt *From, Stmt *To) {
245 // Measaure the old text.
246 int Size = getRangeSize(From->getSourceRange());
247 if (Size == -1)
248 return true;
249
250 // Get the new text.
251 std::ostringstream S;
252 To->printPretty(S);
253 const std::string &Str = S.str();
254
255 ReplaceText(From->getLocStart(), Size, &Str[0], Str.size());
256 return false;
257}
258
259