clang  3.9.0
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 
17 #include "clang/Format/Format.h"
19 #include "clang/Lex/Lexer.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/raw_os_ostream.h"
25 
26 namespace clang {
27 namespace tooling {
28 
30  const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths,
31  std::shared_ptr<PCHContainerOperations> PCHContainerOps)
32  : ClangTool(Compilations, SourcePaths, PCHContainerOps) {}
33 
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 
50  if (!applyAllReplacements(Rewrite)) {
51  llvm::errs() << "Skipped some replacements.\n";
52  }
53 
54  return saveRewrittenFiles(Rewrite);
55 }
56 
58  return tooling::applyAllReplacements(Replace, Rewrite);
59 }
60 
61 int RefactoringTool::saveRewrittenFiles(Rewriter &Rewrite) {
62  return Rewrite.overwriteChangedFiles() ? 1 : 0;
63 }
64 
66  Rewriter &Rewrite, StringRef Style) {
67  SourceManager &SM = Rewrite.getSourceMgr();
68  FileManager &Files = SM.getFileManager();
69 
70  auto FileToReplaces = groupReplacementsByFile(Replaces);
71 
72  bool Result = true;
73  for (const auto &FileAndReplaces : FileToReplaces) {
74  const std::string &FilePath = FileAndReplaces.first;
75  auto &CurReplaces = FileAndReplaces.second;
76 
77  const FileEntry *Entry = Files.getFile(FilePath);
79  StringRef Code = SM.getBufferData(ID);
80 
81  format::FormatStyle CurStyle = format::getStyle(Style, FilePath, "LLVM");
82  auto NewReplacements =
83  format::formatReplacements(Code, CurReplaces, CurStyle);
84  if (!NewReplacements) {
85  llvm::errs() << llvm::toString(NewReplacements.takeError()) << "\n";
86  return false;
87  }
88  Result = applyAllReplacements(*NewReplacements, Rewrite) && Result;
89  }
90  return Result;
91 }
92 
93 } // end namespace tooling
94 } // end namespace clang
FormatStyle getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle, vfs::FileSystem *FS=nullptr)
Construct a FormatStyle based on StyleName.
Definition: Format.cpp:1695
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:117
SourceManager & getSourceMgr() const
Definition: Rewriter.h:64
Defines the clang::FileManager interface and associated types.
Replacements & getReplacements()
Returns the set of replacements to which replacements should be added during the run of the tool...
Definition: Refactoring.cpp:34
Defines the SourceManager interface.
std::set< Replacement > Replacements
A set of Replacements.
Definition: Replacement.h:148
Utility to run a FrontendAction over a set of files.
Definition: Tooling.h:284
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite)
Apply all replacements in Replaces to the Rewriter Rewrite.
const StringRef FilePath
Interface to generate clang::FrontendActions.
Definition: Tooling.h:83
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
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:1417
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.
const FormatStyle & Style
Definition: Format.cpp:1311
std::map< std::string, Replacements > groupReplacementsByFile(const Replacements &Replaces)
Groups a random set of replacements by file path.
FileManager & getFiles()
Returns the file manager used in the tool.
Definition: Tooling.h:333
FileManager & getFileManager() const
The result type of a method or function.
bool overwriteChangedFiles()
overwriteChangedFiles - Save all changed files to disk.
Definition: Rewriter.cpp:446
const SourceManager & SM
Definition: Format.cpp:1184
Interface for compilation databases.
int runAndSave(FrontendActionFactory *ActionFactory)
Call run(), apply all generated replacements, and immediately save the results to disk...
Definition: Refactoring.cpp:36
Various functions to configurably format source code.
Options for controlling the compiler diagnostics engine.
const std::string ID
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:46
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
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:57
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:31
bool formatAndApplyAllReplacements(const Replacements &Replaces, 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:65
int run(ToolAction *Action)
Runs an action over all files specified in the command line.
Definition: Tooling.cpp:360
RefactoringTool(const CompilationDatabase &Compilations, ArrayRef< std::string > SourcePaths, std::shared_ptr< PCHContainerOperations > PCHContainerOps=std::make_shared< PCHContainerOperations >())
Definition: Refactoring.cpp:29
This class handles loading and caching of source files into memory.