clang  14.0.0git
Refactoring.cpp
Go to the documentation of this file.
1 //===--- Refactoring.cpp - Framework for clang refactoring tools ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Implements tools to support refactorings.
10 //
11 //===----------------------------------------------------------------------===//
12 
17 #include "clang/Format/Format.h"
19 #include "clang/Lex/Lexer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_os_ostream.h"
23 
24 namespace clang {
25 namespace tooling {
26 
28  const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths,
29  std::shared_ptr<PCHContainerOperations> PCHContainerOps)
30  : ClangTool(Compilations, SourcePaths, std::move(PCHContainerOps)) {}
31 
32 std::map<std::string, Replacements> &RefactoringTool::getReplacements() {
33  return FileToReplaces;
34 }
35 
37  if (int Result = run(ActionFactory)) {
38  return Result;
39  }
40 
41  LangOptions DefaultLangOptions;
43  TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
44  DiagnosticsEngine Diagnostics(
46  &*DiagOpts, &DiagnosticPrinter, false);
47  SourceManager Sources(Diagnostics, getFiles());
48  Rewriter Rewrite(Sources, DefaultLangOptions);
49 
51  llvm::errs() << "Skipped some replacements.\n";
52  }
53 
54  return saveRewrittenFiles(Rewrite);
55 }
56 
58  bool Result = true;
59  for (const auto &Entry : groupReplacementsByFile(
60  Rewrite.getSourceMgr().getFileManager(), FileToReplaces))
61  Result = tooling::applyAllReplacements(Entry.second, Rewrite) && Result;
62  return Result;
63 }
64 
65 int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
66  return Rewrite.overwriteChangedFiles() ? 1 : 0;
67 }
68 
70  const std::map<std::string, Replacements> &FileToReplaces,
71  Rewriter &Rewrite, StringRef Style) {
72  SourceManager &SM = Rewrite.getSourceMgr();
73  FileManager &Files = SM.getFileManager();
74 
75  bool Result = true;
76  for (const auto &FileAndReplaces : groupReplacementsByFile(
77  Rewrite.getSourceMgr().getFileManager(), FileToReplaces)) {
78  const std::string &FilePath = FileAndReplaces.first;
79  auto &CurReplaces = FileAndReplaces.second;
80 
81  const FileEntry *Entry = nullptr;
82  if (auto File = Files.getFile(FilePath))
83  Entry = *File;
84 
85  FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
86  StringRef Code = SM.getBufferData(ID);
87 
88  auto CurStyle = format::getStyle(Style, FilePath, "LLVM");
89  if (!CurStyle) {
90  llvm::errs() << llvm::toString(CurStyle.takeError()) << "\n";
91  return false;
92  }
93 
94  auto NewReplacements =
95  format::formatReplacements(Code, CurReplaces, *CurStyle);
96  if (!NewReplacements) {
97  llvm::errs() << llvm::toString(NewReplacements.takeError()) << "\n";
98  return false;
99  }
100  Result = applyAllReplacements(*NewReplacements, Rewrite) && Result;
101  }
102  return Result;
103 }
104 
105 } // end namespace tooling
106 } // end namespace clang
clang::tooling::RefactoringTool::getReplacements
std::map< std::string, Replacements > & getReplacements()
Returns the file path to replacements map to which replacements should be added during the run of the...
Definition: Refactoring.cpp:32
clang::DeclaratorContext::File
@ File
clang::tooling::groupReplacementsByFile
std::map< std::string, Replacements > groupReplacementsByFile(FileManager &FileMgr, const std::map< std::string, Replacements > &FileToReplaces)
If there are multiple <File, Replacements> pairs with the same file entry, we only keep one pair and ...
Definition: Replacement.cpp:611
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::format::formatReplacements
llvm::Expected< tooling::Replacements > formatReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Returns the replacements corresponding to applying and formatting Replaces on success; otheriwse,...
Definition: Format.cpp:2801
clang::tooling::ClangTool::run
int run(ToolAction *Action)
Runs an action over all files specified in the command line.
Definition: Tooling.cpp:475
clang::tooling::ClangTool
Utility to run a FrontendAction over a set of files.
Definition: Tooling.h:309
clang::tooling::CompilationDatabase
Interface for compilation databases.
Definition: CompilationDatabase.h:87
clang::TemplateSubstitutionKind::Rewrite
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:191
SourceManager.h
Format.h
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:89
clang::SrcMgr::C_User
@ C_User
Definition: SourceManager.h:79
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:331
clang::tooling::RefactoringTool::runAndSave
int runAndSave(FrontendActionFactory *ActionFactory)
Call run(), apply all generated replacements, and immediately save the results to disk.
Definition: Refactoring.cpp:36
Refactoring.h
clang::tooling::RefactoringTool::RefactoringTool
RefactoringTool(const CompilationDatabase &Compilations, ArrayRef< std::string > SourcePaths, std::shared_ptr< PCHContainerOperations > PCHContainerOps=std::make_shared< PCHContainerOperations >())
Definition: Refactoring.cpp:27
TextDiagnosticPrinter.h
llvm::ArrayRef< std::string >
Lexer.h
clang::tooling::FrontendActionFactory
Interface to generate clang::FrontendActions.
Definition: Tooling.h:99
clang::DiagnosticIDs
Used for handling and querying diagnostic IDs.
Definition: DiagnosticIDs.h:164
clang::format::getStyle
llvm::Expected< FormatStyle > getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code="", llvm::vfs::FileSystem *FS=nullptr, bool AllowUnknownOptions=false)
Construct a FormatStyle based on StyleName.
Definition: Format.cpp:3161
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
std
Definition: Format.h:3899
clang::tooling::ClangTool::getFiles
FileManager & getFiles()
Returns the file manager used in the tool.
Definition: Tooling.h:377
clang::Builtin::ID
ID
Definition: Builtins.h:48
clang
Definition: CalledOnceCheck.h:17
clang::FileManager
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
clang::tooling::formatAndApplyAllReplacements
bool formatAndApplyAllReplacements(const std::map< std::string, Replacements > &FileToReplaces, Rewriter &Rewrite, StringRef Style="file")
Groups Replaces by the file path and applies each group of Replacements on the related file in Rewrit...
Definition: Refactoring.cpp:69
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:40
clang::Rewriter
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:32
clang::TextDiagnosticPrinter
Definition: TextDiagnosticPrinter.h:27
clang::FileManager::getFile
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Definition: FileManager.cpp:196
DiagnosticOptions.h
Rewriter.h
FileManager.h
clang::tooling::applyAllReplacements
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
Definition: Replacement.cpp:567
SM
#define SM(sm)
Definition: Cuda.cpp:78
clang::tooling::RefactoringTool::applyAllReplacements
bool applyAllReplacements(Rewriter &Rewrite)
Apply all stored replacements to the given Rewriter.
Definition: Refactoring.cpp:57
llvm::IntrusiveRefCntPtr
Definition: LLVM.h:47
clang::DiagnosticOptions
Options for controlling the compiler diagnostics engine.
Definition: DiagnosticOptions.h:70