1 //===--- Refactoring.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 tools to support refactorings.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Basic/DiagnosticOptions.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/TextDiagnosticPrinter.h"
18 #include "clang/Lex/Lexer.h"
19 #include "clang/Rewrite/Core/Rewriter.h"
20 #include "clang/Tooling/Refactoring.h"
21 #include "llvm/Support/raw_os_ostream.h"
22
23 namespace clang {
24 namespace tooling {
25
26 static const char * const InvalidLocation = "";
27
Replacement()28 Replacement::Replacement()
29 : FilePath(InvalidLocation) {}
30
Replacement(StringRef FilePath,unsigned Offset,unsigned Length,StringRef ReplacementText)31 Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
32 StringRef ReplacementText)
33 : FilePath(FilePath), ReplacementRange(Offset, Length),
34 ReplacementText(ReplacementText) {}
35
Replacement(SourceManager & Sources,SourceLocation Start,unsigned Length,StringRef ReplacementText)36 Replacement::Replacement(SourceManager &Sources, SourceLocation Start,
37 unsigned Length, StringRef ReplacementText) {
38 setFromSourceLocation(Sources, Start, Length, ReplacementText);
39 }
40
Replacement(SourceManager & Sources,const CharSourceRange & Range,StringRef ReplacementText)41 Replacement::Replacement(SourceManager &Sources, const CharSourceRange &Range,
42 StringRef ReplacementText) {
43 setFromSourceRange(Sources, Range, ReplacementText);
44 }
45
isApplicable() const46 bool Replacement::isApplicable() const {
47 return FilePath != InvalidLocation;
48 }
49
apply(Rewriter & Rewrite) const50 bool Replacement::apply(Rewriter &Rewrite) const {
51 SourceManager &SM = Rewrite.getSourceMgr();
52 const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
53 if (Entry == NULL)
54 return false;
55 FileID ID;
56 // FIXME: Use SM.translateFile directly.
57 SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
58 ID = Location.isValid() ?
59 SM.getFileID(Location) :
60 SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
61 // FIXME: We cannot check whether Offset + Length is in the file, as
62 // the remapping API is not public in the RewriteBuffer.
63 const SourceLocation Start =
64 SM.getLocForStartOfFile(ID).
65 getLocWithOffset(ReplacementRange.getOffset());
66 // ReplaceText returns false on success.
67 // ReplaceText only fails if the source location is not a file location, in
68 // which case we already returned false earlier.
69 bool RewriteSucceeded = !Rewrite.ReplaceText(
70 Start, ReplacementRange.getLength(), ReplacementText);
71 assert(RewriteSucceeded);
72 return RewriteSucceeded;
73 }
74
toString() const75 std::string Replacement::toString() const {
76 std::string result;
77 llvm::raw_string_ostream stream(result);
78 stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
79 << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
80 return result;
81 }
82
operator ()(const Replacement & R1,const Replacement & R2) const83 bool Replacement::Less::operator()(const Replacement &R1,
84 const Replacement &R2) const {
85 if (R1.FilePath != R2.FilePath) return R1.FilePath < R2.FilePath;
86 if (R1.ReplacementRange.getOffset() != R2.ReplacementRange.getOffset())
87 return R1.ReplacementRange.getOffset() < R2.ReplacementRange.getOffset();
88 if (R1.ReplacementRange.getLength() != R2.ReplacementRange.getLength())
89 return R1.ReplacementRange.getLength() < R2.ReplacementRange.getLength();
90 return R1.ReplacementText < R2.ReplacementText;
91 }
92
setFromSourceLocation(SourceManager & Sources,SourceLocation Start,unsigned Length,StringRef ReplacementText)93 void Replacement::setFromSourceLocation(SourceManager &Sources,
94 SourceLocation Start, unsigned Length,
95 StringRef ReplacementText) {
96 const std::pair<FileID, unsigned> DecomposedLocation =
97 Sources.getDecomposedLoc(Start);
98 const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
99 this->FilePath = Entry != NULL ? Entry->getName() : InvalidLocation;
100 this->ReplacementRange = Range(DecomposedLocation.second, Length);
101 this->ReplacementText = ReplacementText;
102 }
103
104 // FIXME: This should go into the Lexer, but we need to figure out how
105 // to handle ranges for refactoring in general first - there is no obvious
106 // good way how to integrate this into the Lexer yet.
getRangeSize(SourceManager & Sources,const CharSourceRange & Range)107 static int getRangeSize(SourceManager &Sources, const CharSourceRange &Range) {
108 SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
109 SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
110 std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
111 std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
112 if (Start.first != End.first) return -1;
113 if (Range.isTokenRange())
114 End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources,
115 LangOptions());
116 return End.second - Start.second;
117 }
118
setFromSourceRange(SourceManager & Sources,const CharSourceRange & Range,StringRef ReplacementText)119 void Replacement::setFromSourceRange(SourceManager &Sources,
120 const CharSourceRange &Range,
121 StringRef ReplacementText) {
122 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
123 getRangeSize(Sources, Range), ReplacementText);
124 }
125
applyAllReplacements(const Replacements & Replaces,Rewriter & Rewrite)126 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
127 bool Result = true;
128 for (Replacements::const_iterator I = Replaces.begin(),
129 E = Replaces.end();
130 I != E; ++I) {
131 if (I->isApplicable()) {
132 Result = I->apply(Rewrite) && Result;
133 } else {
134 Result = false;
135 }
136 }
137 return Result;
138 }
139
applyAllReplacements(StringRef Code,const Replacements & Replaces)140 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
141 FileManager Files((FileSystemOptions()));
142 DiagnosticsEngine Diagnostics(
143 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
144 new DiagnosticOptions);
145 Diagnostics.setClient(new TextDiagnosticPrinter(
146 llvm::outs(), &Diagnostics.getDiagnosticOptions()));
147 SourceManager SourceMgr(Diagnostics, Files);
148 Rewriter Rewrite(SourceMgr, LangOptions());
149 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
150 const clang::FileEntry *Entry =
151 Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
152 SourceMgr.overrideFileContents(Entry, Buf);
153 FileID ID =
154 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
155 for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
156 I != E; ++I) {
157 Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
158 I->getReplacementText());
159 if (!Replace.apply(Rewrite))
160 return "";
161 }
162 std::string Result;
163 llvm::raw_string_ostream OS(Result);
164 Rewrite.getEditBuffer(ID).write(OS);
165 OS.flush();
166 return Result;
167 }
168
shiftedCodePosition(const Replacements & Replaces,unsigned Position)169 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
170 unsigned NewPosition = Position;
171 for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
172 ++I) {
173 if (I->getOffset() >= Position)
174 break;
175 if (I->getOffset() + I->getLength() > Position)
176 NewPosition += I->getOffset() + I->getLength() - Position;
177 NewPosition += I->getReplacementText().size() - I->getLength();
178 }
179 return NewPosition;
180 }
181
RefactoringTool(const CompilationDatabase & Compilations,ArrayRef<std::string> SourcePaths)182 RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
183 ArrayRef<std::string> SourcePaths)
184 : ClangTool(Compilations, SourcePaths) {}
185
getReplacements()186 Replacements &RefactoringTool::getReplacements() { return Replace; }
187
runAndSave(FrontendActionFactory * ActionFactory)188 int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
189 if (int Result = run(ActionFactory)) {
190 return Result;
191 }
192
193 LangOptions DefaultLangOptions;
194 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
195 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
196 DiagnosticsEngine Diagnostics(
197 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
198 &*DiagOpts, &DiagnosticPrinter, false);
199 SourceManager Sources(Diagnostics, getFiles());
200 Rewriter Rewrite(Sources, DefaultLangOptions);
201
202 if (!applyAllReplacements(Rewrite)) {
203 llvm::errs() << "Skipped some replacements.\n";
204 }
205
206 return saveRewrittenFiles(Rewrite);
207 }
208
applyAllReplacements(Rewriter & Rewrite)209 bool RefactoringTool::applyAllReplacements(Rewriter &Rewrite) {
210 return tooling::applyAllReplacements(Replace, Rewrite);
211 }
212
saveRewrittenFiles(Rewriter & Rewrite)213 int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
214 for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
215 E = Rewrite.buffer_end();
216 I != E; ++I) {
217 // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
218 // go into directly into Rewriter (there we also have the Diagnostics to
219 // handle the error cases better).
220 const FileEntry *Entry =
221 Rewrite.getSourceMgr().getFileEntryForID(I->first);
222 std::string ErrorInfo;
223 llvm::raw_fd_ostream FileStream(Entry->getName(), ErrorInfo,
224 llvm::sys::fs::F_Binary);
225 if (!ErrorInfo.empty())
226 return 1;
227 I->second.write(FileStream);
228 FileStream.flush();
229 }
230 return 0;
231 }
232
233 } // end namespace tooling
234 } // end namespace clang
235