blob: 78176808f335571595573f017285f6955aa38b05 [file] [log] [blame]
Haojian Wu357ef992016-09-21 13:18:19 +00001//===-- ClangMove.cpp - Implement ClangMove functationalities ---*- C++ -*-===//
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#include "ClangMove.h"
Haojian Wu36265162017-01-03 09:00:51 +000011#include "HelperDeclRefGraph.h"
Haojian Wu357ef992016-09-21 13:18:19 +000012#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Basic/SourceManager.h"
14#include "clang/Format/Format.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Lex/Lexer.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Rewrite/Core/Rewriter.h"
19#include "clang/Tooling/Core/Replacement.h"
Haojian Wu36265162017-01-03 09:00:51 +000020#include "llvm/Support/Debug.h"
Haojian Wud2a6d7b2016-10-04 09:05:31 +000021#include "llvm/Support/Path.h"
Haojian Wu357ef992016-09-21 13:18:19 +000022
Haojian Wu36265162017-01-03 09:00:51 +000023#define DEBUG_TYPE "clang-move"
24
Haojian Wu357ef992016-09-21 13:18:19 +000025using namespace clang::ast_matchers;
26
27namespace clang {
28namespace move {
29namespace {
30
Haojian Wu7bd492c2016-10-14 10:07:58 +000031// FIXME: Move to ASTMatchers.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000032AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
Haojian Wu7bd492c2016-10-14 10:07:58 +000033
Haojian Wue77bcc72016-10-13 10:31:00 +000034AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
35 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000036 const auto *Context = Node.getDeclContext();
37 if (!Context)
38 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000039 while (const auto *NextContext = Context->getParent()) {
40 if (isa<NamespaceDecl>(NextContext) ||
41 isa<TranslationUnitDecl>(NextContext))
42 break;
43 Context = NextContext;
44 }
45 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
46 Builder);
47}
48
49AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
50 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
51 const CXXRecordDecl *Parent = Node.getParent();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000052 if (!Parent)
53 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000054 while (const auto *NextParent =
55 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
56 Parent = NextParent;
57 }
58
59 return InnerMatcher.matches(*Parent, Finder, Builder);
60}
61
Haojian Wud2a6d7b2016-10-04 09:05:31 +000062// Make the Path absolute using the CurrentDir if the Path is not an absolute
63// path. An empty Path will result in an empty string.
64std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
65 if (Path.empty())
66 return "";
67 llvm::SmallString<128> InitialDirectory(CurrentDir);
68 llvm::SmallString<128> AbsolutePath(Path);
69 if (std::error_code EC =
70 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000071 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000072 << '\n';
73 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wuc6f125e2016-10-04 09:49:20 +000074 llvm::sys::path::native(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +000075 return AbsolutePath.str();
76}
77
78// Make the Path absolute using the current working directory of the given
79// SourceManager if the Path is not an absolute path.
80//
81// The Path can be a path relative to the build directory, or retrieved from
82// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000083std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000084 llvm::SmallString<128> AbsolutePath(Path);
85 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000086 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
87 AbsolutePath))
88 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000089 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000090 // Handle symbolic link path cases.
91 // We are trying to get the real file path of the symlink.
92 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000093 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +000094 if (Dir) {
95 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
96 SmallVector<char, 128> AbsoluteFilename;
97 llvm::sys::path::append(AbsoluteFilename, DirName,
98 llvm::sys::path::filename(AbsolutePath.str()));
99 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
100 .str();
101 }
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000102 return AbsolutePath.str();
103}
104
105// Matches AST nodes that are expanded within the given AbsoluteFilePath.
106AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
107 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
108 std::string, AbsoluteFilePath) {
109 auto &SourceManager = Finder->getASTContext().getSourceManager();
110 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
111 if (ExpansionLoc.isInvalid())
112 return false;
113 auto FileEntry =
114 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
115 if (!FileEntry)
116 return false;
117 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
118 AbsoluteFilePath;
119}
120
Haojian Wu357ef992016-09-21 13:18:19 +0000121class FindAllIncludes : public clang::PPCallbacks {
122public:
123 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
124 : SM(*SM), MoveTool(MoveTool) {}
125
126 void InclusionDirective(clang::SourceLocation HashLoc,
127 const clang::Token & /*IncludeTok*/,
128 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000129 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000130 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000131 StringRef SearchPath, StringRef /*RelativePath*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000132 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000133 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000134 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000135 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000136 }
137
138private:
139 const SourceManager &SM;
140 ClangMoveTool *const MoveTool;
141};
142
Haojian Wu4543fec2016-11-16 13:05:19 +0000143class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
144public:
145 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
146 : MoveTool(MoveTool) {}
147
148 void run(const MatchFinder::MatchResult &Result) override {
149 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
150 assert(FD);
151 const clang::NamedDecl *D = FD;
152 if (const auto *FTD = FD->getDescribedFunctionTemplate())
153 D = FTD;
Haojian Wu08e402a2016-12-02 12:39:39 +0000154 MoveTool->getMovedDecls().push_back(D);
Haojian Wu4543fec2016-11-16 13:05:19 +0000155 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
Haojian Wu08e402a2016-12-02 12:39:39 +0000156 MoveTool->addRemovedDecl(D);
Haojian Wu4543fec2016-11-16 13:05:19 +0000157 }
158
159private:
160 ClangMoveTool *MoveTool;
161};
162
Haojian Wu35ca9462016-11-14 14:15:44 +0000163class ClassDeclarationMatch : public MatchFinder::MatchCallback {
164public:
165 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
166 : MoveTool(MoveTool) {}
167 void run(const MatchFinder::MatchResult &Result) override {
168 clang::SourceManager* SM = &Result.Context->getSourceManager();
169 if (const auto *CMD =
170 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
171 MatchClassMethod(CMD, SM);
172 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
173 "class_static_var_decl"))
174 MatchClassStaticVariable(VD, SM);
175 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
176 "moved_class"))
177 MatchClassDeclaration(CD, SM);
178 }
179
180private:
181 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
182 clang::SourceManager* SM) {
183 // Skip inline class methods. isInline() ast matcher doesn't ignore this
184 // case.
185 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000186 MoveTool->getMovedDecls().push_back(CMD);
187 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000188 // Get template class method from its method declaration as
189 // UnremovedDecls stores template class method.
190 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
191 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
192 else
193 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
194 }
195 }
196
197 void MatchClassStaticVariable(const clang::NamedDecl *VD,
198 clang::SourceManager* SM) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000199 MoveTool->getMovedDecls().push_back(VD);
200 MoveTool->addRemovedDecl(VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000201 MoveTool->getUnremovedDeclsInOldHeader().erase(VD);
202 }
203
204 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
205 clang::SourceManager* SM) {
206 // Get class template from its class declaration as UnremovedDecls stores
207 // class template.
208 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000209 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000210 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000211 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000212 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000213 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000214 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000215 }
216
217 ClangMoveTool *MoveTool;
218};
219
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000220// Expand to get the end location of the line where the EndLoc of the given
221// Decl.
222SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000223getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000224 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000225 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wudc4edba2016-12-13 15:35:47 +0000226 auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
227 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000228 // Try to load the file buffer.
229 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000230 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000231 if (InvalidTemp)
232 return SourceLocation();
233
234 const char *TokBegin = File.data() + LocInfo.second;
235 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000236 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000237 TokBegin, File.end());
238
239 llvm::SmallVector<char, 16> Line;
240 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
241 Lex.setParsingPreprocessorDirective(true);
242 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000243 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000244 // If we already reach EOF, just return the EOF SourceLocation;
245 // otherwise, move 1 offset ahead to include the trailing newline character
246 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000247 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000248 ? EndLoc
249 : EndLoc.getLocWithOffset(1);
250}
251
252// Get full range of a Decl including the comments associated with it.
253clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000254getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000255 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000256 const auto &SM = D->getASTContext().getSourceManager();
257 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
258 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000259 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000260 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000261 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000262 Full.setEnd(Comment->getLocEnd());
263 // FIXME: Don't delete a preceding comment, if there are no other entities
264 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000265 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000266 Full.setBegin(Comment->getLocStart());
267 }
268
269 return clang::CharSourceRange::getCharRange(Full);
270}
271
Haojian Wu08e402a2016-12-02 12:39:39 +0000272std::string getDeclarationSourceText(const clang::Decl *D) {
273 const auto &SM = D->getASTContext().getSourceManager();
274 llvm::StringRef SourceText =
275 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000276 return SourceText.str();
277}
278
Haojian Wu08e402a2016-12-02 12:39:39 +0000279bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000280 llvm::StringRef OriginalRunningDirectory,
281 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000282 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000283 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000284 return false;
285 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
286 if (ExpansionLoc.isInvalid())
287 return false;
288
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000289 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
290 return MakeAbsolutePath(SM, FE->getName()) ==
291 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
292 }
Haojian Wu357ef992016-09-21 13:18:19 +0000293
294 return false;
295}
296
Haojian Wu08e402a2016-12-02 12:39:39 +0000297std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000298 std::vector<std::string> Namespaces;
299 for (const auto *Context = D->getDeclContext(); Context;
300 Context = Context->getParent()) {
301 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
302 llvm::isa<clang::LinkageSpecDecl>(Context))
303 break;
304
305 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
306 Namespaces.push_back(ND->getName().str());
307 }
308 std::reverse(Namespaces.begin(), Namespaces.end());
309 return Namespaces;
310}
311
Haojian Wu357ef992016-09-21 13:18:19 +0000312clang::tooling::Replacements
313createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000314 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000315 llvm::StringRef FileName, bool IsHeader = false,
316 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000317 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000318 std::string GuardName(FileName);
319 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000320 for (size_t i = 0; i < GuardName.size(); ++i) {
321 if (!isAlphanumeric(GuardName[i]))
322 GuardName[i] = '_';
323 }
Haojian Wu220c7552016-10-14 13:01:36 +0000324 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000325 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000326 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000327 }
Haojian Wu357ef992016-09-21 13:18:19 +0000328
Haojian Wu48ac3042016-11-23 10:04:19 +0000329 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000330 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000331 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000332 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000333
Haojian Wu53eab1e2016-10-14 13:43:49 +0000334 if (!Includes.empty())
335 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000336
337 // Add moved class definition and its related declarations. All declarations
338 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000339 //
340 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000341 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000342 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000343 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000344 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000345 auto CurrentIt = CurrentNamespaces.begin();
346 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000347 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000348 while (CurrentIt != CurrentNamespaces.end() &&
349 DeclIt != DeclNamespaces.end()) {
350 if (*CurrentIt != *DeclIt)
351 break;
352 ++CurrentIt;
353 ++DeclIt;
354 }
Haojian Wu53315a72016-11-15 09:06:59 +0000355 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
356 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000357 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
358 CurrentIt);
359 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000360
361
362 // End with CurrentNamespace.
363 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000364 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
365 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
366 --RemainingSize, ++It) {
367 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000368 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000369 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000370 }
Haojian Wu53315a72016-11-15 09:06:59 +0000371 // Add trailing '\n' after the nested namespace definition.
372 if (HasEndCurrentNamespace)
373 NewCode += "\n";
374
375 // If the moved declaration is not in CurrentNamespace, add extra namespace
376 // definitions.
377 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000378 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000379 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000380 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000381 ++DeclIt;
382 }
Haojian Wu53315a72016-11-15 09:06:59 +0000383 // If the moved declaration is in same namespace CurrentNamespace, add
384 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000385 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000386 if (!IsInNewNamespace)
387 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000388 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000389 CurrentNamespaces = std::move(NextNamespaces);
390 }
391 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000392 for (const auto &NS : CurrentNamespaces)
393 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000394
Haojian Wu53eab1e2016-10-14 13:43:49 +0000395 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000396 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000397 return clang::tooling::Replacements(
398 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000399}
400
Haojian Wu36265162017-01-03 09:00:51 +0000401// Return a set of all decls which are used/referenced by the given Decls.
402// Specically, given a class member declaration, this method will return all
403// decls which are used by the whole class.
404llvm::DenseSet<const Decl *>
405getUsedDecls(const HelperDeclRefGraph *RG,
406 const std::vector<const NamedDecl *> &Decls) {
407 assert(RG);
408 llvm::DenseSet<const CallGraphNode *> Nodes;
409 for (const auto *D : Decls) {
410 auto Result = RG->getReachableNodes(
411 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
412 Nodes.insert(Result.begin(), Result.end());
413 }
414 llvm::DenseSet<const Decl *> Results;
415 for (const auto *Node : Nodes)
416 Results.insert(Node->getDecl());
417 return Results;
418}
419
Haojian Wu357ef992016-09-21 13:18:19 +0000420} // namespace
421
422std::unique_ptr<clang::ASTConsumer>
423ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
424 StringRef /*InFile*/) {
425 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
426 &Compiler.getSourceManager(), &MoveTool));
427 return MatchFinder.newASTConsumer();
428}
429
Haojian Wub15c8da2016-11-24 10:17:17 +0000430ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
431 DeclarationReporter *const Reporter)
432 : Context(Context), Reporter(Reporter) {
433 if (!Context->Spec.NewHeader.empty())
434 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000435}
436
Haojian Wu08e402a2016-12-02 12:39:39 +0000437void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
438 const auto &SM = Decl->getASTContext().getSourceManager();
439 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000440 StringRef FilePath = SM.getFilename(Loc);
441 FilePathToFileID[FilePath] = SM.getFileID(Loc);
442 RemovedDecls.push_back(Decl);
443}
444
Haojian Wu357ef992016-09-21 13:18:19 +0000445void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000446 auto InOldHeader =
447 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
448 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000449 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000450 auto ForwardDecls =
451 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
452
453 //============================================================================
454 // Matchers for old header
455 //============================================================================
456 // Match all top-level named declarations (e.g. function, variable, enum) in
457 // old header, exclude forward class declarations and namespace declarations.
458 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000459 // We consider declarations inside a class belongs to the class. So these
460 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000461 auto AllDeclsInHeader = namedDecl(
462 unless(ForwardDecls), unless(namespaceDecl()),
Haojian Wub15c8da2016-11-24 10:17:17 +0000463 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wu2930be12016-11-08 19:55:13 +0000464 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
465 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000466 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
467 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000468 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000469
470 // Don't register other matchers when dumping all declarations in header.
471 if (Context->DumpDeclarations)
472 return;
473
Haojian Wu2930be12016-11-08 19:55:13 +0000474 // Match forward declarations in old header.
475 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
476 this);
477
478 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000479 // Matchers for old cc
480 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000481 auto IsOldCCTopLevelDecl = allOf(
482 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
483 // Matching using decls/type alias decls which are in named/anonymous/global
484 // namespace, these decls are always copied to new.h/cc. Those in classes,
485 // functions are covered in other matchers.
Haojian Wu357ef992016-09-21 13:18:19 +0000486 Finder->addMatcher(
Haojian Wu36265162017-01-03 09:00:51 +0000487 namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
488 usingDirectiveDecl(IsOldCCTopLevelDecl),
489 typeAliasDecl(IsOldCCTopLevelDecl)))
Haojian Wu67bb6512016-10-19 14:13:21 +0000490 .bind("using_decl"),
Haojian Wu357ef992016-09-21 13:18:19 +0000491 this);
492
Haojian Wu67bb6512016-10-19 14:13:21 +0000493 // Match static functions/variable definitions which are defined in named
494 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000495 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
496 for (StringRef SymbolName : Context->Spec.Names) {
497 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
498 const auto HasName = hasName(("::" + GlobalSymbolName).str());
499 HasAnySymbolNames =
500 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
501 }
502
503 if (!HasAnySymbolNames) {
504 llvm::errs() << "No symbols being moved.\n";
505 return;
506 }
507 auto InMovedClass =
508 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000509
510 // Matchers for helper declarations in old.cc.
511 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
512 auto DefinitionInOldCC = allOf(isDefinition(), unless(InMovedClass), InOldCC);
513 auto IsOldCCHelperDefinition =
514 allOf(DefinitionInOldCC, anyOf(isStaticStorageClass(), InAnonymousNS));
515 // Match helper classes separately with helper functions/variables since we
516 // want to reuse these matchers in finding helpers usage below.
517 auto HelperFuncOrVar = namedDecl(anyOf(functionDecl(IsOldCCHelperDefinition),
518 varDecl(IsOldCCHelperDefinition)));
519 auto HelperClasses = cxxRecordDecl(DefinitionInOldCC, InAnonymousNS);
520 // Save all helper declarations in old.cc.
521 Finder->addMatcher(
522 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
523 this);
524
525 // Construct an AST-based call graph of helper declarations in old.cc.
526 // In the following matcheres, "dc" is a caller while "helper_decls" and
527 // "used_class" is a callee, so a new edge starting from caller to callee will
528 // be add in the graph.
529 //
530 // Find helper function/variable usages.
531 Finder->addMatcher(
532 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
533 .bind("func_ref"),
534 &RGBuilder);
535 // Find helper class usages.
536 Finder->addMatcher(
537 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
538 hasAncestor(decl().bind("dc"))),
539 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000540
541 //============================================================================
542 // Matchers for old files, including old.h/old.cc
543 //============================================================================
544 // Create a MatchCallback for class declarations.
545 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
546 // Match moved class declarations.
547 auto MovedClass =
548 cxxRecordDecl(
Haojian Wu4543fec2016-11-16 13:05:19 +0000549 InOldFiles, *HasAnySymbolNames, isDefinition(),
Haojian Wu35ca9462016-11-14 14:15:44 +0000550 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())))
551 .bind("moved_class");
552 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
553 // Match moved class methods (static methods included) which are defined
554 // outside moved class declaration.
555 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000556 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000557 isDefinition())
558 .bind("class_method"),
559 MatchCallbacks.back().get());
560 // Match static member variable definition of the moved class.
561 Finder->addMatcher(
562 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
563 .bind("class_static_var_decl"),
564 MatchCallbacks.back().get());
565
Haojian Wu4543fec2016-11-16 13:05:19 +0000566 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
567 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames,
568 anyOf(hasDeclContext(namespaceDecl()),
569 hasDeclContext(translationUnitDecl())))
570 .bind("function"),
571 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000572}
573
574void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000575 if (const auto *D =
576 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
577 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000578 } else if (const auto *FWD =
579 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000580 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000581 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000582 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000583 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000584 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000585 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000586 }
Haojian Wu357ef992016-09-21 13:18:19 +0000587 } else if (const auto *ND =
588 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000589 MovedDecls.push_back(ND);
Haojian Wu36265162017-01-03 09:00:51 +0000590 } else if (const auto *ND =
591 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
592 MovedDecls.push_back(ND);
593 HelperDeclarations.push_back(ND);
Haojian Wu67bb6512016-10-19 14:13:21 +0000594 } else if (const auto *UD =
595 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000596 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000597 }
598}
599
Haojian Wu2930be12016-11-08 19:55:13 +0000600std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000601 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000602}
603
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000604void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000605 llvm::StringRef SearchPath,
606 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000607 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000608 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000609 SmallVector<char, 128> HeaderWithSearchPath;
610 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000611 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000612 if (AbsoluteOldHeader ==
613 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000614 HeaderWithSearchPath.size()))) {
615 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000616 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000617 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000618
619 std::string IncludeLine =
620 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
621 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000622
Haojian Wudb726572016-10-12 15:50:30 +0000623 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
624 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000625 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000626 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000627 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000628 }
Haojian Wu357ef992016-09-21 13:18:19 +0000629}
630
Haojian Wu08e402a2016-12-02 12:39:39 +0000631void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000632 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000633
634 // If old_header is not specified (only move declarations from old.cc), remain
635 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
636 // is empty in this case, there is no way to verify unused/used helpers.
637 if (!Context->Spec.OldHeader.empty()) {
638 std::vector<const NamedDecl *> UnremovedDecls;
639 for (const auto *D : UnremovedDeclsInOldHeader)
640 UnremovedDecls.push_back(D);
641
642 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
643
644 // We remove the helper declarations which are not used in the old.cc after
645 // moving the given declarations.
646 for (const auto *D : HelperDeclarations) {
647 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D))) {
648 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
649 << D->getNameAsString() << " " << D << "\n");
650 RemovedDecls.push_back(D);
651 }
652 }
653 }
654
Haojian Wu08e402a2016-12-02 12:39:39 +0000655 for (const auto *RemovedDecl : RemovedDecls) {
656 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
657 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000658 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000659 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000660 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000661 "");
662 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000663 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000664 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000665 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000666 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000667 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000668
669 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000670 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000671 StringRef FilePath = FileAndReplacements.first;
672 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000673 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000674 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000675 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000676 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000677 std::string IncludeNewH =
678 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000679 // This replacment for inserting header will be cleaned up at the end.
680 auto Err = FileAndReplacements.second.add(
681 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
682 if (Err)
683 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000684 }
Haojian Wu253d5962016-10-06 08:29:32 +0000685
Haojian Wu48ac3042016-11-23 10:04:19 +0000686 auto SI = FilePathToFileID.find(FilePath);
687 // Ignore replacements for new.h/cc.
688 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000689 llvm::StringRef Code = SM.getBufferData(SI->second);
Haojian Wu253d5962016-10-06 08:29:32 +0000690 format::FormatStyle Style =
Haojian Wub15c8da2016-11-24 10:17:17 +0000691 format::getStyle("file", FilePath, Context->FallbackStyle);
Haojian Wu253d5962016-10-06 08:29:32 +0000692 auto CleanReplacements = format::cleanupAroundReplacements(
Haojian Wub15c8da2016-11-24 10:17:17 +0000693 Code, Context->FileToReplacements[FilePath], Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000694
695 if (!CleanReplacements) {
696 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
697 continue;
698 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000699 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000700 }
701}
702
Haojian Wu08e402a2016-12-02 12:39:39 +0000703void ClangMoveTool::moveDeclsToNewFiles() {
704 std::vector<const NamedDecl *> NewHeaderDecls;
705 std::vector<const NamedDecl *> NewCCDecls;
706 for (const auto *MovedDecl : MovedDecls) {
707 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000708 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000709 NewHeaderDecls.push_back(MovedDecl);
710 else
711 NewCCDecls.push_back(MovedDecl);
712 }
713
Haojian Wu36265162017-01-03 09:00:51 +0000714 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
715 std::vector<const NamedDecl *> ActualNewCCDecls;
716
717 // Filter out all unused helpers in NewCCDecls.
718 // We only move the used helpers (including transively used helpers) and the
719 // given symbols being moved.
720 for (const auto *D : NewCCDecls) {
721 if (llvm::is_contained(HelperDeclarations, D) &&
722 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D)))
723 continue;
724
725 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
726 << " " << D << "\n");
727 ActualNewCCDecls.push_back(D);
728 }
729
Haojian Wub15c8da2016-11-24 10:17:17 +0000730 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000731 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000732 Context->Spec.NewDependOnOld
733 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
734 : "";
735 Context->FileToReplacements[Context->Spec.NewHeader] =
736 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
737 Context->Spec.NewHeader, /*IsHeader=*/true,
738 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000739 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000740 if (!Context->Spec.NewCC.empty())
741 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000742 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
743 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000744}
745
Haojian Wu2930be12016-11-08 19:55:13 +0000746// Move all contents from OldFile to NewFile.
747void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
748 StringRef NewFile) {
749 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
750 if (!FE) {
751 llvm::errs() << "Failed to get file: " << OldFile << "\n";
752 return;
753 }
754 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
755 auto Begin = SM.getLocForStartOfFile(ID);
756 auto End = SM.getLocForEndOfFile(ID);
757 clang::tooling::Replacement RemoveAll (
758 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
759 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000760 Context->FileToReplacements[FilePath] =
761 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000762
763 StringRef Code = SM.getBufferData(ID);
764 if (!NewFile.empty()) {
765 auto AllCode = clang::tooling::Replacements(
766 clang::tooling::Replacement(NewFile, 0, 0, Code));
767 // If we are moving from old.cc, an extra step is required: excluding
768 // the #include of "old.h", instead, we replace it with #include of "new.h".
Haojian Wub15c8da2016-11-24 10:17:17 +0000769 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
Haojian Wu2930be12016-11-08 19:55:13 +0000770 AllCode = AllCode.merge(
771 clang::tooling::Replacements(clang::tooling::Replacement(
Haojian Wub15c8da2016-11-24 10:17:17 +0000772 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wu2930be12016-11-08 19:55:13 +0000773 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000774 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000775 }
776}
777
Haojian Wu357ef992016-09-21 13:18:19 +0000778void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000779 if (Context->DumpDeclarations) {
780 assert(Reporter);
781 for (const auto *Decl : UnremovedDeclsInOldHeader) {
782 auto Kind = Decl->getKind();
783 const std::string QualifiedName = Decl->getQualifiedNameAsString();
784 if (Kind == Decl::Kind::Function || Kind == Decl::Kind::FunctionTemplate)
785 Reporter->reportDeclaration(QualifiedName, "Function");
786 else if (Kind == Decl::Kind::ClassTemplate ||
787 Kind == Decl::Kind::CXXRecord)
788 Reporter->reportDeclaration(QualifiedName, "Class");
789 }
790 return;
791 }
792
Haojian Wu357ef992016-09-21 13:18:19 +0000793 if (RemovedDecls.empty())
794 return;
Eric Liu47a42d52016-12-06 10:12:23 +0000795 // Ignore symbols that are not supported (e.g. typedef and enum) when
796 // checking if there is unremoved symbol in old header. This makes sure that
797 // we always move old files to new files when all symbols produced from
798 // dump_decls are moved.
799 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
800 switch (Decl->getKind()) {
801 case Decl::Kind::Function:
802 case Decl::Kind::FunctionTemplate:
803 case Decl::Kind::ClassTemplate:
804 case Decl::Kind::CXXRecord:
805 return true;
806 default:
807 return false;
808 }
809 };
810 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
811 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
812 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000813 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000814 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
815 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000816 return;
817 }
Haojian Wu36265162017-01-03 09:00:51 +0000818 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000819 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000820 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000821}
822
823} // namespace move
824} // namespace clang