clang  6.0.0svn
Refactoring.cpp
Go to the documentation of this file.
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 
18 #include "clang/Format/Format.h"
20 #include "clang/Lex/Lexer.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/raw_os_ostream.h"
24 
25 namespace clang {
26 namespace tooling {
27 
29  const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths,
30  std::shared_ptr<PCHContainerOperations> PCHContainerOps)
31  : ClangTool(Compilations, SourcePaths, std::move(PCHContainerOps)) {}
32 
33 std::map<std::string, Replacements> &RefactoringTool::getReplacements() {
34  return FileToReplaces;
35 }
36 
38  if (int Result = run(ActionFactory)) {
39  return Result;
40  }
41 
42  LangOptions DefaultLangOptions;
44  TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
45  DiagnosticsEngine Diagnostics(
47  &*DiagOpts, &DiagnosticPrinter, false);
48  SourceManager Sources(Diagnostics, getFiles());
49  Rewriter Rewrite(Sources, DefaultLangOptions);
50 
51  if (!applyAllReplacements(Rewrite)) {
52  llvm::errs() << "Skipped some replacements.\n";
53  }
54 
55  return saveRewrittenFiles(Rewrite);
56 }
57 
59  bool Result = true;
60  for (const auto &Entry : groupReplacementsByFile(
61  Rewrite.getSourceMgr().getFileManager(), FileToReplaces))
62  Result = tooling::applyAllReplacements(Entry.second, Rewrite) && Result;
63  return Result;
64 }
65 
66 int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
67  return Rewrite.overwriteChangedFiles() ? 1 : 0;
68 }
69 
71  const std::map<std::string, Replacements> &FileToReplaces,
72  Rewriter &Rewrite, StringRef Style) {
73  SourceManager &SM = Rewrite.getSourceMgr();
74  FileManager &Files = SM.getFileManager();
75 
76  bool Result = true;
77  for (const auto &FileAndReplaces : groupReplacementsByFile(
78  Rewrite.getSourceMgr().getFileManager(), FileToReplaces)) {
79  const std::string &FilePath = FileAndReplaces.first;
80  auto &CurReplaces = FileAndReplaces.second;
81 
82  const FileEntry *Entry = Files.getFile(FilePath);
84  StringRef Code = SM.getBufferData(ID);
85 
86  auto CurStyle = format::getStyle(Style, FilePath, "LLVM");
87  if (!CurStyle) {
88  llvm::errs() << llvm::toString(CurStyle.takeError()) << "\n";
89  return false;
90  }
91 
92  auto NewReplacements =
93  format::formatReplacements(Code, CurReplaces, *CurStyle);
94  if (!NewReplacements) {
95  llvm::errs() << llvm::toString(NewReplacements.takeError()) << "\n";
96  return false;
97  }
98  Result = applyAllReplacements(*NewReplacements, Rewrite) && Result;
99  }
100  return Result;
101 }
102 
103 } // end namespace tooling
104 } // end namespace clang
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:116
Defines the clang::FileManager interface and associated types.
Defines the SourceManager interface.
Utility to run a FrontendAction over a set of files.
Definition: Tooling.h:289
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
FileManager & getFileManager() const
Interface to generate clang::FrontendActions.
Definition: Tooling.h:84
llvm::Expected< FormatStyle > getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, StringRef Code="", vfs::FileSystem *FS=nullptr)
Construct a FormatStyle based on StyleName.
Definition: Format.cpp:2119
Definition: Format.h:1900
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
SourceManager & getSourceMgr() const
Definition: Rewriter.h:64
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:147
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:1638
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
FileID getOrCreateFileID(const FileEntry *SourceFile, SrcMgr::CharacteristicKind FileCharacter)
Get the FileID for SourceFile if it exists.
FileManager & getFiles()
Returns the file manager used in the tool.
Definition: Tooling.h:338
bool overwriteChangedFiles()
overwriteChangedFiles - Save all changed files to disk.
Definition: Rewriter.cpp:446
const SourceManager & SM
Definition: Format.cpp:1337
Interface for compilation databases.
int runAndSave(FrontendActionFactory *ActionFactory)
Call run(), apply all generated replacements, and immediately save the results to disk...
Definition: Refactoring.cpp:37
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:70
Various functions to configurably format source code.
Options for controlling the compiler diagnostics engine.
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Dataflow Directional Tag Classes.
Used for handling and querying diagnostic IDs.
std::string toString(const til::SExpr *E)
bool applyAllReplacements(Rewriter &Rewrite)
Apply all stored replacements to the given Rewriter.
Definition: Refactoring.cpp:58
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:31
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 ...
int run(ToolAction *Action)
Runs an action over all files specified in the command line.
Definition: Tooling.cpp:370
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:33
RefactoringTool(const CompilationDatabase &Compilations, ArrayRef< std::string > SourcePaths, std::shared_ptr< PCHContainerOperations > PCHContainerOps=std::make_shared< PCHContainerOperations >())
Definition: Refactoring.cpp:28
This class handles loading and caching of source files into memory.
const FormatStyle & Style