blob: 7c27114f1cfda159e77396b98943663928b895fd [file] [log] [blame]
Chris Lattner8bd12b82007-09-15 22:21:22 +00001//===--- Rewriter.cpp - Code rewriting interface --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner8bd12b82007-09-15 22:21:22 +00007//
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 Lattner01c57482007-10-17 22:35:30 +000016#include "clang/AST/Stmt.h"
Ted Kremenek2c3352b2008-10-07 23:08:39 +000017#include "clang/AST/Decl.h"
Manuel Klimekbfbfee52012-05-22 17:01:35 +000018#include "clang/Basic/DiagnosticIDs.h"
19#include "clang/Basic/FileManager.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Manuel Klimekbfbfee52012-05-22 17:01:35 +000021#include "clang/Lex/Lexer.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Manuel Klimekbfbfee52012-05-22 17:01:35 +000023#include "llvm/Support/FileSystem.h"
Chris Lattner8bd12b82007-09-15 22:21:22 +000024using namespace clang;
25
Chris Lattner5f9e2722011-07-23 10:55:15 +000026raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
Nick Lewycky0ade8082010-04-16 18:49:45 +000027 // FIXME: eliminate the copy by writing out each chunk at a time
28 os << std::string(begin(), end());
29 return os;
30}
31
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +000032/// \brief Return true if this character is non-new-line whitespace:
James Dennett8c10f842012-06-15 22:33:08 +000033/// ' ', '\\t', '\\f', '\\v', '\\r'.
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +000034static inline bool isWhitespace(unsigned char c) {
35 switch (c) {
36 case ' ':
37 case '\t':
38 case '\f':
39 case '\v':
40 case '\r':
41 return true;
42 default:
43 return false;
44 }
45}
46
47void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size,
48 bool removeLineIfEmpty) {
Chris Lattner7c239602007-10-13 00:11:23 +000049 // Nothing to remove, exit early.
50 if (Size == 0) return;
51
52 unsigned RealOffset = getMappedOffset(OrigOffset, true);
53 assert(RealOffset+Size < Buffer.size() && "Invalid location");
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner7c239602007-10-13 00:11:23 +000055 // Remove the dead characters.
Chris Lattnerfebe7192008-04-14 07:17:29 +000056 Buffer.erase(RealOffset, Size);
Chris Lattner7c239602007-10-13 00:11:23 +000057
58 // Add a delta so that future changes are offset correctly.
Eli Friedmana0978c22009-05-18 13:56:52 +000059 AddReplaceDelta(OrigOffset, -Size);
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +000060
61 if (removeLineIfEmpty) {
62 // Find the line that the remove occurred and if it is completely empty
63 // remove the line as well.
64
65 iterator curLineStart = begin();
66 unsigned curLineStartOffs = 0;
67 iterator posI = begin();
68 for (unsigned i = 0; i != RealOffset; ++i) {
69 if (*posI == '\n') {
70 curLineStart = posI;
71 ++curLineStart;
72 curLineStartOffs = i + 1;
73 }
74 ++posI;
75 }
76
77 unsigned lineSize = 0;
78 posI = curLineStart;
79 while (posI != end() && isWhitespace(*posI)) {
80 ++posI;
81 ++lineSize;
82 }
83 if (posI != end() && *posI == '\n') {
84 Buffer.erase(curLineStartOffs, lineSize + 1/* + '\n'*/);
85 AddReplaceDelta(curLineStartOffs, -(lineSize + 1/* + '\n'*/));
86 }
87 }
Chris Lattner8bd12b82007-09-15 22:21:22 +000088}
89
Chris Lattner5f9e2722011-07-23 10:55:15 +000090void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str,
Ted Kremenek886c8db2008-03-18 21:17:59 +000091 bool InsertAfter) {
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattner03b07102007-10-13 00:21:23 +000093 // Nothing to insert, exit early.
Daniel Dunbard7407dc2009-08-19 19:10:30 +000094 if (Str.empty()) return;
Chris Lattnerfebe7192008-04-14 07:17:29 +000095
Ted Kremenek886c8db2008-03-18 21:17:59 +000096 unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
Daniel Dunbard7407dc2009-08-19 19:10:30 +000097 Buffer.insert(RealOffset, Str.begin(), Str.end());
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner03b07102007-10-13 00:21:23 +000099 // Add a delta so that future changes are offset correctly.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000100 AddInsertDelta(OrigOffset, Str.size());
Chris Lattner8bd12b82007-09-15 22:21:22 +0000101}
Chris Lattner8a12c272007-10-11 18:38:32 +0000102
Chris Lattner7c239602007-10-13 00:11:23 +0000103/// ReplaceText - This method replaces a range of characters in the input
Chris Lattnerfebe7192008-04-14 07:17:29 +0000104/// buffer with a new string. This is effectively a combined "remove+insert"
Chris Lattner7c239602007-10-13 00:11:23 +0000105/// operation.
106void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 StringRef NewStr) {
Eli Friedmana0978c22009-05-18 13:56:52 +0000108 unsigned RealOffset = getMappedOffset(OrigOffset, true);
Chris Lattnerfebe7192008-04-14 07:17:29 +0000109 Buffer.erase(RealOffset, OrigLength);
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000110 Buffer.insert(RealOffset, NewStr.begin(), NewStr.end());
111 if (OrigLength != NewStr.size())
112 AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength);
Chris Lattner7c239602007-10-13 00:11:23 +0000113}
Chris Lattner8a12c272007-10-11 18:38:32 +0000114
115
116//===----------------------------------------------------------------------===//
117// Rewriter class
118//===----------------------------------------------------------------------===//
119
Chris Lattner311ff022007-10-16 22:36:42 +0000120/// getRangeSize - Return the size in bytes of the specified range if they
121/// are in the same file. If not, this returns -1.
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +0000122int Rewriter::getRangeSize(const CharSourceRange &Range,
Argyrios Kyrtzidisfd183ba2011-04-13 07:15:11 +0000123 RewriteOptions opts) const {
Chris Lattner311ff022007-10-16 22:36:42 +0000124 if (!isRewritable(Range.getBegin()) ||
125 !isRewritable(Range.getEnd())) return -1;
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Chris Lattner2b2453a2009-01-17 06:22:33 +0000127 FileID StartFileID, EndFileID;
128 unsigned StartOff, EndOff;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Chris Lattner311ff022007-10-16 22:36:42 +0000130 StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
131 EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Chris Lattner311ff022007-10-16 22:36:42 +0000133 if (StartFileID != EndFileID)
134 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattnerd6690b22007-10-25 17:18:59 +0000136 // If edits have been made to this buffer, the delta between the range may
137 // have changed.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000138 std::map<FileID, RewriteBuffer>::const_iterator I =
Chris Lattner075eb6e2007-10-25 17:17:34 +0000139 RewriteBuffers.find(StartFileID);
Chris Lattnerd6690b22007-10-25 17:18:59 +0000140 if (I != RewriteBuffers.end()) {
Chris Lattner075eb6e2007-10-25 17:17:34 +0000141 const RewriteBuffer &RB = I->second;
Argyrios Kyrtzidisfd183ba2011-04-13 07:15:11 +0000142 EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange);
143 StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange);
Chris Lattner075eb6e2007-10-25 17:17:34 +0000144 }
145
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Chris Lattner9d62a5b2007-10-17 21:23:07 +0000147 // Adjust the end offset to the end of the last token, instead of being the
Chris Lattner0a76aae2010-06-18 22:45:06 +0000148 // start of the last token if this is a token range.
149 if (Range.isTokenRange())
150 EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattnerd6690b22007-10-25 17:18:59 +0000152 return EndOff-StartOff;
Chris Lattner311ff022007-10-16 22:36:42 +0000153}
154
Argyrios Kyrtzidisfd183ba2011-04-13 07:15:11 +0000155int Rewriter::getRangeSize(SourceRange Range, RewriteOptions opts) const {
156 return getRangeSize(CharSourceRange::getTokenRange(Range), opts);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000157}
158
159
Ted Kremenek6a12a142010-01-07 18:00:35 +0000160/// getRewrittenText - Return the rewritten form of the text in the specified
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000161/// range. If the start or end of the range was unrewritable or if they are
Mike Stump1eb44332009-09-09 15:08:12 +0000162/// in different buffers, this returns an empty string.
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000163///
164/// Note that this method is not particularly efficient.
165///
Ted Kremenek6a12a142010-01-07 18:00:35 +0000166std::string Rewriter::getRewrittenText(SourceRange Range) const {
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000167 if (!isRewritable(Range.getBegin()) ||
168 !isRewritable(Range.getEnd()))
169 return "";
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Chris Lattner2b2453a2009-01-17 06:22:33 +0000171 FileID StartFileID, EndFileID;
172 unsigned StartOff, EndOff;
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000173 StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
174 EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000176 if (StartFileID != EndFileID)
177 return ""; // Start and end in different buffers.
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000179 // If edits have been made to this buffer, the delta between the range may
180 // have changed.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000181 std::map<FileID, RewriteBuffer>::const_iterator I =
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000182 RewriteBuffers.find(StartFileID);
183 if (I == RewriteBuffers.end()) {
184 // If the buffer hasn't been rewritten, just return the text from the input.
185 const char *Ptr = SourceMgr->getCharacterData(Range.getBegin());
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000187 // Adjust the end offset to the end of the last token, instead of being the
188 // start of the last token.
Chris Lattner2c78b872009-04-14 23:22:57 +0000189 EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000190 return std::string(Ptr, Ptr+EndOff-StartOff);
191 }
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000193 const RewriteBuffer &RB = I->second;
194 EndOff = RB.getMappedOffset(EndOff, true);
195 StartOff = RB.getMappedOffset(StartOff);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000197 // Adjust the end offset to the end of the last token, instead of being the
198 // start of the last token.
Chris Lattner2c78b872009-04-14 23:22:57 +0000199 EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000200
201 // Advance the iterators to the right spot, yay for linear time algorithms.
202 RewriteBuffer::iterator Start = RB.begin();
203 std::advance(Start, StartOff);
204 RewriteBuffer::iterator End = Start;
205 std::advance(End, EndOff-StartOff);
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerb5cd09a2008-10-03 23:31:16 +0000207 return std::string(Start, End);
208}
Chris Lattner311ff022007-10-16 22:36:42 +0000209
Chris Lattner7c239602007-10-13 00:11:23 +0000210unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
Chris Lattner2b2453a2009-01-17 06:22:33 +0000211 FileID &FID) const {
Chris Lattner54bd7cb2008-05-28 16:35:02 +0000212 assert(Loc.isValid() && "Invalid location");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000213 std::pair<FileID,unsigned> V = SourceMgr->getDecomposedLoc(Loc);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000214 FID = V.first;
Chris Lattner7c239602007-10-13 00:11:23 +0000215 return V.second;
216}
217
218
Chris Lattner8a12c272007-10-11 18:38:32 +0000219/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
220///
Chris Lattner2b2453a2009-01-17 06:22:33 +0000221RewriteBuffer &Rewriter::getEditBuffer(FileID FID) {
222 std::map<FileID, RewriteBuffer>::iterator I =
223 RewriteBuffers.lower_bound(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000224 if (I != RewriteBuffers.end() && I->first == FID)
Chris Lattner8a12c272007-10-11 18:38:32 +0000225 return I->second;
Chris Lattner2b2453a2009-01-17 06:22:33 +0000226 I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer()));
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattner5f9e2722011-07-23 10:55:15 +0000228 StringRef MB = SourceMgr->getBufferData(FID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000229 I->second.Initialize(MB.begin(), MB.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattner8a12c272007-10-11 18:38:32 +0000231 return I->second;
232}
233
Chris Lattner54a2f072007-11-02 17:26:47 +0000234/// InsertText - Insert the specified string at the specified location in the
Chris Lattneraadaf782008-01-31 19:51:04 +0000235/// original buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000236bool Rewriter::InsertText(SourceLocation Loc, StringRef Str,
John McCallf85e1932011-06-15 23:02:42 +0000237 bool InsertAfter, bool indentNewLines) {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000238 if (!isRewritable(Loc)) return true;
Chris Lattner2b2453a2009-01-17 06:22:33 +0000239 FileID FID;
240 unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
John McCallf85e1932011-06-15 23:02:42 +0000241
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000242 SmallString<128> indentedStr;
John McCallf85e1932011-06-15 23:02:42 +0000243 if (indentNewLines && Str.find('\n') != StringRef::npos) {
244 StringRef MB = SourceMgr->getBufferData(FID);
245
246 unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1;
247 const SrcMgr::ContentCache *
248 Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
249 unsigned lineOffs = Content->SourceLineCache[lineNo];
250
251 // Find the whitespace at the start of the line.
252 StringRef indentSpace;
253 {
254 unsigned i = lineOffs;
255 while (isWhitespace(MB[i]))
256 ++i;
257 indentSpace = MB.substr(lineOffs, i-lineOffs);
258 }
259
Chris Lattner5f9e2722011-07-23 10:55:15 +0000260 SmallVector<StringRef, 4> lines;
John McCallf85e1932011-06-15 23:02:42 +0000261 Str.split(lines, "\n");
262
263 for (unsigned i = 0, e = lines.size(); i != e; ++i) {
264 indentedStr += lines[i];
265 if (i < e-1) {
266 indentedStr += '\n';
267 indentedStr += indentSpace;
268 }
269 }
270 Str = indentedStr.str();
271 }
272
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000273 getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000274 return false;
Chris Lattner54a2f072007-11-02 17:26:47 +0000275}
276
Chris Lattner5f9e2722011-07-23 10:55:15 +0000277bool Rewriter::InsertTextAfterToken(SourceLocation Loc, StringRef Str) {
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +0000278 if (!isRewritable(Loc)) return true;
279 FileID FID;
280 unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
Argyrios Kyrtzidisfd183ba2011-04-13 07:15:11 +0000281 RewriteOptions rangeOpts;
282 rangeOpts.IncludeInsertsAtBeginOfRange = false;
283 StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts);
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +0000284 getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true);
285 return false;
286}
287
Chris Lattneraadaf782008-01-31 19:51:04 +0000288/// RemoveText - Remove the specified text region.
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +0000289bool Rewriter::RemoveText(SourceLocation Start, unsigned Length,
Argyrios Kyrtzidisfd183ba2011-04-13 07:15:11 +0000290 RewriteOptions opts) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000291 if (!isRewritable(Start)) return true;
Chris Lattner2b2453a2009-01-17 06:22:33 +0000292 FileID FID;
293 unsigned StartOffs = getLocationOffsetAndFileID(Start, FID);
Argyrios Kyrtzidisfd183ba2011-04-13 07:15:11 +0000294 getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty);
Chris Lattneraadaf782008-01-31 19:51:04 +0000295 return false;
Chris Lattner674af952007-10-16 22:51:17 +0000296}
Chris Lattner8a12c272007-10-11 18:38:32 +0000297
Chris Lattner674af952007-10-16 22:51:17 +0000298/// ReplaceText - This method replaces a range of characters in the input
299/// buffer with a new string. This is effectively a combined "remove/insert"
300/// operation.
Chris Lattneraadaf782008-01-31 19:51:04 +0000301bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000302 StringRef NewStr) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000303 if (!isRewritable(Start)) return true;
Chris Lattner2b2453a2009-01-17 06:22:33 +0000304 FileID StartFileID;
Chris Lattner7c239602007-10-13 00:11:23 +0000305 unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000307 getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr);
Chris Lattneraadaf782008-01-31 19:51:04 +0000308 return false;
Chris Lattner8a12c272007-10-11 18:38:32 +0000309}
Chris Lattner01c57482007-10-17 22:35:30 +0000310
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +0000311bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) {
312 if (!isRewritable(range.getBegin())) return true;
313 if (!isRewritable(range.getEnd())) return true;
314 if (replacementRange.isInvalid()) return true;
315 SourceLocation start = range.getBegin();
316 unsigned origLength = getRangeSize(range);
317 unsigned newLength = getRangeSize(replacementRange);
318 FileID FID;
319 unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(),
320 FID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000321 StringRef MB = SourceMgr->getBufferData(FID);
Argyrios Kyrtzidisb65ed342011-04-07 18:10:12 +0000322 return ReplaceText(start, origLength, MB.substr(newOffs, newLength));
323}
324
Chris Lattner01c57482007-10-17 22:35:30 +0000325/// ReplaceStmt - This replaces a Stmt/Expr with another, using the pretty
326/// printer to generate the replacement code. This returns true if the input
327/// could not be rewritten, or false if successful.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000328bool Rewriter::ReplaceStmt(Stmt *From, Stmt *To) {
Chris Lattner01c57482007-10-17 22:35:30 +0000329 // Measaure the old text.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000330 int Size = getRangeSize(From->getSourceRange());
Chris Lattner01c57482007-10-17 22:35:30 +0000331 if (Size == -1)
332 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner01c57482007-10-17 22:35:30 +0000334 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +0000335 std::string SStr;
336 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000337 To->printPretty(S, 0, PrintingPolicy(*LangOpts));
Chris Lattner01c57482007-10-17 22:35:30 +0000338 const std::string &Str = S.str();
339
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000340 ReplaceText(From->getLocStart(), Size, Str);
Chris Lattner01c57482007-10-17 22:35:30 +0000341 return false;
342}
Fariborz Jahanian1d015312011-04-11 21:17:02 +0000343
344std::string Rewriter::ConvertToString(Stmt *From) {
345 std::string SStr;
346 llvm::raw_string_ostream S(SStr);
347 From->printPretty(S, 0, PrintingPolicy(*LangOpts));
Fariborz Jahanian85b1c7c2011-04-20 16:38:37 +0000348 return S.str();
Fariborz Jahanian1d015312011-04-11 21:17:02 +0000349}
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000350
351bool Rewriter::IncreaseIndentation(CharSourceRange range,
352 SourceLocation parentIndent) {
John McCallf85e1932011-06-15 23:02:42 +0000353 if (range.isInvalid()) return true;
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000354 if (!isRewritable(range.getBegin())) return true;
355 if (!isRewritable(range.getEnd())) return true;
356 if (!isRewritable(parentIndent)) return true;
357
358 FileID StartFileID, EndFileID, parentFileID;
359 unsigned StartOff, EndOff, parentOff;
360
361 StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID);
362 EndOff = getLocationOffsetAndFileID(range.getEnd(), EndFileID);
363 parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID);
364
365 if (StartFileID != EndFileID || StartFileID != parentFileID)
366 return true;
John McCallf85e1932011-06-15 23:02:42 +0000367 if (StartOff > EndOff)
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000368 return true;
369
370 FileID FID = StartFileID;
371 StringRef MB = SourceMgr->getBufferData(FID);
372
373 unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1;
374 unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1;
375 unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1;
376
377 const SrcMgr::ContentCache *
378 Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
379
John McCallf85e1932011-06-15 23:02:42 +0000380 // Find where the lines start.
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000381 unsigned parentLineOffs = Content->SourceLineCache[parentLineNo];
382 unsigned startLineOffs = Content->SourceLineCache[startLineNo];
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000383
384 // Find the whitespace at the start of each line.
John McCallf85e1932011-06-15 23:02:42 +0000385 StringRef parentSpace, startSpace;
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000386 {
387 unsigned i = parentLineOffs;
388 while (isWhitespace(MB[i]))
389 ++i;
390 parentSpace = MB.substr(parentLineOffs, i-parentLineOffs);
391
392 i = startLineOffs;
393 while (isWhitespace(MB[i]))
394 ++i;
395 startSpace = MB.substr(startLineOffs, i-startLineOffs);
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000396 }
397 if (parentSpace.size() >= startSpace.size())
398 return true;
399 if (!startSpace.startswith(parentSpace))
400 return true;
401
Chris Lattner5f9e2722011-07-23 10:55:15 +0000402 StringRef indent = startSpace.substr(parentSpace.size());
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000403
404 // Indent the lines between start/end offsets.
405 RewriteBuffer &RB = getEditBuffer(FID);
John McCallf85e1932011-06-15 23:02:42 +0000406 for (unsigned lineNo = startLineNo; lineNo <= endLineNo; ++lineNo) {
407 unsigned offs = Content->SourceLineCache[lineNo];
408 unsigned i = offs;
409 while (isWhitespace(MB[i]))
410 ++i;
411 StringRef origIndent = MB.substr(offs, i-offs);
412 if (origIndent.startswith(startSpace))
413 RB.InsertText(offs, indent, /*InsertAfter=*/false);
Argyrios Kyrtzidis10c8d9e2011-04-16 01:03:33 +0000414 }
415
416 return false;
417}
Manuel Klimekbfbfee52012-05-22 17:01:35 +0000418
419// A wrapper for a file stream that atomically overwrites the target.
420//
421// Creates a file output stream for a temporary file in the constructor,
422// which is later accessible via getStream() if ok() return true.
423// Flushes the stream and moves the temporary file to the target location
424// in the destructor.
425class AtomicallyMovedFile {
426public:
427 AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
428 bool &AllWritten)
429 : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
430 TempFilename = Filename;
431 TempFilename += "-%%%%%%%%";
432 int FD;
433 if (llvm::sys::fs::unique_file(TempFilename.str(), FD, TempFilename,
434 /*makeAbsolute=*/true, 0664)) {
435 AllWritten = false;
436 Diagnostics.Report(clang::diag::err_unable_to_make_temp)
437 << TempFilename;
438 } else {
439 FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
440 }
441 }
442
443 ~AtomicallyMovedFile() {
444 if (!ok()) return;
445
446 FileStream->flush();
NAKAMURA Takumi2d9c4df2012-05-27 12:59:58 +0000447#ifdef _WIN32
448 // Win32 does not allow rename/removing opened files.
449 FileStream.reset();
450#endif
Manuel Klimekbfbfee52012-05-22 17:01:35 +0000451 if (llvm::error_code ec =
452 llvm::sys::fs::rename(TempFilename.str(), Filename)) {
453 AllWritten = false;
454 Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
455 << TempFilename << Filename << ec.message();
456 bool existed;
457 // If the remove fails, there's not a lot we can do - this is already an
458 // error.
459 llvm::sys::fs::remove(TempFilename.str(), existed);
460 }
461 }
462
463 bool ok() { return FileStream; }
464 llvm::raw_ostream &getStream() { return *FileStream; }
465
466private:
467 DiagnosticsEngine &Diagnostics;
468 StringRef Filename;
469 SmallString<128> TempFilename;
470 OwningPtr<llvm::raw_fd_ostream> FileStream;
471 bool &AllWritten;
472};
473
474bool Rewriter::overwriteChangedFiles() {
475 bool AllWritten = true;
476 for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
477 const FileEntry *Entry =
478 getSourceMgr().getFileEntryForID(I->first);
479 AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
480 AllWritten);
481 if (File.ok()) {
482 I->second.write(File.getStream());
483 }
484 }
485 return !AllWritten;
486}