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 const LangOptions &LangOpts) {
48 setFromSourceRange(Sources, Range, ReplacementText, LangOpts);
51 bool Replacement::isApplicable() const {
52 return FilePath != InvalidLocation;
55 bool Replacement::apply(Rewriter &Rewrite) const {
56 SourceManager &SM = Rewrite.getSourceMgr();
57 const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
61 // FIXME: Use SM.translateFile directly.
62 SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
63 ID = Location.isValid() ?
64 SM.getFileID(Location) :
65 SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
66 // FIXME: We cannot check whether Offset + Length is in the file, as
67 // the remapping API is not public in the RewriteBuffer.
68 const SourceLocation Start =
69 SM.getLocForStartOfFile(ID).
70 getLocWithOffset(ReplacementRange.getOffset());
71 // ReplaceText returns false on success.
72 // ReplaceText only fails if the source location is not a file location, in
73 // which case we already returned false earlier.
74 bool RewriteSucceeded = !Rewrite.ReplaceText(
75 Start, ReplacementRange.getLength(), ReplacementText);
76 assert(RewriteSucceeded);
77 return RewriteSucceeded;
80 std::string Replacement::toString() const {
82 llvm::raw_string_ostream Stream(Result);
83 Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
84 << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
88 bool operator<(const Replacement &LHS, const Replacement &RHS) {
89 if (LHS.getOffset() != RHS.getOffset())
90 return LHS.getOffset() < RHS.getOffset();
92 // Apply longer replacements first, specifically so that deletions are
93 // executed before insertions. It is (hopefully) never the intention to
94 // delete parts of newly inserted code.
95 if (LHS.getLength() != RHS.getLength())
96 return LHS.getLength() > RHS.getLength();
98 if (LHS.getFilePath() != RHS.getFilePath())
99 return LHS.getFilePath() < RHS.getFilePath();
100 return LHS.getReplacementText() < RHS.getReplacementText();
103 bool operator==(const Replacement &LHS, const Replacement &RHS) {
104 return LHS.getOffset() == RHS.getOffset() &&
105 LHS.getLength() == RHS.getLength() &&
106 LHS.getFilePath() == RHS.getFilePath() &&
107 LHS.getReplacementText() == RHS.getReplacementText();
110 void Replacement::setFromSourceLocation(const SourceManager &Sources,
111 SourceLocation Start, unsigned Length,
112 StringRef ReplacementText) {
113 const std::pair<FileID, unsigned> DecomposedLocation =
114 Sources.getDecomposedLoc(Start);
115 const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
117 // Make FilePath absolute so replacements can be applied correctly when
118 // relative paths for files are used.
119 llvm::SmallString<256> FilePath(Entry->getName());
120 std::error_code EC = llvm::sys::fs::make_absolute(FilePath);
121 this->FilePath = EC ? FilePath.c_str() : Entry->getName();
123 this->FilePath = InvalidLocation;
125 this->ReplacementRange = Range(DecomposedLocation.second, Length);
126 this->ReplacementText = ReplacementText;
129 // FIXME: This should go into the Lexer, but we need to figure out how
130 // to handle ranges for refactoring in general first - there is no obvious
131 // good way how to integrate this into the Lexer yet.
132 static int getRangeSize(const SourceManager &Sources,
133 const CharSourceRange &Range,
134 const LangOptions &LangOpts) {
135 SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
136 SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
137 std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
138 std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
139 if (Start.first != End.first) return -1;
140 if (Range.isTokenRange())
141 End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
142 return End.second - Start.second;
145 void Replacement::setFromSourceRange(const SourceManager &Sources,
146 const CharSourceRange &Range,
147 StringRef ReplacementText,
148 const LangOptions &LangOpts) {
149 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
150 getRangeSize(Sources, Range, LangOpts),
154 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
155 unsigned NewPosition = Position;
156 for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
158 if (I->getOffset() >= Position)
160 if (I->getOffset() + I->getLength() > Position)
161 NewPosition += I->getOffset() + I->getLength() - Position;
162 NewPosition += I->getReplacementText().size() - I->getLength();
167 // FIXME: Remove this function when Replacements is implemented as std::vector
168 // instead of std::set.
169 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
171 unsigned NewPosition = Position;
172 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
175 if (I->getOffset() >= Position)
177 if (I->getOffset() + I->getLength() > Position)
178 NewPosition += I->getOffset() + I->getLength() - Position;
179 NewPosition += I->getReplacementText().size() - I->getLength();
184 void deduplicate(std::vector<Replacement> &Replaces,
185 std::vector<Range> &Conflicts) {
186 if (Replaces.empty())
189 auto LessNoPath = [](const Replacement &LHS, const Replacement &RHS) {
190 if (LHS.getOffset() != RHS.getOffset())
191 return LHS.getOffset() < RHS.getOffset();
192 if (LHS.getLength() != RHS.getLength())
193 return LHS.getLength() < RHS.getLength();
194 return LHS.getReplacementText() < RHS.getReplacementText();
197 auto EqualNoPath = [](const Replacement &LHS, const Replacement &RHS) {
198 return LHS.getOffset() == RHS.getOffset() &&
199 LHS.getLength() == RHS.getLength() &&
200 LHS.getReplacementText() == RHS.getReplacementText();
203 // Deduplicate. We don't want to deduplicate based on the path as we assume
204 // that all replacements refer to the same file (or are symlinks).
205 std::sort(Replaces.begin(), Replaces.end(), LessNoPath);
206 Replaces.erase(std::unique(Replaces.begin(), Replaces.end(), EqualNoPath),
210 Range ConflictRange(Replaces.front().getOffset(),
211 Replaces.front().getLength());
212 unsigned ConflictStart = 0;
213 unsigned ConflictLength = 1;
214 for (unsigned i = 1; i < Replaces.size(); ++i) {
215 Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
216 if (ConflictRange.overlapsWith(Current)) {
217 // Extend conflicted range
218 ConflictRange = Range(ConflictRange.getOffset(),
219 std::max(ConflictRange.getLength(),
220 Current.getOffset() + Current.getLength() -
221 ConflictRange.getOffset()));
224 if (ConflictLength > 1)
225 Conflicts.push_back(Range(ConflictStart, ConflictLength));
226 ConflictRange = Current;
232 if (ConflictLength > 1)
233 Conflicts.push_back(Range(ConflictStart, ConflictLength));
236 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
238 for (Replacements::const_iterator I = Replaces.begin(),
241 if (I->isApplicable()) {
242 Result = I->apply(Rewrite) && Result;
250 // FIXME: Remove this function when Replacements is implemented as std::vector
251 // instead of std::set.
252 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
255 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
258 if (I->isApplicable()) {
259 Result = I->apply(Rewrite) && Result;
267 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
268 FileManager Files((FileSystemOptions()));
269 DiagnosticsEngine Diagnostics(
270 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
271 new DiagnosticOptions);
272 SourceManager SourceMgr(Diagnostics, Files);
273 Rewriter Rewrite(SourceMgr, LangOptions());
274 std::unique_ptr<llvm::MemoryBuffer> Buf =
275 llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
276 const clang::FileEntry *Entry =
277 Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
278 SourceMgr.overrideFileContents(Entry, std::move(Buf));
280 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
281 for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
283 Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
284 I->getReplacementText());
285 if (!Replace.apply(Rewrite))
289 llvm::raw_string_ostream OS(Result);
290 Rewrite.getEditBuffer(ID).write(OS);
295 } // end namespace tooling
296 } // end namespace clang