blob: a88de1c9f4564720109cb664185da3adbc5df5e6 [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
Edwin Vaneb58cfd92013-08-13 17:38:19 +0000123// FIXME: Remove this test case when Replacements is implemented as std::vector
124// instead of std::set. The other ReplacementTest tests will need to be updated
125// at that point as well.
126TEST_F(ReplacementTest, VectorCanApplyReplacements) {
127 FileID ID = Context.createInMemoryFile("input.cpp",
128 "line1\nline2\nline3\nline4");
129 std::vector<Replacement> Replaces;
130 Replaces.push_back(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
131 5, "replaced"));
132 Replaces.push_back(
133 Replacement(Context.Sources, Context.getLocation(ID, 3, 1), 5, "other"));
134 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
135 EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
136}
137
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000138TEST_F(ReplacementTest, SkipsDuplicateReplacements) {
139 FileID ID = Context.createInMemoryFile("input.cpp",
140 "line1\nline2\nline3\nline4");
141 Replacements Replaces;
142 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
143 5, "replaced"));
144 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
145 5, "replaced"));
146 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
147 5, "replaced"));
148 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
149 EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
150}
151
152TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
153 // This test depends on the value of the file name of an invalid source
154 // location being in the range ]a, z[.
155 FileID IDa = Context.createInMemoryFile("a.cpp", "text");
156 FileID IDz = Context.createInMemoryFile("z.cpp", "text");
157 Replacements Replaces;
158 Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDa, 1, 1),
159 4, "a"));
160 Replaces.insert(Replacement(Context.Sources, SourceLocation(),
161 5, "2"));
162 Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDz, 1, 1),
163 4, "z"));
164 EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
165 EXPECT_EQ("a", Context.getRewrittenText(IDa));
166 EXPECT_EQ("z", Context.getRewrittenText(IDz));
167}
168
Daniel Jasper6bd3b932013-05-21 12:21:39 +0000169TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
170 Replacements Replaces;
171 Replaces.insert(Replacement("", 0, 1, ""));
172 Replaces.insert(Replacement("", 4, 3, " "));
173 // Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
174 EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
175 EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
176 EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
177 EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
178 EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
179 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
180 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
181 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
182 EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
183}
184
185TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
186 Replacements Replaces;
187 Replaces.insert(Replacement("", 4, 0, "\"\n\""));
188 // Assume '"12345678"' is turned into '"1234"\n"5678"'.
189 EXPECT_EQ(4u, shiftedCodePosition(Replaces, 4)); // "123|5678"
190 EXPECT_EQ(8u, shiftedCodePosition(Replaces, 5)); // "1234|678"
191}
192
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000193class FlushRewrittenFilesTest : public ::testing::Test {
Rafael Espindola902a8632013-06-26 15:01:50 +0000194public:
195 FlushRewrittenFilesTest() {}
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000196
197 ~FlushRewrittenFilesTest() {
Rafael Espindola902a8632013-06-26 15:01:50 +0000198 for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
199 E = TemporaryFiles.end();
200 I != E; ++I) {
201 llvm::StringRef Name = I->second;
202 llvm::error_code EC = llvm::sys::fs::remove(Name);
203 (void)EC;
204 assert(!EC);
205 }
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000206 }
207
208 FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
Rafael Espindola902a8632013-06-26 15:01:50 +0000209 SmallString<1024> Path;
210 int FD;
211 llvm::error_code EC =
Rafael Espindola1ec4a862013-07-05 20:00:06 +0000212 llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
Rafael Espindola902a8632013-06-26 15:01:50 +0000213 assert(!EC);
214 (void)EC;
215
216 llvm::raw_fd_ostream OutStream(FD, true);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000217 OutStream << Content;
218 OutStream.close();
219 const FileEntry *File = Context.Files.getFile(Path);
220 assert(File != NULL);
Rafael Espindola902a8632013-06-26 15:01:50 +0000221
222 StringRef Found = TemporaryFiles.GetOrCreateValue(Name, Path.str()).second;
223 assert(Found == Path);
224 (void)Found;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000225 return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
226 }
227
228 std::string getFileContentFromDisk(llvm::StringRef Name) {
Rafael Espindola902a8632013-06-26 15:01:50 +0000229 std::string Path = TemporaryFiles.lookup(Name);
230 assert(!Path.empty());
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000231 // We need to read directly from the FileManager without relaying through
232 // a FileEntry, as otherwise we'd read through an already opened file
233 // descriptor, which might not see the changes made.
234 // FIXME: Figure out whether there is a way to get the SourceManger to
235 // reopen the file.
236 return Context.Files.getBufferForFile(Path, NULL)->getBuffer();
237 }
238
Rafael Espindola902a8632013-06-26 15:01:50 +0000239 llvm::StringMap<std::string> TemporaryFiles;
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000240 RewriterTestContext Context;
241};
242
243TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
244 FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
245 Replacements Replaces;
246 Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
247 5, "replaced"));
248 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
249 EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
250 EXPECT_EQ("line1\nreplaced\nline3\nline4",
251 getFileContentFromDisk("input.cpp"));
252}
253
254namespace {
255template <typename T>
256class TestVisitor : public clang::RecursiveASTVisitor<T> {
257public:
258 bool runOver(StringRef Code) {
259 return runToolOnCode(new TestAction(this), Code);
260 }
261
262protected:
263 clang::SourceManager *SM;
264
265private:
266 class FindConsumer : public clang::ASTConsumer {
267 public:
268 FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
269
270 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
271 Visitor->TraverseDecl(Context.getTranslationUnitDecl());
272 }
273
274 private:
275 TestVisitor *Visitor;
276 };
277
278 class TestAction : public clang::ASTFrontendAction {
279 public:
280 TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
281
282 virtual clang::ASTConsumer* CreateASTConsumer(
283 clang::CompilerInstance& compiler, llvm::StringRef dummy) {
284 Visitor->SM = &compiler.getSourceManager();
285 /// TestConsumer will be deleted by the framework calling us.
286 return new FindConsumer(Visitor);
287 }
288
289 private:
290 TestVisitor *Visitor;
291 };
292};
293} // end namespace
294
295void expectReplacementAt(const Replacement &Replace,
296 StringRef File, unsigned Offset, unsigned Length) {
297 ASSERT_TRUE(Replace.isApplicable());
298 EXPECT_EQ(File, Replace.getFilePath());
299 EXPECT_EQ(Offset, Replace.getOffset());
300 EXPECT_EQ(Length, Replace.getLength());
301}
302
303class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
304public:
305 bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
306 if (Record->getName() == "X") {
307 Replace = Replacement(*SM, Record, "");
308 }
309 return true;
310 }
311 Replacement Replace;
312};
313
314TEST(Replacement, CanBeConstructedFromNode) {
315 ClassDeclXVisitor ClassDeclX;
316 EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
317 expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
318}
319
320TEST(Replacement, ReplacesAtSpellingLocation) {
321 ClassDeclXVisitor ClassDeclX;
322 EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
323 expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
324}
325
326class CallToFVisitor : public TestVisitor<CallToFVisitor> {
327public:
328 bool VisitCallExpr(CallExpr *Call) {
329 if (Call->getDirectCallee()->getName() == "F") {
330 Replace = Replacement(*SM, Call, "");
331 }
332 return true;
333 }
334 Replacement Replace;
335};
336
337TEST(Replacement, FunctionCall) {
338 CallToFVisitor CallToF;
339 EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
340 expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
341}
342
343TEST(Replacement, TemplatedFunctionCall) {
344 CallToFVisitor CallToF;
345 EXPECT_TRUE(CallToF.runOver(
346 "template <typename T> void F(); void G() { F<int>(); }"));
347 expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
348}
349
Manuel Klimek46fa4c32013-07-19 12:12:36 +0000350TEST(Range, overlaps) {
351 EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
352 EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
353 EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
354 EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
355 EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
Edwin Vanef758bc72013-08-13 18:11:16 +0000356 EXPECT_TRUE(Range(2, 6).overlapsWith(Range(0, 10)));
Manuel Klimek46fa4c32013-07-19 12:12:36 +0000357}
358
359TEST(Range, contains) {
360 EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
361 EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
362 EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
363 EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
364}
365
Edwin Vaned5692db2013-08-08 13:31:14 +0000366TEST(DeduplicateTest, removesDuplicates) {
367 std::vector<Replacement> Input;
368 Input.push_back(Replacement("fileA", 50, 0, " foo "));
369 Input.push_back(Replacement("fileA", 10, 3, " bar "));
370 Input.push_back(Replacement("fileA", 10, 2, " bar ")); // Length differs
371 Input.push_back(Replacement("fileA", 9, 3, " bar ")); // Offset differs
372 Input.push_back(Replacement("fileA", 50, 0, " foo ")); // Duplicate
373 Input.push_back(Replacement("fileA", 51, 3, " bar "));
374 Input.push_back(Replacement("fileB", 51, 3, " bar ")); // Filename differs!
375 Input.push_back(Replacement("fileA", 51, 3, " moo ")); // Replacement text
376 // differs!
377
378 std::vector<Replacement> Expected;
379 Expected.push_back(Replacement("fileA", 9, 3, " bar "));
380 Expected.push_back(Replacement("fileA", 10, 2, " bar "));
381 Expected.push_back(Replacement("fileA", 10, 3, " bar "));
382 Expected.push_back(Replacement("fileA", 50, 0, " foo "));
383 Expected.push_back(Replacement("fileA", 51, 3, " bar "));
384 Expected.push_back(Replacement("fileA", 51, 3, " moo "));
385 Expected.push_back(Replacement("fileB", 51, 3, " bar "));
386
387 std::vector<Range> Conflicts; // Ignored for this test
388 deduplicate(Input, Conflicts);
389
390 ASSERT_TRUE(Expected == Input);
391}
392
393TEST(DeduplicateTest, detectsConflicts) {
394 {
395 std::vector<Replacement> Input;
396 Input.push_back(Replacement("fileA", 0, 5, " foo "));
397 Input.push_back(Replacement("fileA", 0, 5, " foo ")); // Duplicate not a
398 // conflict.
399 Input.push_back(Replacement("fileA", 2, 6, " bar "));
400 Input.push_back(Replacement("fileA", 7, 3, " moo "));
401
402 std::vector<Range> Conflicts;
403 deduplicate(Input, Conflicts);
404
405 // One duplicate is removed and the remaining three items form one
406 // conflicted range.
407 ASSERT_EQ(3u, Input.size());
408 ASSERT_EQ(1u, Conflicts.size());
409 ASSERT_EQ(0u, Conflicts.front().getOffset());
410 ASSERT_EQ(3u, Conflicts.front().getLength());
411 }
412 {
413 std::vector<Replacement> Input;
414
415 // Expected sorted order is shown. It is the sorted order to which the
416 // returned conflict info refers to.
417 Input.push_back(Replacement("fileA", 0, 5, " foo ")); // 0
418 Input.push_back(Replacement("fileA", 5, 5, " bar ")); // 1
Edwin Vane95f07662013-08-13 16:26:44 +0000419 Input.push_back(Replacement("fileA", 6, 0, " bar ")); // 3
Edwin Vaned5692db2013-08-08 13:31:14 +0000420 Input.push_back(Replacement("fileA", 5, 5, " moo ")); // 2
Edwin Vane95f07662013-08-13 16:26:44 +0000421 Input.push_back(Replacement("fileA", 7, 2, " bar ")); // 4
422 Input.push_back(Replacement("fileA", 15, 5, " golf ")); // 5
423 Input.push_back(Replacement("fileA", 16, 5, " bag ")); // 6
424 Input.push_back(Replacement("fileA", 10, 3, " club ")); // 7
425
426 // #3 is special in that it is completely contained by another conflicting
427 // Replacement. #4 ensures #3 hasn't messed up the conflicting range size.
Edwin Vaned5692db2013-08-08 13:31:14 +0000428
429 std::vector<Range> Conflicts;
430 deduplicate(Input, Conflicts);
431
432 // No duplicates
Edwin Vane95f07662013-08-13 16:26:44 +0000433 ASSERT_EQ(8u, Input.size());
Edwin Vaned5692db2013-08-08 13:31:14 +0000434 ASSERT_EQ(2u, Conflicts.size());
435 ASSERT_EQ(1u, Conflicts[0].getOffset());
Edwin Vane95f07662013-08-13 16:26:44 +0000436 ASSERT_EQ(4u, Conflicts[0].getLength());
437 ASSERT_EQ(6u, Conflicts[1].getOffset());
Edwin Vaned5692db2013-08-08 13:31:14 +0000438 ASSERT_EQ(2u, Conflicts[1].getLength());
439 }
440}
441
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000442} // end namespace tooling
443} // end namespace clang