blob: 9e58db0f482443c6a01ad42a8506e87110bf7c8f [file] [log] [blame]
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +00001//===--- Refactoring.cpp - Framework for clang refactoring tools ----------===//
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// Implements tools to support refactorings.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregor02c23eb2012-10-23 22:26:28 +000014#include "clang/Basic/DiagnosticOptions.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000017#include "clang/Frontend/TextDiagnosticPrinter.h"
18#include "clang/Lex/Lexer.h"
Ted Kremenek305c6132012-09-01 05:09:24 +000019#include "clang/Rewrite/Core/Rewriter.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000020#include "clang/Tooling/Refactoring.h"
21#include "llvm/Support/raw_os_ostream.h"
Ariel J. Bernald11344a2013-10-01 14:59:00 +000022#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/Path.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000024
25namespace clang {
26namespace tooling {
27
28static const char * const InvalidLocation = "";
29
30Replacement::Replacement()
Daniel Jasper8a999452013-05-16 10:40:07 +000031 : FilePath(InvalidLocation) {}
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000032
Daniel Jasper8a999452013-05-16 10:40:07 +000033Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
34 StringRef ReplacementText)
35 : FilePath(FilePath), ReplacementRange(Offset, Length),
36 ReplacementText(ReplacementText) {}
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000037
38Replacement::Replacement(SourceManager &Sources, SourceLocation Start,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000039 unsigned Length, StringRef ReplacementText) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000040 setFromSourceLocation(Sources, Start, Length, ReplacementText);
41}
42
43Replacement::Replacement(SourceManager &Sources, const CharSourceRange &Range,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000044 StringRef ReplacementText) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000045 setFromSourceRange(Sources, Range, ReplacementText);
46}
47
48bool Replacement::isApplicable() const {
49 return FilePath != InvalidLocation;
50}
51
52bool Replacement::apply(Rewriter &Rewrite) const {
53 SourceManager &SM = Rewrite.getSourceMgr();
54 const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
55 if (Entry == NULL)
56 return false;
57 FileID ID;
58 // FIXME: Use SM.translateFile directly.
59 SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
60 ID = Location.isValid() ?
61 SM.getFileID(Location) :
62 SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
63 // FIXME: We cannot check whether Offset + Length is in the file, as
64 // the remapping API is not public in the RewriteBuffer.
65 const SourceLocation Start =
66 SM.getLocForStartOfFile(ID).
Daniel Jasper8a999452013-05-16 10:40:07 +000067 getLocWithOffset(ReplacementRange.getOffset());
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000068 // ReplaceText returns false on success.
69 // ReplaceText only fails if the source location is not a file location, in
70 // which case we already returned false earlier.
Daniel Jasper8a999452013-05-16 10:40:07 +000071 bool RewriteSucceeded = !Rewrite.ReplaceText(
72 Start, ReplacementRange.getLength(), ReplacementText);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000073 assert(RewriteSucceeded);
74 return RewriteSucceeded;
75}
76
Manuel Klimek5d51e882012-05-30 16:04:29 +000077std::string Replacement::toString() const {
78 std::string result;
79 llvm::raw_string_ostream stream(result);
Daniel Jasper8a999452013-05-16 10:40:07 +000080 stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
81 << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
Manuel Klimek5d51e882012-05-30 16:04:29 +000082 return result;
83}
84
Edwin Vane05e4af02013-08-16 12:18:53 +000085bool operator<(const Replacement &LHS, const Replacement &RHS) {
86 if (LHS.getOffset() != RHS.getOffset())
87 return LHS.getOffset() < RHS.getOffset();
88 if (LHS.getLength() != RHS.getLength())
89 return LHS.getLength() < RHS.getLength();
90 if (LHS.getFilePath() != RHS.getFilePath())
91 return LHS.getFilePath() < RHS.getFilePath();
92 return LHS.getReplacementText() < RHS.getReplacementText();
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000093}
94
Edwin Vane05e4af02013-08-16 12:18:53 +000095bool operator==(const Replacement &LHS, const Replacement &RHS) {
96 return LHS.getOffset() == RHS.getOffset() &&
97 LHS.getLength() == RHS.getLength() &&
98 LHS.getFilePath() == RHS.getFilePath() &&
99 LHS.getReplacementText() == RHS.getReplacementText();
Edwin Vaned5692db2013-08-08 13:31:14 +0000100}
101
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000102void Replacement::setFromSourceLocation(SourceManager &Sources,
103 SourceLocation Start, unsigned Length,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000104 StringRef ReplacementText) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000105 const std::pair<FileID, unsigned> DecomposedLocation =
106 Sources.getDecomposedLoc(Start);
107 const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
Ariel J. Bernald11344a2013-10-01 14:59:00 +0000108 if (Entry != NULL) {
109 // Make FilePath absolute so replacements can be applied correctly when
Ariel J. Bernal19b60a52013-10-18 19:48:31 +0000110 // relative paths for files are used.
111 llvm::SmallString<256> FilePath(Entry->getName());
112 llvm::error_code EC = llvm::sys::fs::make_absolute(FilePath);
113 this->FilePath = EC ? FilePath.c_str() : Entry->getName();
Ariel J. Bernalb71aa7a2013-10-09 16:09:23 +0000114 } else {
Ariel J. Bernald11344a2013-10-01 14:59:00 +0000115 this->FilePath = InvalidLocation;
Ariel J. Bernalb71aa7a2013-10-09 16:09:23 +0000116 }
Daniel Jasper8a999452013-05-16 10:40:07 +0000117 this->ReplacementRange = Range(DecomposedLocation.second, Length);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000118 this->ReplacementText = ReplacementText;
119}
120
121// FIXME: This should go into the Lexer, but we need to figure out how
122// to handle ranges for refactoring in general first - there is no obvious
123// good way how to integrate this into the Lexer yet.
124static int getRangeSize(SourceManager &Sources, const CharSourceRange &Range) {
125 SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
126 SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
127 std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
128 std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
129 if (Start.first != End.first) return -1;
130 if (Range.isTokenRange())
131 End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources,
132 LangOptions());
133 return End.second - Start.second;
134}
135
136void Replacement::setFromSourceRange(SourceManager &Sources,
137 const CharSourceRange &Range,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000138 StringRef ReplacementText) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000139 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
140 getRangeSize(Sources, Range), ReplacementText);
141}
142
David Blaikie76a2ea32013-07-17 18:29:58 +0000143bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000144 bool Result = true;
145 for (Replacements::const_iterator I = Replaces.begin(),
146 E = Replaces.end();
147 I != E; ++I) {
148 if (I->isApplicable()) {
149 Result = I->apply(Rewrite) && Result;
150 } else {
151 Result = false;
152 }
153 }
154 return Result;
155}
156
Edwin Vaneb58cfd92013-08-13 17:38:19 +0000157// FIXME: Remove this function when Replacements is implemented as std::vector
158// instead of std::set.
159bool applyAllReplacements(const std::vector<Replacement> &Replaces,
160 Rewriter &Rewrite) {
161 bool Result = true;
162 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
163 E = Replaces.end();
164 I != E; ++I) {
165 if (I->isApplicable()) {
166 Result = I->apply(Rewrite) && Result;
167 } else {
168 Result = false;
169 }
170 }
171 return Result;
172}
173
David Blaikie76a2ea32013-07-17 18:29:58 +0000174std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
Daniel Jasper8a999452013-05-16 10:40:07 +0000175 FileManager Files((FileSystemOptions()));
176 DiagnosticsEngine Diagnostics(
177 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
178 new DiagnosticOptions);
179 Diagnostics.setClient(new TextDiagnosticPrinter(
180 llvm::outs(), &Diagnostics.getDiagnosticOptions()));
181 SourceManager SourceMgr(Diagnostics, Files);
182 Rewriter Rewrite(SourceMgr, LangOptions());
183 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
184 const clang::FileEntry *Entry =
185 Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
186 SourceMgr.overrideFileContents(Entry, Buf);
187 FileID ID =
188 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
David Blaikie76a2ea32013-07-17 18:29:58 +0000189 for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
190 I != E; ++I) {
Daniel Jasper8a999452013-05-16 10:40:07 +0000191 Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
192 I->getReplacementText());
193 if (!Replace.apply(Rewrite))
194 return "";
195 }
196 std::string Result;
197 llvm::raw_string_ostream OS(Result);
198 Rewrite.getEditBuffer(ID).write(OS);
199 OS.flush();
200 return Result;
201}
202
Daniel Jasper6bd3b932013-05-21 12:21:39 +0000203unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
204 unsigned NewPosition = Position;
205 for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
206 ++I) {
207 if (I->getOffset() >= Position)
208 break;
209 if (I->getOffset() + I->getLength() > Position)
210 NewPosition += I->getOffset() + I->getLength() - Position;
211 NewPosition += I->getReplacementText().size() - I->getLength();
212 }
213 return NewPosition;
214}
215
Edwin Vanea778cde2013-08-27 15:44:26 +0000216// FIXME: Remove this function when Replacements is implemented as std::vector
217// instead of std::set.
218unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
219 unsigned Position) {
220 unsigned NewPosition = Position;
221 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
222 E = Replaces.end();
223 I != E; ++I) {
224 if (I->getOffset() >= Position)
225 break;
226 if (I->getOffset() + I->getLength() > Position)
227 NewPosition += I->getOffset() + I->getLength() - Position;
228 NewPosition += I->getReplacementText().size() - I->getLength();
229 }
230 return NewPosition;
231}
232
Edwin Vaned5692db2013-08-08 13:31:14 +0000233void deduplicate(std::vector<Replacement> &Replaces,
234 std::vector<Range> &Conflicts) {
235 if (Replaces.empty())
236 return;
237
238 // Deduplicate
Edwin Vane05e4af02013-08-16 12:18:53 +0000239 std::sort(Replaces.begin(), Replaces.end());
Edwin Vaned5692db2013-08-08 13:31:14 +0000240 std::vector<Replacement>::iterator End =
241 std::unique(Replaces.begin(), Replaces.end());
242 Replaces.erase(End, Replaces.end());
243
244 // Detect conflicts
245 Range ConflictRange(Replaces.front().getOffset(),
246 Replaces.front().getLength());
247 unsigned ConflictStart = 0;
248 unsigned ConflictLength = 1;
249 for (unsigned i = 1; i < Replaces.size(); ++i) {
250 Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
251 if (ConflictRange.overlapsWith(Current)) {
252 // Extend conflicted range
253 ConflictRange = Range(ConflictRange.getOffset(),
Edwin Vane95f07662013-08-13 16:26:44 +0000254 std::max(ConflictRange.getLength(),
255 Current.getOffset() + Current.getLength() -
256 ConflictRange.getOffset()));
Edwin Vaned5692db2013-08-08 13:31:14 +0000257 ++ConflictLength;
258 } else {
259 if (ConflictLength > 1)
260 Conflicts.push_back(Range(ConflictStart, ConflictLength));
261 ConflictRange = Current;
262 ConflictStart = i;
263 ConflictLength = 1;
264 }
265 }
266
267 if (ConflictLength > 1)
268 Conflicts.push_back(Range(ConflictStart, ConflictLength));
269}
270
271
Edwin Vaned088a5f2013-01-11 17:04:55 +0000272RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
273 ArrayRef<std::string> SourcePaths)
274 : ClangTool(Compilations, SourcePaths) {}
275
276Replacements &RefactoringTool::getReplacements() { return Replace; }
277
278int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
279 if (int Result = run(ActionFactory)) {
280 return Result;
281 }
282
283 LangOptions DefaultLangOptions;
284 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
285 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
286 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000287 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
Edwin Vaned088a5f2013-01-11 17:04:55 +0000288 &*DiagOpts, &DiagnosticPrinter, false);
289 SourceManager Sources(Diagnostics, getFiles());
290 Rewriter Rewrite(Sources, DefaultLangOptions);
291
292 if (!applyAllReplacements(Rewrite)) {
293 llvm::errs() << "Skipped some replacements.\n";
294 }
295
296 return saveRewrittenFiles(Rewrite);
297}
298
299bool RefactoringTool::applyAllReplacements(Rewriter &Rewrite) {
300 return tooling::applyAllReplacements(Replace, Rewrite);
301}
302
303int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000304 for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
305 E = Rewrite.buffer_end();
306 I != E; ++I) {
307 // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
308 // go into directly into Rewriter (there we also have the Diagnostics to
309 // handle the error cases better).
310 const FileEntry *Entry =
311 Rewrite.getSourceMgr().getFileEntryForID(I->first);
312 std::string ErrorInfo;
Rafael Espindolad965f952013-07-16 19:44:23 +0000313 llvm::raw_fd_ostream FileStream(Entry->getName(), ErrorInfo,
314 llvm::sys::fs::F_Binary);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000315 if (!ErrorInfo.empty())
Edwin Vaned088a5f2013-01-11 17:04:55 +0000316 return 1;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000317 I->second.write(FileStream);
318 FileStream.flush();
319 }
Edwin Vaned088a5f2013-01-11 17:04:55 +0000320 return 0;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000321}
322
323} // end namespace tooling
324} // end namespace clang