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