Home | History | Annotate | Download | only in Tooling
      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 
     10 #include "RewriterTestContext.h"
     11 #include "clang/AST/ASTConsumer.h"
     12 #include "clang/AST/ASTContext.h"
     13 #include "clang/AST/DeclCXX.h"
     14 #include "clang/AST/DeclGroup.h"
     15 #include "clang/AST/RecursiveASTVisitor.h"
     16 #include "clang/Basic/Diagnostic.h"
     17 #include "clang/Basic/DiagnosticOptions.h"
     18 #include "clang/Basic/FileManager.h"
     19 #include "clang/Basic/LangOptions.h"
     20 #include "clang/Basic/SourceManager.h"
     21 #include "clang/Frontend/CompilerInstance.h"
     22 #include "clang/Frontend/FrontendAction.h"
     23 #include "clang/Frontend/TextDiagnosticPrinter.h"
     24 #include "clang/Rewrite/Core/Rewriter.h"
     25 #include "clang/Tooling/Refactoring.h"
     26 #include "clang/Tooling/Tooling.h"
     27 #include "llvm/ADT/SmallString.h"
     28 #include "llvm/Support/Path.h"
     29 #include "gtest/gtest.h"
     30 
     31 namespace clang {
     32 namespace tooling {
     33 
     34 class 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 
     44 TEST_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 
     52 TEST_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 
     60 TEST_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 
     68 TEST_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 
     77 TEST_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 
     93 TEST_F(ReplacementTest, ApplyFailsForNonExistentLocation) {
     94   Replacement Replace("nonexistent-file.cpp", 0, 1, "");
     95   EXPECT_FALSE(Replace.apply(Context.Rewrite));
     96 }
     97 
     98 TEST_F(ReplacementTest, CanRetrivePath) {
     99   Replacement Replace("/path/to/file.cpp", 0, 1, "");
    100   EXPECT_EQ("/path/to/file.cpp", Replace.getFilePath());
    101 }
    102 
    103 TEST_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 
    111 TEST_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 
    123 TEST_F(ReplacementTest, SkipsDuplicateReplacements) {
    124   FileID ID = Context.createInMemoryFile("input.cpp",
    125                                          "line1\nline2\nline3\nline4");
    126   Replacements Replaces;
    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   Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
    132                               5, "replaced"));
    133   EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
    134   EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
    135 }
    136 
    137 TEST_F(ReplacementTest, ApplyAllFailsIfOneApplyFails) {
    138   // This test depends on the value of the file name of an invalid source
    139   // location being in the range ]a, z[.
    140   FileID IDa = Context.createInMemoryFile("a.cpp", "text");
    141   FileID IDz = Context.createInMemoryFile("z.cpp", "text");
    142   Replacements Replaces;
    143   Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDa, 1, 1),
    144                               4, "a"));
    145   Replaces.insert(Replacement(Context.Sources, SourceLocation(),
    146                               5, "2"));
    147   Replaces.insert(Replacement(Context.Sources, Context.getLocation(IDz, 1, 1),
    148                               4, "z"));
    149   EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
    150   EXPECT_EQ("a", Context.getRewrittenText(IDa));
    151   EXPECT_EQ("z", Context.getRewrittenText(IDz));
    152 }
    153 
    154 TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
    155   Replacements Replaces;
    156   Replaces.insert(Replacement("", 0, 1, ""));
    157   Replaces.insert(Replacement("", 4, 3, " "));
    158   // Assume ' int   i;' is turned into 'int i;' and cursor is located at '|'.
    159   EXPECT_EQ(0u, shiftedCodePosition(Replaces, 0)); // |int   i;
    160   EXPECT_EQ(0u, shiftedCodePosition(Replaces, 1)); //  |nt   i;
    161   EXPECT_EQ(1u, shiftedCodePosition(Replaces, 2)); //  i|t   i;
    162   EXPECT_EQ(2u, shiftedCodePosition(Replaces, 3)); //  in|   i;
    163   EXPECT_EQ(3u, shiftedCodePosition(Replaces, 4)); //  int|  i;
    164   EXPECT_EQ(4u, shiftedCodePosition(Replaces, 5)); //  int | i;
    165   EXPECT_EQ(4u, shiftedCodePosition(Replaces, 6)); //  int  |i;
    166   EXPECT_EQ(4u, shiftedCodePosition(Replaces, 7)); //  int   |;
    167   EXPECT_EQ(5u, shiftedCodePosition(Replaces, 8)); //  int   i|
    168 }
    169 
    170 TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
    171   Replacements Replaces;
    172   Replaces.insert(Replacement("", 4, 0, "\"\n\""));
    173   // Assume '"12345678"' is turned into '"1234"\n"5678"'.
    174   EXPECT_EQ(4u, shiftedCodePosition(Replaces, 4)); // "123|5678"
    175   EXPECT_EQ(8u, shiftedCodePosition(Replaces, 5)); // "1234|678"
    176 }
    177 
    178 class FlushRewrittenFilesTest : public ::testing::Test {
    179 public:
    180    FlushRewrittenFilesTest() {}
    181 
    182   ~FlushRewrittenFilesTest() {
    183     for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
    184                                                 E = TemporaryFiles.end();
    185          I != E; ++I) {
    186       llvm::StringRef Name = I->second;
    187       llvm::error_code EC = llvm::sys::fs::remove(Name);
    188       (void)EC;
    189       assert(!EC);
    190     }
    191   }
    192 
    193   FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
    194     SmallString<1024> Path;
    195     int FD;
    196     llvm::error_code EC =
    197         llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
    198     assert(!EC);
    199     (void)EC;
    200 
    201     llvm::raw_fd_ostream OutStream(FD, true);
    202     OutStream << Content;
    203     OutStream.close();
    204     const FileEntry *File = Context.Files.getFile(Path);
    205     assert(File != NULL);
    206 
    207     StringRef Found = TemporaryFiles.GetOrCreateValue(Name, Path.str()).second;
    208     assert(Found == Path);
    209     (void)Found;
    210     return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
    211   }
    212 
    213   std::string getFileContentFromDisk(llvm::StringRef Name) {
    214     std::string Path = TemporaryFiles.lookup(Name);
    215     assert(!Path.empty());
    216     // We need to read directly from the FileManager without relaying through
    217     // a FileEntry, as otherwise we'd read through an already opened file
    218     // descriptor, which might not see the changes made.
    219     // FIXME: Figure out whether there is a way to get the SourceManger to
    220     // reopen the file.
    221     return Context.Files.getBufferForFile(Path, NULL)->getBuffer();
    222   }
    223 
    224   llvm::StringMap<std::string> TemporaryFiles;
    225   RewriterTestContext Context;
    226 };
    227 
    228 TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
    229   FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
    230   Replacements Replaces;
    231   Replaces.insert(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
    232                               5, "replaced"));
    233   EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
    234   EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
    235   EXPECT_EQ("line1\nreplaced\nline3\nline4",
    236             getFileContentFromDisk("input.cpp"));
    237 }
    238 
    239 namespace {
    240 template <typename T>
    241 class TestVisitor : public clang::RecursiveASTVisitor<T> {
    242 public:
    243   bool runOver(StringRef Code) {
    244     return runToolOnCode(new TestAction(this), Code);
    245   }
    246 
    247 protected:
    248   clang::SourceManager *SM;
    249 
    250 private:
    251   class FindConsumer : public clang::ASTConsumer {
    252   public:
    253     FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
    254 
    255     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
    256       Visitor->TraverseDecl(Context.getTranslationUnitDecl());
    257     }
    258 
    259   private:
    260     TestVisitor *Visitor;
    261   };
    262 
    263   class TestAction : public clang::ASTFrontendAction {
    264   public:
    265     TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
    266 
    267     virtual clang::ASTConsumer* CreateASTConsumer(
    268         clang::CompilerInstance& compiler, llvm::StringRef dummy) {
    269       Visitor->SM = &compiler.getSourceManager();
    270       /// TestConsumer will be deleted by the framework calling us.
    271       return new FindConsumer(Visitor);
    272     }
    273 
    274   private:
    275     TestVisitor *Visitor;
    276   };
    277 };
    278 } // end namespace
    279 
    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 
    288 class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
    289 public:
    290   bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
    291     if (Record->getName() == "X") {
    292       Replace = Replacement(*SM, Record, "");
    293     }
    294     return true;
    295   }
    296   Replacement Replace;
    297 };
    298 
    299 TEST(Replacement, CanBeConstructedFromNode) {
    300   ClassDeclXVisitor ClassDeclX;
    301   EXPECT_TRUE(ClassDeclX.runOver("     class X;"));
    302   expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
    303 }
    304 
    305 TEST(Replacement, ReplacesAtSpellingLocation) {
    306   ClassDeclXVisitor ClassDeclX;
    307   EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
    308   expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
    309 }
    310 
    311 class CallToFVisitor : public TestVisitor<CallToFVisitor> {
    312 public:
    313   bool VisitCallExpr(CallExpr *Call) {
    314     if (Call->getDirectCallee()->getName() == "F") {
    315       Replace = Replacement(*SM, Call, "");
    316     }
    317     return true;
    318   }
    319   Replacement Replace;
    320 };
    321 
    322 TEST(Replacement, FunctionCall) {
    323   CallToFVisitor CallToF;
    324   EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
    325   expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
    326 }
    327 
    328 TEST(Replacement, TemplatedFunctionCall) {
    329   CallToFVisitor CallToF;
    330   EXPECT_TRUE(CallToF.runOver(
    331         "template <typename T> void F(); void G() { F<int>(); }"));
    332   expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
    333 }
    334 
    335 TEST(Range, overlaps) {
    336   EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
    337   EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
    338   EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
    339   EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
    340   EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
    341 }
    342 
    343 TEST(Range, contains) {
    344   EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
    345   EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
    346   EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
    347   EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
    348 }
    349 
    350 } // end namespace tooling
    351 } // end namespace clang
    352