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