RefactoringTest.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //===- 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. #include "RewriterTestContext.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclCXX.h"
  13. #include "clang/AST/DeclGroup.h"
  14. #include "clang/AST/RecursiveASTVisitor.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/DiagnosticOptions.h"
  17. #include "clang/Basic/FileManager.h"
  18. #include "clang/Basic/LangOptions.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Frontend/CompilerInstance.h"
  21. #include "clang/Frontend/FrontendAction.h"
  22. #include "clang/Frontend/TextDiagnosticPrinter.h"
  23. #include "clang/Rewrite/Core/Rewriter.h"
  24. #include "clang/Tooling/Refactoring.h"
  25. #include "clang/Tooling/Tooling.h"
  26. #include "llvm/ADT/SmallString.h"
  27. #include "llvm/Support/Path.h"
  28. #include "gtest/gtest.h"
  29. namespace clang {
  30. namespace tooling {
  31. class ReplacementTest : public ::testing::Test {
  32. protected:
  33. Replacement createReplacement(SourceLocation Start, unsigned Length,
  34. llvm::StringRef ReplacementText) {
  35. return Replacement(Context.Sources, Start, Length, ReplacementText);
  36. }
  37. RewriterTestContext Context;
  38. };
  39. TEST_F(ReplacementTest, CanDeleteAllText) {
  40. FileID ID = Context.createInMemoryFile("input.cpp", "text");
  41. SourceLocation Location = Context.getLocation(ID, 1, 1);
  42. Replacement Replace(createReplacement(Location, 4, ""));
  43. EXPECT_TRUE(Replace.apply(Context.Rewrite));
  44. EXPECT_EQ("", Context.getRewrittenText(ID));
  45. }
  46. TEST_F(ReplacementTest, CanDeleteAllTextInTextWithNewlines) {
  47. FileID ID = Context.createInMemoryFile("input.cpp", "line1\nline2\nline3");
  48. SourceLocation Location = Context.getLocation(ID, 1, 1);
  49. Replacement Replace(createReplacement(Location, 17, ""));
  50. EXPECT_TRUE(Replace.apply(Context.Rewrite));
  51. EXPECT_EQ("", Context.getRewrittenText(ID));
  52. }
  53. TEST_F(ReplacementTest, CanAddText) {
  54. FileID ID = Context.createInMemoryFile("input.cpp", "");
  55. SourceLocation Location = Context.getLocation(ID, 1, 1);
  56. Replacement Replace(createReplacement(Location, 0, "result"));
  57. EXPECT_TRUE(Replace.apply(Context.Rewrite));
  58. EXPECT_EQ("result", Context.getRewrittenText(ID));
  59. }
  60. TEST_F(ReplacementTest, CanReplaceTextAtPosition) {
  61. FileID ID = Context.createInMemoryFile("input.cpp",
  62. "line1\nline2\nline3\nline4");
  63. SourceLocation Location = Context.getLocation(ID, 2, 3);
  64. Replacement Replace(createReplacement(Location, 12, "x"));
  65. EXPECT_TRUE(Replace.apply(Context.Rewrite));
  66. EXPECT_EQ("line1\nlixne4", Context.getRewrittenText(ID));
  67. }
  68. TEST_F(ReplacementTest, CanReplaceTextAtPositionMultipleTimes) {
  69. FileID ID = Context.createInMemoryFile("input.cpp",
  70. "line1\nline2\nline3\nline4");
  71. SourceLocation Location1 = Context.getLocation(ID, 2, 3);
  72. Replacement Replace1(createReplacement(Location1, 12, "x\ny\n"));
  73. EXPECT_TRUE(Replace1.apply(Context.Rewrite));
  74. EXPECT_EQ("line1\nlix\ny\nne4", Context.getRewrittenText(ID));
  75. // Since the original source has not been modified, the (4, 4) points to the
  76. // 'e' in the original content.
  77. SourceLocation Location2 = Context.getLocation(ID, 4, 4);
  78. Replacement Replace2(createReplacement(Location2, 1, "f"));
  79. EXPECT_TRUE(Replace2.apply(Context.Rewrite));
  80. EXPECT_EQ("line1\nlix\ny\nnf4", Context.getRewrittenText(ID));
  81. }
  82. TEST_F(ReplacementTest, ApplyFailsForNonExistentLocation) {
  83. Replacement Replace("nonexistent-file.cpp", 0, 1, "");
  84. EXPECT_FALSE(Replace.apply(Context.Rewrite));
  85. }
  86. TEST_F(ReplacementTest, CanRetrivePath) {
  87. Replacement Replace("/path/to/file.cpp", 0, 1, "");
  88. EXPECT_EQ("/path/to/file.cpp", Replace.getFilePath());
  89. }
  90. TEST_F(ReplacementTest, ReturnsInvalidPath) {
  91. Replacement Replace1(Context.Sources, SourceLocation(), 0, "");
  92. EXPECT_TRUE(Replace1.getFilePath().empty());
  93. Replacement Replace2;
  94. EXPECT_TRUE(Replace2.getFilePath().empty());
  95. }
  96. TEST_F(ReplacementTest, CanApplyReplacements) {
  97. FileID ID = Context.createInMemoryFile("input.cpp",
  98. "line1\nline2\nline3\nline4");
  99. Replacements Replaces;
  100. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  101. 5, "replaced"));
  102. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 3, 1),
  103. 5, "other"));
  104. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  105. EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
  106. }
  107. // FIXME: Remove this test case when Replacements is implemented as std::vector
  108. // instead of std::set. The other ReplacementTest tests will need to be updated
  109. // at that point as well.
  110. TEST_F(ReplacementTest, VectorCanApplyReplacements) {
  111. FileID ID = Context.createInMemoryFile("input.cpp",
  112. "line1\nline2\nline3\nline4");
  113. std::vector<Replacement> Replaces;
  114. Replaces.push_back(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  115. 5, "replaced"));
  116. Replaces.push_back(
  117. Replacement(Context.Sources, Context.getLocation(ID, 3, 1), 5, "other"));
  118. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  119. EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
  120. }
  121. TEST_F(ReplacementTest, SkipsDuplicateReplacements) {
  122. FileID ID = Context.createInMemoryFile("input.cpp",
  123. "line1\nline2\nline3\nline4");
  124. Replacements Replaces;
  125. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  126. 5, "replaced"));
  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. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  132. EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
  133. }
  134. TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
  135. // This test depends on the value of the file name of an invalid source
  136. // location being in the range ]a, z[.
  137. FileID IDa = Context.createInMemoryFile("a.cpp", "text");
  138. FileID IDz = Context.createInMemoryFile("z.cpp", "text");
  139. Replacements Replaces;
  140. Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDa, 1, 1),
  141. 4, "a"));
  142. Replaces.insert(Replacement(Context.Sources, SourceLocation(),
  143. 5, "2"));
  144. Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDz, 1, 1),
  145. 4, "z"));
  146. EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
  147. EXPECT_EQ("a", Context.getRewrittenText(IDa));
  148. EXPECT_EQ("z", Context.getRewrittenText(IDz));
  149. }
  150. TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
  151. Replacements Replaces;
  152. Replaces.insert(Replacement("", 0, 1, ""));
  153. Replaces.insert(Replacement("", 4, 3, " "));
  154. // Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
  155. EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
  156. EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
  157. EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
  158. EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
  159. EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
  160. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
  161. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
  162. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
  163. EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
  164. }
  165. // FIXME: Remove this test case when Replacements is implemented as std::vector
  166. // instead of std::set. The other ReplacementTest tests will need to be updated
  167. // at that point as well.
  168. TEST(ShiftedCodePositionTest, VectorFindsNewCodePositionWithInserts) {
  169. std::vector<Replacement> Replaces;
  170. Replaces.push_back(Replacement("", 0, 1, ""));
  171. Replaces.push_back(Replacement("", 4, 3, " "));
  172. // Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
  173. EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
  174. EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
  175. EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
  176. EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
  177. EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
  178. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
  179. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
  180. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
  181. EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
  182. }
  183. TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
  184. Replacements Replaces;
  185. Replaces.insert(Replacement("", 4, 0, "\"\n\""));
  186. // Assume '"12345678"' is turned into '"1234"\n"5678"'.
  187. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 4)); // "123|5678"
  188. EXPECT_EQ(8u, shiftedCodePosition(Replaces, 5)); // "1234|678"
  189. }
  190. class FlushRewrittenFilesTest : public ::testing::Test {
  191. public:
  192. FlushRewrittenFilesTest() {}
  193. ~FlushRewrittenFilesTest() {
  194. for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
  195. E = TemporaryFiles.end();
  196. I != E; ++I) {
  197. llvm::StringRef Name = I->second;
  198. std::error_code EC = llvm::sys::fs::remove(Name);
  199. (void)EC;
  200. assert(!EC);
  201. }
  202. }
  203. FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
  204. SmallString<1024> Path;
  205. int FD;
  206. std::error_code EC = llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
  207. assert(!EC);
  208. (void)EC;
  209. llvm::raw_fd_ostream OutStream(FD, true);
  210. OutStream << Content;
  211. OutStream.close();
  212. const FileEntry *File = Context.Files.getFile(Path);
  213. assert(File != nullptr);
  214. StringRef Found = TemporaryFiles.GetOrCreateValue(Name, Path.str()).second;
  215. assert(Found == Path);
  216. (void)Found;
  217. return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
  218. }
  219. std::string getFileContentFromDisk(llvm::StringRef Name) {
  220. std::string Path = TemporaryFiles.lookup(Name);
  221. assert(!Path.empty());
  222. // We need to read directly from the FileManager without relaying through
  223. // a FileEntry, as otherwise we'd read through an already opened file
  224. // descriptor, which might not see the changes made.
  225. // FIXME: Figure out whether there is a way to get the SourceManger to
  226. // reopen the file.
  227. std::unique_ptr<const llvm::MemoryBuffer> FileBuffer(
  228. Context.Files.getBufferForFile(Path, nullptr));
  229. return FileBuffer->getBuffer();
  230. }
  231. llvm::StringMap<std::string> TemporaryFiles;
  232. RewriterTestContext Context;
  233. };
  234. TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
  235. FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
  236. Replacements Replaces;
  237. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  238. 5, "replaced"));
  239. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  240. EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
  241. EXPECT_EQ("line1\nreplaced\nline3\nline4",
  242. getFileContentFromDisk("input.cpp"));
  243. }
  244. namespace {
  245. template <typename T>
  246. class TestVisitor : public clang::RecursiveASTVisitor<T> {
  247. public:
  248. bool runOver(StringRef Code) {
  249. return runToolOnCode(new TestAction(this), Code);
  250. }
  251. protected:
  252. clang::SourceManager *SM;
  253. private:
  254. class FindConsumer : public clang::ASTConsumer {
  255. public:
  256. FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
  257. virtual void HandleTranslationUnit(clang::ASTContext &Context) {
  258. Visitor->TraverseDecl(Context.getTranslationUnitDecl());
  259. }
  260. private:
  261. TestVisitor *Visitor;
  262. };
  263. class TestAction : public clang::ASTFrontendAction {
  264. public:
  265. TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
  266. virtual std::unique_ptr<clang::ASTConsumer>
  267. CreateASTConsumer(clang::CompilerInstance &compiler,
  268. llvm::StringRef dummy) {
  269. Visitor->SM = &compiler.getSourceManager();
  270. /// TestConsumer will be deleted by the framework calling us.
  271. return llvm::make_unique<FindConsumer>(Visitor);
  272. }
  273. private:
  274. TestVisitor *Visitor;
  275. };
  276. };
  277. } // end namespace
  278. void expectReplacementAt(const Replacement &Replace,
  279. StringRef File, unsigned Offset, unsigned Length) {
  280. ASSERT_TRUE(Replace.isApplicable());
  281. EXPECT_EQ(File, Replace.getFilePath());
  282. EXPECT_EQ(Offset, Replace.getOffset());
  283. EXPECT_EQ(Length, Replace.getLength());
  284. }
  285. class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
  286. public:
  287. bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
  288. if (Record->getName() == "X") {
  289. Replace = Replacement(*SM, Record, "");
  290. }
  291. return true;
  292. }
  293. Replacement Replace;
  294. };
  295. TEST(Replacement, CanBeConstructedFromNode) {
  296. ClassDeclXVisitor ClassDeclX;
  297. EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
  298. expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
  299. }
  300. TEST(Replacement, ReplacesAtSpellingLocation) {
  301. ClassDeclXVisitor ClassDeclX;
  302. EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
  303. expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
  304. }
  305. class CallToFVisitor : public TestVisitor<CallToFVisitor> {
  306. public:
  307. bool VisitCallExpr(CallExpr *Call) {
  308. if (Call->getDirectCallee()->getName() == "F") {
  309. Replace = Replacement(*SM, Call, "");
  310. }
  311. return true;
  312. }
  313. Replacement Replace;
  314. };
  315. TEST(Replacement, FunctionCall) {
  316. CallToFVisitor CallToF;
  317. EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
  318. expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
  319. }
  320. TEST(Replacement, TemplatedFunctionCall) {
  321. CallToFVisitor CallToF;
  322. EXPECT_TRUE(CallToF.runOver(
  323. "template <typename T> void F(); void G() { F<int>(); }"));
  324. expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
  325. }
  326. TEST(Range, overlaps) {
  327. EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
  328. EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
  329. EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
  330. EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
  331. EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
  332. EXPECT_TRUE(Range(2, 6).overlapsWith(Range(0, 10)));
  333. }
  334. TEST(Range, contains) {
  335. EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
  336. EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
  337. EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
  338. EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
  339. }
  340. TEST(DeduplicateTest, removesDuplicates) {
  341. std::vector<Replacement> Input;
  342. Input.push_back(Replacement("fileA", 50, 0, " foo "));
  343. Input.push_back(Replacement("fileA", 10, 3, " bar "));
  344. Input.push_back(Replacement("fileA", 10, 2, " bar ")); // Length differs
  345. Input.push_back(Replacement("fileA", 9, 3, " bar ")); // Offset differs
  346. Input.push_back(Replacement("fileA", 50, 0, " foo ")); // Duplicate
  347. Input.push_back(Replacement("fileA", 51, 3, " bar "));
  348. Input.push_back(Replacement("fileB", 51, 3, " bar ")); // Filename differs!
  349. Input.push_back(Replacement("fileA", 51, 3, " moo ")); // Replacement text
  350. // differs!
  351. std::vector<Replacement> Expected;
  352. Expected.push_back(Replacement("fileA", 9, 3, " bar "));
  353. Expected.push_back(Replacement("fileA", 10, 2, " bar "));
  354. Expected.push_back(Replacement("fileA", 10, 3, " bar "));
  355. Expected.push_back(Replacement("fileA", 50, 0, " foo "));
  356. Expected.push_back(Replacement("fileA", 51, 3, " bar "));
  357. Expected.push_back(Replacement("fileA", 51, 3, " moo "));
  358. Expected.push_back(Replacement("fileB", 51, 3, " bar "));
  359. std::vector<Range> Conflicts; // Ignored for this test
  360. deduplicate(Input, Conflicts);
  361. ASSERT_TRUE(Expected == Input);
  362. }
  363. TEST(DeduplicateTest, detectsConflicts) {
  364. {
  365. std::vector<Replacement> Input;
  366. Input.push_back(Replacement("fileA", 0, 5, " foo "));
  367. Input.push_back(Replacement("fileA", 0, 5, " foo ")); // Duplicate not a
  368. // conflict.
  369. Input.push_back(Replacement("fileA", 2, 6, " bar "));
  370. Input.push_back(Replacement("fileA", 7, 3, " moo "));
  371. std::vector<Range> Conflicts;
  372. deduplicate(Input, Conflicts);
  373. // One duplicate is removed and the remaining three items form one
  374. // conflicted range.
  375. ASSERT_EQ(3u, Input.size());
  376. ASSERT_EQ(1u, Conflicts.size());
  377. ASSERT_EQ(0u, Conflicts.front().getOffset());
  378. ASSERT_EQ(3u, Conflicts.front().getLength());
  379. }
  380. {
  381. std::vector<Replacement> Input;
  382. // Expected sorted order is shown. It is the sorted order to which the
  383. // returned conflict info refers to.
  384. Input.push_back(Replacement("fileA", 0, 5, " foo ")); // 0
  385. Input.push_back(Replacement("fileA", 5, 5, " bar ")); // 1
  386. Input.push_back(Replacement("fileA", 6, 0, " bar ")); // 3
  387. Input.push_back(Replacement("fileA", 5, 5, " moo ")); // 2
  388. Input.push_back(Replacement("fileA", 7, 2, " bar ")); // 4
  389. Input.push_back(Replacement("fileA", 15, 5, " golf ")); // 5
  390. Input.push_back(Replacement("fileA", 16, 5, " bag ")); // 6
  391. Input.push_back(Replacement("fileA", 10, 3, " club ")); // 7
  392. // #3 is special in that it is completely contained by another conflicting
  393. // Replacement. #4 ensures #3 hasn't messed up the conflicting range size.
  394. std::vector<Range> Conflicts;
  395. deduplicate(Input, Conflicts);
  396. // No duplicates
  397. ASSERT_EQ(8u, Input.size());
  398. ASSERT_EQ(2u, Conflicts.size());
  399. ASSERT_EQ(1u, Conflicts[0].getOffset());
  400. ASSERT_EQ(4u, Conflicts[0].getLength());
  401. ASSERT_EQ(6u, Conflicts[1].getOffset());
  402. ASSERT_EQ(2u, Conflicts[1].getLength());
  403. }
  404. }
  405. } // end namespace tooling
  406. } // end namespace clang