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/FileSystem.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/raw_os_ostream.h"
24 
25 namespace clang {
26 namespace tooling {
27 
RefactoringTool(const CompilationDatabase & Compilations,ArrayRef<std::string> SourcePaths)28 RefactoringTool::RefactoringTool(const CompilationDatabase &Compilations,
29                                  ArrayRef<std::string> SourcePaths)
30   : ClangTool(Compilations, SourcePaths) {}
31 
getReplacements()32 Replacements &RefactoringTool::getReplacements() { return Replace; }
33 
runAndSave(FrontendActionFactory * ActionFactory)34 int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
35   if (int Result = run(ActionFactory)) {
36     return Result;
37   }
38 
39   LangOptions DefaultLangOptions;
40   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
41   TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
42   DiagnosticsEngine Diagnostics(
43       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
44       &*DiagOpts, &DiagnosticPrinter, false);
45   SourceManager Sources(Diagnostics, getFiles());
46   Rewriter Rewrite(Sources, DefaultLangOptions);
47 
48   if (!applyAllReplacements(Rewrite)) {
49     llvm::errs() << "Skipped some replacements.\n";
50   }
51 
52   return saveRewrittenFiles(Rewrite);
53 }
54 
applyAllReplacements(Rewriter & Rewrite)55 bool RefactoringTool::applyAllReplacements(Rewriter &Rewrite) {
56   return tooling::applyAllReplacements(Replace, Rewrite);
57 }
58 
saveRewrittenFiles(Rewriter & Rewrite)59 int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
60   return Rewrite.overwriteChangedFiles() ? 1 : 0;
61 }
62 
63 } // end namespace tooling
64 } // end namespace clang
65