blob: f4c086c4a35d2905dd040a26bca1c5b78d00ceb7 [file] [log] [blame]
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +00001//===- unittest/Tooling/RefactoringTest.cpp - Refactoring unit tests ------===//
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#include "RewriterTestContext.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000011#include "clang/AST/ASTConsumer.h"
Chandler Carruth1050e8b2012-12-04 09:45:34 +000012#include "clang/AST/ASTContext.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000013#include "clang/AST/DeclCXX.h"
14#include "clang/AST/DeclGroup.h"
15#include "clang/AST/RecursiveASTVisitor.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor99eb4a72012-10-23 22:55:10 +000017#include "clang/Basic/DiagnosticOptions.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000018#include "clang/Basic/FileManager.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Frontend/CompilerInstance.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000022#include "clang/Frontend/FrontendAction.h"
23#include "clang/Frontend/TextDiagnosticPrinter.h"
Ted Kremenek305c6132012-09-01 05:09:24 +000024#include "clang/Rewrite/Core/Rewriter.h"
Chandler Carruth1050e8b2012-12-04 09:45:34 +000025#include "clang/Tooling/Refactoring.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000026#include "clang/Tooling/Tooling.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/Support/Path.h"
29#include "gtest/gtest.h"
30
31namespace clang {
32namespace tooling {
33
34class ReplacementTest : public ::testing::Test {
35 protected:
36 Replacement createReplacement(SourceLocation Start, unsigned Length,
37 llvm::StringRef ReplacementText) {
38 return Replacement(Context.Sources, Start, Length, ReplacementText);
39 }
40
41 RewriterTestContext Context;
42};
43
44TEST_F(ReplacementTest, CanDeleteAllText) {
45 FileID ID = Context.createInMemoryFile("input.cpp", "text");
46 SourceLocation Location = Context.getLocation(ID, 1, 1);
47 Replacement Replace(createReplacement(Location, 4, ""));
48 EXPECT_TRUE(Replace.apply(Context.Rewrite));
49 EXPECT_EQ("", Context.getRewrittenText(ID));
50}
51
52TEST_F(ReplacementTest, CanDeleteAllTextInTextWithNewlines) {
53 FileID ID = Context.createInMemoryFile("input.cpp", "line1\nline2\nline3");
54 SourceLocation Location = Context.getLocation(ID, 1, 1);
55 Replacement Replace(createReplacement(Location, 17, ""));
56 EXPECT_TRUE(Replace.apply(Context.Rewrite));
57 EXPECT_EQ("", Context.getRewrittenText(ID));
58}
59
60TEST_F(ReplacementTest, CanAddText) {
61 FileID ID = Context.createInMemoryFile("input.cpp", "");
62 SourceLocation Location = Context.getLocation(ID, 1, 1);
63 Replacement Replace(createReplacement(Location, 0, "result"));
64 EXPECT_TRUE(Replace.apply(Context.Rewrite));
65 EXPECT_EQ("result", Context.getRewrittenText(ID));
66}
67
68TEST_F(ReplacementTest, CanReplaceTextAtPosition) {
69 FileID ID = Context.createInMemoryFile("input.cpp",
70 "line1\nline2\nline3\nline4");
71 SourceLocation Location = Context.getLocation(ID, 2, 3);
72 Replacement Replace(createReplacement(Location, 12, "x"));
73 EXPECT_TRUE(Replace.apply(Context.Rewrite));
74 EXPECT_EQ("line1\nlixne4", Context.getRewrittenText(ID));
75}
76
77TEST_F(ReplacementTest, CanReplaceTextAtPositionMultipleTimes) {
78 FileID ID = Context.createInMemoryFile("input.cpp",
79 "line1\nline2\nline3\nline4");
80 SourceLocation Location1 = Context.getLocation(ID, 2, 3);
81 Replacement Replace1(createReplacement(Location1, 12, "x\ny\n"));
82 EXPECT_TRUE(Replace1.apply(Context.Rewrite));
83 EXPECT_EQ("line1\nlix\ny\nne4", Context.getRewrittenText(ID));
84
85 // Since the original source has not been modified, the (4, 4) points to the
86 // 'e' in the original content.
87 SourceLocation Location2 = Context.getLocation(ID, 4, 4);
88 Replacement Replace2(createReplacement(Location2, 1, "f"));
89 EXPECT_TRUE(Replace2.apply(Context.Rewrite));
90 EXPECT_EQ("line1\nlix\ny\nnf4", Context.getRewrittenText(ID));
91}
92
93TEST_F(ReplacementTest, ApplyFailsForNonExistentLocation) {
94 Replacement Replace("nonexistent-file.cpp", 0, 1, "");
95 EXPECT_FALSE(Replace.apply(Context.Rewrite));
96}
97
98TEST_F(ReplacementTest, CanRetrivePath) {
99 Replacement Replace("/path/to/file.cpp", 0, 1, "");
100 EXPECT_EQ("/path/to/file.cpp", Replace.getFilePath());
101}
102
103TEST_F(ReplacementTest, ReturnsInvalidPath) {
104 Replacement Replace1(Context.Sources, SourceLocation(), 0, "");
105 EXPECT_TRUE(Replace1.getFilePath().empty());
106
107 Replacement Replace2;
108 EXPECT_TRUE(Replace2.getFilePath().empty());
109}
110
111TEST_F(ReplacementTest, CanApplyReplacements) {
112 FileID ID = Context.createInMemoryFile("input.cpp",
113 "line1\nline2\nline3\nline4");
114 Replacements Replaces;
115 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
116 5, "replaced"));
117 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 3, 1),
118 5, "other"));
119 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
120 EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
121}
122
123TEST_F(ReplacementTest, SkipsDuplicateReplacements) {
124 FileID ID = Context.createInMemoryFile("input.cpp",
125 "line1\nline2\nline3\nline4");
126 Replacements Replaces;
127 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
128 5, "replaced"));
129 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
130 5, "replaced"));
131 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
132 5, "replaced"));
133 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
134 EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
135}
136
137TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
138 // This test depends on the value of the file name of an invalid source
139 // location being in the range ]a, z[.
140 FileID IDa = Context.createInMemoryFile("a.cpp", "text");
141 FileID IDz = Context.createInMemoryFile("z.cpp", "text");
142 Replacements Replaces;
143 Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDa, 1, 1),
144 4, "a"));
145 Replaces.insert(Replacement(Context.Sources, SourceLocation(),
146 5, "2"));
147 Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDz, 1, 1),
148 4, "z"));
149 EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
150 EXPECT_EQ("a", Context.getRewrittenText(IDa));
151 EXPECT_EQ("z", Context.getRewrittenText(IDz));
152}
153
Daniel Jasper6bd3b932013-05-21 12:21:39 +0000154TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
155 Replacements Replaces;
156 Replaces.insert(Replacement("", 0, 1, ""));
157 Replaces.insert(Replacement("", 4, 3, " "));
158 // Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
159 EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
160 EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
161 EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
162 EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
163 EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
164 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
165 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
166 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
167 EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
168}
169
170TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
171 Replacements Replaces;
172 Replaces.insert(Replacement("", 4, 0, "\"\n\""));
173 // Assume '"12345678"' is turned into '"1234"\n"5678"'.
174 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 4)); // "123|5678"
175 EXPECT_EQ(8u, shiftedCodePosition(Replaces, 5)); // "1234|678"
176}
177
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000178class FlushRewrittenFilesTest : public ::testing::Test {
Rafael Espindola902a8632013-06-26 15:01:50 +0000179public:
180 FlushRewrittenFilesTest() {}
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000181
182 ~FlushRewrittenFilesTest() {
Rafael Espindola902a8632013-06-26 15:01:50 +0000183 for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
184 E = TemporaryFiles.end();
185 I != E; ++I) {
186 llvm::StringRef Name = I->second;
187 llvm::error_code EC = llvm::sys::fs::remove(Name);
188 (void)EC;
189 assert(!EC);
190 }
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000191 }
192
193 FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
Rafael Espindola902a8632013-06-26 15:01:50 +0000194 SmallString<1024> Path;
195 int FD;
196 llvm::error_code EC =
197 llvm::sys::fs::unique_file(Twine(Name) + "%%%%%%", FD, Path);
198 assert(!EC);
199 (void)EC;
200
201 llvm::raw_fd_ostream OutStream(FD, true);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000202 OutStream << Content;
203 OutStream.close();
204 const FileEntry *File = Context.Files.getFile(Path);
205 assert(File != NULL);
Rafael Espindola902a8632013-06-26 15:01:50 +0000206
207 StringRef Found = TemporaryFiles.GetOrCreateValue(Name, Path.str()).second;
208 assert(Found == Path);
209 (void)Found;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000210 return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
211 }
212
213 std::string getFileContentFromDisk(llvm::StringRef Name) {
Rafael Espindola902a8632013-06-26 15:01:50 +0000214 std::string Path = TemporaryFiles.lookup(Name);
215 assert(!Path.empty());
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000216 // We need to read directly from the FileManager without relaying through
217 // a FileEntry, as otherwise we'd read through an already opened file
218 // descriptor, which might not see the changes made.
219 // FIXME: Figure out whether there is a way to get the SourceManger to
220 // reopen the file.
221 return Context.Files.getBufferForFile(Path, NULL)->getBuffer();
222 }
223
Rafael Espindola902a8632013-06-26 15:01:50 +0000224 llvm::StringMap<std::string> TemporaryFiles;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000225 RewriterTestContext Context;
226};
227
228TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
229 FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
230 Replacements Replaces;
231 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
232 5, "replaced"));
233 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
234 EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
235 EXPECT_EQ("line1\nreplaced\nline3\nline4",
236 getFileContentFromDisk("input.cpp"));
237}
238
239namespace {
240template <typename T>
241class TestVisitor : public clang::RecursiveASTVisitor<T> {
242public:
243 bool runOver(StringRef Code) {
244 return runToolOnCode(new TestAction(this), Code);
245 }
246
247protected:
248 clang::SourceManager *SM;
249
250private:
251 class FindConsumer : public clang::ASTConsumer {
252 public:
253 FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
254
255 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
256 Visitor->TraverseDecl(Context.getTranslationUnitDecl());
257 }
258
259 private:
260 TestVisitor *Visitor;
261 };
262
263 class TestAction : public clang::ASTFrontendAction {
264 public:
265 TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
266
267 virtual clang::ASTConsumer* CreateASTConsumer(
268 clang::CompilerInstance& compiler, llvm::StringRef dummy) {
269 Visitor->SM = &compiler.getSourceManager();
270 /// TestConsumer will be deleted by the framework calling us.
271 return new FindConsumer(Visitor);
272 }
273
274 private:
275 TestVisitor *Visitor;
276 };
277};
278} // end namespace
279
280void expectReplacementAt(const Replacement &Replace,
281 StringRef File, unsigned Offset, unsigned Length) {
282 ASSERT_TRUE(Replace.isApplicable());
283 EXPECT_EQ(File, Replace.getFilePath());
284 EXPECT_EQ(Offset, Replace.getOffset());
285 EXPECT_EQ(Length, Replace.getLength());
286}
287
288class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
289public:
290 bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
291 if (Record->getName() == "X") {
292 Replace = Replacement(*SM, Record, "");
293 }
294 return true;
295 }
296 Replacement Replace;
297};
298
299TEST(Replacement, CanBeConstructedFromNode) {
300 ClassDeclXVisitor ClassDeclX;
301 EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
302 expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
303}
304
305TEST(Replacement, ReplacesAtSpellingLocation) {
306 ClassDeclXVisitor ClassDeclX;
307 EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
308 expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
309}
310
311class CallToFVisitor : public TestVisitor<CallToFVisitor> {
312public:
313 bool VisitCallExpr(CallExpr *Call) {
314 if (Call->getDirectCallee()->getName() == "F") {
315 Replace = Replacement(*SM, Call, "");
316 }
317 return true;
318 }
319 Replacement Replace;
320};
321
322TEST(Replacement, FunctionCall) {
323 CallToFVisitor CallToF;
324 EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
325 expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
326}
327
328TEST(Replacement, TemplatedFunctionCall) {
329 CallToFVisitor CallToF;
330 EXPECT_TRUE(CallToF.runOver(
331 "template <typename T> void F(); void G() { F<int>(); }"));
332 expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
333}
334
335} // end namespace tooling
336} // end namespace clang