Home | History | Annotate | Download | only in Core
      1 //===--- Replacement.cpp - Framework for clang refactoring tools ----------===//
      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 //  Implements classes to support/store refactorings.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Basic/Diagnostic.h"
     15 #include "clang/Basic/DiagnosticIDs.h"
     16 #include "clang/Basic/DiagnosticOptions.h"
     17 #include "clang/Basic/FileManager.h"
     18 #include "clang/Basic/SourceManager.h"
     19 #include "clang/Lex/Lexer.h"
     20 #include "clang/Rewrite/Core/Rewriter.h"
     21 #include "clang/Tooling/Core/Replacement.h"
     22 #include "llvm/Support/FileSystem.h"
     23 #include "llvm/Support/Path.h"
     24 #include "llvm/Support/raw_os_ostream.h"
     25 
     26 namespace clang {
     27 namespace tooling {
     28 
     29 static const char * const InvalidLocation = "";
     30 
     31 Replacement::Replacement()
     32   : FilePath(InvalidLocation) {}
     33 
     34 Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
     35                          StringRef ReplacementText)
     36     : FilePath(FilePath), ReplacementRange(Offset, Length),
     37       ReplacementText(ReplacementText) {}
     38 
     39 Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
     40                          unsigned Length, StringRef ReplacementText) {
     41   setFromSourceLocation(Sources, Start, Length, ReplacementText);
     42 }
     43 
     44 Replacement::Replacement(const SourceManager &Sources,
     45                          const CharSourceRange &Range,
     46                          StringRef ReplacementText) {
     47   setFromSourceRange(Sources, Range, ReplacementText);
     48 }
     49 
     50 bool Replacement::isApplicable() const {
     51   return FilePath != InvalidLocation;
     52 }
     53 
     54 bool Replacement::apply(Rewriter &Rewrite) const {
     55   SourceManager &SM = Rewrite.getSourceMgr();
     56   const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
     57   if (!Entry)
     58     return false;
     59   FileID ID;
     60   // FIXME: Use SM.translateFile directly.
     61   SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
     62   ID = Location.isValid() ?
     63     SM.getFileID(Location) :
     64     SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
     65   // FIXME: We cannot check whether Offset + Length is in the file, as
     66   // the remapping API is not public in the RewriteBuffer.
     67   const SourceLocation Start =
     68     SM.getLocForStartOfFile(ID).
     69     getLocWithOffset(ReplacementRange.getOffset());
     70   // ReplaceText returns false on success.
     71   // ReplaceText only fails if the source location is not a file location, in
     72   // which case we already returned false earlier.
     73   bool RewriteSucceeded = !Rewrite.ReplaceText(
     74       Start, ReplacementRange.getLength(), ReplacementText);
     75   assert(RewriteSucceeded);
     76   return RewriteSucceeded;
     77 }
     78 
     79 std::string Replacement::toString() const {
     80   std::string result;
     81   llvm::raw_string_ostream stream(result);
     82   stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
     83          << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
     84   return result;
     85 }
     86 
     87 bool operator<(const Replacement &LHS, const Replacement &RHS) {
     88   if (LHS.getOffset() != RHS.getOffset())
     89     return LHS.getOffset() < RHS.getOffset();
     90   if (LHS.getLength() != RHS.getLength())
     91     return LHS.getLength() < RHS.getLength();
     92   if (LHS.getFilePath() != RHS.getFilePath())
     93     return LHS.getFilePath() < RHS.getFilePath();
     94   return LHS.getReplacementText() < RHS.getReplacementText();
     95 }
     96 
     97 bool operator==(const Replacement &LHS, const Replacement &RHS) {
     98   return LHS.getOffset() == RHS.getOffset() &&
     99          LHS.getLength() == RHS.getLength() &&
    100          LHS.getFilePath() == RHS.getFilePath() &&
    101          LHS.getReplacementText() == RHS.getReplacementText();
    102 }
    103 
    104 void Replacement::setFromSourceLocation(const SourceManager &Sources,
    105                                         SourceLocation Start, unsigned Length,
    106                                         StringRef ReplacementText) {
    107   const std::pair<FileID, unsigned> DecomposedLocation =
    108       Sources.getDecomposedLoc(Start);
    109   const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
    110   if (Entry) {
    111     // Make FilePath absolute so replacements can be applied correctly when
    112     // relative paths for files are used.
    113     llvm::SmallString<256> FilePath(Entry->getName());
    114     std::error_code EC = llvm::sys::fs::make_absolute(FilePath);
    115     this->FilePath = EC ? FilePath.c_str() : Entry->getName();
    116   } else {
    117     this->FilePath = InvalidLocation;
    118   }
    119   this->ReplacementRange = Range(DecomposedLocation.second, Length);
    120   this->ReplacementText = ReplacementText;
    121 }
    122 
    123 // FIXME: This should go into the Lexer, but we need to figure out how
    124 // to handle ranges for refactoring in general first - there is no obvious
    125 // good way how to integrate this into the Lexer yet.
    126 static int getRangeSize(const SourceManager &Sources,
    127                         const CharSourceRange &Range) {
    128   SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
    129   SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
    130   std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
    131   std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
    132   if (Start.first != End.first) return -1;
    133   if (Range.isTokenRange())
    134     End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources,
    135                                             LangOptions());
    136   return End.second - Start.second;
    137 }
    138 
    139 void Replacement::setFromSourceRange(const SourceManager &Sources,
    140                                      const CharSourceRange &Range,
    141                                      StringRef ReplacementText) {
    142   setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
    143                         getRangeSize(Sources, Range), ReplacementText);
    144 }
    145 
    146 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
    147   unsigned NewPosition = Position;
    148   for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
    149        ++I) {
    150     if (I->getOffset() >= Position)
    151       break;
    152     if (I->getOffset() + I->getLength() > Position)
    153       NewPosition += I->getOffset() + I->getLength() - Position;
    154     NewPosition += I->getReplacementText().size() - I->getLength();
    155   }
    156   return NewPosition;
    157 }
    158 
    159 // FIXME: Remove this function when Replacements is implemented as std::vector
    160 // instead of std::set.
    161 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
    162                              unsigned Position) {
    163   unsigned NewPosition = Position;
    164   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
    165                                                 E = Replaces.end();
    166        I != E; ++I) {
    167     if (I->getOffset() >= Position)
    168       break;
    169     if (I->getOffset() + I->getLength() > Position)
    170       NewPosition += I->getOffset() + I->getLength() - Position;
    171     NewPosition += I->getReplacementText().size() - I->getLength();
    172   }
    173   return NewPosition;
    174 }
    175 
    176 void deduplicate(std::vector<Replacement> &Replaces,
    177                  std::vector<Range> &Conflicts) {
    178   if (Replaces.empty())
    179     return;
    180 
    181   auto LessNoPath = [](const Replacement &LHS, const Replacement &RHS) {
    182     if (LHS.getOffset() != RHS.getOffset())
    183       return LHS.getOffset() < RHS.getOffset();
    184     if (LHS.getLength() != RHS.getLength())
    185       return LHS.getLength() < RHS.getLength();
    186     return LHS.getReplacementText() < RHS.getReplacementText();
    187   };
    188 
    189   auto EqualNoPath = [](const Replacement &LHS, const Replacement &RHS) {
    190     return LHS.getOffset() == RHS.getOffset() &&
    191            LHS.getLength() == RHS.getLength() &&
    192            LHS.getReplacementText() == RHS.getReplacementText();
    193   };
    194 
    195   // Deduplicate. We don't want to deduplicate based on the path as we assume
    196   // that all replacements refer to the same file (or are symlinks).
    197   std::sort(Replaces.begin(), Replaces.end(), LessNoPath);
    198   Replaces.erase(std::unique(Replaces.begin(), Replaces.end(), EqualNoPath),
    199                  Replaces.end());
    200 
    201   // Detect conflicts
    202   Range ConflictRange(Replaces.front().getOffset(),
    203                       Replaces.front().getLength());
    204   unsigned ConflictStart = 0;
    205   unsigned ConflictLength = 1;
    206   for (unsigned i = 1; i < Replaces.size(); ++i) {
    207     Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
    208     if (ConflictRange.overlapsWith(Current)) {
    209       // Extend conflicted range
    210       ConflictRange = Range(ConflictRange.getOffset(),
    211                             std::max(ConflictRange.getLength(),
    212                                      Current.getOffset() + Current.getLength() -
    213                                          ConflictRange.getOffset()));
    214       ++ConflictLength;
    215     } else {
    216       if (ConflictLength > 1)
    217         Conflicts.push_back(Range(ConflictStart, ConflictLength));
    218       ConflictRange = Current;
    219       ConflictStart = i;
    220       ConflictLength = 1;
    221     }
    222   }
    223 
    224   if (ConflictLength > 1)
    225     Conflicts.push_back(Range(ConflictStart, ConflictLength));
    226 }
    227 
    228 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
    229   bool Result = true;
    230   for (Replacements::const_iterator I = Replaces.begin(),
    231                                     E = Replaces.end();
    232        I != E; ++I) {
    233     if (I->isApplicable()) {
    234       Result = I->apply(Rewrite) && Result;
    235     } else {
    236       Result = false;
    237     }
    238   }
    239   return Result;
    240 }
    241 
    242 // FIXME: Remove this function when Replacements is implemented as std::vector
    243 // instead of std::set.
    244 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
    245                           Rewriter &Rewrite) {
    246   bool Result = true;
    247   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
    248                                                 E = Replaces.end();
    249        I != E; ++I) {
    250     if (I->isApplicable()) {
    251       Result = I->apply(Rewrite) && Result;
    252     } else {
    253       Result = false;
    254     }
    255   }
    256   return Result;
    257 }
    258 
    259 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
    260   FileManager Files((FileSystemOptions()));
    261   DiagnosticsEngine Diagnostics(
    262       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
    263       new DiagnosticOptions);
    264   SourceManager SourceMgr(Diagnostics, Files);
    265   Rewriter Rewrite(SourceMgr, LangOptions());
    266   std::unique_ptr<llvm::MemoryBuffer> Buf =
    267       llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
    268   const clang::FileEntry *Entry =
    269       Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
    270   SourceMgr.overrideFileContents(Entry, std::move(Buf));
    271   FileID ID =
    272       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
    273   for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
    274        I != E; ++I) {
    275     Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
    276                         I->getReplacementText());
    277     if (!Replace.apply(Rewrite))
    278       return "";
    279   }
    280   std::string Result;
    281   llvm::raw_string_ostream OS(Result);
    282   Rewrite.getEditBuffer(ID).write(OS);
    283   OS.flush();
    284   return Result;
    285 }
    286 
    287 } // end namespace tooling
    288 } // end namespace clang
    289 
    290