10b57cec5SDimitry Andric //===- Rewriter.cpp - Code rewriting interface ----------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the Rewriter class, which is used for code
100b57cec5SDimitry Andric // transformations.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric
140b57cec5SDimitry Andric #include "clang/Rewrite/Core/Rewriter.h"
150b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
160b57cec5SDimitry Andric #include "clang/Basic/DiagnosticIDs.h"
170b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
180b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
190b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
200b57cec5SDimitry Andric #include "clang/Rewrite/Core/RewriteBuffer.h"
210b57cec5SDimitry Andric #include "clang/Rewrite/Core/RewriteRope.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
230b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
2406c3fb27SDimitry Andric #include "llvm/Support/Error.h"
250b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
260b57cec5SDimitry Andric #include <cassert>
270b57cec5SDimitry Andric #include <iterator>
280b57cec5SDimitry Andric #include <map>
290b57cec5SDimitry Andric #include <utility>
300b57cec5SDimitry Andric
310b57cec5SDimitry Andric using namespace clang;
320b57cec5SDimitry Andric
write(raw_ostream & os) const330b57cec5SDimitry Andric raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
340b57cec5SDimitry Andric // Walk RewriteRope chunks efficiently using MoveToNextPiece() instead of the
350b57cec5SDimitry Andric // character iterator.
360b57cec5SDimitry Andric for (RopePieceBTreeIterator I = begin(), E = end(); I != E;
370b57cec5SDimitry Andric I.MoveToNextPiece())
380b57cec5SDimitry Andric os << I.piece();
390b57cec5SDimitry Andric return os;
400b57cec5SDimitry Andric }
410b57cec5SDimitry Andric
420b57cec5SDimitry Andric /// Return true if this character is non-new-line whitespace:
430b57cec5SDimitry Andric /// ' ', '\\t', '\\f', '\\v', '\\r'.
isWhitespaceExceptNL(unsigned char c)440b57cec5SDimitry Andric static inline bool isWhitespaceExceptNL(unsigned char c) {
450b57cec5SDimitry Andric switch (c) {
460b57cec5SDimitry Andric case ' ':
470b57cec5SDimitry Andric case '\t':
480b57cec5SDimitry Andric case '\f':
490b57cec5SDimitry Andric case '\v':
500b57cec5SDimitry Andric case '\r':
510b57cec5SDimitry Andric return true;
520b57cec5SDimitry Andric default:
530b57cec5SDimitry Andric return false;
540b57cec5SDimitry Andric }
550b57cec5SDimitry Andric }
560b57cec5SDimitry Andric
RemoveText(unsigned OrigOffset,unsigned Size,bool removeLineIfEmpty)570b57cec5SDimitry Andric void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size,
580b57cec5SDimitry Andric bool removeLineIfEmpty) {
590b57cec5SDimitry Andric // Nothing to remove, exit early.
600b57cec5SDimitry Andric if (Size == 0) return;
610b57cec5SDimitry Andric
620b57cec5SDimitry Andric unsigned RealOffset = getMappedOffset(OrigOffset, true);
630b57cec5SDimitry Andric assert(RealOffset+Size <= Buffer.size() && "Invalid location");
640b57cec5SDimitry Andric
650b57cec5SDimitry Andric // Remove the dead characters.
660b57cec5SDimitry Andric Buffer.erase(RealOffset, Size);
670b57cec5SDimitry Andric
680b57cec5SDimitry Andric // Add a delta so that future changes are offset correctly.
690b57cec5SDimitry Andric AddReplaceDelta(OrigOffset, -Size);
700b57cec5SDimitry Andric
710b57cec5SDimitry Andric if (removeLineIfEmpty) {
720b57cec5SDimitry Andric // Find the line that the remove occurred and if it is completely empty
730b57cec5SDimitry Andric // remove the line as well.
740b57cec5SDimitry Andric
750b57cec5SDimitry Andric iterator curLineStart = begin();
760b57cec5SDimitry Andric unsigned curLineStartOffs = 0;
770b57cec5SDimitry Andric iterator posI = begin();
780b57cec5SDimitry Andric for (unsigned i = 0; i != RealOffset; ++i) {
790b57cec5SDimitry Andric if (*posI == '\n') {
800b57cec5SDimitry Andric curLineStart = posI;
810b57cec5SDimitry Andric ++curLineStart;
820b57cec5SDimitry Andric curLineStartOffs = i + 1;
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric ++posI;
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric
870b57cec5SDimitry Andric unsigned lineSize = 0;
880b57cec5SDimitry Andric posI = curLineStart;
890b57cec5SDimitry Andric while (posI != end() && isWhitespaceExceptNL(*posI)) {
900b57cec5SDimitry Andric ++posI;
910b57cec5SDimitry Andric ++lineSize;
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric if (posI != end() && *posI == '\n') {
940b57cec5SDimitry Andric Buffer.erase(curLineStartOffs, lineSize + 1/* + '\n'*/);
95a7dea167SDimitry Andric // FIXME: Here, the offset of the start of the line is supposed to be
96a7dea167SDimitry Andric // expressed in terms of the original input not the "real" rewrite
97a7dea167SDimitry Andric // buffer. How do we compute that reliably? It might be tempting to use
98a7dea167SDimitry Andric // curLineStartOffs + OrigOffset - RealOffset, but that assumes the
99a7dea167SDimitry Andric // difference between the original and real offset is the same at the
100a7dea167SDimitry Andric // removed text and at the start of the line, but that's not true if
101a7dea167SDimitry Andric // edits were previously made earlier on the line. This bug is also
102a7dea167SDimitry Andric // documented by a FIXME on the definition of
103a7dea167SDimitry Andric // clang::Rewriter::RewriteOptions::RemoveLineIfEmpty. A reproducer for
104a7dea167SDimitry Andric // the implementation below is the test RemoveLineIfEmpty in
105a7dea167SDimitry Andric // clang/unittests/Rewrite/RewriteBufferTest.cpp.
1060b57cec5SDimitry Andric AddReplaceDelta(curLineStartOffs, -(lineSize + 1/* + '\n'*/));
1070b57cec5SDimitry Andric }
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric
InsertText(unsigned OrigOffset,StringRef Str,bool InsertAfter)1110b57cec5SDimitry Andric void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str,
1120b57cec5SDimitry Andric bool InsertAfter) {
1130b57cec5SDimitry Andric // Nothing to insert, exit early.
1140b57cec5SDimitry Andric if (Str.empty()) return;
1150b57cec5SDimitry Andric
1160b57cec5SDimitry Andric unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
1170b57cec5SDimitry Andric Buffer.insert(RealOffset, Str.begin(), Str.end());
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric // Add a delta so that future changes are offset correctly.
1200b57cec5SDimitry Andric AddInsertDelta(OrigOffset, Str.size());
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric
1230b57cec5SDimitry Andric /// ReplaceText - This method replaces a range of characters in the input
1240b57cec5SDimitry Andric /// buffer with a new string. This is effectively a combined "remove+insert"
1250b57cec5SDimitry Andric /// operation.
ReplaceText(unsigned OrigOffset,unsigned OrigLength,StringRef NewStr)1260b57cec5SDimitry Andric void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
1270b57cec5SDimitry Andric StringRef NewStr) {
1280b57cec5SDimitry Andric unsigned RealOffset = getMappedOffset(OrigOffset, true);
1290b57cec5SDimitry Andric Buffer.erase(RealOffset, OrigLength);
1300b57cec5SDimitry Andric Buffer.insert(RealOffset, NewStr.begin(), NewStr.end());
1310b57cec5SDimitry Andric if (OrigLength != NewStr.size())
1320b57cec5SDimitry Andric AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength);
1330b57cec5SDimitry Andric }
1340b57cec5SDimitry Andric
1350b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1360b57cec5SDimitry Andric // Rewriter class
1370b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1380b57cec5SDimitry Andric
1390b57cec5SDimitry Andric /// getRangeSize - Return the size in bytes of the specified range if they
1400b57cec5SDimitry Andric /// are in the same file. If not, this returns -1.
getRangeSize(const CharSourceRange & Range,RewriteOptions opts) const1410b57cec5SDimitry Andric int Rewriter::getRangeSize(const CharSourceRange &Range,
1420b57cec5SDimitry Andric RewriteOptions opts) const {
1430b57cec5SDimitry Andric if (!isRewritable(Range.getBegin()) ||
1440b57cec5SDimitry Andric !isRewritable(Range.getEnd())) return -1;
1450b57cec5SDimitry Andric
1460b57cec5SDimitry Andric FileID StartFileID, EndFileID;
1470b57cec5SDimitry Andric unsigned StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
1480b57cec5SDimitry Andric unsigned EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
1490b57cec5SDimitry Andric
1500b57cec5SDimitry Andric if (StartFileID != EndFileID)
1510b57cec5SDimitry Andric return -1;
1520b57cec5SDimitry Andric
1530b57cec5SDimitry Andric // If edits have been made to this buffer, the delta between the range may
1540b57cec5SDimitry Andric // have changed.
1550b57cec5SDimitry Andric std::map<FileID, RewriteBuffer>::const_iterator I =
1560b57cec5SDimitry Andric RewriteBuffers.find(StartFileID);
1570b57cec5SDimitry Andric if (I != RewriteBuffers.end()) {
1580b57cec5SDimitry Andric const RewriteBuffer &RB = I->second;
1590b57cec5SDimitry Andric EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange);
1600b57cec5SDimitry Andric StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange);
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric
1630b57cec5SDimitry Andric // Adjust the end offset to the end of the last token, instead of being the
1640b57cec5SDimitry Andric // start of the last token if this is a token range.
1650b57cec5SDimitry Andric if (Range.isTokenRange())
1660b57cec5SDimitry Andric EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
1670b57cec5SDimitry Andric
1680b57cec5SDimitry Andric return EndOff-StartOff;
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric
getRangeSize(SourceRange Range,RewriteOptions opts) const1710b57cec5SDimitry Andric int Rewriter::getRangeSize(SourceRange Range, RewriteOptions opts) const {
1720b57cec5SDimitry Andric return getRangeSize(CharSourceRange::getTokenRange(Range), opts);
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric
1750b57cec5SDimitry Andric /// getRewrittenText - Return the rewritten form of the text in the specified
1760b57cec5SDimitry Andric /// range. If the start or end of the range was unrewritable or if they are
1770b57cec5SDimitry Andric /// in different buffers, this returns an empty string.
1780b57cec5SDimitry Andric ///
1790b57cec5SDimitry Andric /// Note that this method is not particularly efficient.
getRewrittenText(CharSourceRange Range) const1800b57cec5SDimitry Andric std::string Rewriter::getRewrittenText(CharSourceRange Range) const {
1810b57cec5SDimitry Andric if (!isRewritable(Range.getBegin()) ||
1820b57cec5SDimitry Andric !isRewritable(Range.getEnd()))
1830b57cec5SDimitry Andric return {};
1840b57cec5SDimitry Andric
1850b57cec5SDimitry Andric FileID StartFileID, EndFileID;
1860b57cec5SDimitry Andric unsigned StartOff, EndOff;
1870b57cec5SDimitry Andric StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
1880b57cec5SDimitry Andric EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric if (StartFileID != EndFileID)
1910b57cec5SDimitry Andric return {}; // Start and end in different buffers.
1920b57cec5SDimitry Andric
1930b57cec5SDimitry Andric // If edits have been made to this buffer, the delta between the range may
1940b57cec5SDimitry Andric // have changed.
1950b57cec5SDimitry Andric std::map<FileID, RewriteBuffer>::const_iterator I =
1960b57cec5SDimitry Andric RewriteBuffers.find(StartFileID);
1970b57cec5SDimitry Andric if (I == RewriteBuffers.end()) {
1980b57cec5SDimitry Andric // If the buffer hasn't been rewritten, just return the text from the input.
1990b57cec5SDimitry Andric const char *Ptr = SourceMgr->getCharacterData(Range.getBegin());
2000b57cec5SDimitry Andric
2010b57cec5SDimitry Andric // Adjust the end offset to the end of the last token, instead of being the
2020b57cec5SDimitry Andric // start of the last token.
2030b57cec5SDimitry Andric if (Range.isTokenRange())
2040b57cec5SDimitry Andric EndOff +=
2050b57cec5SDimitry Andric Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
2060b57cec5SDimitry Andric return std::string(Ptr, Ptr+EndOff-StartOff);
2070b57cec5SDimitry Andric }
2080b57cec5SDimitry Andric
2090b57cec5SDimitry Andric const RewriteBuffer &RB = I->second;
2100b57cec5SDimitry Andric EndOff = RB.getMappedOffset(EndOff, true);
2110b57cec5SDimitry Andric StartOff = RB.getMappedOffset(StartOff);
2120b57cec5SDimitry Andric
2130b57cec5SDimitry Andric // Adjust the end offset to the end of the last token, instead of being the
2140b57cec5SDimitry Andric // start of the last token.
2150b57cec5SDimitry Andric if (Range.isTokenRange())
2160b57cec5SDimitry Andric EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
2170b57cec5SDimitry Andric
2180b57cec5SDimitry Andric // Advance the iterators to the right spot, yay for linear time algorithms.
2190b57cec5SDimitry Andric RewriteBuffer::iterator Start = RB.begin();
2200b57cec5SDimitry Andric std::advance(Start, StartOff);
2210b57cec5SDimitry Andric RewriteBuffer::iterator End = Start;
22204eeddc0SDimitry Andric assert(EndOff >= StartOff && "Invalid iteration distance");
2230b57cec5SDimitry Andric std::advance(End, EndOff-StartOff);
2240b57cec5SDimitry Andric
2250b57cec5SDimitry Andric return std::string(Start, End);
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric
getLocationOffsetAndFileID(SourceLocation Loc,FileID & FID) const2280b57cec5SDimitry Andric unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
2290b57cec5SDimitry Andric FileID &FID) const {
2300b57cec5SDimitry Andric assert(Loc.isValid() && "Invalid location");
2310b57cec5SDimitry Andric std::pair<FileID, unsigned> V = SourceMgr->getDecomposedLoc(Loc);
2320b57cec5SDimitry Andric FID = V.first;
2330b57cec5SDimitry Andric return V.second;
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric
2360b57cec5SDimitry Andric /// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
getEditBuffer(FileID FID)2370b57cec5SDimitry Andric RewriteBuffer &Rewriter::getEditBuffer(FileID FID) {
2380b57cec5SDimitry Andric std::map<FileID, RewriteBuffer>::iterator I =
2390b57cec5SDimitry Andric RewriteBuffers.lower_bound(FID);
2400b57cec5SDimitry Andric if (I != RewriteBuffers.end() && I->first == FID)
2410b57cec5SDimitry Andric return I->second;
2420b57cec5SDimitry Andric I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer()));
2430b57cec5SDimitry Andric
2440b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID);
2450b57cec5SDimitry Andric I->second.Initialize(MB.begin(), MB.end());
2460b57cec5SDimitry Andric
2470b57cec5SDimitry Andric return I->second;
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric
2500b57cec5SDimitry Andric /// InsertText - Insert the specified string at the specified location in the
2510b57cec5SDimitry Andric /// original buffer.
InsertText(SourceLocation Loc,StringRef Str,bool InsertAfter,bool indentNewLines)2520b57cec5SDimitry Andric bool Rewriter::InsertText(SourceLocation Loc, StringRef Str,
2530b57cec5SDimitry Andric bool InsertAfter, bool indentNewLines) {
2540b57cec5SDimitry Andric if (!isRewritable(Loc)) return true;
2550b57cec5SDimitry Andric FileID FID;
2560b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
2570b57cec5SDimitry Andric
2580b57cec5SDimitry Andric SmallString<128> indentedStr;
259349cc55cSDimitry Andric if (indentNewLines && Str.contains('\n')) {
2600b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID);
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1;
263e8d8bef9SDimitry Andric const SrcMgr::ContentCache *Content =
264e8d8bef9SDimitry Andric &SourceMgr->getSLocEntry(FID).getFile().getContentCache();
2650b57cec5SDimitry Andric unsigned lineOffs = Content->SourceLineCache[lineNo];
2660b57cec5SDimitry Andric
2670b57cec5SDimitry Andric // Find the whitespace at the start of the line.
2680b57cec5SDimitry Andric StringRef indentSpace;
2690b57cec5SDimitry Andric {
2700b57cec5SDimitry Andric unsigned i = lineOffs;
2710b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i]))
2720b57cec5SDimitry Andric ++i;
2730b57cec5SDimitry Andric indentSpace = MB.substr(lineOffs, i-lineOffs);
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric
2760b57cec5SDimitry Andric SmallVector<StringRef, 4> lines;
2770b57cec5SDimitry Andric Str.split(lines, "\n");
2780b57cec5SDimitry Andric
2790b57cec5SDimitry Andric for (unsigned i = 0, e = lines.size(); i != e; ++i) {
2800b57cec5SDimitry Andric indentedStr += lines[i];
2810b57cec5SDimitry Andric if (i < e-1) {
2820b57cec5SDimitry Andric indentedStr += '\n';
2830b57cec5SDimitry Andric indentedStr += indentSpace;
2840b57cec5SDimitry Andric }
2850b57cec5SDimitry Andric }
2860b57cec5SDimitry Andric Str = indentedStr.str();
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric
2890b57cec5SDimitry Andric getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter);
2900b57cec5SDimitry Andric return false;
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric
InsertTextAfterToken(SourceLocation Loc,StringRef Str)2930b57cec5SDimitry Andric bool Rewriter::InsertTextAfterToken(SourceLocation Loc, StringRef Str) {
2940b57cec5SDimitry Andric if (!isRewritable(Loc)) return true;
2950b57cec5SDimitry Andric FileID FID;
2960b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
2970b57cec5SDimitry Andric RewriteOptions rangeOpts;
2980b57cec5SDimitry Andric rangeOpts.IncludeInsertsAtBeginOfRange = false;
2990b57cec5SDimitry Andric StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts);
3000b57cec5SDimitry Andric getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true);
3010b57cec5SDimitry Andric return false;
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric
3040b57cec5SDimitry Andric /// RemoveText - Remove the specified text region.
RemoveText(SourceLocation Start,unsigned Length,RewriteOptions opts)3050b57cec5SDimitry Andric bool Rewriter::RemoveText(SourceLocation Start, unsigned Length,
3060b57cec5SDimitry Andric RewriteOptions opts) {
3070b57cec5SDimitry Andric if (!isRewritable(Start)) return true;
3080b57cec5SDimitry Andric FileID FID;
3090b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Start, FID);
3100b57cec5SDimitry Andric getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty);
3110b57cec5SDimitry Andric return false;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric
3140b57cec5SDimitry Andric /// ReplaceText - This method replaces a range of characters in the input
3150b57cec5SDimitry Andric /// buffer with a new string. This is effectively a combined "remove/insert"
3160b57cec5SDimitry Andric /// operation.
ReplaceText(SourceLocation Start,unsigned OrigLength,StringRef NewStr)3170b57cec5SDimitry Andric bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
3180b57cec5SDimitry Andric StringRef NewStr) {
3190b57cec5SDimitry Andric if (!isRewritable(Start)) return true;
3200b57cec5SDimitry Andric FileID StartFileID;
3210b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
3220b57cec5SDimitry Andric
3230b57cec5SDimitry Andric getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr);
3240b57cec5SDimitry Andric return false;
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric
ReplaceText(SourceRange range,SourceRange replacementRange)3270b57cec5SDimitry Andric bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) {
3280b57cec5SDimitry Andric if (!isRewritable(range.getBegin())) return true;
3290b57cec5SDimitry Andric if (!isRewritable(range.getEnd())) return true;
3300b57cec5SDimitry Andric if (replacementRange.isInvalid()) return true;
3310b57cec5SDimitry Andric SourceLocation start = range.getBegin();
3320b57cec5SDimitry Andric unsigned origLength = getRangeSize(range);
3330b57cec5SDimitry Andric unsigned newLength = getRangeSize(replacementRange);
3340b57cec5SDimitry Andric FileID FID;
3350b57cec5SDimitry Andric unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(),
3360b57cec5SDimitry Andric FID);
3370b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID);
3380b57cec5SDimitry Andric return ReplaceText(start, origLength, MB.substr(newOffs, newLength));
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric
IncreaseIndentation(CharSourceRange range,SourceLocation parentIndent)3410b57cec5SDimitry Andric bool Rewriter::IncreaseIndentation(CharSourceRange range,
3420b57cec5SDimitry Andric SourceLocation parentIndent) {
3430b57cec5SDimitry Andric if (range.isInvalid()) return true;
3440b57cec5SDimitry Andric if (!isRewritable(range.getBegin())) return true;
3450b57cec5SDimitry Andric if (!isRewritable(range.getEnd())) return true;
3460b57cec5SDimitry Andric if (!isRewritable(parentIndent)) return true;
3470b57cec5SDimitry Andric
3480b57cec5SDimitry Andric FileID StartFileID, EndFileID, parentFileID;
3490b57cec5SDimitry Andric unsigned StartOff, EndOff, parentOff;
3500b57cec5SDimitry Andric
3510b57cec5SDimitry Andric StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID);
3520b57cec5SDimitry Andric EndOff = getLocationOffsetAndFileID(range.getEnd(), EndFileID);
3530b57cec5SDimitry Andric parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID);
3540b57cec5SDimitry Andric
3550b57cec5SDimitry Andric if (StartFileID != EndFileID || StartFileID != parentFileID)
3560b57cec5SDimitry Andric return true;
3570b57cec5SDimitry Andric if (StartOff > EndOff)
3580b57cec5SDimitry Andric return true;
3590b57cec5SDimitry Andric
3600b57cec5SDimitry Andric FileID FID = StartFileID;
3610b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID);
3620b57cec5SDimitry Andric
3630b57cec5SDimitry Andric unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1;
3640b57cec5SDimitry Andric unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1;
3650b57cec5SDimitry Andric unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1;
3660b57cec5SDimitry Andric
367e8d8bef9SDimitry Andric const SrcMgr::ContentCache *Content =
368e8d8bef9SDimitry Andric &SourceMgr->getSLocEntry(FID).getFile().getContentCache();
3690b57cec5SDimitry Andric
3700b57cec5SDimitry Andric // Find where the lines start.
3710b57cec5SDimitry Andric unsigned parentLineOffs = Content->SourceLineCache[parentLineNo];
3720b57cec5SDimitry Andric unsigned startLineOffs = Content->SourceLineCache[startLineNo];
3730b57cec5SDimitry Andric
3740b57cec5SDimitry Andric // Find the whitespace at the start of each line.
3750b57cec5SDimitry Andric StringRef parentSpace, startSpace;
3760b57cec5SDimitry Andric {
3770b57cec5SDimitry Andric unsigned i = parentLineOffs;
3780b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i]))
3790b57cec5SDimitry Andric ++i;
3800b57cec5SDimitry Andric parentSpace = MB.substr(parentLineOffs, i-parentLineOffs);
3810b57cec5SDimitry Andric
3820b57cec5SDimitry Andric i = startLineOffs;
3830b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i]))
3840b57cec5SDimitry Andric ++i;
3850b57cec5SDimitry Andric startSpace = MB.substr(startLineOffs, i-startLineOffs);
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric if (parentSpace.size() >= startSpace.size())
3880b57cec5SDimitry Andric return true;
389*5f757f3fSDimitry Andric if (!startSpace.starts_with(parentSpace))
3900b57cec5SDimitry Andric return true;
3910b57cec5SDimitry Andric
3920b57cec5SDimitry Andric StringRef indent = startSpace.substr(parentSpace.size());
3930b57cec5SDimitry Andric
3940b57cec5SDimitry Andric // Indent the lines between start/end offsets.
3950b57cec5SDimitry Andric RewriteBuffer &RB = getEditBuffer(FID);
3960b57cec5SDimitry Andric for (unsigned lineNo = startLineNo; lineNo <= endLineNo; ++lineNo) {
3970b57cec5SDimitry Andric unsigned offs = Content->SourceLineCache[lineNo];
3980b57cec5SDimitry Andric unsigned i = offs;
3990b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i]))
4000b57cec5SDimitry Andric ++i;
4010b57cec5SDimitry Andric StringRef origIndent = MB.substr(offs, i-offs);
402*5f757f3fSDimitry Andric if (origIndent.starts_with(startSpace))
4030b57cec5SDimitry Andric RB.InsertText(offs, indent, /*InsertAfter=*/false);
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric
4060b57cec5SDimitry Andric return false;
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric
overwriteChangedFiles()4090b57cec5SDimitry Andric bool Rewriter::overwriteChangedFiles() {
4100b57cec5SDimitry Andric bool AllWritten = true;
41106c3fb27SDimitry Andric auto& Diag = getSourceMgr().getDiagnostics();
41206c3fb27SDimitry Andric unsigned OverwriteFailure = Diag.getCustomDiagID(
41306c3fb27SDimitry Andric DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
4140b57cec5SDimitry Andric for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
415*5f757f3fSDimitry Andric OptionalFileEntryRef Entry = getSourceMgr().getFileEntryRefForID(I->first);
416*5f757f3fSDimitry Andric llvm::SmallString<128> Path(Entry->getName());
417*5f757f3fSDimitry Andric getSourceMgr().getFileManager().makeAbsolutePath(Path);
418*5f757f3fSDimitry Andric if (auto Error = llvm::writeToOutput(Path, [&](llvm::raw_ostream &OS) {
41906c3fb27SDimitry Andric I->second.write(OS);
42006c3fb27SDimitry Andric return llvm::Error::success();
42106c3fb27SDimitry Andric })) {
42206c3fb27SDimitry Andric Diag.Report(OverwriteFailure)
42306c3fb27SDimitry Andric << Entry->getName() << llvm::toString(std::move(Error));
42406c3fb27SDimitry Andric AllWritten = false;
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric }
4270b57cec5SDimitry Andric return !AllWritten;
4280b57cec5SDimitry Andric }
429