1 //===--- Refactoring.cpp - Framework for clang refactoring tools ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements tools to support refactorings.
12 //===----------------------------------------------------------------------===//
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"
26 static const char * const InvalidLocation = "";
28 Replacement::Replacement()
29 : FilePath(InvalidLocation), Offset(0), Length(0) {}
31 Replacement::Replacement(StringRef FilePath, unsigned Offset,
32 unsigned Length, StringRef ReplacementText)
33 : FilePath(FilePath), Offset(Offset),
34 Length(Length), ReplacementText(ReplacementText) {}
36 Replacement::Replacement(SourceManager &Sources, SourceLocation Start,
37 unsigned Length, StringRef ReplacementText) {
38 setFromSourceLocation(Sources, Start, Length, ReplacementText);
41 Replacement::Replacement(SourceManager &Sources, const CharSourceRange &Range,
42 StringRef ReplacementText) {
43 setFromSourceRange(Sources, Range, ReplacementText);
46 bool Replacement::isApplicable() const {
47 return FilePath != InvalidLocation;
50 bool Replacement::apply(Rewriter &Rewrite) const {
51 SourceManager &SM = Rewrite.getSourceMgr();
52 const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
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;
74 std::string Replacement::toString() const {
76 llvm::raw_string_ostream stream(result);
77 stream << FilePath << ": " << Offset << ":+" << Length
78 << ":\"" << ReplacementText << "\"";
82 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;
90 void Replacement::setFromSourceLocation(SourceManager &Sources,
91 SourceLocation Start, unsigned Length,
92 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;
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.
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,
114 return End.second - Start.second;
117 void Replacement::setFromSourceRange(SourceManager &Sources,
118 const CharSourceRange &Range,
119 StringRef ReplacementText) {
120 setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
121 getRangeSize(Sources, Range), ReplacementText);
124 bool applyAllReplacements(Replacements &Replaces, Rewriter &Rewrite) {
126 for (Replacements::const_iterator I = Replaces.begin(),
129 if (I->isApplicable()) {
130 Result = I->apply(Rewrite) && Result;
138 RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
139 ArrayRef<std::string> SourcePaths)
140 : ClangTool(Compilations, SourcePaths) {}
142 Replacements &RefactoringTool::getReplacements() { return Replace; }
144 int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
145 if (int Result = run(ActionFactory)) {
149 LangOptions DefaultLangOptions;
150 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
151 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
152 DiagnosticsEngine Diagnostics(
153 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
154 &*DiagOpts, &DiagnosticPrinter, false);
155 SourceManager Sources(Diagnostics, getFiles());
156 Rewriter Rewrite(Sources, DefaultLangOptions);
158 if (!applyAllReplacements(Rewrite)) {
159 llvm::errs() << "Skipped some replacements.\n";
162 return saveRewrittenFiles(Rewrite);
165 bool RefactoringTool::applyAllReplacements(Rewriter &Rewrite) {
166 return tooling::applyAllReplacements(Replace, Rewrite);
169 int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
170 for (Rewriter::buffer_iterator I = Rewrite.buffer_begin(),
171 E = Rewrite.buffer_end();
173 // FIXME: This code is copied from the FixItRewriter.cpp - I think it should
174 // go into directly into Rewriter (there we also have the Diagnostics to
175 // handle the error cases better).
176 const FileEntry *Entry =
177 Rewrite.getSourceMgr().getFileEntryForID(I->first);
178 std::string ErrorInfo;
179 llvm::raw_fd_ostream FileStream(
180 Entry->getName(), ErrorInfo, llvm::raw_fd_ostream::F_Binary);
181 if (!ErrorInfo.empty())
183 I->second.write(FileStream);
189 } // end namespace tooling
190 } // end namespace clang