xref: /freebsd/contrib/llvm-project/clang/lib/Rewrite/Rewriter.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===- Rewriter.cpp - Code rewriting interface ----------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric //  This file defines the Rewriter class, which is used for code
10*0b57cec5SDimitry Andric //  transformations.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "clang/Rewrite/Core/Rewriter.h"
15*0b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
16*0b57cec5SDimitry Andric #include "clang/Basic/DiagnosticIDs.h"
17*0b57cec5SDimitry Andric #include "clang/Basic/FileManager.h"
18*0b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
19*0b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
20*0b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
21*0b57cec5SDimitry Andric #include "clang/Rewrite/Core/RewriteBuffer.h"
22*0b57cec5SDimitry Andric #include "clang/Rewrite/Core/RewriteRope.h"
23*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
24*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
25*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
26*0b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
27*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
28*0b57cec5SDimitry Andric #include <cassert>
29*0b57cec5SDimitry Andric #include <iterator>
30*0b57cec5SDimitry Andric #include <map>
31*0b57cec5SDimitry Andric #include <memory>
32*0b57cec5SDimitry Andric #include <system_error>
33*0b57cec5SDimitry Andric #include <utility>
34*0b57cec5SDimitry Andric 
35*0b57cec5SDimitry Andric using namespace clang;
36*0b57cec5SDimitry Andric 
37*0b57cec5SDimitry Andric raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
38*0b57cec5SDimitry Andric   // Walk RewriteRope chunks efficiently using MoveToNextPiece() instead of the
39*0b57cec5SDimitry Andric   // character iterator.
40*0b57cec5SDimitry Andric   for (RopePieceBTreeIterator I = begin(), E = end(); I != E;
41*0b57cec5SDimitry Andric        I.MoveToNextPiece())
42*0b57cec5SDimitry Andric     os << I.piece();
43*0b57cec5SDimitry Andric   return os;
44*0b57cec5SDimitry Andric }
45*0b57cec5SDimitry Andric 
46*0b57cec5SDimitry Andric /// Return true if this character is non-new-line whitespace:
47*0b57cec5SDimitry Andric /// ' ', '\\t', '\\f', '\\v', '\\r'.
48*0b57cec5SDimitry Andric static inline bool isWhitespaceExceptNL(unsigned char c) {
49*0b57cec5SDimitry Andric   switch (c) {
50*0b57cec5SDimitry Andric   case ' ':
51*0b57cec5SDimitry Andric   case '\t':
52*0b57cec5SDimitry Andric   case '\f':
53*0b57cec5SDimitry Andric   case '\v':
54*0b57cec5SDimitry Andric   case '\r':
55*0b57cec5SDimitry Andric     return true;
56*0b57cec5SDimitry Andric   default:
57*0b57cec5SDimitry Andric     return false;
58*0b57cec5SDimitry Andric   }
59*0b57cec5SDimitry Andric }
60*0b57cec5SDimitry Andric 
61*0b57cec5SDimitry Andric void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size,
62*0b57cec5SDimitry Andric                                bool removeLineIfEmpty) {
63*0b57cec5SDimitry Andric   // Nothing to remove, exit early.
64*0b57cec5SDimitry Andric   if (Size == 0) return;
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric   unsigned RealOffset = getMappedOffset(OrigOffset, true);
67*0b57cec5SDimitry Andric   assert(RealOffset+Size <= Buffer.size() && "Invalid location");
68*0b57cec5SDimitry Andric 
69*0b57cec5SDimitry Andric   // Remove the dead characters.
70*0b57cec5SDimitry Andric   Buffer.erase(RealOffset, Size);
71*0b57cec5SDimitry Andric 
72*0b57cec5SDimitry Andric   // Add a delta so that future changes are offset correctly.
73*0b57cec5SDimitry Andric   AddReplaceDelta(OrigOffset, -Size);
74*0b57cec5SDimitry Andric 
75*0b57cec5SDimitry Andric   if (removeLineIfEmpty) {
76*0b57cec5SDimitry Andric     // Find the line that the remove occurred and if it is completely empty
77*0b57cec5SDimitry Andric     // remove the line as well.
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric     iterator curLineStart = begin();
80*0b57cec5SDimitry Andric     unsigned curLineStartOffs = 0;
81*0b57cec5SDimitry Andric     iterator posI = begin();
82*0b57cec5SDimitry Andric     for (unsigned i = 0; i != RealOffset; ++i) {
83*0b57cec5SDimitry Andric       if (*posI == '\n') {
84*0b57cec5SDimitry Andric         curLineStart = posI;
85*0b57cec5SDimitry Andric         ++curLineStart;
86*0b57cec5SDimitry Andric         curLineStartOffs = i + 1;
87*0b57cec5SDimitry Andric       }
88*0b57cec5SDimitry Andric       ++posI;
89*0b57cec5SDimitry Andric     }
90*0b57cec5SDimitry Andric 
91*0b57cec5SDimitry Andric     unsigned lineSize = 0;
92*0b57cec5SDimitry Andric     posI = curLineStart;
93*0b57cec5SDimitry Andric     while (posI != end() && isWhitespaceExceptNL(*posI)) {
94*0b57cec5SDimitry Andric       ++posI;
95*0b57cec5SDimitry Andric       ++lineSize;
96*0b57cec5SDimitry Andric     }
97*0b57cec5SDimitry Andric     if (posI != end() && *posI == '\n') {
98*0b57cec5SDimitry Andric       Buffer.erase(curLineStartOffs, lineSize + 1/* + '\n'*/);
99*0b57cec5SDimitry Andric       AddReplaceDelta(curLineStartOffs, -(lineSize + 1/* + '\n'*/));
100*0b57cec5SDimitry Andric     }
101*0b57cec5SDimitry Andric   }
102*0b57cec5SDimitry Andric }
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str,
105*0b57cec5SDimitry Andric                                bool InsertAfter) {
106*0b57cec5SDimitry Andric   // Nothing to insert, exit early.
107*0b57cec5SDimitry Andric   if (Str.empty()) return;
108*0b57cec5SDimitry Andric 
109*0b57cec5SDimitry Andric   unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
110*0b57cec5SDimitry Andric   Buffer.insert(RealOffset, Str.begin(), Str.end());
111*0b57cec5SDimitry Andric 
112*0b57cec5SDimitry Andric   // Add a delta so that future changes are offset correctly.
113*0b57cec5SDimitry Andric   AddInsertDelta(OrigOffset, Str.size());
114*0b57cec5SDimitry Andric }
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric /// ReplaceText - This method replaces a range of characters in the input
117*0b57cec5SDimitry Andric /// buffer with a new string.  This is effectively a combined "remove+insert"
118*0b57cec5SDimitry Andric /// operation.
119*0b57cec5SDimitry Andric void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
120*0b57cec5SDimitry Andric                                 StringRef NewStr) {
121*0b57cec5SDimitry Andric   unsigned RealOffset = getMappedOffset(OrigOffset, true);
122*0b57cec5SDimitry Andric   Buffer.erase(RealOffset, OrigLength);
123*0b57cec5SDimitry Andric   Buffer.insert(RealOffset, NewStr.begin(), NewStr.end());
124*0b57cec5SDimitry Andric   if (OrigLength != NewStr.size())
125*0b57cec5SDimitry Andric     AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength);
126*0b57cec5SDimitry Andric }
127*0b57cec5SDimitry Andric 
128*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
129*0b57cec5SDimitry Andric // Rewriter class
130*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric /// getRangeSize - Return the size in bytes of the specified range if they
133*0b57cec5SDimitry Andric /// are in the same file.  If not, this returns -1.
134*0b57cec5SDimitry Andric int Rewriter::getRangeSize(const CharSourceRange &Range,
135*0b57cec5SDimitry Andric                            RewriteOptions opts) const {
136*0b57cec5SDimitry Andric   if (!isRewritable(Range.getBegin()) ||
137*0b57cec5SDimitry Andric       !isRewritable(Range.getEnd())) return -1;
138*0b57cec5SDimitry Andric 
139*0b57cec5SDimitry Andric   FileID StartFileID, EndFileID;
140*0b57cec5SDimitry Andric   unsigned StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
141*0b57cec5SDimitry Andric   unsigned EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric   if (StartFileID != EndFileID)
144*0b57cec5SDimitry Andric     return -1;
145*0b57cec5SDimitry Andric 
146*0b57cec5SDimitry Andric   // If edits have been made to this buffer, the delta between the range may
147*0b57cec5SDimitry Andric   // have changed.
148*0b57cec5SDimitry Andric   std::map<FileID, RewriteBuffer>::const_iterator I =
149*0b57cec5SDimitry Andric     RewriteBuffers.find(StartFileID);
150*0b57cec5SDimitry Andric   if (I != RewriteBuffers.end()) {
151*0b57cec5SDimitry Andric     const RewriteBuffer &RB = I->second;
152*0b57cec5SDimitry Andric     EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange);
153*0b57cec5SDimitry Andric     StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange);
154*0b57cec5SDimitry Andric   }
155*0b57cec5SDimitry Andric 
156*0b57cec5SDimitry Andric   // Adjust the end offset to the end of the last token, instead of being the
157*0b57cec5SDimitry Andric   // start of the last token if this is a token range.
158*0b57cec5SDimitry Andric   if (Range.isTokenRange())
159*0b57cec5SDimitry Andric     EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
160*0b57cec5SDimitry Andric 
161*0b57cec5SDimitry Andric   return EndOff-StartOff;
162*0b57cec5SDimitry Andric }
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric int Rewriter::getRangeSize(SourceRange Range, RewriteOptions opts) const {
165*0b57cec5SDimitry Andric   return getRangeSize(CharSourceRange::getTokenRange(Range), opts);
166*0b57cec5SDimitry Andric }
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric /// getRewrittenText - Return the rewritten form of the text in the specified
169*0b57cec5SDimitry Andric /// range.  If the start or end of the range was unrewritable or if they are
170*0b57cec5SDimitry Andric /// in different buffers, this returns an empty string.
171*0b57cec5SDimitry Andric ///
172*0b57cec5SDimitry Andric /// Note that this method is not particularly efficient.
173*0b57cec5SDimitry Andric std::string Rewriter::getRewrittenText(CharSourceRange Range) const {
174*0b57cec5SDimitry Andric   if (!isRewritable(Range.getBegin()) ||
175*0b57cec5SDimitry Andric       !isRewritable(Range.getEnd()))
176*0b57cec5SDimitry Andric     return {};
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   FileID StartFileID, EndFileID;
179*0b57cec5SDimitry Andric   unsigned StartOff, EndOff;
180*0b57cec5SDimitry Andric   StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
181*0b57cec5SDimitry Andric   EndOff   = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric   if (StartFileID != EndFileID)
184*0b57cec5SDimitry Andric     return {}; // Start and end in different buffers.
185*0b57cec5SDimitry Andric 
186*0b57cec5SDimitry Andric   // If edits have been made to this buffer, the delta between the range may
187*0b57cec5SDimitry Andric   // have changed.
188*0b57cec5SDimitry Andric   std::map<FileID, RewriteBuffer>::const_iterator I =
189*0b57cec5SDimitry Andric     RewriteBuffers.find(StartFileID);
190*0b57cec5SDimitry Andric   if (I == RewriteBuffers.end()) {
191*0b57cec5SDimitry Andric     // If the buffer hasn't been rewritten, just return the text from the input.
192*0b57cec5SDimitry Andric     const char *Ptr = SourceMgr->getCharacterData(Range.getBegin());
193*0b57cec5SDimitry Andric 
194*0b57cec5SDimitry Andric     // Adjust the end offset to the end of the last token, instead of being the
195*0b57cec5SDimitry Andric     // start of the last token.
196*0b57cec5SDimitry Andric     if (Range.isTokenRange())
197*0b57cec5SDimitry Andric       EndOff +=
198*0b57cec5SDimitry Andric           Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
199*0b57cec5SDimitry Andric     return std::string(Ptr, Ptr+EndOff-StartOff);
200*0b57cec5SDimitry Andric   }
201*0b57cec5SDimitry Andric 
202*0b57cec5SDimitry Andric   const RewriteBuffer &RB = I->second;
203*0b57cec5SDimitry Andric   EndOff = RB.getMappedOffset(EndOff, true);
204*0b57cec5SDimitry Andric   StartOff = RB.getMappedOffset(StartOff);
205*0b57cec5SDimitry Andric 
206*0b57cec5SDimitry Andric   // Adjust the end offset to the end of the last token, instead of being the
207*0b57cec5SDimitry Andric   // start of the last token.
208*0b57cec5SDimitry Andric   if (Range.isTokenRange())
209*0b57cec5SDimitry Andric     EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
210*0b57cec5SDimitry Andric 
211*0b57cec5SDimitry Andric   // Advance the iterators to the right spot, yay for linear time algorithms.
212*0b57cec5SDimitry Andric   RewriteBuffer::iterator Start = RB.begin();
213*0b57cec5SDimitry Andric   std::advance(Start, StartOff);
214*0b57cec5SDimitry Andric   RewriteBuffer::iterator End = Start;
215*0b57cec5SDimitry Andric   std::advance(End, EndOff-StartOff);
216*0b57cec5SDimitry Andric 
217*0b57cec5SDimitry Andric   return std::string(Start, End);
218*0b57cec5SDimitry Andric }
219*0b57cec5SDimitry Andric 
220*0b57cec5SDimitry Andric unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
221*0b57cec5SDimitry Andric                                               FileID &FID) const {
222*0b57cec5SDimitry Andric   assert(Loc.isValid() && "Invalid location");
223*0b57cec5SDimitry Andric   std::pair<FileID, unsigned> V = SourceMgr->getDecomposedLoc(Loc);
224*0b57cec5SDimitry Andric   FID = V.first;
225*0b57cec5SDimitry Andric   return V.second;
226*0b57cec5SDimitry Andric }
227*0b57cec5SDimitry Andric 
228*0b57cec5SDimitry Andric /// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
229*0b57cec5SDimitry Andric RewriteBuffer &Rewriter::getEditBuffer(FileID FID) {
230*0b57cec5SDimitry Andric   std::map<FileID, RewriteBuffer>::iterator I =
231*0b57cec5SDimitry Andric     RewriteBuffers.lower_bound(FID);
232*0b57cec5SDimitry Andric   if (I != RewriteBuffers.end() && I->first == FID)
233*0b57cec5SDimitry Andric     return I->second;
234*0b57cec5SDimitry Andric   I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer()));
235*0b57cec5SDimitry Andric 
236*0b57cec5SDimitry Andric   StringRef MB = SourceMgr->getBufferData(FID);
237*0b57cec5SDimitry Andric   I->second.Initialize(MB.begin(), MB.end());
238*0b57cec5SDimitry Andric 
239*0b57cec5SDimitry Andric   return I->second;
240*0b57cec5SDimitry Andric }
241*0b57cec5SDimitry Andric 
242*0b57cec5SDimitry Andric /// InsertText - Insert the specified string at the specified location in the
243*0b57cec5SDimitry Andric /// original buffer.
244*0b57cec5SDimitry Andric bool Rewriter::InsertText(SourceLocation Loc, StringRef Str,
245*0b57cec5SDimitry Andric                           bool InsertAfter, bool indentNewLines) {
246*0b57cec5SDimitry Andric   if (!isRewritable(Loc)) return true;
247*0b57cec5SDimitry Andric   FileID FID;
248*0b57cec5SDimitry Andric   unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
249*0b57cec5SDimitry Andric 
250*0b57cec5SDimitry Andric   SmallString<128> indentedStr;
251*0b57cec5SDimitry Andric   if (indentNewLines && Str.find('\n') != StringRef::npos) {
252*0b57cec5SDimitry Andric     StringRef MB = SourceMgr->getBufferData(FID);
253*0b57cec5SDimitry Andric 
254*0b57cec5SDimitry Andric     unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1;
255*0b57cec5SDimitry Andric     const SrcMgr::ContentCache *
256*0b57cec5SDimitry Andric         Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
257*0b57cec5SDimitry Andric     unsigned lineOffs = Content->SourceLineCache[lineNo];
258*0b57cec5SDimitry Andric 
259*0b57cec5SDimitry Andric     // Find the whitespace at the start of the line.
260*0b57cec5SDimitry Andric     StringRef indentSpace;
261*0b57cec5SDimitry Andric     {
262*0b57cec5SDimitry Andric       unsigned i = lineOffs;
263*0b57cec5SDimitry Andric       while (isWhitespaceExceptNL(MB[i]))
264*0b57cec5SDimitry Andric         ++i;
265*0b57cec5SDimitry Andric       indentSpace = MB.substr(lineOffs, i-lineOffs);
266*0b57cec5SDimitry Andric     }
267*0b57cec5SDimitry Andric 
268*0b57cec5SDimitry Andric     SmallVector<StringRef, 4> lines;
269*0b57cec5SDimitry Andric     Str.split(lines, "\n");
270*0b57cec5SDimitry Andric 
271*0b57cec5SDimitry Andric     for (unsigned i = 0, e = lines.size(); i != e; ++i) {
272*0b57cec5SDimitry Andric       indentedStr += lines[i];
273*0b57cec5SDimitry Andric       if (i < e-1) {
274*0b57cec5SDimitry Andric         indentedStr += '\n';
275*0b57cec5SDimitry Andric         indentedStr += indentSpace;
276*0b57cec5SDimitry Andric       }
277*0b57cec5SDimitry Andric     }
278*0b57cec5SDimitry Andric     Str = indentedStr.str();
279*0b57cec5SDimitry Andric   }
280*0b57cec5SDimitry Andric 
281*0b57cec5SDimitry Andric   getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter);
282*0b57cec5SDimitry Andric   return false;
283*0b57cec5SDimitry Andric }
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric bool Rewriter::InsertTextAfterToken(SourceLocation Loc, StringRef Str) {
286*0b57cec5SDimitry Andric   if (!isRewritable(Loc)) return true;
287*0b57cec5SDimitry Andric   FileID FID;
288*0b57cec5SDimitry Andric   unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
289*0b57cec5SDimitry Andric   RewriteOptions rangeOpts;
290*0b57cec5SDimitry Andric   rangeOpts.IncludeInsertsAtBeginOfRange = false;
291*0b57cec5SDimitry Andric   StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts);
292*0b57cec5SDimitry Andric   getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true);
293*0b57cec5SDimitry Andric   return false;
294*0b57cec5SDimitry Andric }
295*0b57cec5SDimitry Andric 
296*0b57cec5SDimitry Andric /// RemoveText - Remove the specified text region.
297*0b57cec5SDimitry Andric bool Rewriter::RemoveText(SourceLocation Start, unsigned Length,
298*0b57cec5SDimitry Andric                           RewriteOptions opts) {
299*0b57cec5SDimitry Andric   if (!isRewritable(Start)) return true;
300*0b57cec5SDimitry Andric   FileID FID;
301*0b57cec5SDimitry Andric   unsigned StartOffs = getLocationOffsetAndFileID(Start, FID);
302*0b57cec5SDimitry Andric   getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty);
303*0b57cec5SDimitry Andric   return false;
304*0b57cec5SDimitry Andric }
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric /// ReplaceText - This method replaces a range of characters in the input
307*0b57cec5SDimitry Andric /// buffer with a new string.  This is effectively a combined "remove/insert"
308*0b57cec5SDimitry Andric /// operation.
309*0b57cec5SDimitry Andric bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
310*0b57cec5SDimitry Andric                            StringRef NewStr) {
311*0b57cec5SDimitry Andric   if (!isRewritable(Start)) return true;
312*0b57cec5SDimitry Andric   FileID StartFileID;
313*0b57cec5SDimitry Andric   unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric   getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr);
316*0b57cec5SDimitry Andric   return false;
317*0b57cec5SDimitry Andric }
318*0b57cec5SDimitry Andric 
319*0b57cec5SDimitry Andric bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) {
320*0b57cec5SDimitry Andric   if (!isRewritable(range.getBegin())) return true;
321*0b57cec5SDimitry Andric   if (!isRewritable(range.getEnd())) return true;
322*0b57cec5SDimitry Andric   if (replacementRange.isInvalid()) return true;
323*0b57cec5SDimitry Andric   SourceLocation start = range.getBegin();
324*0b57cec5SDimitry Andric   unsigned origLength = getRangeSize(range);
325*0b57cec5SDimitry Andric   unsigned newLength = getRangeSize(replacementRange);
326*0b57cec5SDimitry Andric   FileID FID;
327*0b57cec5SDimitry Andric   unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(),
328*0b57cec5SDimitry Andric                                                 FID);
329*0b57cec5SDimitry Andric   StringRef MB = SourceMgr->getBufferData(FID);
330*0b57cec5SDimitry Andric   return ReplaceText(start, origLength, MB.substr(newOffs, newLength));
331*0b57cec5SDimitry Andric }
332*0b57cec5SDimitry Andric 
333*0b57cec5SDimitry Andric bool Rewriter::IncreaseIndentation(CharSourceRange range,
334*0b57cec5SDimitry Andric                                    SourceLocation parentIndent) {
335*0b57cec5SDimitry Andric   if (range.isInvalid()) return true;
336*0b57cec5SDimitry Andric   if (!isRewritable(range.getBegin())) return true;
337*0b57cec5SDimitry Andric   if (!isRewritable(range.getEnd())) return true;
338*0b57cec5SDimitry Andric   if (!isRewritable(parentIndent)) return true;
339*0b57cec5SDimitry Andric 
340*0b57cec5SDimitry Andric   FileID StartFileID, EndFileID, parentFileID;
341*0b57cec5SDimitry Andric   unsigned StartOff, EndOff, parentOff;
342*0b57cec5SDimitry Andric 
343*0b57cec5SDimitry Andric   StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID);
344*0b57cec5SDimitry Andric   EndOff   = getLocationOffsetAndFileID(range.getEnd(), EndFileID);
345*0b57cec5SDimitry Andric   parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID);
346*0b57cec5SDimitry Andric 
347*0b57cec5SDimitry Andric   if (StartFileID != EndFileID || StartFileID != parentFileID)
348*0b57cec5SDimitry Andric     return true;
349*0b57cec5SDimitry Andric   if (StartOff > EndOff)
350*0b57cec5SDimitry Andric     return true;
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric   FileID FID = StartFileID;
353*0b57cec5SDimitry Andric   StringRef MB = SourceMgr->getBufferData(FID);
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric   unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1;
356*0b57cec5SDimitry Andric   unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1;
357*0b57cec5SDimitry Andric   unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1;
358*0b57cec5SDimitry Andric 
359*0b57cec5SDimitry Andric   const SrcMgr::ContentCache *
360*0b57cec5SDimitry Andric       Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
361*0b57cec5SDimitry Andric 
362*0b57cec5SDimitry Andric   // Find where the lines start.
363*0b57cec5SDimitry Andric   unsigned parentLineOffs = Content->SourceLineCache[parentLineNo];
364*0b57cec5SDimitry Andric   unsigned startLineOffs = Content->SourceLineCache[startLineNo];
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric   // Find the whitespace at the start of each line.
367*0b57cec5SDimitry Andric   StringRef parentSpace, startSpace;
368*0b57cec5SDimitry Andric   {
369*0b57cec5SDimitry Andric     unsigned i = parentLineOffs;
370*0b57cec5SDimitry Andric     while (isWhitespaceExceptNL(MB[i]))
371*0b57cec5SDimitry Andric       ++i;
372*0b57cec5SDimitry Andric     parentSpace = MB.substr(parentLineOffs, i-parentLineOffs);
373*0b57cec5SDimitry Andric 
374*0b57cec5SDimitry Andric     i = startLineOffs;
375*0b57cec5SDimitry Andric     while (isWhitespaceExceptNL(MB[i]))
376*0b57cec5SDimitry Andric       ++i;
377*0b57cec5SDimitry Andric     startSpace = MB.substr(startLineOffs, i-startLineOffs);
378*0b57cec5SDimitry Andric   }
379*0b57cec5SDimitry Andric   if (parentSpace.size() >= startSpace.size())
380*0b57cec5SDimitry Andric     return true;
381*0b57cec5SDimitry Andric   if (!startSpace.startswith(parentSpace))
382*0b57cec5SDimitry Andric     return true;
383*0b57cec5SDimitry Andric 
384*0b57cec5SDimitry Andric   StringRef indent = startSpace.substr(parentSpace.size());
385*0b57cec5SDimitry Andric 
386*0b57cec5SDimitry Andric   // Indent the lines between start/end offsets.
387*0b57cec5SDimitry Andric   RewriteBuffer &RB = getEditBuffer(FID);
388*0b57cec5SDimitry Andric   for (unsigned lineNo = startLineNo; lineNo <= endLineNo; ++lineNo) {
389*0b57cec5SDimitry Andric     unsigned offs = Content->SourceLineCache[lineNo];
390*0b57cec5SDimitry Andric     unsigned i = offs;
391*0b57cec5SDimitry Andric     while (isWhitespaceExceptNL(MB[i]))
392*0b57cec5SDimitry Andric       ++i;
393*0b57cec5SDimitry Andric     StringRef origIndent = MB.substr(offs, i-offs);
394*0b57cec5SDimitry Andric     if (origIndent.startswith(startSpace))
395*0b57cec5SDimitry Andric       RB.InsertText(offs, indent, /*InsertAfter=*/false);
396*0b57cec5SDimitry Andric   }
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric   return false;
399*0b57cec5SDimitry Andric }
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric namespace {
402*0b57cec5SDimitry Andric 
403*0b57cec5SDimitry Andric // A wrapper for a file stream that atomically overwrites the target.
404*0b57cec5SDimitry Andric //
405*0b57cec5SDimitry Andric // Creates a file output stream for a temporary file in the constructor,
406*0b57cec5SDimitry Andric // which is later accessible via getStream() if ok() return true.
407*0b57cec5SDimitry Andric // Flushes the stream and moves the temporary file to the target location
408*0b57cec5SDimitry Andric // in the destructor.
409*0b57cec5SDimitry Andric class AtomicallyMovedFile {
410*0b57cec5SDimitry Andric public:
411*0b57cec5SDimitry Andric   AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
412*0b57cec5SDimitry Andric                       bool &AllWritten)
413*0b57cec5SDimitry Andric       : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
414*0b57cec5SDimitry Andric     TempFilename = Filename;
415*0b57cec5SDimitry Andric     TempFilename += "-%%%%%%%%";
416*0b57cec5SDimitry Andric     int FD;
417*0b57cec5SDimitry Andric     if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
418*0b57cec5SDimitry Andric       AllWritten = false;
419*0b57cec5SDimitry Andric       Diagnostics.Report(clang::diag::err_unable_to_make_temp)
420*0b57cec5SDimitry Andric         << TempFilename;
421*0b57cec5SDimitry Andric     } else {
422*0b57cec5SDimitry Andric       FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
423*0b57cec5SDimitry Andric     }
424*0b57cec5SDimitry Andric   }
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric   ~AtomicallyMovedFile() {
427*0b57cec5SDimitry Andric     if (!ok()) return;
428*0b57cec5SDimitry Andric 
429*0b57cec5SDimitry Andric     // Close (will also flush) theFileStream.
430*0b57cec5SDimitry Andric     FileStream->close();
431*0b57cec5SDimitry Andric     if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
432*0b57cec5SDimitry Andric       AllWritten = false;
433*0b57cec5SDimitry Andric       Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
434*0b57cec5SDimitry Andric         << TempFilename << Filename << ec.message();
435*0b57cec5SDimitry Andric       // If the remove fails, there's not a lot we can do - this is already an
436*0b57cec5SDimitry Andric       // error.
437*0b57cec5SDimitry Andric       llvm::sys::fs::remove(TempFilename);
438*0b57cec5SDimitry Andric     }
439*0b57cec5SDimitry Andric   }
440*0b57cec5SDimitry Andric 
441*0b57cec5SDimitry Andric   bool ok() { return (bool)FileStream; }
442*0b57cec5SDimitry Andric   raw_ostream &getStream() { return *FileStream; }
443*0b57cec5SDimitry Andric 
444*0b57cec5SDimitry Andric private:
445*0b57cec5SDimitry Andric   DiagnosticsEngine &Diagnostics;
446*0b57cec5SDimitry Andric   StringRef Filename;
447*0b57cec5SDimitry Andric   SmallString<128> TempFilename;
448*0b57cec5SDimitry Andric   std::unique_ptr<llvm::raw_fd_ostream> FileStream;
449*0b57cec5SDimitry Andric   bool &AllWritten;
450*0b57cec5SDimitry Andric };
451*0b57cec5SDimitry Andric 
452*0b57cec5SDimitry Andric } // namespace
453*0b57cec5SDimitry Andric 
454*0b57cec5SDimitry Andric bool Rewriter::overwriteChangedFiles() {
455*0b57cec5SDimitry Andric   bool AllWritten = true;
456*0b57cec5SDimitry Andric   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
457*0b57cec5SDimitry Andric     const FileEntry *Entry =
458*0b57cec5SDimitry Andric         getSourceMgr().getFileEntryForID(I->first);
459*0b57cec5SDimitry Andric     AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
460*0b57cec5SDimitry Andric                              AllWritten);
461*0b57cec5SDimitry Andric     if (File.ok()) {
462*0b57cec5SDimitry Andric       I->second.write(File.getStream());
463*0b57cec5SDimitry Andric     }
464*0b57cec5SDimitry Andric   }
465*0b57cec5SDimitry Andric   return !AllWritten;
466*0b57cec5SDimitry Andric }
467