blob: c5002ef9fcfccbbd0d371fb29d3d7a4a8489b929 [file] [log] [blame]
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +00001//===--- 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
Douglas Gregor02c23eb2012-10-23 22:26:28 +000014#include "clang/Basic/DiagnosticOptions.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000017#include "clang/Frontend/TextDiagnosticPrinter.h"
18#include "clang/Lex/Lexer.h"
Ted Kremenek305c6132012-09-01 05:09:24 +000019#include "clang/Rewrite/Core/Rewriter.h"
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000020#include "clang/Tooling/Refactoring.h"
21#include "llvm/Support/raw_os_ostream.h"
22
23namespace clang {
24namespace tooling {
25
26static const char * const InvalidLocation = "";
27
28Replacement::Replacement()
29 : FilePath(InvalidLocation), Offset(0), Length(0) {}
30
31Replacement::Replacement(llvm::StringRef FilePath, unsigned Offset,
32 unsigned Length, llvm::StringRef ReplacementText)
33 : FilePath(FilePath), Offset(Offset),
34 Length(Length), ReplacementText(ReplacementText) {}
35
36Replacement::Replacement(SourceManager &Sources, SourceLocation Start,
37 unsigned Length, llvm::StringRef ReplacementText) {
38 setFromSourceLocation(Sources, Start, Length, ReplacementText);
39}
40
41Replacement::Replacement(SourceManager &Sources, const CharSourceRange &Range,
42 llvm::StringRef ReplacementText) {
43 setFromSourceRange(Sources, Range, ReplacementText);
44}
45
46bool Replacement::isApplicable() const {
47 return FilePath != InvalidLocation;
48}
49
50bool 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
Manuel Klimek5d51e882012-05-30 16:04:29 +000074std::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
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +000082bool 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
90void 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.
105static 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
117void 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
124bool 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
138bool 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
158RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
159 ArrayRef<std::string> SourcePaths)
160 : Tool(Compilations, SourcePaths) {}
161
162Replacements &RefactoringTool::getReplacements() { return Replace; }
163
164int RefactoringTool::run(FrontendActionFactory *ActionFactory) {
165 int Result = Tool.run(ActionFactory);
166 LangOptions DefaultLangOptions;
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000167 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
168 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000169 DiagnosticsEngine Diagnostics(
170 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000171 &*DiagOpts, &DiagnosticPrinter, false);
Manuel Klimekf9d4cbd2012-05-23 16:29:20 +0000172 SourceManager Sources(Diagnostics, Tool.getFiles());
173 Rewriter Rewrite(Sources, DefaultLangOptions);
174 if (!applyAllReplacements(Replace, Rewrite)) {
175 llvm::errs() << "Skipped some replacements.\n";
176 }
177 if (!saveRewrittenFiles(Rewrite)) {
178 llvm::errs() << "Could not save rewritten files.\n";
179 return 1;
180 }
181 return Result;
182}
183
184} // end namespace tooling
185} // end namespace clang