blob: 13811648eef2be4701ff32194fc1b68503673ba3 [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
109 if (Entry != NULL) {
110 // Make FilePath absolute so replacements can be applied correctly when
111 // relative paths for files are used.
112 llvm::SmallString<256> FilePath(Entry->getName());
113 llvm::error_code EC = llvm::sys::fs::make_absolute(FilePath);
114 // Don't change the FilePath if the file is a virtual file.
115 this->FilePath = EC ? FilePath.c_str() : Entry->getName();
116 } else
117 this->FilePath = InvalidLocation;
Daniel Jasper8a999452013-05-16 10:40:07 +0000118 this->ReplacementRange = Range(DecomposedLocation.second, Length);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000119 this->ReplacementText = ReplacementText;
120}
121
122// FIXME: This should go into the Lexer, but we need to figure out how
123// to handle ranges for refactoring in general first - there is no obvious
124// good way how to integrate this into the Lexer yet.
125static int getRangeSize(SourceManager &Sources, const CharSourceRange &Range) {
126 SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
127 SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
128 std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
129 std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
130 if (Start.first != End.first) return -1;
131 if (Range.isTokenRange())
132 End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources,
133 LangOptions());
134 return End.second - Start.second;
135}
136
137void Replacement::setFromSourceRange(SourceManager &Sources,
138 const CharSourceRange &Range,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000139 StringRef ReplacementText) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000140 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
141 getRangeSize(Sources, Range), ReplacementText);
142}
143
David Blaikie76a2ea32013-07-17 18:29:58 +0000144bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000145 bool Result = true;
146 for (Replacements::const_iterator I = Replaces.begin(),
147 E = Replaces.end();
148 I != E; ++I) {
149 if (I->isApplicable()) {
150 Result = I->apply(Rewrite) && Result;
151 } else {
152 Result = false;
153 }
154 }
155 return Result;
156}
157
Edwin Vaneb58cfd92013-08-13 17:38:19 +0000158// FIXME: Remove this function when Replacements is implemented as std::vector
159// instead of std::set.
160bool applyAllReplacements(const std::vector<Replacement> &Replaces,
161 Rewriter &Rewrite) {
162 bool Result = true;
163 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
164 E = Replaces.end();
165 I != E; ++I) {
166 if (I->isApplicable()) {
167 Result = I->apply(Rewrite) && Result;
168 } else {
169 Result = false;
170 }
171 }
172 return Result;
173}
174
David Blaikie76a2ea32013-07-17 18:29:58 +0000175std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
Daniel Jasper8a999452013-05-16 10:40:07 +0000176 FileManager Files((FileSystemOptions()));
177 DiagnosticsEngine Diagnostics(
178 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
179 new DiagnosticOptions);
180 Diagnostics.setClient(new TextDiagnosticPrinter(
181 llvm::outs(), &Diagnostics.getDiagnosticOptions()));
182 SourceManager SourceMgr(Diagnostics, Files);
183 Rewriter Rewrite(SourceMgr, LangOptions());
184 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
185 const clang::FileEntry *Entry =
186 Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
187 SourceMgr.overrideFileContents(Entry, Buf);
188 FileID ID =
189 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
David Blaikie76a2ea32013-07-17 18:29:58 +0000190 for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
191 I != E; ++I) {
Daniel Jasper8a999452013-05-16 10:40:07 +0000192 Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
193 I->getReplacementText());
194 if (!Replace.apply(Rewrite))
195 return "";
196 }
197 std::string Result;
198 llvm::raw_string_ostream OS(Result);
199 Rewrite.getEditBuffer(ID).write(OS);
200 OS.flush();
201 return Result;
202}
203
Daniel Jasper6bd3b932013-05-21 12:21:39 +0000204unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
205 unsigned NewPosition = Position;
206 for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
207 ++I) {
208 if (I->getOffset() >= Position)
209 break;
210 if (I->getOffset() + I->getLength() > Position)
211 NewPosition += I->getOffset() + I->getLength() - Position;
212 NewPosition += I->getReplacementText().size() - I->getLength();
213 }
214 return NewPosition;
215}
216
Edwin Vanea778cde2013-08-27 15:44:26 +0000217// FIXME: Remove this function when Replacements is implemented as std::vector
218// instead of std::set.
219unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
220 unsigned Position) {
221 unsigned NewPosition = Position;
222 for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
223 E = Replaces.end();
224 I != E; ++I) {
225 if (I->getOffset() >= Position)
226 break;
227 if (I->getOffset() + I->getLength() > Position)
228 NewPosition += I->getOffset() + I->getLength() - Position;
229 NewPosition += I->getReplacementText().size() - I->getLength();
230 }
231 return NewPosition;
232}
233
Edwin Vaned5692db2013-08-08 13:31:14 +0000234void deduplicate(std::vector<Replacement> &Replaces,
235 std::vector<Range> &Conflicts) {
236 if (Replaces.empty())
237 return;
238
239 // Deduplicate
Edwin Vane05e4af02013-08-16 12:18:53 +0000240 std::sort(Replaces.begin(), Replaces.end());
Edwin Vaned5692db2013-08-08 13:31:14 +0000241 std::vector<Replacement>::iterator End =
242 std::unique(Replaces.begin(), Replaces.end());
243 Replaces.erase(End, Replaces.end());
244
245 // Detect conflicts
246 Range ConflictRange(Replaces.front().getOffset(),
247 Replaces.front().getLength());
248 unsigned ConflictStart = 0;
249 unsigned ConflictLength = 1;
250 for (unsigned i = 1; i < Replaces.size(); ++i) {
251 Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
252 if (ConflictRange.overlapsWith(Current)) {
253 // Extend conflicted range
254 ConflictRange = Range(ConflictRange.getOffset(),
Edwin Vane95f07662013-08-13 16:26:44 +0000255 std::max(ConflictRange.getLength(),
256 Current.getOffset() + Current.getLength() -
257 ConflictRange.getOffset()));
Edwin Vaned5692db2013-08-08 13:31:14 +0000258 ++ConflictLength;
259 } else {
260 if (ConflictLength > 1)
261 Conflicts.push_back(Range(ConflictStart, ConflictLength));
262 ConflictRange = Current;
263 ConflictStart = i;
264 ConflictLength = 1;
265 }
266 }
267
268 if (ConflictLength > 1)
269 Conflicts.push_back(Range(ConflictStart, ConflictLength));
270}
271
272
Edwin Vaned088a5f2013-01-11 17:04:55 +0000273RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
274 ArrayRef<std::string> SourcePaths)
275 : ClangTool(Compilations, SourcePaths) {}
276
277Replacements &RefactoringTool::getReplacements() { return Replace; }
278
279int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
280 if (int Result = run(ActionFactory)) {
281 return Result;
282 }
283
284 LangOptions DefaultLangOptions;
285 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
286 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
287 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000288 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
Edwin Vaned088a5f2013-01-11 17:04:55 +0000289 &*DiagOpts, &DiagnosticPrinter, false);
290 SourceManager Sources(Diagnostics, getFiles());
291 Rewriter Rewrite(Sources, DefaultLangOptions);
292
293 if (!applyAllReplacements(Rewrite)) {
294 llvm::errs() << "Skipped some replacements.\n";
295 }
296
297 return saveRewrittenFiles(Rewrite);
298}
299
300bool RefactoringTool::applyAllReplacements(Rewriter &Rewrite) {
301 return tooling::applyAllReplacements(Replace, Rewrite);
302}
303
304int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000305 for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
306 E = Rewrite.buffer_end();
307 I != E; ++I) {
308 // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
309 // go into directly into Rewriter (there we also have the Diagnostics to
310 // handle the error cases better).
311 const FileEntry *Entry =
312 Rewrite.getSourceMgr().getFileEntryForID(I->first);
313 std::string ErrorInfo;
Rafael Espindolad965f952013-07-16 19:44:23 +0000314 llvm::raw_fd_ostream FileStream(Entry->getName(), ErrorInfo,
315 llvm::sys::fs::F_Binary);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000316 if (!ErrorInfo.empty())
Edwin Vaned088a5f2013-01-11 17:04:55 +0000317 return 1;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000318 I->second.write(FileStream);
319 FileStream.flush();
320 }
Edwin Vaned088a5f2013-01-11 17:04:55 +0000321 return 0;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000322}
323
324} // end namespace tooling
325} // end namespace clang