blob: ec9db738d27471e6d63445752f97f332e67ca16f [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 Wub3d98882017-01-17 10:08:11 +000034AST_MATCHER(NamedDecl, notInMacro) { return !Node.getLocation().isMacroID(); }
35
Haojian Wue77bcc72016-10-13 10:31:00 +000036AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
37 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000038 const auto *Context = Node.getDeclContext();
39 if (!Context)
40 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000041 while (const auto *NextContext = Context->getParent()) {
42 if (isa<NamespaceDecl>(NextContext) ||
43 isa<TranslationUnitDecl>(NextContext))
44 break;
45 Context = NextContext;
46 }
47 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
48 Builder);
49}
50
51AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
52 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
53 const CXXRecordDecl *Parent = Node.getParent();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000054 if (!Parent)
55 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000056 while (const auto *NextParent =
57 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
58 Parent = NextParent;
59 }
60
61 return InnerMatcher.matches(*Parent, Finder, Builder);
62}
63
Eric Liu5e721372018-05-17 12:40:50 +000064std::string CleanPath(StringRef PathRef) {
65 llvm::SmallString<128> Path(PathRef);
66 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Eric Liu07d47302018-05-17 14:59:15 +000067 // FIXME: figure out why this is necessary.
68 llvm::sys::path::native(Path);
Eric Liu5e721372018-05-17 12:40:50 +000069 return Path.str();
70}
71
Haojian Wud2a6d7b2016-10-04 09:05:31 +000072// Make the Path absolute using the CurrentDir if the Path is not an absolute
73// path. An empty Path will result in an empty string.
74std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
75 if (Path.empty())
76 return "";
77 llvm::SmallString<128> InitialDirectory(CurrentDir);
78 llvm::SmallString<128> AbsolutePath(Path);
79 if (std::error_code EC =
80 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000081 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000082 << '\n';
Eric Liu5e721372018-05-17 12:40:50 +000083 return CleanPath(std::move(AbsolutePath));
Haojian Wud2a6d7b2016-10-04 09:05:31 +000084}
85
86// Make the Path absolute using the current working directory of the given
87// SourceManager if the Path is not an absolute path.
88//
89// The Path can be a path relative to the build directory, or retrieved from
90// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000091std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000092 llvm::SmallString<128> AbsolutePath(Path);
93 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000094 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
95 AbsolutePath))
96 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000097 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000098 // Handle symbolic link path cases.
99 // We are trying to get the real file path of the symlink.
100 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000101 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +0000102 if (Dir) {
103 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
Eric Liuad3fed62018-05-16 20:10:10 +0000104 // FIXME: getCanonicalName might fail to get real path on VFS.
105 if (llvm::sys::path::is_absolute(DirName)) {
Eric Liu5e721372018-05-17 12:40:50 +0000106 SmallString<128> AbsoluteFilename;
Eric Liuad3fed62018-05-16 20:10:10 +0000107 llvm::sys::path::append(AbsoluteFilename, DirName,
108 llvm::sys::path::filename(AbsolutePath.str()));
Eric Liu5e721372018-05-17 12:40:50 +0000109 return CleanPath(AbsoluteFilename);
Eric Liuad3fed62018-05-16 20:10:10 +0000110 }
Haojian Wudb726572016-10-12 15:50:30 +0000111 }
Eric Liu5e721372018-05-17 12:40:50 +0000112 return CleanPath(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000113}
114
115// Matches AST nodes that are expanded within the given AbsoluteFilePath.
116AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
117 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
118 std::string, AbsoluteFilePath) {
119 auto &SourceManager = Finder->getASTContext().getSourceManager();
Stephen Kelly43465bf2018-08-09 22:42:26 +0000120 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000121 if (ExpansionLoc.isInvalid())
122 return false;
123 auto FileEntry =
124 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
125 if (!FileEntry)
126 return false;
127 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
128 AbsoluteFilePath;
129}
130
Fangrui Song95b45cb2018-10-11 16:09:26 +0000131class FindAllIncludes : public PPCallbacks {
Haojian Wu357ef992016-09-21 13:18:19 +0000132public:
133 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
134 : SM(*SM), MoveTool(MoveTool) {}
135
Fangrui Song95b45cb2018-10-11 16:09:26 +0000136 void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000137 StringRef FileName, bool IsAngled,
Fangrui Song95b45cb2018-10-11 16:09:26 +0000138 CharSourceRange FilenameRange,
139 const FileEntry * /*File*/, StringRef SearchPath,
140 StringRef /*RelativePath*/,
141 const Module * /*Imported*/,
Julie Hockett546943f2018-05-10 19:13:14 +0000142 SrcMgr::CharacteristicKind /*FileType*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000143 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000144 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000145 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000146 }
147
148private:
149 const SourceManager &SM;
150 ClangMoveTool *const MoveTool;
151};
152
Haojian Wu32a552f2017-01-03 14:22:25 +0000153/// Add a declatration being moved to new.h/cc. Note that the declaration will
154/// also be deleted in old.h/cc.
155void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
156 MoveTool->getMovedDecls().push_back(D);
157 MoveTool->addRemovedDecl(D);
158 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
159}
160
Haojian Wu4543fec2016-11-16 13:05:19 +0000161class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
162public:
163 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
164 : MoveTool(MoveTool) {}
165
166 void run(const MatchFinder::MatchResult &Result) override {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000167 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("function");
Haojian Wu4543fec2016-11-16 13:05:19 +0000168 assert(FD);
Fangrui Song95b45cb2018-10-11 16:09:26 +0000169 const NamedDecl *D = FD;
Haojian Wu4543fec2016-11-16 13:05:19 +0000170 if (const auto *FTD = FD->getDescribedFunctionTemplate())
171 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000172 MoveDeclFromOldFileToNewFile(MoveTool, D);
173 }
174
175private:
176 ClangMoveTool *MoveTool;
177};
178
Haojian Wu4a920502017-02-27 13:19:13 +0000179class VarDeclarationMatch : public MatchFinder::MatchCallback {
180public:
181 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
182 : MoveTool(MoveTool) {}
183
184 void run(const MatchFinder::MatchResult &Result) override {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000185 const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var");
Haojian Wu4a920502017-02-27 13:19:13 +0000186 assert(VD);
187 MoveDeclFromOldFileToNewFile(MoveTool, VD);
188 }
189
190private:
191 ClangMoveTool *MoveTool;
192};
193
Haojian Wud69d9072017-01-04 14:50:49 +0000194class TypeAliasMatch : public MatchFinder::MatchCallback {
195public:
196 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
197 : MoveTool(MoveTool) {}
198
199 void run(const MatchFinder::MatchResult &Result) override {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000200 if (const auto *TD = Result.Nodes.getNodeAs<TypedefDecl>("typedef"))
Haojian Wud69d9072017-01-04 14:50:49 +0000201 MoveDeclFromOldFileToNewFile(MoveTool, TD);
202 else if (const auto *TAD =
Fangrui Song95b45cb2018-10-11 16:09:26 +0000203 Result.Nodes.getNodeAs<TypeAliasDecl>("type_alias")) {
Haojian Wud69d9072017-01-04 14:50:49 +0000204 const NamedDecl * D = TAD;
205 if (const auto * TD = TAD->getDescribedAliasTemplate())
206 D = TD;
207 MoveDeclFromOldFileToNewFile(MoveTool, D);
208 }
209 }
210
211private:
212 ClangMoveTool *MoveTool;
213};
214
Haojian Wu32a552f2017-01-03 14:22:25 +0000215class EnumDeclarationMatch : public MatchFinder::MatchCallback {
216public:
217 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
218 : MoveTool(MoveTool) {}
219
220 void run(const MatchFinder::MatchResult &Result) override {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000221 const auto *ED = Result.Nodes.getNodeAs<EnumDecl>("enum");
Haojian Wu32a552f2017-01-03 14:22:25 +0000222 assert(ED);
223 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000224 }
225
226private:
227 ClangMoveTool *MoveTool;
228};
229
Haojian Wu35ca9462016-11-14 14:15:44 +0000230class ClassDeclarationMatch : public MatchFinder::MatchCallback {
231public:
232 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
233 : MoveTool(MoveTool) {}
234 void run(const MatchFinder::MatchResult &Result) override {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000235 SourceManager *SM = &Result.Context->getSourceManager();
236 if (const auto *CMD = Result.Nodes.getNodeAs<CXXMethodDecl>("class_method"))
Haojian Wu35ca9462016-11-14 14:15:44 +0000237 MatchClassMethod(CMD, SM);
Fangrui Song95b45cb2018-10-11 16:09:26 +0000238 else if (const auto *VD =
239 Result.Nodes.getNodeAs<VarDecl>("class_static_var_decl"))
Haojian Wu35ca9462016-11-14 14:15:44 +0000240 MatchClassStaticVariable(VD, SM);
Fangrui Song95b45cb2018-10-11 16:09:26 +0000241 else if (const auto *CD =
242 Result.Nodes.getNodeAs<CXXRecordDecl>("moved_class"))
Haojian Wu35ca9462016-11-14 14:15:44 +0000243 MatchClassDeclaration(CD, SM);
244 }
245
246private:
Fangrui Song95b45cb2018-10-11 16:09:26 +0000247 void MatchClassMethod(const CXXMethodDecl *CMD, SourceManager *SM) {
Haojian Wu35ca9462016-11-14 14:15:44 +0000248 // Skip inline class methods. isInline() ast matcher doesn't ignore this
249 // case.
250 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000251 MoveTool->getMovedDecls().push_back(CMD);
252 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000253 // Get template class method from its method declaration as
254 // UnremovedDecls stores template class method.
255 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
256 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
257 else
258 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
259 }
260 }
261
Fangrui Song95b45cb2018-10-11 16:09:26 +0000262 void MatchClassStaticVariable(const NamedDecl *VD, SourceManager *SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000263 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000264 }
265
Fangrui Song95b45cb2018-10-11 16:09:26 +0000266 void MatchClassDeclaration(const CXXRecordDecl *CD, SourceManager *SM) {
Haojian Wu35ca9462016-11-14 14:15:44 +0000267 // Get class template from its class declaration as UnremovedDecls stores
268 // class template.
269 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000270 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000271 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000272 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000273 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000274 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000275 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000276 }
277
278 ClangMoveTool *MoveTool;
279};
280
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000281// Expand to get the end location of the line where the EndLoc of the given
282// Decl.
Fangrui Song95b45cb2018-10-11 16:09:26 +0000283SourceLocation getLocForEndOfDecl(const Decl *D,
284 const LangOptions &LangOpts = LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000285 const auto &SM = D->getASTContext().getSourceManager();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000286 // If the expansion range is a character range, this is the location of
287 // the first character past the end. Otherwise it's the location of the
288 // first character in the final token in the range.
Stephen Kellyc09197e2018-08-09 22:43:02 +0000289 auto EndExpansionLoc = SM.getExpansionRange(D->getEndLoc()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000290 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000291 // Try to load the file buffer.
292 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000293 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000294 if (InvalidTemp)
295 return SourceLocation();
296
297 const char *TokBegin = File.data() + LocInfo.second;
298 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000299 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000300 TokBegin, File.end());
301
302 llvm::SmallVector<char, 16> Line;
303 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
304 Lex.setParsingPreprocessorDirective(true);
305 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000306 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000307 // If we already reach EOF, just return the EOF SourceLocation;
308 // otherwise, move 1 offset ahead to include the trailing newline character
309 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000310 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000311 ? EndLoc
312 : EndLoc.getLocWithOffset(1);
313}
314
315// Get full range of a Decl including the comments associated with it.
Fangrui Song95b45cb2018-10-11 16:09:26 +0000316CharSourceRange getFullRange(const Decl *D,
317 const LangOptions &options = LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000318 const auto &SM = D->getASTContext().getSourceManager();
Fangrui Song95b45cb2018-10-11 16:09:26 +0000319 SourceRange Full(SM.getExpansionLoc(D->getBeginLoc()), getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000320 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000321 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Stephen Kellyc09197e2018-08-09 22:43:02 +0000322 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getEndLoc()))
323 Full.setEnd(Comment->getEndLoc());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000324 // FIXME: Don't delete a preceding comment, if there are no other entities
325 // it could refer to.
Stephen Kelly43465bf2018-08-09 22:42:26 +0000326 if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(), Full.getBegin()))
327 Full.setBegin(Comment->getBeginLoc());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000328 }
329
Fangrui Song95b45cb2018-10-11 16:09:26 +0000330 return CharSourceRange::getCharRange(Full);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000331}
332
Fangrui Song95b45cb2018-10-11 16:09:26 +0000333std::string getDeclarationSourceText(const Decl *D) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000334 const auto &SM = D->getASTContext().getSourceManager();
335 llvm::StringRef SourceText =
Fangrui Song95b45cb2018-10-11 16:09:26 +0000336 Lexer::getSourceText(getFullRange(D), SM, LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000337 return SourceText.str();
338}
339
Fangrui Song95b45cb2018-10-11 16:09:26 +0000340bool isInHeaderFile(const Decl *D, llvm::StringRef OriginalRunningDirectory,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000341 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000342 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000343 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000344 return false;
Stephen Kelly43465bf2018-08-09 22:42:26 +0000345 auto ExpansionLoc = SM.getExpansionLoc(D->getBeginLoc());
Haojian Wu357ef992016-09-21 13:18:19 +0000346 if (ExpansionLoc.isInvalid())
347 return false;
348
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000349 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
350 return MakeAbsolutePath(SM, FE->getName()) ==
351 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
352 }
Haojian Wu357ef992016-09-21 13:18:19 +0000353
354 return false;
355}
356
Fangrui Song95b45cb2018-10-11 16:09:26 +0000357std::vector<std::string> getNamespaces(const Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000358 std::vector<std::string> Namespaces;
359 for (const auto *Context = D->getDeclContext(); Context;
360 Context = Context->getParent()) {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000361 if (llvm::isa<TranslationUnitDecl>(Context) ||
362 llvm::isa<LinkageSpecDecl>(Context))
Haojian Wu357ef992016-09-21 13:18:19 +0000363 break;
364
Fangrui Song95b45cb2018-10-11 16:09:26 +0000365 if (const auto *ND = llvm::dyn_cast<NamespaceDecl>(Context))
Haojian Wu357ef992016-09-21 13:18:19 +0000366 Namespaces.push_back(ND->getName().str());
367 }
368 std::reverse(Namespaces.begin(), Namespaces.end());
369 return Namespaces;
370}
371
Fangrui Song95b45cb2018-10-11 16:09:26 +0000372tooling::Replacements
Haojian Wu357ef992016-09-21 13:18:19 +0000373createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000374 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000375 llvm::StringRef FileName, bool IsHeader = false,
376 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000377 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000378 std::string GuardName(FileName);
379 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000380 for (size_t i = 0; i < GuardName.size(); ++i) {
381 if (!isAlphanumeric(GuardName[i]))
382 GuardName[i] = '_';
383 }
Haojian Wu220c7552016-10-14 13:01:36 +0000384 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000385 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000386 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000387 }
Haojian Wu357ef992016-09-21 13:18:19 +0000388
Haojian Wu48ac3042016-11-23 10:04:19 +0000389 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000390 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000391 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000392 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000393
Haojian Wu53eab1e2016-10-14 13:43:49 +0000394 if (!Includes.empty())
395 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000396
397 // Add moved class definition and its related declarations. All declarations
398 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000399 //
400 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000401 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000402 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000403 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000404 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000405 auto CurrentIt = CurrentNamespaces.begin();
406 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000407 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000408 while (CurrentIt != CurrentNamespaces.end() &&
409 DeclIt != DeclNamespaces.end()) {
410 if (*CurrentIt != *DeclIt)
411 break;
412 ++CurrentIt;
413 ++DeclIt;
414 }
Haojian Wu53315a72016-11-15 09:06:59 +0000415 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
416 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000417 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
418 CurrentIt);
419 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000420
421
422 // End with CurrentNamespace.
423 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000424 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
425 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
426 --RemainingSize, ++It) {
427 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000428 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000429 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000430 }
Haojian Wu53315a72016-11-15 09:06:59 +0000431 // Add trailing '\n' after the nested namespace definition.
432 if (HasEndCurrentNamespace)
433 NewCode += "\n";
434
435 // If the moved declaration is not in CurrentNamespace, add extra namespace
436 // definitions.
437 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000438 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000439 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000440 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000441 ++DeclIt;
442 }
Haojian Wu53315a72016-11-15 09:06:59 +0000443 // If the moved declaration is in same namespace CurrentNamespace, add
444 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000445 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000446 if (!IsInNewNamespace)
447 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000448 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000449 CurrentNamespaces = std::move(NextNamespaces);
450 }
451 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000452 for (const auto &NS : CurrentNamespaces)
453 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000454
Haojian Wu53eab1e2016-10-14 13:43:49 +0000455 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000456 NewCode += "\n#endif // " + GuardName + "\n";
Fangrui Song95b45cb2018-10-11 16:09:26 +0000457 return tooling::Replacements(tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000458}
459
Haojian Wu36265162017-01-03 09:00:51 +0000460// Return a set of all decls which are used/referenced by the given Decls.
461// Specically, given a class member declaration, this method will return all
462// decls which are used by the whole class.
463llvm::DenseSet<const Decl *>
464getUsedDecls(const HelperDeclRefGraph *RG,
465 const std::vector<const NamedDecl *> &Decls) {
466 assert(RG);
467 llvm::DenseSet<const CallGraphNode *> Nodes;
468 for (const auto *D : Decls) {
469 auto Result = RG->getReachableNodes(
470 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
471 Nodes.insert(Result.begin(), Result.end());
472 }
473 llvm::DenseSet<const Decl *> Results;
474 for (const auto *Node : Nodes)
475 Results.insert(Node->getDecl());
476 return Results;
477}
478
Haojian Wu357ef992016-09-21 13:18:19 +0000479} // namespace
480
Fangrui Song95b45cb2018-10-11 16:09:26 +0000481std::unique_ptr<ASTConsumer>
482ClangMoveAction::CreateASTConsumer(CompilerInstance &Compiler,
Haojian Wu357ef992016-09-21 13:18:19 +0000483 StringRef /*InFile*/) {
484 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
485 &Compiler.getSourceManager(), &MoveTool));
486 return MatchFinder.newASTConsumer();
487}
488
Haojian Wub15c8da2016-11-24 10:17:17 +0000489ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
490 DeclarationReporter *const Reporter)
491 : Context(Context), Reporter(Reporter) {
492 if (!Context->Spec.NewHeader.empty())
493 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000494}
495
Haojian Wu08e402a2016-12-02 12:39:39 +0000496void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
497 const auto &SM = Decl->getASTContext().getSourceManager();
498 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000499 StringRef FilePath = SM.getFilename(Loc);
500 FilePathToFileID[FilePath] = SM.getFileID(Loc);
501 RemovedDecls.push_back(Decl);
502}
503
Haojian Wu357ef992016-09-21 13:18:19 +0000504void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000505 auto InOldHeader =
506 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
507 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000508 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000509 auto classTemplateForwardDecls =
510 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
511 auto ForwardClassDecls = namedDecl(
512 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
513 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000514 auto TopLevelDecl =
515 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000516
517 //============================================================================
518 // Matchers for old header
519 //============================================================================
520 // Match all top-level named declarations (e.g. function, variable, enum) in
521 // old header, exclude forward class declarations and namespace declarations.
522 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000523 // We consider declarations inside a class belongs to the class. So these
524 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000525 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000526 unless(ForwardClassDecls), unless(namespaceDecl()),
527 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000528 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000529 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000530 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
531 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000532 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000533
534 // Don't register other matchers when dumping all declarations in header.
535 if (Context->DumpDeclarations)
536 return;
537
Haojian Wu2930be12016-11-08 19:55:13 +0000538 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000539 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000540 this);
541
542 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000543 // Matchers for old cc
544 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000545 auto IsOldCCTopLevelDecl = allOf(
546 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
547 // Matching using decls/type alias decls which are in named/anonymous/global
548 // namespace, these decls are always copied to new.h/cc. Those in classes,
549 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000550 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
Argyrios Kyrtzidis2b6ec652018-08-31 03:51:33 +0000551 usingDirectiveDecl(unless(isImplicit()),
552 IsOldCCTopLevelDecl),
Haojian Wub3d98882017-01-17 10:08:11 +0000553 typeAliasDecl(IsOldCCTopLevelDecl)),
554 notInMacro())
555 .bind("using_decl"),
556 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000557
Haojian Wu67bb6512016-10-19 14:13:21 +0000558 // Match static functions/variable definitions which are defined in named
559 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000560 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
561 for (StringRef SymbolName : Context->Spec.Names) {
562 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
563 const auto HasName = hasName(("::" + GlobalSymbolName).str());
564 HasAnySymbolNames =
565 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
566 }
567
568 if (!HasAnySymbolNames) {
569 llvm::errs() << "No symbols being moved.\n";
570 return;
571 }
572 auto InMovedClass =
573 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000574
575 // Matchers for helper declarations in old.cc.
576 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000577 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
578 auto IsOldCCHelper =
579 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000580 // Match helper classes separately with helper functions/variables since we
581 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000582 //
583 // There could be forward declarations usage for helpers, especially for
584 // classes and functions. We need include these forward declarations.
585 //
586 // Forward declarations for variable helpers will be excluded as these
587 // declarations (with "extern") are not supposed in cpp file.
588 auto HelperFuncOrVar =
589 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
590 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000591 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000592 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000593 // Save all helper declarations in old.cc.
594 Finder->addMatcher(
595 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
596 this);
597
598 // Construct an AST-based call graph of helper declarations in old.cc.
599 // In the following matcheres, "dc" is a caller while "helper_decls" and
600 // "used_class" is a callee, so a new edge starting from caller to callee will
601 // be add in the graph.
602 //
603 // Find helper function/variable usages.
604 Finder->addMatcher(
605 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
606 .bind("func_ref"),
607 &RGBuilder);
608 // Find helper class usages.
609 Finder->addMatcher(
610 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
611 hasAncestor(decl().bind("dc"))),
612 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000613
614 //============================================================================
615 // Matchers for old files, including old.h/old.cc
616 //============================================================================
617 // Create a MatchCallback for class declarations.
618 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
619 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000620 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
621 isDefinition(), TopLevelDecl)
622 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000623 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
624 // Match moved class methods (static methods included) which are defined
625 // outside moved class declaration.
626 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000627 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000628 isDefinition())
629 .bind("class_method"),
630 MatchCallbacks.back().get());
631 // Match static member variable definition of the moved class.
632 Finder->addMatcher(
633 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
634 .bind("class_static_var_decl"),
635 MatchCallbacks.back().get());
636
Haojian Wu4543fec2016-11-16 13:05:19 +0000637 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000638 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000639 .bind("function"),
640 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000641
Haojian Wu4a920502017-02-27 13:19:13 +0000642 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
643 Finder->addMatcher(
644 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
645 MatchCallbacks.back().get());
646
Haojian Wud69d9072017-01-04 14:50:49 +0000647 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000648 // will not be moved for now no matter whether they are used or not.
649 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
650 Finder->addMatcher(
651 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
652 .bind("enum"),
653 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000654
655 // Match type alias in old.h, this includes "typedef" and "using" type alias
656 // declarations. Type alias helpers (which are defined in old.cc) will not be
657 // moved for now no matter whether they are used or not.
658 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
659 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
660 typeAliasDecl().bind("type_alias")),
661 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
662 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000663}
664
665void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000666 if (const auto *D = Result.Nodes.getNodeAs<NamedDecl>("decls_in_header")) {
Haojian Wu2930be12016-11-08 19:55:13 +0000667 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000668 } else if (const auto *FWD =
Fangrui Song95b45cb2018-10-11 16:09:26 +0000669 Result.Nodes.getNodeAs<CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000670 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000671 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000672 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000673 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000674 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000675 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000676 }
Haojian Wu357ef992016-09-21 13:18:19 +0000677 } else if (const auto *ND =
Fangrui Song95b45cb2018-10-11 16:09:26 +0000678 Result.Nodes.getNodeAs<NamedDecl>("helper_decls")) {
Haojian Wu36265162017-01-03 09:00:51 +0000679 MovedDecls.push_back(ND);
680 HelperDeclarations.push_back(ND);
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000681 LLVM_DEBUG(llvm::dbgs() << "Add helper : " << ND->getNameAsString() << " ("
682 << ND << ")\n");
Fangrui Song95b45cb2018-10-11 16:09:26 +0000683 } else if (const auto *UD = Result.Nodes.getNodeAs<NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000684 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000685 }
686}
687
Haojian Wu2930be12016-11-08 19:55:13 +0000688std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000689 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000690}
691
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000692void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000693 llvm::StringRef SearchPath,
694 llvm::StringRef FileName,
Fangrui Song95b45cb2018-10-11 16:09:26 +0000695 CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000696 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000697 SmallVector<char, 128> HeaderWithSearchPath;
698 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000699 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000700 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000701 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000702 std::string IncludeLine =
703 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
704 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000705
Haojian Wufb68ca12018-01-31 12:12:29 +0000706 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000707 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
708 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000709 // Find old.h includes "old.h".
710 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
711 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
712 return;
713 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000714 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000715 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000716 // Find old.cc includes "old.h".
717 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
718 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
719 return;
720 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000721 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000722 }
Haojian Wu357ef992016-09-21 13:18:19 +0000723}
724
Haojian Wu08e402a2016-12-02 12:39:39 +0000725void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000726 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000727
728 // If old_header is not specified (only move declarations from old.cc), remain
729 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
730 // is empty in this case, there is no way to verify unused/used helpers.
731 if (!Context->Spec.OldHeader.empty()) {
732 std::vector<const NamedDecl *> UnremovedDecls;
733 for (const auto *D : UnremovedDeclsInOldHeader)
734 UnremovedDecls.push_back(D);
735
736 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
737
738 // We remove the helper declarations which are not used in the old.cc after
739 // moving the given declarations.
740 for (const auto *D : HelperDeclarations) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000741 LLVM_DEBUG(llvm::dbgs() << "Check helper is used: "
742 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu4775ce52017-01-17 13:22:37 +0000743 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
744 D->getCanonicalDecl()))) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000745 LLVM_DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
746 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000747 RemovedDecls.push_back(D);
748 }
749 }
750 }
751
Haojian Wu08e402a2016-12-02 12:39:39 +0000752 for (const auto *RemovedDecl : RemovedDecls) {
753 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
754 auto Range = getFullRange(RemovedDecl);
Fangrui Song95b45cb2018-10-11 16:09:26 +0000755 tooling::Replacement RemoveReplacement(
756 SM, CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000757 "");
758 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000759 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000760 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000761 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000762 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000763 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000764
765 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000766 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000767 StringRef FilePath = FileAndReplacements.first;
768 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000769 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000770 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000771 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000772 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000773 std::string IncludeNewH =
774 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000775 // This replacment for inserting header will be cleaned up at the end.
776 auto Err = FileAndReplacements.second.add(
777 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
778 if (Err)
779 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000780 }
Haojian Wu253d5962016-10-06 08:29:32 +0000781
Haojian Wu48ac3042016-11-23 10:04:19 +0000782 auto SI = FilePathToFileID.find(FilePath);
783 // Ignore replacements for new.h/cc.
784 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000785 llvm::StringRef Code = SM.getBufferData(SI->second);
Eric Liufa63e982018-08-02 10:30:56 +0000786 auto Style = format::getStyle(format::DefaultFormatStyle, FilePath,
787 Context->FallbackStyle);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000788 if (!Style) {
789 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
790 continue;
791 }
Haojian Wu253d5962016-10-06 08:29:32 +0000792 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000793 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000794
795 if (!CleanReplacements) {
796 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
797 continue;
798 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000799 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000800 }
801}
802
Haojian Wu08e402a2016-12-02 12:39:39 +0000803void ClangMoveTool::moveDeclsToNewFiles() {
804 std::vector<const NamedDecl *> NewHeaderDecls;
805 std::vector<const NamedDecl *> NewCCDecls;
806 for (const auto *MovedDecl : MovedDecls) {
807 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000808 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000809 NewHeaderDecls.push_back(MovedDecl);
810 else
811 NewCCDecls.push_back(MovedDecl);
812 }
813
Haojian Wu36265162017-01-03 09:00:51 +0000814 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
815 std::vector<const NamedDecl *> ActualNewCCDecls;
816
817 // Filter out all unused helpers in NewCCDecls.
818 // We only move the used helpers (including transively used helpers) and the
819 // given symbols being moved.
820 for (const auto *D : NewCCDecls) {
821 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000822 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
823 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000824 continue;
825
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000826 LLVM_DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
827 << " " << D << "\n");
Haojian Wu36265162017-01-03 09:00:51 +0000828 ActualNewCCDecls.push_back(D);
829 }
830
Haojian Wub15c8da2016-11-24 10:17:17 +0000831 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000832 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000833 Context->Spec.NewDependOnOld
834 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
835 : "";
836 Context->FileToReplacements[Context->Spec.NewHeader] =
837 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
838 Context->Spec.NewHeader, /*IsHeader=*/true,
839 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000840 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000841 if (!Context->Spec.NewCC.empty())
842 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000843 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
844 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000845}
846
Haojian Wu2930be12016-11-08 19:55:13 +0000847// Move all contents from OldFile to NewFile.
848void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
849 StringRef NewFile) {
850 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
851 if (!FE) {
852 llvm::errs() << "Failed to get file: " << OldFile << "\n";
853 return;
854 }
855 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
856 auto Begin = SM.getLocForStartOfFile(ID);
857 auto End = SM.getLocForEndOfFile(ID);
Fangrui Song95b45cb2018-10-11 16:09:26 +0000858 tooling::Replacement RemoveAll(SM, CharSourceRange::getCharRange(Begin, End),
859 "");
Haojian Wu2930be12016-11-08 19:55:13 +0000860 std::string FilePath = RemoveAll.getFilePath().str();
Fangrui Song95b45cb2018-10-11 16:09:26 +0000861 Context->FileToReplacements[FilePath] = tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000862
863 StringRef Code = SM.getBufferData(ID);
864 if (!NewFile.empty()) {
Fangrui Song95b45cb2018-10-11 16:09:26 +0000865 auto AllCode =
866 tooling::Replacements(tooling::Replacement(NewFile, 0, 0, Code));
867 auto ReplaceOldInclude = [&](CharSourceRange OldHeaderIncludeRange) {
868 AllCode = AllCode.merge(tooling::Replacements(tooling::Replacement(
869 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wufb68ca12018-01-31 12:12:29 +0000870 };
871 // Fix the case where old.h/old.cc includes "old.h", we replace the
872 // `#include "old.h"` with `#include "new.h"`.
873 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
874 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
875 else if (Context->Spec.NewHeader == NewFile &&
876 OldHeaderIncludeRangeInHeader.isValid())
877 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000878 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000879 }
880}
881
Haojian Wu357ef992016-09-21 13:18:19 +0000882void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000883 if (Context->DumpDeclarations) {
884 assert(Reporter);
885 for (const auto *Decl : UnremovedDeclsInOldHeader) {
886 auto Kind = Decl->getKind();
Eric Liubce181c2018-10-08 17:22:50 +0000887 bool Templated = Decl->isTemplated();
Haojian Wub15c8da2016-11-24 10:17:17 +0000888 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000889 if (Kind == Decl::Kind::Var)
Eric Liubce181c2018-10-08 17:22:50 +0000890 Reporter->reportDeclaration(QualifiedName, "Variable", Templated);
Haojian Wu4a920502017-02-27 13:19:13 +0000891 else if (Kind == Decl::Kind::Function ||
892 Kind == Decl::Kind::FunctionTemplate)
Eric Liubce181c2018-10-08 17:22:50 +0000893 Reporter->reportDeclaration(QualifiedName, "Function", Templated);
Haojian Wub15c8da2016-11-24 10:17:17 +0000894 else if (Kind == Decl::Kind::ClassTemplate ||
895 Kind == Decl::Kind::CXXRecord)
Eric Liubce181c2018-10-08 17:22:50 +0000896 Reporter->reportDeclaration(QualifiedName, "Class", Templated);
Haojian Wu85867722017-01-16 09:34:07 +0000897 else if (Kind == Decl::Kind::Enum)
Eric Liubce181c2018-10-08 17:22:50 +0000898 Reporter->reportDeclaration(QualifiedName, "Enum", Templated);
899 else if (Kind == Decl::Kind::Typedef || Kind == Decl::Kind::TypeAlias ||
Haojian Wu85867722017-01-16 09:34:07 +0000900 Kind == Decl::Kind::TypeAliasTemplate)
Eric Liubce181c2018-10-08 17:22:50 +0000901 Reporter->reportDeclaration(QualifiedName, "TypeAlias", Templated);
Haojian Wub15c8da2016-11-24 10:17:17 +0000902 }
903 return;
904 }
905
Haojian Wu357ef992016-09-21 13:18:19 +0000906 if (RemovedDecls.empty())
907 return;
Haojian Wud4786342018-02-09 15:57:30 +0000908 // Ignore symbols that are not supported when checking if there is unremoved
909 // symbol in old header. This makes sure that we always move old files to new
910 // files when all symbols produced from dump_decls are moved.
Fangrui Song95b45cb2018-10-11 16:09:26 +0000911 auto IsSupportedKind = [](const NamedDecl *Decl) {
Eric Liu47a42d52016-12-06 10:12:23 +0000912 switch (Decl->getKind()) {
913 case Decl::Kind::Function:
914 case Decl::Kind::FunctionTemplate:
915 case Decl::Kind::ClassTemplate:
916 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000917 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000918 case Decl::Kind::Typedef:
919 case Decl::Kind::TypeAlias:
920 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000921 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000922 return true;
923 default:
924 return false;
925 }
926 };
927 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
928 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
929 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000930 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000931 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
932 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000933 return;
934 }
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000935 LLVM_DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000936 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000937 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000938}
939
940} // namespace move
941} // namespace clang