clang 22.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
22namespace clang {
23namespace tooling {
24
26 const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths,
27 std::shared_ptr<PCHContainerOperations> PCHContainerOps)
28 : ClangTool(Compilations, SourcePaths, std::move(PCHContainerOps)) {}
29
30std::map<std::string, Replacements> &RefactoringTool::getReplacements() {
31 return FileToReplaces;
32}
33
35 if (int Result = run(ActionFactory)) {
36 return Result;
37 }
38
39 LangOptions DefaultLangOptions;
40 DiagnosticOptions DiagOpts;
41 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), DiagOpts);
42 DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts,
43 &DiagnosticPrinter, false);
44 SourceManager Sources(Diagnostics, getFiles());
45 Rewriter Rewrite(Sources, DefaultLangOptions);
46
48 llvm::errs() << "Skipped some replacements.\n";
49 }
50
51 return saveRewrittenFiles(Rewrite);
52}
53
55 bool Result = true;
56 for (const auto &Entry : groupReplacementsByFile(
57 Rewrite.getSourceMgr().getFileManager(), FileToReplaces))
59 return Result;
60}
61
62int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
63 return Rewrite.overwriteChangedFiles() ? 1 : 0;
64}
65
67 const std::map<std::string, Replacements> &FileToReplaces,
68 Rewriter &Rewrite, StringRef Style) {
69 SourceManager &SM = Rewrite.getSourceMgr();
70 FileManager &Files = SM.getFileManager();
71
72 bool Result = true;
73 for (const auto &FileAndReplaces : groupReplacementsByFile(
74 Rewrite.getSourceMgr().getFileManager(), FileToReplaces)) {
75 const std::string &FilePath = FileAndReplaces.first;
76 auto &CurReplaces = FileAndReplaces.second;
77
78 FileEntryRef Entry = llvm::cantFail(Files.getFileRef(FilePath));
79 FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
80 StringRef Code = SM.getBufferData(ID);
81
82 auto CurStyle = format::getStyle(Style, FilePath, "LLVM");
83 if (!CurStyle) {
84 llvm::errs() << llvm::toString(CurStyle.takeError()) << "\n";
85 return false;
86 }
87
88 auto NewReplacements =
89 format::formatReplacements(Code, CurReplaces, *CurStyle);
90 if (!NewReplacements) {
91 llvm::errs() << llvm::toString(NewReplacements.takeError()) << "\n";
92 return false;
93 }
94 Result = applyAllReplacements(*NewReplacements, Rewrite) && Result;
95 }
96 return Result;
97}
98
99} // end namespace tooling
100} // end namespace clang
Defines the clang::FileManager interface and associated types.
Various functions to configurably format source code.
#define SM(sm)
Defines the SourceManager interface.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Lookup, cache, and verify the specified file (real or virtual).
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Rewriter - This is the main interface to the rewrite buffers.
Definition Rewriter.h:32
This class handles loading and caching of source files into memory.
int run(ToolAction *Action)
Runs an action over all files specified in the command line.
Definition Tooling.cpp:519
ClangTool(const CompilationDatabase &Compilations, ArrayRef< std::string > SourcePaths, std::shared_ptr< PCHContainerOperations > PCHContainerOps=std::make_shared< PCHContainerOperations >(), IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS=llvm::vfs::getRealFileSystem(), IntrusiveRefCntPtr< FileManager > Files=nullptr)
Constructs a clang tool to run over a list of files.
Definition Tooling.cpp:470
FileManager & getFiles()
Returns the file manager used in the tool.
Definition Tooling.h:382
Interface for compilation databases.
Interface to generate clang::FrontendActions.
Definition Tooling.h:99
bool applyAllReplacements(Rewriter &Rewrite)
Apply all stored replacements to the given Rewriter.
int runAndSave(FrontendActionFactory *ActionFactory)
Call run(), apply all generated replacements, and immediately save the results to disk.
std::map< std::string, Replacements > & getReplacements()
Returns the file path to replacements map to which replacements should be added during the run of the...
RefactoringTool(const CompilationDatabase &Compilations, ArrayRef< std::string > SourcePaths, std::shared_ptr< PCHContainerOperations > PCHContainerOps=std::make_shared< PCHContainerOperations >())
Expected< FormatStyle > getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, StringRef Code, llvm::vfs::FileSystem *FS, bool AllowUnknownOptions, llvm::SourceMgr::DiagHandlerTy DiagHandler)
Definition Format.cpp:4251
Expected< tooling::Replacements > formatReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style)
Definition Format.cpp:3700
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
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...
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 ...
The JSON file list parser is used to communicate input to InstallAPI.
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
Definition Template.h:54
@ Result
The result type of a method or function.
Definition TypeBase.h:905