RefactoringTest.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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() override {
  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 =
  215. TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
  216. assert(Found == Path);
  217. (void)Found;
  218. return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
  219. }
  220. std::string getFileContentFromDisk(llvm::StringRef Name) {
  221. std::string Path = TemporaryFiles.lookup(Name);
  222. assert(!Path.empty());
  223. // We need to read directly from the FileManager without relaying through
  224. // a FileEntry, as otherwise we'd read through an already opened file
  225. // descriptor, which might not see the changes made.
  226. // FIXME: Figure out whether there is a way to get the SourceManger to
  227. // reopen the file.
  228. auto FileBuffer = Context.Files.getBufferForFile(Path);
  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. clang::ASTContext *Context;
  254. private:
  255. class FindConsumer : public clang::ASTConsumer {
  256. public:
  257. FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
  258. void HandleTranslationUnit(clang::ASTContext &Context) override {
  259. Visitor->TraverseDecl(Context.getTranslationUnitDecl());
  260. }
  261. private:
  262. TestVisitor *Visitor;
  263. };
  264. class TestAction : public clang::ASTFrontendAction {
  265. public:
  266. TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
  267. std::unique_ptr<clang::ASTConsumer>
  268. CreateASTConsumer(clang::CompilerInstance &compiler,
  269. llvm::StringRef dummy) override {
  270. Visitor->SM = &compiler.getSourceManager();
  271. Visitor->Context = &compiler.getASTContext();
  272. /// TestConsumer will be deleted by the framework calling us.
  273. return llvm::make_unique<FindConsumer>(Visitor);
  274. }
  275. private:
  276. TestVisitor *Visitor;
  277. };
  278. };
  279. } // end namespace
  280. void 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. class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
  288. public:
  289. bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
  290. if (Record->getName() == "X") {
  291. Replace = Replacement(*SM, Record, "");
  292. }
  293. return true;
  294. }
  295. Replacement Replace;
  296. };
  297. TEST(Replacement, CanBeConstructedFromNode) {
  298. ClassDeclXVisitor ClassDeclX;
  299. EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
  300. expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
  301. }
  302. TEST(Replacement, ReplacesAtSpellingLocation) {
  303. ClassDeclXVisitor ClassDeclX;
  304. EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
  305. expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
  306. }
  307. class CallToFVisitor : public TestVisitor<CallToFVisitor> {
  308. public:
  309. bool VisitCallExpr(CallExpr *Call) {
  310. if (Call->getDirectCallee()->getName() == "F") {
  311. Replace = Replacement(*SM, Call, "");
  312. }
  313. return true;
  314. }
  315. Replacement Replace;
  316. };
  317. TEST(Replacement, FunctionCall) {
  318. CallToFVisitor CallToF;
  319. EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
  320. expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
  321. }
  322. TEST(Replacement, TemplatedFunctionCall) {
  323. CallToFVisitor CallToF;
  324. EXPECT_TRUE(CallToF.runOver(
  325. "template <typename T> void F(); void G() { F<int>(); }"));
  326. expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
  327. }
  328. class NestedNameSpecifierAVisitor
  329. : public TestVisitor<NestedNameSpecifierAVisitor> {
  330. public:
  331. bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLoc) {
  332. if (NNSLoc.getNestedNameSpecifier()) {
  333. if (const NamespaceDecl* NS = NNSLoc.getNestedNameSpecifier()->getAsNamespace()) {
  334. if (NS->getName() == "a") {
  335. Replace = Replacement(*SM, &NNSLoc, "", Context->getLangOpts());
  336. }
  337. }
  338. }
  339. return TestVisitor<NestedNameSpecifierAVisitor>::TraverseNestedNameSpecifierLoc(
  340. NNSLoc);
  341. }
  342. Replacement Replace;
  343. };
  344. TEST(Replacement, ColonColon) {
  345. NestedNameSpecifierAVisitor VisitNNSA;
  346. EXPECT_TRUE(VisitNNSA.runOver("namespace a { void f() { ::a::f(); } }"));
  347. expectReplacementAt(VisitNNSA.Replace, "input.cc", 25, 5);
  348. }
  349. TEST(Range, overlaps) {
  350. EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
  351. EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
  352. EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
  353. EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
  354. EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
  355. EXPECT_TRUE(Range(2, 6).overlapsWith(Range(0, 10)));
  356. }
  357. TEST(Range, contains) {
  358. EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
  359. EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
  360. EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
  361. EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
  362. }
  363. TEST(DeduplicateTest, removesDuplicates) {
  364. std::vector<Replacement> Input;
  365. Input.push_back(Replacement("fileA", 50, 0, " foo "));
  366. Input.push_back(Replacement("fileA", 10, 3, " bar "));
  367. Input.push_back(Replacement("fileA", 10, 2, " bar ")); // Length differs
  368. Input.push_back(Replacement("fileA", 9, 3, " bar ")); // Offset differs
  369. Input.push_back(Replacement("fileA", 50, 0, " foo ")); // Duplicate
  370. Input.push_back(Replacement("fileA", 51, 3, " bar "));
  371. Input.push_back(Replacement("fileB", 51, 3, " bar ")); // Filename differs!
  372. Input.push_back(Replacement("fileB", 60, 1, " bar "));
  373. Input.push_back(Replacement("fileA", 60, 2, " bar "));
  374. Input.push_back(Replacement("fileA", 51, 3, " moo ")); // Replacement text
  375. // differs!
  376. std::vector<Replacement> Expected;
  377. Expected.push_back(Replacement("fileA", 9, 3, " bar "));
  378. Expected.push_back(Replacement("fileA", 10, 2, " bar "));
  379. Expected.push_back(Replacement("fileA", 10, 3, " bar "));
  380. Expected.push_back(Replacement("fileA", 50, 0, " foo "));
  381. Expected.push_back(Replacement("fileA", 51, 3, " bar "));
  382. Expected.push_back(Replacement("fileA", 51, 3, " moo "));
  383. Expected.push_back(Replacement("fileB", 60, 1, " bar "));
  384. Expected.push_back(Replacement("fileA", 60, 2, " bar "));
  385. std::vector<Range> Conflicts; // Ignored for this test
  386. deduplicate(Input, Conflicts);
  387. EXPECT_EQ(3U, Conflicts.size());
  388. EXPECT_EQ(Expected, Input);
  389. }
  390. TEST(DeduplicateTest, detectsConflicts) {
  391. {
  392. std::vector<Replacement> Input;
  393. Input.push_back(Replacement("fileA", 0, 5, " foo "));
  394. Input.push_back(Replacement("fileA", 0, 5, " foo ")); // Duplicate not a
  395. // conflict.
  396. Input.push_back(Replacement("fileA", 2, 6, " bar "));
  397. Input.push_back(Replacement("fileA", 7, 3, " moo "));
  398. std::vector<Range> Conflicts;
  399. deduplicate(Input, Conflicts);
  400. // One duplicate is removed and the remaining three items form one
  401. // conflicted range.
  402. ASSERT_EQ(3u, Input.size());
  403. ASSERT_EQ(1u, Conflicts.size());
  404. ASSERT_EQ(0u, Conflicts.front().getOffset());
  405. ASSERT_EQ(3u, Conflicts.front().getLength());
  406. }
  407. {
  408. std::vector<Replacement> Input;
  409. // Expected sorted order is shown. It is the sorted order to which the
  410. // returned conflict info refers to.
  411. Input.push_back(Replacement("fileA", 0, 5, " foo ")); // 0
  412. Input.push_back(Replacement("fileA", 5, 5, " bar ")); // 1
  413. Input.push_back(Replacement("fileA", 6, 0, " bar ")); // 3
  414. Input.push_back(Replacement("fileA", 5, 5, " moo ")); // 2
  415. Input.push_back(Replacement("fileA", 7, 2, " bar ")); // 4
  416. Input.push_back(Replacement("fileA", 15, 5, " golf ")); // 5
  417. Input.push_back(Replacement("fileA", 16, 5, " bag ")); // 6
  418. Input.push_back(Replacement("fileA", 10, 3, " club ")); // 7
  419. // #3 is special in that it is completely contained by another conflicting
  420. // Replacement. #4 ensures #3 hasn't messed up the conflicting range size.
  421. std::vector<Range> Conflicts;
  422. deduplicate(Input, Conflicts);
  423. // No duplicates
  424. ASSERT_EQ(8u, Input.size());
  425. ASSERT_EQ(2u, Conflicts.size());
  426. ASSERT_EQ(1u, Conflicts[0].getOffset());
  427. ASSERT_EQ(4u, Conflicts[0].getLength());
  428. ASSERT_EQ(6u, Conflicts[1].getOffset());
  429. ASSERT_EQ(2u, Conflicts[1].getLength());
  430. }
  431. }
  432. class MergeReplacementsTest : public ::testing::Test {
  433. protected:
  434. void mergeAndTestRewrite(StringRef Code, StringRef Intermediate,
  435. StringRef Result, const Replacements &First,
  436. const Replacements &Second) {
  437. // These are mainly to verify the test itself and make it easier to read.
  438. std::string AfterFirst = applyAllReplacements(Code, First);
  439. std::string InSequenceRewrite = applyAllReplacements(AfterFirst, Second);
  440. EXPECT_EQ(Intermediate, AfterFirst);
  441. EXPECT_EQ(Result, InSequenceRewrite);
  442. tooling::Replacements Merged = mergeReplacements(First, Second);
  443. std::string MergedRewrite = applyAllReplacements(Code, Merged);
  444. EXPECT_EQ(InSequenceRewrite, MergedRewrite);
  445. if (InSequenceRewrite != MergedRewrite)
  446. for (tooling::Replacement M : Merged)
  447. llvm::errs() << M.getOffset() << " " << M.getLength() << " "
  448. << M.getReplacementText() << "\n";
  449. }
  450. void mergeAndTestRewrite(StringRef Code, const Replacements &First,
  451. const Replacements &Second) {
  452. std::string InSequenceRewrite =
  453. applyAllReplacements(applyAllReplacements(Code, First), Second);
  454. tooling::Replacements Merged = mergeReplacements(First, Second);
  455. std::string MergedRewrite = applyAllReplacements(Code, Merged);
  456. EXPECT_EQ(InSequenceRewrite, MergedRewrite);
  457. if (InSequenceRewrite != MergedRewrite)
  458. for (tooling::Replacement M : Merged)
  459. llvm::errs() << M.getOffset() << " " << M.getLength() << " "
  460. << M.getReplacementText() << "\n";
  461. }
  462. };
  463. TEST_F(MergeReplacementsTest, Offsets) {
  464. mergeAndTestRewrite("aaa", "aabab", "cacabab",
  465. {{"", 2, 0, "b"}, {"", 3, 0, "b"}},
  466. {{"", 0, 0, "c"}, {"", 1, 0, "c"}});
  467. mergeAndTestRewrite("aaa", "babaa", "babacac",
  468. {{"", 0, 0, "b"}, {"", 1, 0, "b"}},
  469. {{"", 4, 0, "c"}, {"", 5, 0, "c"}});
  470. mergeAndTestRewrite("aaaa", "aaa", "aac", {{"", 1, 1, ""}},
  471. {{"", 2, 1, "c"}});
  472. mergeAndTestRewrite("aa", "bbabba", "bbabcba",
  473. {{"", 0, 0, "bb"}, {"", 1, 0, "bb"}}, {{"", 4, 0, "c"}});
  474. }
  475. TEST_F(MergeReplacementsTest, Concatenations) {
  476. // Basic concatenations. It is important to merge these into a single
  477. // replacement to ensure the correct order.
  478. EXPECT_EQ((Replacements{{"", 0, 0, "ab"}}),
  479. mergeReplacements({{"", 0, 0, "a"}}, {{"", 1, 0, "b"}}));
  480. EXPECT_EQ((Replacements{{"", 0, 0, "ba"}}),
  481. mergeReplacements({{"", 0, 0, "a"}}, {{"", 0, 0, "b"}}));
  482. mergeAndTestRewrite("", "a", "ab", {{"", 0, 0, "a"}}, {{"", 1, 0, "b"}});
  483. mergeAndTestRewrite("", "a", "ba", {{"", 0, 0, "a"}}, {{"", 0, 0, "b"}});
  484. }
  485. TEST_F(MergeReplacementsTest, NotChangingLengths) {
  486. mergeAndTestRewrite("aaaa", "abba", "acca", {{"", 1, 2, "bb"}},
  487. {{"", 1, 2, "cc"}});
  488. mergeAndTestRewrite("aaaa", "abba", "abcc", {{"", 1, 2, "bb"}},
  489. {{"", 2, 2, "cc"}});
  490. mergeAndTestRewrite("aaaa", "abba", "ccba", {{"", 1, 2, "bb"}},
  491. {{"", 0, 2, "cc"}});
  492. mergeAndTestRewrite("aaaaaa", "abbdda", "abccda",
  493. {{"", 1, 2, "bb"}, {"", 3, 2, "dd"}}, {{"", 2, 2, "cc"}});
  494. }
  495. TEST_F(MergeReplacementsTest, OverlappingRanges) {
  496. mergeAndTestRewrite("aaa", "bbd", "bcbcd",
  497. {{"", 0, 1, "bb"}, {"", 1, 2, "d"}},
  498. {{"", 1, 0, "c"}, {"", 2, 0, "c"}});
  499. mergeAndTestRewrite("aaaa", "aabbaa", "acccca", {{"", 2, 0, "bb"}},
  500. {{"", 1, 4, "cccc"}});
  501. mergeAndTestRewrite("aaaa", "aababa", "acccca",
  502. {{"", 2, 0, "b"}, {"", 3, 0, "b"}}, {{"", 1, 4, "cccc"}});
  503. mergeAndTestRewrite("aaaaaa", "abbbba", "abba", {{"", 1, 4, "bbbb"}},
  504. {{"", 2, 2, ""}});
  505. mergeAndTestRewrite("aaaa", "aa", "cc", {{"", 1, 1, ""}, {"", 2, 1, ""}},
  506. {{"", 0, 2, "cc"}});
  507. mergeAndTestRewrite("aa", "abbba", "abcbcba", {{"", 1, 0, "bbb"}},
  508. {{"", 2, 0, "c"}, {"", 3, 0, "c"}});
  509. mergeAndTestRewrite("aaa", "abbab", "ccdd",
  510. {{"", 0, 1, ""}, {"", 2, 0, "bb"}, {"", 3, 0, "b"}},
  511. {{"", 0, 2, "cc"}, {"", 2, 3, "dd"}});
  512. mergeAndTestRewrite("aa", "babbab", "ccdd",
  513. {{"", 0, 0, "b"}, {"", 1, 0, "bb"}, {"", 2, 0, "b"}},
  514. {{"", 0, 3, "cc"}, {"", 3, 3, "dd"}});
  515. }
  516. } // end namespace tooling
  517. } // end namespace clang