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/FileManager.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Frontend/DiagnosticOptions.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), Offset(0), Length(0) {}
30
Replacement(llvm::StringRef FilePath,unsigned Offset,unsigned Length,llvm::StringRef ReplacementText)31 Replacement::Replacement(llvm::StringRef FilePath, unsigned Offset,
32 unsigned Length, llvm::StringRef ReplacementText)
33 : FilePath(FilePath), Offset(Offset),
34 Length(Length), ReplacementText(ReplacementText) {}
35
Replacement(SourceManager & Sources,SourceLocation Start,unsigned Length,llvm::StringRef ReplacementText)36 Replacement::Replacement(SourceManager &Sources, SourceLocation Start,
37 unsigned Length, llvm::StringRef ReplacementText) {
38 setFromSourceLocation(Sources, Start, Length, ReplacementText);
39 }
40
Replacement(SourceManager & Sources,const CharSourceRange & Range,llvm::StringRef ReplacementText)41 Replacement::Replacement(SourceManager &Sources, const CharSourceRange &Range,
42 llvm::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(Offset);
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(Start, Length, ReplacementText);
70 assert(RewriteSucceeded);
71 return RewriteSucceeded;
72 }
73
toString() const74 std::string Replacement::toString() const {
75 std::string result;
76 llvm::raw_string_ostream stream(result);
77 stream << FilePath << ": " << Offset << ":+" << Length
78 << ":\"" << ReplacementText << "\"";
79 return result;
80 }
81
operator ()(const Replacement & R1,const Replacement & R2) const82 bool Replacement::Less::operator()(const Replacement &R1,
83 const Replacement &R2) const {
84 if (R1.FilePath != R2.FilePath) return R1.FilePath < R2.FilePath;
85 if (R1.Offset != R2.Offset) return R1.Offset < R2.Offset;
86 if (R1.Length != R2.Length) return R1.Length < R2.Length;
87 return R1.ReplacementText < R2.ReplacementText;
88 }
89
setFromSourceLocation(SourceManager & Sources,SourceLocation Start,unsigned Length,llvm::StringRef ReplacementText)90 void Replacement::setFromSourceLocation(SourceManager &Sources,
91 SourceLocation Start, unsigned Length,
92 llvm::StringRef ReplacementText) {
93 const std::pair<FileID, unsigned> DecomposedLocation =
94 Sources.getDecomposedLoc(Start);
95 const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
96 this->FilePath = Entry != NULL ? Entry->getName() : InvalidLocation;
97 this->Offset = DecomposedLocation.second;
98 this->Length = Length;
99 this->ReplacementText = ReplacementText;
100 }
101
102 // FIXME: This should go into the Lexer, but we need to figure out how
103 // to handle ranges for refactoring in general first - there is no obvious
104 // good way how to integrate this into the Lexer yet.
getRangeSize(SourceManager & Sources,const CharSourceRange & Range)105 static int getRangeSize(SourceManager &Sources, const CharSourceRange &Range) {
106 SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
107 SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
108 std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
109 std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
110 if (Start.first != End.first) return -1;
111 if (Range.isTokenRange())
112 End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources,
113 LangOptions());
114 return End.second - Start.second;
115 }
116
setFromSourceRange(SourceManager & Sources,const CharSourceRange & Range,llvm::StringRef ReplacementText)117 void Replacement::setFromSourceRange(SourceManager &Sources,
118 const CharSourceRange &Range,
119 llvm::StringRef ReplacementText) {
120 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
121 getRangeSize(Sources, Range), ReplacementText);
122 }
123
applyAllReplacements(Replacements & Replaces,Rewriter & Rewrite)124 bool applyAllReplacements(Replacements &Replaces, Rewriter &Rewrite) {
125 bool Result = true;
126 for (Replacements::const_iterator I = Replaces.begin(),
127 E = Replaces.end();
128 I != E; ++I) {
129 if (I->isApplicable()) {
130 Result = I->apply(Rewrite) && Result;
131 } else {
132 Result = false;
133 }
134 }
135 return Result;
136 }
137
saveRewrittenFiles(Rewriter & Rewrite)138 bool saveRewrittenFiles(Rewriter &Rewrite) {
139 for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
140 E = Rewrite.buffer_end();
141 I != E; ++I) {
142 // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
143 // go into directly into Rewriter (there we also have the Diagnostics to
144 // handle the error cases better).
145 const FileEntry *Entry =
146 Rewrite.getSourceMgr().getFileEntryForID(I->first);
147 std::string ErrorInfo;
148 llvm::raw_fd_ostream FileStream(
149 Entry->getName(), ErrorInfo, llvm::raw_fd_ostream::F_Binary);
150 if (!ErrorInfo.empty())
151 return false;
152 I->second.write(FileStream);
153 FileStream.flush();
154 }
155 return true;
156 }
157
RefactoringTool(const CompilationDatabase & Compilations,ArrayRef<std::string> SourcePaths)158 RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
159 ArrayRef<std::string> SourcePaths)
160 : Tool(Compilations, SourcePaths) {}
161
getReplacements()162 Replacements &RefactoringTool::getReplacements() { return Replace; }
163
run(FrontendActionFactory * ActionFactory)164 int RefactoringTool::run(FrontendActionFactory *ActionFactory) {
165 int Result = Tool.run(ActionFactory);
166 LangOptions DefaultLangOptions;
167 DiagnosticOptions DefaultDiagnosticOptions;
168 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(),
169 DefaultDiagnosticOptions);
170 DiagnosticsEngine Diagnostics(
171 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
172 &DiagnosticPrinter, false);
173 SourceManager Sources(Diagnostics, Tool.getFiles());
174 Rewriter Rewrite(Sources, DefaultLangOptions);
175 if (!applyAllReplacements(Replace, Rewrite)) {
176 llvm::errs() << "Skipped some replacements.\n";
177 }
178 if (!saveRewrittenFiles(Rewrite)) {
179 llvm::errs() << "Could not save rewritten files.\n";
180 return 1;
181 }
182 return Result;
183 }
184
185 } // end namespace tooling
186 } // end namespace clang
187