blob: 06a76f23a72adaf42d742d22af8e57cd72f80476 [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 Wu32a552f2017-01-03 14:22:25 +0000143/// Add a declatration being moved to new.h/cc. Note that the declaration will
144/// also be deleted in old.h/cc.
145void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
146 MoveTool->getMovedDecls().push_back(D);
147 MoveTool->addRemovedDecl(D);
148 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
149}
150
Haojian Wu4543fec2016-11-16 13:05:19 +0000151class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
152public:
153 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
154 : MoveTool(MoveTool) {}
155
156 void run(const MatchFinder::MatchResult &Result) override {
157 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
158 assert(FD);
159 const clang::NamedDecl *D = FD;
160 if (const auto *FTD = FD->getDescribedFunctionTemplate())
161 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000162 MoveDeclFromOldFileToNewFile(MoveTool, D);
163 }
164
165private:
166 ClangMoveTool *MoveTool;
167};
168
169class EnumDeclarationMatch : public MatchFinder::MatchCallback {
170public:
171 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
172 : MoveTool(MoveTool) {}
173
174 void run(const MatchFinder::MatchResult &Result) override {
175 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
176 assert(ED);
177 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000178 }
179
180private:
181 ClangMoveTool *MoveTool;
182};
183
Haojian Wu35ca9462016-11-14 14:15:44 +0000184class ClassDeclarationMatch : public MatchFinder::MatchCallback {
185public:
186 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
187 : MoveTool(MoveTool) {}
188 void run(const MatchFinder::MatchResult &Result) override {
189 clang::SourceManager* SM = &Result.Context->getSourceManager();
190 if (const auto *CMD =
191 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
192 MatchClassMethod(CMD, SM);
193 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
194 "class_static_var_decl"))
195 MatchClassStaticVariable(VD, SM);
196 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
197 "moved_class"))
198 MatchClassDeclaration(CD, SM);
199 }
200
201private:
202 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
203 clang::SourceManager* SM) {
204 // Skip inline class methods. isInline() ast matcher doesn't ignore this
205 // case.
206 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000207 MoveTool->getMovedDecls().push_back(CMD);
208 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000209 // Get template class method from its method declaration as
210 // UnremovedDecls stores template class method.
211 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
212 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
213 else
214 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
215 }
216 }
217
218 void MatchClassStaticVariable(const clang::NamedDecl *VD,
219 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000220 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000221 }
222
223 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
224 clang::SourceManager* SM) {
225 // Get class template from its class declaration as UnremovedDecls stores
226 // class template.
227 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000228 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000229 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000230 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000231 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000232 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000233 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000234 }
235
236 ClangMoveTool *MoveTool;
237};
238
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000239// Expand to get the end location of the line where the EndLoc of the given
240// Decl.
241SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000242getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000243 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000244 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wudc4edba2016-12-13 15:35:47 +0000245 auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
246 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000247 // Try to load the file buffer.
248 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000249 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000250 if (InvalidTemp)
251 return SourceLocation();
252
253 const char *TokBegin = File.data() + LocInfo.second;
254 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000255 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000256 TokBegin, File.end());
257
258 llvm::SmallVector<char, 16> Line;
259 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
260 Lex.setParsingPreprocessorDirective(true);
261 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000262 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000263 // If we already reach EOF, just return the EOF SourceLocation;
264 // otherwise, move 1 offset ahead to include the trailing newline character
265 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000266 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000267 ? EndLoc
268 : EndLoc.getLocWithOffset(1);
269}
270
271// Get full range of a Decl including the comments associated with it.
272clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000273getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000274 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000275 const auto &SM = D->getASTContext().getSourceManager();
276 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
277 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000278 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000279 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000280 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000281 Full.setEnd(Comment->getLocEnd());
282 // FIXME: Don't delete a preceding comment, if there are no other entities
283 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000284 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000285 Full.setBegin(Comment->getLocStart());
286 }
287
288 return clang::CharSourceRange::getCharRange(Full);
289}
290
Haojian Wu08e402a2016-12-02 12:39:39 +0000291std::string getDeclarationSourceText(const clang::Decl *D) {
292 const auto &SM = D->getASTContext().getSourceManager();
293 llvm::StringRef SourceText =
294 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000295 return SourceText.str();
296}
297
Haojian Wu08e402a2016-12-02 12:39:39 +0000298bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000299 llvm::StringRef OriginalRunningDirectory,
300 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000301 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000302 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000303 return false;
304 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
305 if (ExpansionLoc.isInvalid())
306 return false;
307
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000308 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
309 return MakeAbsolutePath(SM, FE->getName()) ==
310 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
311 }
Haojian Wu357ef992016-09-21 13:18:19 +0000312
313 return false;
314}
315
Haojian Wu08e402a2016-12-02 12:39:39 +0000316std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000317 std::vector<std::string> Namespaces;
318 for (const auto *Context = D->getDeclContext(); Context;
319 Context = Context->getParent()) {
320 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
321 llvm::isa<clang::LinkageSpecDecl>(Context))
322 break;
323
324 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
325 Namespaces.push_back(ND->getName().str());
326 }
327 std::reverse(Namespaces.begin(), Namespaces.end());
328 return Namespaces;
329}
330
Haojian Wu357ef992016-09-21 13:18:19 +0000331clang::tooling::Replacements
332createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000333 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000334 llvm::StringRef FileName, bool IsHeader = false,
335 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000336 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000337 std::string GuardName(FileName);
338 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000339 for (size_t i = 0; i < GuardName.size(); ++i) {
340 if (!isAlphanumeric(GuardName[i]))
341 GuardName[i] = '_';
342 }
Haojian Wu220c7552016-10-14 13:01:36 +0000343 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000344 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000345 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000346 }
Haojian Wu357ef992016-09-21 13:18:19 +0000347
Haojian Wu48ac3042016-11-23 10:04:19 +0000348 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000349 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000350 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000351 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000352
Haojian Wu53eab1e2016-10-14 13:43:49 +0000353 if (!Includes.empty())
354 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000355
356 // Add moved class definition and its related declarations. All declarations
357 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000358 //
359 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000360 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000361 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000362 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000363 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000364 auto CurrentIt = CurrentNamespaces.begin();
365 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000366 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000367 while (CurrentIt != CurrentNamespaces.end() &&
368 DeclIt != DeclNamespaces.end()) {
369 if (*CurrentIt != *DeclIt)
370 break;
371 ++CurrentIt;
372 ++DeclIt;
373 }
Haojian Wu53315a72016-11-15 09:06:59 +0000374 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
375 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000376 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
377 CurrentIt);
378 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000379
380
381 // End with CurrentNamespace.
382 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000383 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
384 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
385 --RemainingSize, ++It) {
386 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000387 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000388 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000389 }
Haojian Wu53315a72016-11-15 09:06:59 +0000390 // Add trailing '\n' after the nested namespace definition.
391 if (HasEndCurrentNamespace)
392 NewCode += "\n";
393
394 // If the moved declaration is not in CurrentNamespace, add extra namespace
395 // definitions.
396 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000397 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000398 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000399 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000400 ++DeclIt;
401 }
Haojian Wu53315a72016-11-15 09:06:59 +0000402 // If the moved declaration is in same namespace CurrentNamespace, add
403 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000404 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000405 if (!IsInNewNamespace)
406 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000407 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000408 CurrentNamespaces = std::move(NextNamespaces);
409 }
410 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000411 for (const auto &NS : CurrentNamespaces)
412 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000413
Haojian Wu53eab1e2016-10-14 13:43:49 +0000414 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000415 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000416 return clang::tooling::Replacements(
417 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000418}
419
Haojian Wu36265162017-01-03 09:00:51 +0000420// Return a set of all decls which are used/referenced by the given Decls.
421// Specically, given a class member declaration, this method will return all
422// decls which are used by the whole class.
423llvm::DenseSet<const Decl *>
424getUsedDecls(const HelperDeclRefGraph *RG,
425 const std::vector<const NamedDecl *> &Decls) {
426 assert(RG);
427 llvm::DenseSet<const CallGraphNode *> Nodes;
428 for (const auto *D : Decls) {
429 auto Result = RG->getReachableNodes(
430 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
431 Nodes.insert(Result.begin(), Result.end());
432 }
433 llvm::DenseSet<const Decl *> Results;
434 for (const auto *Node : Nodes)
435 Results.insert(Node->getDecl());
436 return Results;
437}
438
Haojian Wu357ef992016-09-21 13:18:19 +0000439} // namespace
440
441std::unique_ptr<clang::ASTConsumer>
442ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
443 StringRef /*InFile*/) {
444 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
445 &Compiler.getSourceManager(), &MoveTool));
446 return MatchFinder.newASTConsumer();
447}
448
Haojian Wub15c8da2016-11-24 10:17:17 +0000449ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
450 DeclarationReporter *const Reporter)
451 : Context(Context), Reporter(Reporter) {
452 if (!Context->Spec.NewHeader.empty())
453 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000454}
455
Haojian Wu08e402a2016-12-02 12:39:39 +0000456void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
457 const auto &SM = Decl->getASTContext().getSourceManager();
458 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000459 StringRef FilePath = SM.getFilename(Loc);
460 FilePathToFileID[FilePath] = SM.getFileID(Loc);
461 RemovedDecls.push_back(Decl);
462}
463
Haojian Wu357ef992016-09-21 13:18:19 +0000464void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000465 auto InOldHeader =
466 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
467 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000468 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000469 auto ForwardDecls =
470 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
Haojian Wu32a552f2017-01-03 14:22:25 +0000471 auto TopLevelDecl =
472 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000473
474 //============================================================================
475 // Matchers for old header
476 //============================================================================
477 // Match all top-level named declarations (e.g. function, variable, enum) in
478 // old header, exclude forward class declarations and namespace declarations.
479 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000480 // We consider declarations inside a class belongs to the class. So these
481 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000482 auto AllDeclsInHeader = namedDecl(
483 unless(ForwardDecls), unless(namespaceDecl()),
Haojian Wub15c8da2016-11-24 10:17:17 +0000484 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wu2930be12016-11-08 19:55:13 +0000485 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
486 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000487 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
488 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000489 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000490
491 // Don't register other matchers when dumping all declarations in header.
492 if (Context->DumpDeclarations)
493 return;
494
Haojian Wu2930be12016-11-08 19:55:13 +0000495 // Match forward declarations in old header.
496 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
497 this);
498
499 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000500 // Matchers for old cc
501 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000502 auto IsOldCCTopLevelDecl = allOf(
503 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
504 // Matching using decls/type alias decls which are in named/anonymous/global
505 // namespace, these decls are always copied to new.h/cc. Those in classes,
506 // functions are covered in other matchers.
Haojian Wu357ef992016-09-21 13:18:19 +0000507 Finder->addMatcher(
Haojian Wu36265162017-01-03 09:00:51 +0000508 namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
509 usingDirectiveDecl(IsOldCCTopLevelDecl),
510 typeAliasDecl(IsOldCCTopLevelDecl)))
Haojian Wu67bb6512016-10-19 14:13:21 +0000511 .bind("using_decl"),
Haojian Wu357ef992016-09-21 13:18:19 +0000512 this);
513
Haojian Wu67bb6512016-10-19 14:13:21 +0000514 // Match static functions/variable definitions which are defined in named
515 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000516 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
517 for (StringRef SymbolName : Context->Spec.Names) {
518 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
519 const auto HasName = hasName(("::" + GlobalSymbolName).str());
520 HasAnySymbolNames =
521 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
522 }
523
524 if (!HasAnySymbolNames) {
525 llvm::errs() << "No symbols being moved.\n";
526 return;
527 }
528 auto InMovedClass =
529 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000530
531 // Matchers for helper declarations in old.cc.
532 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
533 auto DefinitionInOldCC = allOf(isDefinition(), unless(InMovedClass), InOldCC);
534 auto IsOldCCHelperDefinition =
535 allOf(DefinitionInOldCC, anyOf(isStaticStorageClass(), InAnonymousNS));
536 // Match helper classes separately with helper functions/variables since we
537 // want to reuse these matchers in finding helpers usage below.
538 auto HelperFuncOrVar = namedDecl(anyOf(functionDecl(IsOldCCHelperDefinition),
539 varDecl(IsOldCCHelperDefinition)));
540 auto HelperClasses = cxxRecordDecl(DefinitionInOldCC, InAnonymousNS);
541 // Save all helper declarations in old.cc.
542 Finder->addMatcher(
543 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
544 this);
545
546 // Construct an AST-based call graph of helper declarations in old.cc.
547 // In the following matcheres, "dc" is a caller while "helper_decls" and
548 // "used_class" is a callee, so a new edge starting from caller to callee will
549 // be add in the graph.
550 //
551 // Find helper function/variable usages.
552 Finder->addMatcher(
553 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
554 .bind("func_ref"),
555 &RGBuilder);
556 // Find helper class usages.
557 Finder->addMatcher(
558 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
559 hasAncestor(decl().bind("dc"))),
560 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000561
562 //============================================================================
563 // Matchers for old files, including old.h/old.cc
564 //============================================================================
565 // Create a MatchCallback for class declarations.
566 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
567 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000568 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
569 isDefinition(), TopLevelDecl)
570 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000571 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
572 // Match moved class methods (static methods included) which are defined
573 // outside moved class declaration.
574 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000575 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000576 isDefinition())
577 .bind("class_method"),
578 MatchCallbacks.back().get());
579 // Match static member variable definition of the moved class.
580 Finder->addMatcher(
581 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
582 .bind("class_static_var_decl"),
583 MatchCallbacks.back().get());
584
Haojian Wu4543fec2016-11-16 13:05:19 +0000585 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000586 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000587 .bind("function"),
588 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000589
590 // Match enum definition in old.h. Enum helpers (which are definied in old.cc)
591 // will not be moved for now no matter whether they are used or not.
592 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
593 Finder->addMatcher(
594 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
595 .bind("enum"),
596 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000597}
598
599void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000600 if (const auto *D =
601 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
602 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000603 } else if (const auto *FWD =
604 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000605 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000606 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000607 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000608 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000609 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000610 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000611 }
Haojian Wu357ef992016-09-21 13:18:19 +0000612 } else if (const auto *ND =
613 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000614 MovedDecls.push_back(ND);
Haojian Wu36265162017-01-03 09:00:51 +0000615 } else if (const auto *ND =
616 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
617 MovedDecls.push_back(ND);
618 HelperDeclarations.push_back(ND);
Haojian Wu67bb6512016-10-19 14:13:21 +0000619 } else if (const auto *UD =
620 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000621 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000622 }
623}
624
Haojian Wu2930be12016-11-08 19:55:13 +0000625std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000626 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000627}
628
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000629void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000630 llvm::StringRef SearchPath,
631 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000632 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000633 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000634 SmallVector<char, 128> HeaderWithSearchPath;
635 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000636 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000637 if (AbsoluteOldHeader ==
638 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000639 HeaderWithSearchPath.size()))) {
640 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000641 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000642 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000643
644 std::string IncludeLine =
645 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
646 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000647
Haojian Wudb726572016-10-12 15:50:30 +0000648 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
649 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000650 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000651 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000652 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000653 }
Haojian Wu357ef992016-09-21 13:18:19 +0000654}
655
Haojian Wu08e402a2016-12-02 12:39:39 +0000656void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000657 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000658
659 // If old_header is not specified (only move declarations from old.cc), remain
660 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
661 // is empty in this case, there is no way to verify unused/used helpers.
662 if (!Context->Spec.OldHeader.empty()) {
663 std::vector<const NamedDecl *> UnremovedDecls;
664 for (const auto *D : UnremovedDeclsInOldHeader)
665 UnremovedDecls.push_back(D);
666
667 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
668
669 // We remove the helper declarations which are not used in the old.cc after
670 // moving the given declarations.
671 for (const auto *D : HelperDeclarations) {
672 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D))) {
673 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
674 << D->getNameAsString() << " " << D << "\n");
675 RemovedDecls.push_back(D);
676 }
677 }
678 }
679
Haojian Wu08e402a2016-12-02 12:39:39 +0000680 for (const auto *RemovedDecl : RemovedDecls) {
681 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
682 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000683 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000684 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000685 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000686 "");
687 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000688 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000689 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000690 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000691 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000692 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000693
694 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000695 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000696 StringRef FilePath = FileAndReplacements.first;
697 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000698 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000699 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000700 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000701 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000702 std::string IncludeNewH =
703 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000704 // This replacment for inserting header will be cleaned up at the end.
705 auto Err = FileAndReplacements.second.add(
706 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
707 if (Err)
708 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000709 }
Haojian Wu253d5962016-10-06 08:29:32 +0000710
Haojian Wu48ac3042016-11-23 10:04:19 +0000711 auto SI = FilePathToFileID.find(FilePath);
712 // Ignore replacements for new.h/cc.
713 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000714 llvm::StringRef Code = SM.getBufferData(SI->second);
Haojian Wu253d5962016-10-06 08:29:32 +0000715 format::FormatStyle Style =
Haojian Wub15c8da2016-11-24 10:17:17 +0000716 format::getStyle("file", FilePath, Context->FallbackStyle);
Haojian Wu253d5962016-10-06 08:29:32 +0000717 auto CleanReplacements = format::cleanupAroundReplacements(
Haojian Wub15c8da2016-11-24 10:17:17 +0000718 Code, Context->FileToReplacements[FilePath], Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000719
720 if (!CleanReplacements) {
721 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
722 continue;
723 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000724 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000725 }
726}
727
Haojian Wu08e402a2016-12-02 12:39:39 +0000728void ClangMoveTool::moveDeclsToNewFiles() {
729 std::vector<const NamedDecl *> NewHeaderDecls;
730 std::vector<const NamedDecl *> NewCCDecls;
731 for (const auto *MovedDecl : MovedDecls) {
732 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000733 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000734 NewHeaderDecls.push_back(MovedDecl);
735 else
736 NewCCDecls.push_back(MovedDecl);
737 }
738
Haojian Wu36265162017-01-03 09:00:51 +0000739 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
740 std::vector<const NamedDecl *> ActualNewCCDecls;
741
742 // Filter out all unused helpers in NewCCDecls.
743 // We only move the used helpers (including transively used helpers) and the
744 // given symbols being moved.
745 for (const auto *D : NewCCDecls) {
746 if (llvm::is_contained(HelperDeclarations, D) &&
747 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D)))
748 continue;
749
750 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
751 << " " << D << "\n");
752 ActualNewCCDecls.push_back(D);
753 }
754
Haojian Wub15c8da2016-11-24 10:17:17 +0000755 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000756 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000757 Context->Spec.NewDependOnOld
758 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
759 : "";
760 Context->FileToReplacements[Context->Spec.NewHeader] =
761 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
762 Context->Spec.NewHeader, /*IsHeader=*/true,
763 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000764 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000765 if (!Context->Spec.NewCC.empty())
766 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000767 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
768 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000769}
770
Haojian Wu2930be12016-11-08 19:55:13 +0000771// Move all contents from OldFile to NewFile.
772void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
773 StringRef NewFile) {
774 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
775 if (!FE) {
776 llvm::errs() << "Failed to get file: " << OldFile << "\n";
777 return;
778 }
779 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
780 auto Begin = SM.getLocForStartOfFile(ID);
781 auto End = SM.getLocForEndOfFile(ID);
782 clang::tooling::Replacement RemoveAll (
783 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
784 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000785 Context->FileToReplacements[FilePath] =
786 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000787
788 StringRef Code = SM.getBufferData(ID);
789 if (!NewFile.empty()) {
790 auto AllCode = clang::tooling::Replacements(
791 clang::tooling::Replacement(NewFile, 0, 0, Code));
792 // If we are moving from old.cc, an extra step is required: excluding
793 // the #include of "old.h", instead, we replace it with #include of "new.h".
Haojian Wub15c8da2016-11-24 10:17:17 +0000794 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
Haojian Wu2930be12016-11-08 19:55:13 +0000795 AllCode = AllCode.merge(
796 clang::tooling::Replacements(clang::tooling::Replacement(
Haojian Wub15c8da2016-11-24 10:17:17 +0000797 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wu2930be12016-11-08 19:55:13 +0000798 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000799 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000800 }
801}
802
Haojian Wu357ef992016-09-21 13:18:19 +0000803void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000804 if (Context->DumpDeclarations) {
805 assert(Reporter);
806 for (const auto *Decl : UnremovedDeclsInOldHeader) {
807 auto Kind = Decl->getKind();
808 const std::string QualifiedName = Decl->getQualifiedNameAsString();
809 if (Kind == Decl::Kind::Function || Kind == Decl::Kind::FunctionTemplate)
810 Reporter->reportDeclaration(QualifiedName, "Function");
811 else if (Kind == Decl::Kind::ClassTemplate ||
812 Kind == Decl::Kind::CXXRecord)
813 Reporter->reportDeclaration(QualifiedName, "Class");
814 }
815 return;
816 }
817
Haojian Wu357ef992016-09-21 13:18:19 +0000818 if (RemovedDecls.empty())
819 return;
Eric Liu47a42d52016-12-06 10:12:23 +0000820 // Ignore symbols that are not supported (e.g. typedef and enum) when
821 // checking if there is unremoved symbol in old header. This makes sure that
822 // we always move old files to new files when all symbols produced from
823 // dump_decls are moved.
824 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
825 switch (Decl->getKind()) {
826 case Decl::Kind::Function:
827 case Decl::Kind::FunctionTemplate:
828 case Decl::Kind::ClassTemplate:
829 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000830 case Decl::Kind::Enum:
Eric Liu47a42d52016-12-06 10:12:23 +0000831 return true;
832 default:
833 return false;
834 }
835 };
836 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
837 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
838 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000839 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000840 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
841 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000842 return;
843 }
Haojian Wu36265162017-01-03 09:00:51 +0000844 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000845 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000846 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000847}
848
849} // namespace move
850} // namespace clang