Refactoring.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #include "clang/Basic/DiagnosticOptions.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Frontend/TextDiagnosticPrinter.h"
  17. #include "clang/Lex/Lexer.h"
  18. #include "clang/Rewrite/Core/Rewriter.h"
  19. #include "clang/Tooling/Refactoring.h"
  20. #include "llvm/Support/FileSystem.h"
  21. #include "llvm/Support/Path.h"
  22. #include "llvm/Support/raw_os_ostream.h"
  23. namespace clang {
  24. namespace tooling {
  25. RefactoringTool::RefactoringTool(
  26. const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths,
  27. std::shared_ptr<PCHContainerOperations> PCHContainerOps)
  28. : ClangTool(Compilations, SourcePaths, PCHContainerOps) {}
  29. Replacements &RefactoringTool::getReplacements() { return Replace; }
  30. int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
  31. if (int Result = run(ActionFactory)) {
  32. return Result;
  33. }
  34. LangOptions DefaultLangOptions;
  35. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  36. TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
  37. DiagnosticsEngine Diagnostics(
  38. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
  39. &*DiagOpts, &DiagnosticPrinter, false);
  40. SourceManager Sources(Diagnostics, getFiles());
  41. Rewriter Rewrite(Sources, DefaultLangOptions);
  42. if (!applyAllReplacements(Rewrite)) {
  43. llvm::errs() << "Skipped some replacements.\n";
  44. }
  45. return saveRewrittenFiles(Rewrite);
  46. }
  47. bool RefactoringTool::applyAllReplacements(Rewriter &Rewrite) {
  48. return tooling::applyAllReplacements(Replace, Rewrite);
  49. }
  50. int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
  51. return Rewrite.overwriteChangedFiles() ? 1 : 0;
  52. }
  53. } // end namespace tooling
  54. } // end namespace clang