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/FileManager.h" 180b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h" 190b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 200b57cec5SDimitry Andric #include "clang/Lex/Lexer.h" 210b57cec5SDimitry Andric #include "clang/Rewrite/Core/RewriteBuffer.h" 220b57cec5SDimitry Andric #include "clang/Rewrite/Core/RewriteRope.h" 230b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h" 240b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 250b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 260b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h" 270b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 280b57cec5SDimitry Andric #include <cassert> 290b57cec5SDimitry Andric #include <iterator> 300b57cec5SDimitry Andric #include <map> 310b57cec5SDimitry Andric #include <memory> 320b57cec5SDimitry Andric #include <system_error> 330b57cec5SDimitry Andric #include <utility> 340b57cec5SDimitry Andric 350b57cec5SDimitry Andric using namespace clang; 360b57cec5SDimitry Andric 370b57cec5SDimitry Andric raw_ostream &RewriteBuffer::write(raw_ostream &os) const { 380b57cec5SDimitry Andric // Walk RewriteRope chunks efficiently using MoveToNextPiece() instead of the 390b57cec5SDimitry Andric // character iterator. 400b57cec5SDimitry Andric for (RopePieceBTreeIterator I = begin(), E = end(); I != E; 410b57cec5SDimitry Andric I.MoveToNextPiece()) 420b57cec5SDimitry Andric os << I.piece(); 430b57cec5SDimitry Andric return os; 440b57cec5SDimitry Andric } 450b57cec5SDimitry Andric 460b57cec5SDimitry Andric /// Return true if this character is non-new-line whitespace: 470b57cec5SDimitry Andric /// ' ', '\\t', '\\f', '\\v', '\\r'. 480b57cec5SDimitry Andric static inline bool isWhitespaceExceptNL(unsigned char c) { 490b57cec5SDimitry Andric switch (c) { 500b57cec5SDimitry Andric case ' ': 510b57cec5SDimitry Andric case '\t': 520b57cec5SDimitry Andric case '\f': 530b57cec5SDimitry Andric case '\v': 540b57cec5SDimitry Andric case '\r': 550b57cec5SDimitry Andric return true; 560b57cec5SDimitry Andric default: 570b57cec5SDimitry Andric return false; 580b57cec5SDimitry Andric } 590b57cec5SDimitry Andric } 600b57cec5SDimitry Andric 610b57cec5SDimitry Andric void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size, 620b57cec5SDimitry Andric bool removeLineIfEmpty) { 630b57cec5SDimitry Andric // Nothing to remove, exit early. 640b57cec5SDimitry Andric if (Size == 0) return; 650b57cec5SDimitry Andric 660b57cec5SDimitry Andric unsigned RealOffset = getMappedOffset(OrigOffset, true); 670b57cec5SDimitry Andric assert(RealOffset+Size <= Buffer.size() && "Invalid location"); 680b57cec5SDimitry Andric 690b57cec5SDimitry Andric // Remove the dead characters. 700b57cec5SDimitry Andric Buffer.erase(RealOffset, Size); 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric // Add a delta so that future changes are offset correctly. 730b57cec5SDimitry Andric AddReplaceDelta(OrigOffset, -Size); 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric if (removeLineIfEmpty) { 760b57cec5SDimitry Andric // Find the line that the remove occurred and if it is completely empty 770b57cec5SDimitry Andric // remove the line as well. 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric iterator curLineStart = begin(); 800b57cec5SDimitry Andric unsigned curLineStartOffs = 0; 810b57cec5SDimitry Andric iterator posI = begin(); 820b57cec5SDimitry Andric for (unsigned i = 0; i != RealOffset; ++i) { 830b57cec5SDimitry Andric if (*posI == '\n') { 840b57cec5SDimitry Andric curLineStart = posI; 850b57cec5SDimitry Andric ++curLineStart; 860b57cec5SDimitry Andric curLineStartOffs = i + 1; 870b57cec5SDimitry Andric } 880b57cec5SDimitry Andric ++posI; 890b57cec5SDimitry Andric } 900b57cec5SDimitry Andric 910b57cec5SDimitry Andric unsigned lineSize = 0; 920b57cec5SDimitry Andric posI = curLineStart; 930b57cec5SDimitry Andric while (posI != end() && isWhitespaceExceptNL(*posI)) { 940b57cec5SDimitry Andric ++posI; 950b57cec5SDimitry Andric ++lineSize; 960b57cec5SDimitry Andric } 970b57cec5SDimitry Andric if (posI != end() && *posI == '\n') { 980b57cec5SDimitry Andric Buffer.erase(curLineStartOffs, lineSize + 1/* + '\n'*/); 99a7dea167SDimitry Andric // FIXME: Here, the offset of the start of the line is supposed to be 100a7dea167SDimitry Andric // expressed in terms of the original input not the "real" rewrite 101a7dea167SDimitry Andric // buffer. How do we compute that reliably? It might be tempting to use 102a7dea167SDimitry Andric // curLineStartOffs + OrigOffset - RealOffset, but that assumes the 103a7dea167SDimitry Andric // difference between the original and real offset is the same at the 104a7dea167SDimitry Andric // removed text and at the start of the line, but that's not true if 105a7dea167SDimitry Andric // edits were previously made earlier on the line. This bug is also 106a7dea167SDimitry Andric // documented by a FIXME on the definition of 107a7dea167SDimitry Andric // clang::Rewriter::RewriteOptions::RemoveLineIfEmpty. A reproducer for 108a7dea167SDimitry Andric // the implementation below is the test RemoveLineIfEmpty in 109a7dea167SDimitry Andric // clang/unittests/Rewrite/RewriteBufferTest.cpp. 1100b57cec5SDimitry Andric AddReplaceDelta(curLineStartOffs, -(lineSize + 1/* + '\n'*/)); 1110b57cec5SDimitry Andric } 1120b57cec5SDimitry Andric } 1130b57cec5SDimitry Andric } 1140b57cec5SDimitry Andric 1150b57cec5SDimitry Andric void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str, 1160b57cec5SDimitry Andric bool InsertAfter) { 1170b57cec5SDimitry Andric // Nothing to insert, exit early. 1180b57cec5SDimitry Andric if (Str.empty()) return; 1190b57cec5SDimitry Andric 1200b57cec5SDimitry Andric unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter); 1210b57cec5SDimitry Andric Buffer.insert(RealOffset, Str.begin(), Str.end()); 1220b57cec5SDimitry Andric 1230b57cec5SDimitry Andric // Add a delta so that future changes are offset correctly. 1240b57cec5SDimitry Andric AddInsertDelta(OrigOffset, Str.size()); 1250b57cec5SDimitry Andric } 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric /// ReplaceText - This method replaces a range of characters in the input 1280b57cec5SDimitry Andric /// buffer with a new string. This is effectively a combined "remove+insert" 1290b57cec5SDimitry Andric /// operation. 1300b57cec5SDimitry Andric void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength, 1310b57cec5SDimitry Andric StringRef NewStr) { 1320b57cec5SDimitry Andric unsigned RealOffset = getMappedOffset(OrigOffset, true); 1330b57cec5SDimitry Andric Buffer.erase(RealOffset, OrigLength); 1340b57cec5SDimitry Andric Buffer.insert(RealOffset, NewStr.begin(), NewStr.end()); 1350b57cec5SDimitry Andric if (OrigLength != NewStr.size()) 1360b57cec5SDimitry Andric AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength); 1370b57cec5SDimitry Andric } 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1400b57cec5SDimitry Andric // Rewriter class 1410b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1420b57cec5SDimitry Andric 1430b57cec5SDimitry Andric /// getRangeSize - Return the size in bytes of the specified range if they 1440b57cec5SDimitry Andric /// are in the same file. If not, this returns -1. 1450b57cec5SDimitry Andric int Rewriter::getRangeSize(const CharSourceRange &Range, 1460b57cec5SDimitry Andric RewriteOptions opts) const { 1470b57cec5SDimitry Andric if (!isRewritable(Range.getBegin()) || 1480b57cec5SDimitry Andric !isRewritable(Range.getEnd())) return -1; 1490b57cec5SDimitry Andric 1500b57cec5SDimitry Andric FileID StartFileID, EndFileID; 1510b57cec5SDimitry Andric unsigned StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID); 1520b57cec5SDimitry Andric unsigned EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID); 1530b57cec5SDimitry Andric 1540b57cec5SDimitry Andric if (StartFileID != EndFileID) 1550b57cec5SDimitry Andric return -1; 1560b57cec5SDimitry Andric 1570b57cec5SDimitry Andric // If edits have been made to this buffer, the delta between the range may 1580b57cec5SDimitry Andric // have changed. 1590b57cec5SDimitry Andric std::map<FileID, RewriteBuffer>::const_iterator I = 1600b57cec5SDimitry Andric RewriteBuffers.find(StartFileID); 1610b57cec5SDimitry Andric if (I != RewriteBuffers.end()) { 1620b57cec5SDimitry Andric const RewriteBuffer &RB = I->second; 1630b57cec5SDimitry Andric EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange); 1640b57cec5SDimitry Andric StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange); 1650b57cec5SDimitry Andric } 1660b57cec5SDimitry Andric 1670b57cec5SDimitry Andric // Adjust the end offset to the end of the last token, instead of being the 1680b57cec5SDimitry Andric // start of the last token if this is a token range. 1690b57cec5SDimitry Andric if (Range.isTokenRange()) 1700b57cec5SDimitry Andric EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts); 1710b57cec5SDimitry Andric 1720b57cec5SDimitry Andric return EndOff-StartOff; 1730b57cec5SDimitry Andric } 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric int Rewriter::getRangeSize(SourceRange Range, RewriteOptions opts) const { 1760b57cec5SDimitry Andric return getRangeSize(CharSourceRange::getTokenRange(Range), opts); 1770b57cec5SDimitry Andric } 1780b57cec5SDimitry Andric 1790b57cec5SDimitry Andric /// getRewrittenText - Return the rewritten form of the text in the specified 1800b57cec5SDimitry Andric /// range. If the start or end of the range was unrewritable or if they are 1810b57cec5SDimitry Andric /// in different buffers, this returns an empty string. 1820b57cec5SDimitry Andric /// 1830b57cec5SDimitry Andric /// Note that this method is not particularly efficient. 1840b57cec5SDimitry Andric std::string Rewriter::getRewrittenText(CharSourceRange Range) const { 1850b57cec5SDimitry Andric if (!isRewritable(Range.getBegin()) || 1860b57cec5SDimitry Andric !isRewritable(Range.getEnd())) 1870b57cec5SDimitry Andric return {}; 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric FileID StartFileID, EndFileID; 1900b57cec5SDimitry Andric unsigned StartOff, EndOff; 1910b57cec5SDimitry Andric StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID); 1920b57cec5SDimitry Andric EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID); 1930b57cec5SDimitry Andric 1940b57cec5SDimitry Andric if (StartFileID != EndFileID) 1950b57cec5SDimitry Andric return {}; // Start and end in different buffers. 1960b57cec5SDimitry Andric 1970b57cec5SDimitry Andric // If edits have been made to this buffer, the delta between the range may 1980b57cec5SDimitry Andric // have changed. 1990b57cec5SDimitry Andric std::map<FileID, RewriteBuffer>::const_iterator I = 2000b57cec5SDimitry Andric RewriteBuffers.find(StartFileID); 2010b57cec5SDimitry Andric if (I == RewriteBuffers.end()) { 2020b57cec5SDimitry Andric // If the buffer hasn't been rewritten, just return the text from the input. 2030b57cec5SDimitry Andric const char *Ptr = SourceMgr->getCharacterData(Range.getBegin()); 2040b57cec5SDimitry Andric 2050b57cec5SDimitry Andric // Adjust the end offset to the end of the last token, instead of being the 2060b57cec5SDimitry Andric // start of the last token. 2070b57cec5SDimitry Andric if (Range.isTokenRange()) 2080b57cec5SDimitry Andric EndOff += 2090b57cec5SDimitry Andric Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts); 2100b57cec5SDimitry Andric return std::string(Ptr, Ptr+EndOff-StartOff); 2110b57cec5SDimitry Andric } 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric const RewriteBuffer &RB = I->second; 2140b57cec5SDimitry Andric EndOff = RB.getMappedOffset(EndOff, true); 2150b57cec5SDimitry Andric StartOff = RB.getMappedOffset(StartOff); 2160b57cec5SDimitry Andric 2170b57cec5SDimitry Andric // Adjust the end offset to the end of the last token, instead of being the 2180b57cec5SDimitry Andric // start of the last token. 2190b57cec5SDimitry Andric if (Range.isTokenRange()) 2200b57cec5SDimitry Andric EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts); 2210b57cec5SDimitry Andric 2220b57cec5SDimitry Andric // Advance the iterators to the right spot, yay for linear time algorithms. 2230b57cec5SDimitry Andric RewriteBuffer::iterator Start = RB.begin(); 2240b57cec5SDimitry Andric std::advance(Start, StartOff); 2250b57cec5SDimitry Andric RewriteBuffer::iterator End = Start; 2260b57cec5SDimitry Andric std::advance(End, EndOff-StartOff); 2270b57cec5SDimitry Andric 2280b57cec5SDimitry Andric return std::string(Start, End); 2290b57cec5SDimitry Andric } 2300b57cec5SDimitry Andric 2310b57cec5SDimitry Andric unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc, 2320b57cec5SDimitry Andric FileID &FID) const { 2330b57cec5SDimitry Andric assert(Loc.isValid() && "Invalid location"); 2340b57cec5SDimitry Andric std::pair<FileID, unsigned> V = SourceMgr->getDecomposedLoc(Loc); 2350b57cec5SDimitry Andric FID = V.first; 2360b57cec5SDimitry Andric return V.second; 2370b57cec5SDimitry Andric } 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric /// getEditBuffer - Get or create a RewriteBuffer for the specified FileID. 2400b57cec5SDimitry Andric RewriteBuffer &Rewriter::getEditBuffer(FileID FID) { 2410b57cec5SDimitry Andric std::map<FileID, RewriteBuffer>::iterator I = 2420b57cec5SDimitry Andric RewriteBuffers.lower_bound(FID); 2430b57cec5SDimitry Andric if (I != RewriteBuffers.end() && I->first == FID) 2440b57cec5SDimitry Andric return I->second; 2450b57cec5SDimitry Andric I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer())); 2460b57cec5SDimitry Andric 2470b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID); 2480b57cec5SDimitry Andric I->second.Initialize(MB.begin(), MB.end()); 2490b57cec5SDimitry Andric 2500b57cec5SDimitry Andric return I->second; 2510b57cec5SDimitry Andric } 2520b57cec5SDimitry Andric 2530b57cec5SDimitry Andric /// InsertText - Insert the specified string at the specified location in the 2540b57cec5SDimitry Andric /// original buffer. 2550b57cec5SDimitry Andric bool Rewriter::InsertText(SourceLocation Loc, StringRef Str, 2560b57cec5SDimitry Andric bool InsertAfter, bool indentNewLines) { 2570b57cec5SDimitry Andric if (!isRewritable(Loc)) return true; 2580b57cec5SDimitry Andric FileID FID; 2590b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID); 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric SmallString<128> indentedStr; 2620b57cec5SDimitry Andric if (indentNewLines && Str.find('\n') != StringRef::npos) { 2630b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID); 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1; 266*e8d8bef9SDimitry Andric const SrcMgr::ContentCache *Content = 267*e8d8bef9SDimitry Andric &SourceMgr->getSLocEntry(FID).getFile().getContentCache(); 2680b57cec5SDimitry Andric unsigned lineOffs = Content->SourceLineCache[lineNo]; 2690b57cec5SDimitry Andric 2700b57cec5SDimitry Andric // Find the whitespace at the start of the line. 2710b57cec5SDimitry Andric StringRef indentSpace; 2720b57cec5SDimitry Andric { 2730b57cec5SDimitry Andric unsigned i = lineOffs; 2740b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i])) 2750b57cec5SDimitry Andric ++i; 2760b57cec5SDimitry Andric indentSpace = MB.substr(lineOffs, i-lineOffs); 2770b57cec5SDimitry Andric } 2780b57cec5SDimitry Andric 2790b57cec5SDimitry Andric SmallVector<StringRef, 4> lines; 2800b57cec5SDimitry Andric Str.split(lines, "\n"); 2810b57cec5SDimitry Andric 2820b57cec5SDimitry Andric for (unsigned i = 0, e = lines.size(); i != e; ++i) { 2830b57cec5SDimitry Andric indentedStr += lines[i]; 2840b57cec5SDimitry Andric if (i < e-1) { 2850b57cec5SDimitry Andric indentedStr += '\n'; 2860b57cec5SDimitry Andric indentedStr += indentSpace; 2870b57cec5SDimitry Andric } 2880b57cec5SDimitry Andric } 2890b57cec5SDimitry Andric Str = indentedStr.str(); 2900b57cec5SDimitry Andric } 2910b57cec5SDimitry Andric 2920b57cec5SDimitry Andric getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter); 2930b57cec5SDimitry Andric return false; 2940b57cec5SDimitry Andric } 2950b57cec5SDimitry Andric 2960b57cec5SDimitry Andric bool Rewriter::InsertTextAfterToken(SourceLocation Loc, StringRef Str) { 2970b57cec5SDimitry Andric if (!isRewritable(Loc)) return true; 2980b57cec5SDimitry Andric FileID FID; 2990b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID); 3000b57cec5SDimitry Andric RewriteOptions rangeOpts; 3010b57cec5SDimitry Andric rangeOpts.IncludeInsertsAtBeginOfRange = false; 3020b57cec5SDimitry Andric StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts); 3030b57cec5SDimitry Andric getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true); 3040b57cec5SDimitry Andric return false; 3050b57cec5SDimitry Andric } 3060b57cec5SDimitry Andric 3070b57cec5SDimitry Andric /// RemoveText - Remove the specified text region. 3080b57cec5SDimitry Andric bool Rewriter::RemoveText(SourceLocation Start, unsigned Length, 3090b57cec5SDimitry Andric RewriteOptions opts) { 3100b57cec5SDimitry Andric if (!isRewritable(Start)) return true; 3110b57cec5SDimitry Andric FileID FID; 3120b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Start, FID); 3130b57cec5SDimitry Andric getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty); 3140b57cec5SDimitry Andric return false; 3150b57cec5SDimitry Andric } 3160b57cec5SDimitry Andric 3170b57cec5SDimitry Andric /// ReplaceText - This method replaces a range of characters in the input 3180b57cec5SDimitry Andric /// buffer with a new string. This is effectively a combined "remove/insert" 3190b57cec5SDimitry Andric /// operation. 3200b57cec5SDimitry Andric bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength, 3210b57cec5SDimitry Andric StringRef NewStr) { 3220b57cec5SDimitry Andric if (!isRewritable(Start)) return true; 3230b57cec5SDimitry Andric FileID StartFileID; 3240b57cec5SDimitry Andric unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID); 3250b57cec5SDimitry Andric 3260b57cec5SDimitry Andric getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr); 3270b57cec5SDimitry Andric return false; 3280b57cec5SDimitry Andric } 3290b57cec5SDimitry Andric 3300b57cec5SDimitry Andric bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) { 3310b57cec5SDimitry Andric if (!isRewritable(range.getBegin())) return true; 3320b57cec5SDimitry Andric if (!isRewritable(range.getEnd())) return true; 3330b57cec5SDimitry Andric if (replacementRange.isInvalid()) return true; 3340b57cec5SDimitry Andric SourceLocation start = range.getBegin(); 3350b57cec5SDimitry Andric unsigned origLength = getRangeSize(range); 3360b57cec5SDimitry Andric unsigned newLength = getRangeSize(replacementRange); 3370b57cec5SDimitry Andric FileID FID; 3380b57cec5SDimitry Andric unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(), 3390b57cec5SDimitry Andric FID); 3400b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID); 3410b57cec5SDimitry Andric return ReplaceText(start, origLength, MB.substr(newOffs, newLength)); 3420b57cec5SDimitry Andric } 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric bool Rewriter::IncreaseIndentation(CharSourceRange range, 3450b57cec5SDimitry Andric SourceLocation parentIndent) { 3460b57cec5SDimitry Andric if (range.isInvalid()) return true; 3470b57cec5SDimitry Andric if (!isRewritable(range.getBegin())) return true; 3480b57cec5SDimitry Andric if (!isRewritable(range.getEnd())) return true; 3490b57cec5SDimitry Andric if (!isRewritable(parentIndent)) return true; 3500b57cec5SDimitry Andric 3510b57cec5SDimitry Andric FileID StartFileID, EndFileID, parentFileID; 3520b57cec5SDimitry Andric unsigned StartOff, EndOff, parentOff; 3530b57cec5SDimitry Andric 3540b57cec5SDimitry Andric StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID); 3550b57cec5SDimitry Andric EndOff = getLocationOffsetAndFileID(range.getEnd(), EndFileID); 3560b57cec5SDimitry Andric parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID); 3570b57cec5SDimitry Andric 3580b57cec5SDimitry Andric if (StartFileID != EndFileID || StartFileID != parentFileID) 3590b57cec5SDimitry Andric return true; 3600b57cec5SDimitry Andric if (StartOff > EndOff) 3610b57cec5SDimitry Andric return true; 3620b57cec5SDimitry Andric 3630b57cec5SDimitry Andric FileID FID = StartFileID; 3640b57cec5SDimitry Andric StringRef MB = SourceMgr->getBufferData(FID); 3650b57cec5SDimitry Andric 3660b57cec5SDimitry Andric unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1; 3670b57cec5SDimitry Andric unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1; 3680b57cec5SDimitry Andric unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1; 3690b57cec5SDimitry Andric 370*e8d8bef9SDimitry Andric const SrcMgr::ContentCache *Content = 371*e8d8bef9SDimitry Andric &SourceMgr->getSLocEntry(FID).getFile().getContentCache(); 3720b57cec5SDimitry Andric 3730b57cec5SDimitry Andric // Find where the lines start. 3740b57cec5SDimitry Andric unsigned parentLineOffs = Content->SourceLineCache[parentLineNo]; 3750b57cec5SDimitry Andric unsigned startLineOffs = Content->SourceLineCache[startLineNo]; 3760b57cec5SDimitry Andric 3770b57cec5SDimitry Andric // Find the whitespace at the start of each line. 3780b57cec5SDimitry Andric StringRef parentSpace, startSpace; 3790b57cec5SDimitry Andric { 3800b57cec5SDimitry Andric unsigned i = parentLineOffs; 3810b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i])) 3820b57cec5SDimitry Andric ++i; 3830b57cec5SDimitry Andric parentSpace = MB.substr(parentLineOffs, i-parentLineOffs); 3840b57cec5SDimitry Andric 3850b57cec5SDimitry Andric i = startLineOffs; 3860b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i])) 3870b57cec5SDimitry Andric ++i; 3880b57cec5SDimitry Andric startSpace = MB.substr(startLineOffs, i-startLineOffs); 3890b57cec5SDimitry Andric } 3900b57cec5SDimitry Andric if (parentSpace.size() >= startSpace.size()) 3910b57cec5SDimitry Andric return true; 3920b57cec5SDimitry Andric if (!startSpace.startswith(parentSpace)) 3930b57cec5SDimitry Andric return true; 3940b57cec5SDimitry Andric 3950b57cec5SDimitry Andric StringRef indent = startSpace.substr(parentSpace.size()); 3960b57cec5SDimitry Andric 3970b57cec5SDimitry Andric // Indent the lines between start/end offsets. 3980b57cec5SDimitry Andric RewriteBuffer &RB = getEditBuffer(FID); 3990b57cec5SDimitry Andric for (unsigned lineNo = startLineNo; lineNo <= endLineNo; ++lineNo) { 4000b57cec5SDimitry Andric unsigned offs = Content->SourceLineCache[lineNo]; 4010b57cec5SDimitry Andric unsigned i = offs; 4020b57cec5SDimitry Andric while (isWhitespaceExceptNL(MB[i])) 4030b57cec5SDimitry Andric ++i; 4040b57cec5SDimitry Andric StringRef origIndent = MB.substr(offs, i-offs); 4050b57cec5SDimitry Andric if (origIndent.startswith(startSpace)) 4060b57cec5SDimitry Andric RB.InsertText(offs, indent, /*InsertAfter=*/false); 4070b57cec5SDimitry Andric } 4080b57cec5SDimitry Andric 4090b57cec5SDimitry Andric return false; 4100b57cec5SDimitry Andric } 4110b57cec5SDimitry Andric 4120b57cec5SDimitry Andric namespace { 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric // A wrapper for a file stream that atomically overwrites the target. 4150b57cec5SDimitry Andric // 4160b57cec5SDimitry Andric // Creates a file output stream for a temporary file in the constructor, 4170b57cec5SDimitry Andric // which is later accessible via getStream() if ok() return true. 4180b57cec5SDimitry Andric // Flushes the stream and moves the temporary file to the target location 4190b57cec5SDimitry Andric // in the destructor. 4200b57cec5SDimitry Andric class AtomicallyMovedFile { 4210b57cec5SDimitry Andric public: 4220b57cec5SDimitry Andric AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename, 4230b57cec5SDimitry Andric bool &AllWritten) 4240b57cec5SDimitry Andric : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) { 4250b57cec5SDimitry Andric TempFilename = Filename; 4260b57cec5SDimitry Andric TempFilename += "-%%%%%%%%"; 4270b57cec5SDimitry Andric int FD; 4280b57cec5SDimitry Andric if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) { 4290b57cec5SDimitry Andric AllWritten = false; 4300b57cec5SDimitry Andric Diagnostics.Report(clang::diag::err_unable_to_make_temp) 4310b57cec5SDimitry Andric << TempFilename; 4320b57cec5SDimitry Andric } else { 4330b57cec5SDimitry Andric FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true)); 4340b57cec5SDimitry Andric } 4350b57cec5SDimitry Andric } 4360b57cec5SDimitry Andric 4370b57cec5SDimitry Andric ~AtomicallyMovedFile() { 4380b57cec5SDimitry Andric if (!ok()) return; 4390b57cec5SDimitry Andric 4400b57cec5SDimitry Andric // Close (will also flush) theFileStream. 4410b57cec5SDimitry Andric FileStream->close(); 4420b57cec5SDimitry Andric if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) { 4430b57cec5SDimitry Andric AllWritten = false; 4440b57cec5SDimitry Andric Diagnostics.Report(clang::diag::err_unable_to_rename_temp) 4450b57cec5SDimitry Andric << TempFilename << Filename << ec.message(); 4460b57cec5SDimitry Andric // If the remove fails, there's not a lot we can do - this is already an 4470b57cec5SDimitry Andric // error. 4480b57cec5SDimitry Andric llvm::sys::fs::remove(TempFilename); 4490b57cec5SDimitry Andric } 4500b57cec5SDimitry Andric } 4510b57cec5SDimitry Andric 4520b57cec5SDimitry Andric bool ok() { return (bool)FileStream; } 4530b57cec5SDimitry Andric raw_ostream &getStream() { return *FileStream; } 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric private: 4560b57cec5SDimitry Andric DiagnosticsEngine &Diagnostics; 4570b57cec5SDimitry Andric StringRef Filename; 4580b57cec5SDimitry Andric SmallString<128> TempFilename; 4590b57cec5SDimitry Andric std::unique_ptr<llvm::raw_fd_ostream> FileStream; 4600b57cec5SDimitry Andric bool &AllWritten; 4610b57cec5SDimitry Andric }; 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric } // namespace 4640b57cec5SDimitry Andric 4650b57cec5SDimitry Andric bool Rewriter::overwriteChangedFiles() { 4660b57cec5SDimitry Andric bool AllWritten = true; 4670b57cec5SDimitry Andric for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) { 4680b57cec5SDimitry Andric const FileEntry *Entry = 4690b57cec5SDimitry Andric getSourceMgr().getFileEntryForID(I->first); 4700b57cec5SDimitry Andric AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(), 4710b57cec5SDimitry Andric AllWritten); 4720b57cec5SDimitry Andric if (File.ok()) { 4730b57cec5SDimitry Andric I->second.write(File.getStream()); 4740b57cec5SDimitry Andric } 4750b57cec5SDimitry Andric } 4760b57cec5SDimitry Andric return !AllWritten; 4770b57cec5SDimitry Andric } 478