RefactoringTest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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/ASTContext.h"
  11. #include "clang/AST/ASTConsumer.h"
  12. #include "clang/AST/DeclCXX.h"
  13. #include "clang/AST/DeclGroup.h"
  14. #include "clang/AST/RecursiveASTVisitor.h"
  15. #include "clang/Tooling/Refactoring.h"
  16. #include "clang/Basic/Diagnostic.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/DiagnosticOptions.h"
  22. #include "clang/Frontend/FrontendAction.h"
  23. #include "clang/Frontend/TextDiagnosticPrinter.h"
  24. #include "clang/Rewrite/Rewriter.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. class FlushRewrittenFilesTest : public ::testing::Test {
  137. public:
  138. FlushRewrittenFilesTest() {
  139. std::string ErrorInfo;
  140. TemporaryDirectory = llvm::sys::Path::GetTemporaryDirectory(&ErrorInfo);
  141. assert(ErrorInfo.empty());
  142. }
  143. ~FlushRewrittenFilesTest() {
  144. std::string ErrorInfo;
  145. TemporaryDirectory.eraseFromDisk(true, &ErrorInfo);
  146. assert(ErrorInfo.empty());
  147. }
  148. FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
  149. llvm::SmallString<1024> Path(TemporaryDirectory.str());
  150. llvm::sys::path::append(Path, Name);
  151. std::string ErrorInfo;
  152. llvm::raw_fd_ostream OutStream(Path.c_str(),
  153. ErrorInfo, llvm::raw_fd_ostream::F_Binary);
  154. assert(ErrorInfo.empty());
  155. OutStream << Content;
  156. OutStream.close();
  157. const FileEntry *File = Context.Files.getFile(Path);
  158. assert(File != NULL);
  159. return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
  160. }
  161. std::string getFileContentFromDisk(llvm::StringRef Name) {
  162. llvm::SmallString<1024> Path(TemporaryDirectory.str());
  163. llvm::sys::path::append(Path, Name);
  164. // We need to read directly from the FileManager without relaying through
  165. // a FileEntry, as otherwise we'd read through an already opened file
  166. // descriptor, which might not see the changes made.
  167. // FIXME: Figure out whether there is a way to get the SourceManger to
  168. // reopen the file.
  169. return Context.Files.getBufferForFile(Path, NULL)->getBuffer();
  170. }
  171. llvm::sys::Path TemporaryDirectory;
  172. RewriterTestContext Context;
  173. };
  174. TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
  175. FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
  176. Replacements Replaces;
  177. Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
  178. 5, "replaced"));
  179. EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
  180. EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
  181. EXPECT_EQ("line1\nreplaced\nline3\nline4",
  182. getFileContentFromDisk("input.cpp"));
  183. }
  184. namespace {
  185. template <typename T>
  186. class TestVisitor : public clang::RecursiveASTVisitor<T> {
  187. public:
  188. bool runOver(StringRef Code) {
  189. return runToolOnCode(new TestAction(this), Code);
  190. }
  191. protected:
  192. clang::SourceManager *SM;
  193. private:
  194. class FindConsumer : public clang::ASTConsumer {
  195. public:
  196. FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
  197. virtual void HandleTranslationUnit(clang::ASTContext &Context) {
  198. Visitor->TraverseDecl(Context.getTranslationUnitDecl());
  199. }
  200. private:
  201. TestVisitor *Visitor;
  202. };
  203. class TestAction : public clang::ASTFrontendAction {
  204. public:
  205. TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
  206. virtual clang::ASTConsumer* CreateASTConsumer(
  207. clang::CompilerInstance& compiler, llvm::StringRef dummy) {
  208. Visitor->SM = &compiler.getSourceManager();
  209. /// TestConsumer will be deleted by the framework calling us.
  210. return new FindConsumer(Visitor);
  211. }
  212. private:
  213. TestVisitor *Visitor;
  214. };
  215. };
  216. } // end namespace
  217. void expectReplacementAt(const Replacement &Replace,
  218. StringRef File, unsigned Offset, unsigned Length) {
  219. ASSERT_TRUE(Replace.isApplicable());
  220. EXPECT_EQ(File, Replace.getFilePath());
  221. EXPECT_EQ(Offset, Replace.getOffset());
  222. EXPECT_EQ(Length, Replace.getLength());
  223. }
  224. class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
  225. public:
  226. bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
  227. if (Record->getName() == "X") {
  228. Replace = Replacement(*SM, Record, "");
  229. }
  230. return true;
  231. }
  232. Replacement Replace;
  233. };
  234. TEST(Replacement, CanBeConstructedFromNode) {
  235. ClassDeclXVisitor ClassDeclX;
  236. EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
  237. expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
  238. }
  239. TEST(Replacement, ReplacesAtSpellingLocation) {
  240. ClassDeclXVisitor ClassDeclX;
  241. EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
  242. expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
  243. }
  244. class CallToFVisitor : public TestVisitor<CallToFVisitor> {
  245. public:
  246. bool VisitCallExpr(CallExpr *Call) {
  247. if (Call->getDirectCallee()->getName() == "F") {
  248. Replace = Replacement(*SM, Call, "");
  249. }
  250. return true;
  251. }
  252. Replacement Replace;
  253. };
  254. TEST(Replacement, FunctionCall) {
  255. CallToFVisitor CallToF;
  256. EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
  257. expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
  258. }
  259. TEST(Replacement, TemplatedFunctionCall) {
  260. CallToFVisitor CallToF;
  261. EXPECT_TRUE(CallToF.runOver(
  262. "template <typename T> void F(); void G() { F<int>(); }"));
  263. expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
  264. }
  265. } // end namespace tooling
  266. } // end namespace clang