1 //===--- Replacement.cpp - Framework for clang refactoring tools ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements classes to support/store refactorings.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticIDs.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/Lexer.h"
20 #include "clang/Rewrite/Core/Rewriter.h"
21 #include "clang/Tooling/Core/Replacement.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/raw_os_ostream.h"
29 static const char * const InvalidLocation = "";
31 Replacement::Replacement()
32 : FilePath(InvalidLocation) {}
34 Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
35 StringRef ReplacementText)
36 : FilePath(FilePath), ReplacementRange(Offset, Length),
37 ReplacementText(ReplacementText) {}
39 Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
40 unsigned Length, StringRef ReplacementText) {
41 setFromSourceLocation(Sources, Start, Length, ReplacementText);
44 Replacement::Replacement(const SourceManager &Sources,
45 const CharSourceRange &Range,
46 StringRef ReplacementText) {
47 setFromSourceRange(Sources, Range, ReplacementText);
50 bool Replacement::isApplicable() const {
51 return FilePath != InvalidLocation;
54 bool Replacement::apply(Rewriter &Rewrite) const {
55 SourceManager &SM = Rewrite.getSourceMgr();
56 const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
60 // FIXME: Use SM.translateFile directly.
61 SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
62 ID = Location.isValid() ?
63 SM.getFileID(Location) :
64 SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
65 // FIXME: We cannot check whether Offset + Length is in the file, as
66 // the remapping API is not public in the RewriteBuffer.
67 const SourceLocation Start =
68 SM.getLocForStartOfFile(ID).
69 getLocWithOffset(ReplacementRange.getOffset());
70 // ReplaceText returns false on success.
71 // ReplaceText only fails if the source location is not a file location, in
72 // which case we already returned false earlier.
73 bool RewriteSucceeded = !Rewrite.ReplaceText(
74 Start, ReplacementRange.getLength(), ReplacementText);
75 assert(RewriteSucceeded);
76 return RewriteSucceeded;
79 std::string Replacement::toString() const {
81 llvm::raw_string_ostream stream(result);
82 stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
83 << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
87 bool operator<(const Replacement &LHS, const Replacement &RHS) {
88 if (LHS.getOffset() != RHS.getOffset())
89 return LHS.getOffset() < RHS.getOffset();
90 if (LHS.getLength() != RHS.getLength())
91 return LHS.getLength() < RHS.getLength();
92 if (LHS.getFilePath() != RHS.getFilePath())
93 return LHS.getFilePath() < RHS.getFilePath();
94 return LHS.getReplacementText() < RHS.getReplacementText();
97 bool operator==(const Replacement &LHS, const Replacement &RHS) {
98 return LHS.getOffset() == RHS.getOffset() &&
99 LHS.getLength() == RHS.getLength() &&
100 LHS.getFilePath() == RHS.getFilePath() &&
101 LHS.getReplacementText() == RHS.getReplacementText();
104 void Replacement::setFromSourceLocation(const SourceManager &Sources,
105 SourceLocation Start, unsigned Length,
106 StringRef ReplacementText) {
107 const std::pair<FileID, unsigned> DecomposedLocation =
108 Sources.getDecomposedLoc(Start);
109 const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
111 // Make FilePath absolute so replacements can be applied correctly when
112 // relative paths for files are used.
113 llvm::SmallString<256> FilePath(Entry->getName());
114 std::error_code EC = llvm::sys::fs::make_absolute(FilePath);
115 this->FilePath = EC ? FilePath.c_str() : Entry->getName();
117 this->FilePath = InvalidLocation;
119 this->ReplacementRange = Range(DecomposedLocation.second, Length);
120 this->ReplacementText = ReplacementText;
123 // FIXME: This should go into the Lexer, but we need to figure out how
124 // to handle ranges for refactoring in general first - there is no obvious
125 // good way how to integrate this into the Lexer yet.
126 static int getRangeSize(const SourceManager &Sources,
127 const CharSourceRange &Range) {
128 SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
129 SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
130 std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
131 std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
132 if (Start.first != End.first) return -1;
133 if (Range.isTokenRange())
134 End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources,
136 return End.second - Start.second;
139 void Replacement::setFromSourceRange(const SourceManager &Sources,
140 const CharSourceRange &Range,
141 StringRef ReplacementText) {
142 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
143 getRangeSize(Sources, Range), ReplacementText);
146 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
147 unsigned NewPosition = Position;
148 for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
150 if (I->getOffset() >= Position)
152 if (I->getOffset() + I->getLength() > Position)
153 NewPosition += I->getOffset() + I->getLength() - Position;
154 NewPosition += I->getReplacementText().size() - I->getLength();
159 // FIXME: Remove this function when Replacements is implemented as std::vector
160 // instead of std::set.
161 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
163 unsigned NewPosition = Position;
164 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
167 if (I->getOffset() >= Position)
169 if (I->getOffset() + I->getLength() > Position)
170 NewPosition += I->getOffset() + I->getLength() - Position;
171 NewPosition += I->getReplacementText().size() - I->getLength();
176 void deduplicate(std::vector<Replacement> &Replaces,
177 std::vector<Range> &Conflicts) {
178 if (Replaces.empty())
181 auto LessNoPath = [](const Replacement &LHS, const Replacement &RHS) {
182 if (LHS.getOffset() != RHS.getOffset())
183 return LHS.getOffset() < RHS.getOffset();
184 if (LHS.getLength() != RHS.getLength())
185 return LHS.getLength() < RHS.getLength();
186 return LHS.getReplacementText() < RHS.getReplacementText();
189 auto EqualNoPath = [](const Replacement &LHS, const Replacement &RHS) {
190 return LHS.getOffset() == RHS.getOffset() &&
191 LHS.getLength() == RHS.getLength() &&
192 LHS.getReplacementText() == RHS.getReplacementText();
195 // Deduplicate. We don't want to deduplicate based on the path as we assume
196 // that all replacements refer to the same file (or are symlinks).
197 std::sort(Replaces.begin(), Replaces.end(), LessNoPath);
198 Replaces.erase(std::unique(Replaces.begin(), Replaces.end(), EqualNoPath),
202 Range ConflictRange(Replaces.front().getOffset(),
203 Replaces.front().getLength());
204 unsigned ConflictStart = 0;
205 unsigned ConflictLength = 1;
206 for (unsigned i = 1; i < Replaces.size(); ++i) {
207 Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
208 if (ConflictRange.overlapsWith(Current)) {
209 // Extend conflicted range
210 ConflictRange = Range(ConflictRange.getOffset(),
211 std::max(ConflictRange.getLength(),
212 Current.getOffset() + Current.getLength() -
213 ConflictRange.getOffset()));
216 if (ConflictLength > 1)
217 Conflicts.push_back(Range(ConflictStart, ConflictLength));
218 ConflictRange = Current;
224 if (ConflictLength > 1)
225 Conflicts.push_back(Range(ConflictStart, ConflictLength));
228 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
230 for (Replacements::const_iterator I = Replaces.begin(),
233 if (I->isApplicable()) {
234 Result = I->apply(Rewrite) && Result;
242 // FIXME: Remove this function when Replacements is implemented as std::vector
243 // instead of std::set.
244 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
247 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
250 if (I->isApplicable()) {
251 Result = I->apply(Rewrite) && Result;
259 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
260 FileManager Files((FileSystemOptions()));
261 DiagnosticsEngine Diagnostics(
262 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
263 new DiagnosticOptions);
264 SourceManager SourceMgr(Diagnostics, Files);
265 Rewriter Rewrite(SourceMgr, LangOptions());
266 std::unique_ptr<llvm::MemoryBuffer> Buf =
267 llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
268 const clang::FileEntry *Entry =
269 Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
270 SourceMgr.overrideFileContents(Entry, std::move(Buf));
272 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
273 for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
275 Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
276 I->getReplacementText());
277 if (!Replace.apply(Rewrite))
281 llvm::raw_string_ostream OS(Result);
282 Rewrite.getEditBuffer(ID).write(OS);
287 } // end namespace tooling
288 } // end namespace clang