RefactoringTest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. TEST_F(ReplacementTest, SkipsDuplicateReplacements) {
  108. FileID ID = Context.createInMemoryFile("input.cpp",
  109. "line1\nline2\nline3\nline4");
  110. Replacements Replaces;
  111. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  112. 5, "replaced"));
  113. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  114. 5, "replaced"));
  115. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  116. 5, "replaced"));
  117. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  118. EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
  119. }
  120. TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
  121. // This test depends on the value of the file name of an invalid source
  122. // location being in the range ]a, z[.
  123. FileID IDa = Context.createInMemoryFile("a.cpp", "text");
  124. FileID IDz = Context.createInMemoryFile("z.cpp", "text");
  125. Replacements Replaces;
  126. Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDa, 1, 1),
  127. 4, "a"));
  128. Replaces.insert(Replacement(Context.Sources, SourceLocation(),
  129. 5, "2"));
  130. Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDz, 1, 1),
  131. 4, "z"));
  132. EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
  133. EXPECT_EQ("a", Context.getRewrittenText(IDa));
  134. EXPECT_EQ("z", Context.getRewrittenText(IDz));
  135. }
  136. TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
  137. Replacements Replaces;
  138. Replaces.insert(Replacement("", 0, 1, ""));
  139. Replaces.insert(Replacement("", 4, 3, " "));
  140. // Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
  141. EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int i;
  142. EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); // |nt i;
  143. EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); // i|t i;
  144. EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); // in| i;
  145. EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); // int| i;
  146. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); // int | i;
  147. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); // int |i;
  148. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); // int |;
  149. EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); // int i|
  150. }
  151. TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
  152. Replacements Replaces;
  153. Replaces.insert(Replacement("", 4, 0, "\"\n\""));
  154. // Assume '"12345678"' is turned into '"1234"\n"5678"'.
  155. EXPECT_EQ(4u, shiftedCodePosition(Replaces, 4)); // "123|5678"
  156. EXPECT_EQ(8u, shiftedCodePosition(Replaces, 5)); // "1234|678"
  157. }
  158. class FlushRewrittenFilesTest : public ::testing::Test {
  159. public:
  160. FlushRewrittenFilesTest() {}
  161. ~FlushRewrittenFilesTest() {
  162. for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
  163. E = TemporaryFiles.end();
  164. I != E; ++I) {
  165. llvm::StringRef Name = I->second;
  166. llvm::error_code EC = llvm::sys::fs::remove(Name);
  167. (void)EC;
  168. assert(!EC);
  169. }
  170. }
  171. FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
  172. SmallString<1024> Path;
  173. int FD;
  174. llvm::error_code EC =
  175. llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
  176. assert(!EC);
  177. (void)EC;
  178. llvm::raw_fd_ostream OutStream(FD, true);
  179. OutStream << Content;
  180. OutStream.close();
  181. const FileEntry *File = Context.Files.getFile(Path);
  182. assert(File != NULL);
  183. StringRef Found = TemporaryFiles.GetOrCreateValue(Name, Path.str()).second;
  184. assert(Found == Path);
  185. (void)Found;
  186. return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
  187. }
  188. std::string getFileContentFromDisk(llvm::StringRef Name) {
  189. std::string Path = TemporaryFiles.lookup(Name);
  190. assert(!Path.empty());
  191. // We need to read directly from the FileManager without relaying through
  192. // a FileEntry, as otherwise we'd read through an already opened file
  193. // descriptor, which might not see the changes made.
  194. // FIXME: Figure out whether there is a way to get the SourceManger to
  195. // reopen the file.
  196. return Context.Files.getBufferForFile(Path, NULL)->getBuffer();
  197. }
  198. llvm::StringMap<std::string> TemporaryFiles;
  199. RewriterTestContext Context;
  200. };
  201. TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
  202. FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
  203. Replacements Replaces;
  204. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  205. 5, "replaced"));
  206. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  207. EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
  208. EXPECT_EQ("line1\nreplaced\nline3\nline4",
  209. getFileContentFromDisk("input.cpp"));
  210. }
  211. namespace {
  212. template <typename T>
  213. class TestVisitor : public clang::RecursiveASTVisitor<T> {
  214. public:
  215. bool runOver(StringRef Code) {
  216. return runToolOnCode(new TestAction(this), Code);
  217. }
  218. protected:
  219. clang::SourceManager *SM;
  220. private:
  221. class FindConsumer : public clang::ASTConsumer {
  222. public:
  223. FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
  224. virtual void HandleTranslationUnit(clang::ASTContext &Context) {
  225. Visitor->TraverseDecl(Context.getTranslationUnitDecl());
  226. }
  227. private:
  228. TestVisitor *Visitor;
  229. };
  230. class TestAction : public clang::ASTFrontendAction {
  231. public:
  232. TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
  233. virtual clang::ASTConsumer* CreateASTConsumer(
  234. clang::CompilerInstance& compiler, llvm::StringRef dummy) {
  235. Visitor->SM = &compiler.getSourceManager();
  236. /// TestConsumer will be deleted by the framework calling us.
  237. return new FindConsumer(Visitor);
  238. }
  239. private:
  240. TestVisitor *Visitor;
  241. };
  242. };
  243. } // end namespace
  244. void expectReplacementAt(const Replacement &Replace,
  245. StringRef File, unsigned Offset, unsigned Length) {
  246. ASSERT_TRUE(Replace.isApplicable());
  247. EXPECT_EQ(File, Replace.getFilePath());
  248. EXPECT_EQ(Offset, Replace.getOffset());
  249. EXPECT_EQ(Length, Replace.getLength());
  250. }
  251. class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
  252. public:
  253. bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
  254. if (Record->getName() == "X") {
  255. Replace = Replacement(*SM, Record, "");
  256. }
  257. return true;
  258. }
  259. Replacement Replace;
  260. };
  261. TEST(Replacement, CanBeConstructedFromNode) {
  262. ClassDeclXVisitor ClassDeclX;
  263. EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
  264. expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
  265. }
  266. TEST(Replacement, ReplacesAtSpellingLocation) {
  267. ClassDeclXVisitor ClassDeclX;
  268. EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
  269. expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
  270. }
  271. class CallToFVisitor : public TestVisitor<CallToFVisitor> {
  272. public:
  273. bool VisitCallExpr(CallExpr *Call) {
  274. if (Call->getDirectCallee()->getName() == "F") {
  275. Replace = Replacement(*SM, Call, "");
  276. }
  277. return true;
  278. }
  279. Replacement Replace;
  280. };
  281. TEST(Replacement, FunctionCall) {
  282. CallToFVisitor CallToF;
  283. EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
  284. expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
  285. }
  286. TEST(Replacement, TemplatedFunctionCall) {
  287. CallToFVisitor CallToF;
  288. EXPECT_TRUE(CallToF.runOver(
  289. "template <typename T> void F(); void G() { F<int>(); }"));
  290. expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
  291. }
  292. } // end namespace tooling
  293. } // end namespace clang