Rewriter.cpp 15 KB

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