blob: 7626d1ccedfc4e30229ae2520f78c931d52ffd52 [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
Haojian Wud2a6d7b2016-10-04 09:05:31 +000064// Make the Path absolute using the CurrentDir if the Path is not an absolute
65// path. An empty Path will result in an empty string.
66std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
67 if (Path.empty())
68 return "";
69 llvm::SmallString<128> InitialDirectory(CurrentDir);
70 llvm::SmallString<128> AbsolutePath(Path);
71 if (std::error_code EC =
72 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000073 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000074 << '\n';
75 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wuc6f125e2016-10-04 09:49:20 +000076 llvm::sys::path::native(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +000077 return AbsolutePath.str();
78}
79
80// Make the Path absolute using the current working directory of the given
81// SourceManager if the Path is not an absolute path.
82//
83// The Path can be a path relative to the build directory, or retrieved from
84// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000085std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000086 llvm::SmallString<128> AbsolutePath(Path);
87 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000088 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
89 AbsolutePath))
90 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000091 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000092 // Handle symbolic link path cases.
93 // We are trying to get the real file path of the symlink.
94 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000095 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +000096 if (Dir) {
97 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
Eric Liuad3fed62018-05-16 20:10:10 +000098 // FIXME: getCanonicalName might fail to get real path on VFS.
99 if (llvm::sys::path::is_absolute(DirName)) {
100 SmallVector<char, 128> AbsoluteFilename;
101 llvm::sys::path::append(AbsoluteFilename, DirName,
102 llvm::sys::path::filename(AbsolutePath.str()));
103 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
104 .str();
105 }
Haojian Wudb726572016-10-12 15:50:30 +0000106 }
Eric Liuad3fed62018-05-16 20:10:10 +0000107 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000108 return AbsolutePath.str();
109}
110
111// Matches AST nodes that are expanded within the given AbsoluteFilePath.
112AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
113 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
114 std::string, AbsoluteFilePath) {
115 auto &SourceManager = Finder->getASTContext().getSourceManager();
116 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
117 if (ExpansionLoc.isInvalid())
118 return false;
119 auto FileEntry =
120 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
121 if (!FileEntry)
122 return false;
123 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
124 AbsoluteFilePath;
125}
126
Haojian Wu357ef992016-09-21 13:18:19 +0000127class FindAllIncludes : public clang::PPCallbacks {
128public:
129 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
130 : SM(*SM), MoveTool(MoveTool) {}
131
132 void InclusionDirective(clang::SourceLocation HashLoc,
133 const clang::Token & /*IncludeTok*/,
134 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000135 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000136 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000137 StringRef SearchPath, StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +0000138 const clang::Module * /*Imported*/,
139 SrcMgr::CharacteristicKind /*FileType*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000140 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000141 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000142 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000143 }
144
145private:
146 const SourceManager &SM;
147 ClangMoveTool *const MoveTool;
148};
149
Haojian Wu32a552f2017-01-03 14:22:25 +0000150/// Add a declatration being moved to new.h/cc. Note that the declaration will
151/// also be deleted in old.h/cc.
152void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
153 MoveTool->getMovedDecls().push_back(D);
154 MoveTool->addRemovedDecl(D);
155 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
156}
157
Haojian Wu4543fec2016-11-16 13:05:19 +0000158class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
159public:
160 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
161 : MoveTool(MoveTool) {}
162
163 void run(const MatchFinder::MatchResult &Result) override {
164 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
165 assert(FD);
166 const clang::NamedDecl *D = FD;
167 if (const auto *FTD = FD->getDescribedFunctionTemplate())
168 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000169 MoveDeclFromOldFileToNewFile(MoveTool, D);
170 }
171
172private:
173 ClangMoveTool *MoveTool;
174};
175
Haojian Wu4a920502017-02-27 13:19:13 +0000176class VarDeclarationMatch : public MatchFinder::MatchCallback {
177public:
178 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
179 : MoveTool(MoveTool) {}
180
181 void run(const MatchFinder::MatchResult &Result) override {
182 const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>("var");
183 assert(VD);
184 MoveDeclFromOldFileToNewFile(MoveTool, VD);
185 }
186
187private:
188 ClangMoveTool *MoveTool;
189};
190
Haojian Wud69d9072017-01-04 14:50:49 +0000191class TypeAliasMatch : public MatchFinder::MatchCallback {
192public:
193 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
194 : MoveTool(MoveTool) {}
195
196 void run(const MatchFinder::MatchResult &Result) override {
197 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
198 MoveDeclFromOldFileToNewFile(MoveTool, TD);
199 else if (const auto *TAD =
200 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
201 const NamedDecl * D = TAD;
202 if (const auto * TD = TAD->getDescribedAliasTemplate())
203 D = TD;
204 MoveDeclFromOldFileToNewFile(MoveTool, D);
205 }
206 }
207
208private:
209 ClangMoveTool *MoveTool;
210};
211
Haojian Wu32a552f2017-01-03 14:22:25 +0000212class EnumDeclarationMatch : public MatchFinder::MatchCallback {
213public:
214 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
215 : MoveTool(MoveTool) {}
216
217 void run(const MatchFinder::MatchResult &Result) override {
218 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
219 assert(ED);
220 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000221 }
222
223private:
224 ClangMoveTool *MoveTool;
225};
226
Haojian Wu35ca9462016-11-14 14:15:44 +0000227class ClassDeclarationMatch : public MatchFinder::MatchCallback {
228public:
229 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
230 : MoveTool(MoveTool) {}
231 void run(const MatchFinder::MatchResult &Result) override {
232 clang::SourceManager* SM = &Result.Context->getSourceManager();
233 if (const auto *CMD =
234 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
235 MatchClassMethod(CMD, SM);
236 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
237 "class_static_var_decl"))
238 MatchClassStaticVariable(VD, SM);
239 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
240 "moved_class"))
241 MatchClassDeclaration(CD, SM);
242 }
243
244private:
245 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
246 clang::SourceManager* SM) {
247 // Skip inline class methods. isInline() ast matcher doesn't ignore this
248 // case.
249 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000250 MoveTool->getMovedDecls().push_back(CMD);
251 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000252 // Get template class method from its method declaration as
253 // UnremovedDecls stores template class method.
254 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
255 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
256 else
257 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
258 }
259 }
260
261 void MatchClassStaticVariable(const clang::NamedDecl *VD,
262 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000263 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000264 }
265
266 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
267 clang::SourceManager* SM) {
268 // Get class template from its class declaration as UnremovedDecls stores
269 // class template.
270 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000271 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000272 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000273 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000274 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000275 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000276 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000277 }
278
279 ClangMoveTool *MoveTool;
280};
281
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000282// Expand to get the end location of the line where the EndLoc of the given
283// Decl.
284SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000285getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000286 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000287 const auto &SM = D->getASTContext().getSourceManager();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000288 // If the expansion range is a character range, this is the location of
289 // the first character past the end. Otherwise it's the location of the
290 // first character in the final token in the range.
291 auto EndExpansionLoc = SM.getExpansionRange(D->getLocEnd()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000292 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000293 // Try to load the file buffer.
294 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000295 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000296 if (InvalidTemp)
297 return SourceLocation();
298
299 const char *TokBegin = File.data() + LocInfo.second;
300 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000301 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000302 TokBegin, File.end());
303
304 llvm::SmallVector<char, 16> Line;
305 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
306 Lex.setParsingPreprocessorDirective(true);
307 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000308 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000309 // If we already reach EOF, just return the EOF SourceLocation;
310 // otherwise, move 1 offset ahead to include the trailing newline character
311 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000312 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000313 ? EndLoc
314 : EndLoc.getLocWithOffset(1);
315}
316
317// Get full range of a Decl including the comments associated with it.
318clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000319getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000320 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000321 const auto &SM = D->getASTContext().getSourceManager();
322 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
323 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000324 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000325 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000326 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000327 Full.setEnd(Comment->getLocEnd());
328 // FIXME: Don't delete a preceding comment, if there are no other entities
329 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000330 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000331 Full.setBegin(Comment->getLocStart());
332 }
333
334 return clang::CharSourceRange::getCharRange(Full);
335}
336
Haojian Wu08e402a2016-12-02 12:39:39 +0000337std::string getDeclarationSourceText(const clang::Decl *D) {
338 const auto &SM = D->getASTContext().getSourceManager();
339 llvm::StringRef SourceText =
340 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000341 return SourceText.str();
342}
343
Haojian Wu08e402a2016-12-02 12:39:39 +0000344bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000345 llvm::StringRef OriginalRunningDirectory,
346 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000347 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000348 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000349 return false;
350 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
351 if (ExpansionLoc.isInvalid())
352 return false;
353
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000354 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
355 return MakeAbsolutePath(SM, FE->getName()) ==
356 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
357 }
Haojian Wu357ef992016-09-21 13:18:19 +0000358
359 return false;
360}
361
Haojian Wu08e402a2016-12-02 12:39:39 +0000362std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000363 std::vector<std::string> Namespaces;
364 for (const auto *Context = D->getDeclContext(); Context;
365 Context = Context->getParent()) {
366 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
367 llvm::isa<clang::LinkageSpecDecl>(Context))
368 break;
369
370 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
371 Namespaces.push_back(ND->getName().str());
372 }
373 std::reverse(Namespaces.begin(), Namespaces.end());
374 return Namespaces;
375}
376
Haojian Wu357ef992016-09-21 13:18:19 +0000377clang::tooling::Replacements
378createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000379 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000380 llvm::StringRef FileName, bool IsHeader = false,
381 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000382 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000383 std::string GuardName(FileName);
384 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000385 for (size_t i = 0; i < GuardName.size(); ++i) {
386 if (!isAlphanumeric(GuardName[i]))
387 GuardName[i] = '_';
388 }
Haojian Wu220c7552016-10-14 13:01:36 +0000389 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000390 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000391 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000392 }
Haojian Wu357ef992016-09-21 13:18:19 +0000393
Haojian Wu48ac3042016-11-23 10:04:19 +0000394 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000395 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000396 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000397 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000398
Haojian Wu53eab1e2016-10-14 13:43:49 +0000399 if (!Includes.empty())
400 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000401
402 // Add moved class definition and its related declarations. All declarations
403 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000404 //
405 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000406 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000407 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000408 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000409 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000410 auto CurrentIt = CurrentNamespaces.begin();
411 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000412 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000413 while (CurrentIt != CurrentNamespaces.end() &&
414 DeclIt != DeclNamespaces.end()) {
415 if (*CurrentIt != *DeclIt)
416 break;
417 ++CurrentIt;
418 ++DeclIt;
419 }
Haojian Wu53315a72016-11-15 09:06:59 +0000420 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
421 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000422 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
423 CurrentIt);
424 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000425
426
427 // End with CurrentNamespace.
428 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000429 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
430 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
431 --RemainingSize, ++It) {
432 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000433 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000434 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000435 }
Haojian Wu53315a72016-11-15 09:06:59 +0000436 // Add trailing '\n' after the nested namespace definition.
437 if (HasEndCurrentNamespace)
438 NewCode += "\n";
439
440 // If the moved declaration is not in CurrentNamespace, add extra namespace
441 // definitions.
442 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000443 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000444 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000445 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000446 ++DeclIt;
447 }
Haojian Wu53315a72016-11-15 09:06:59 +0000448 // If the moved declaration is in same namespace CurrentNamespace, add
449 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000450 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000451 if (!IsInNewNamespace)
452 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000453 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000454 CurrentNamespaces = std::move(NextNamespaces);
455 }
456 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000457 for (const auto &NS : CurrentNamespaces)
458 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000459
Haojian Wu53eab1e2016-10-14 13:43:49 +0000460 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000461 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000462 return clang::tooling::Replacements(
463 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000464}
465
Haojian Wu36265162017-01-03 09:00:51 +0000466// Return a set of all decls which are used/referenced by the given Decls.
467// Specically, given a class member declaration, this method will return all
468// decls which are used by the whole class.
469llvm::DenseSet<const Decl *>
470getUsedDecls(const HelperDeclRefGraph *RG,
471 const std::vector<const NamedDecl *> &Decls) {
472 assert(RG);
473 llvm::DenseSet<const CallGraphNode *> Nodes;
474 for (const auto *D : Decls) {
475 auto Result = RG->getReachableNodes(
476 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
477 Nodes.insert(Result.begin(), Result.end());
478 }
479 llvm::DenseSet<const Decl *> Results;
480 for (const auto *Node : Nodes)
481 Results.insert(Node->getDecl());
482 return Results;
483}
484
Haojian Wu357ef992016-09-21 13:18:19 +0000485} // namespace
486
487std::unique_ptr<clang::ASTConsumer>
488ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
489 StringRef /*InFile*/) {
490 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
491 &Compiler.getSourceManager(), &MoveTool));
492 return MatchFinder.newASTConsumer();
493}
494
Haojian Wub15c8da2016-11-24 10:17:17 +0000495ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
496 DeclarationReporter *const Reporter)
497 : Context(Context), Reporter(Reporter) {
498 if (!Context->Spec.NewHeader.empty())
499 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000500}
501
Haojian Wu08e402a2016-12-02 12:39:39 +0000502void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
503 const auto &SM = Decl->getASTContext().getSourceManager();
504 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000505 StringRef FilePath = SM.getFilename(Loc);
506 FilePathToFileID[FilePath] = SM.getFileID(Loc);
507 RemovedDecls.push_back(Decl);
508}
509
Haojian Wu357ef992016-09-21 13:18:19 +0000510void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000511 auto InOldHeader =
512 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
513 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000514 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000515 auto classTemplateForwardDecls =
516 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
517 auto ForwardClassDecls = namedDecl(
518 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
519 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000520 auto TopLevelDecl =
521 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000522
523 //============================================================================
524 // Matchers for old header
525 //============================================================================
526 // Match all top-level named declarations (e.g. function, variable, enum) in
527 // old header, exclude forward class declarations and namespace declarations.
528 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000529 // We consider declarations inside a class belongs to the class. So these
530 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000531 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000532 unless(ForwardClassDecls), unless(namespaceDecl()),
533 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000534 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000535 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000536 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
537 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000538 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000539
540 // Don't register other matchers when dumping all declarations in header.
541 if (Context->DumpDeclarations)
542 return;
543
Haojian Wu2930be12016-11-08 19:55:13 +0000544 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000545 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000546 this);
547
548 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000549 // Matchers for old cc
550 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000551 auto IsOldCCTopLevelDecl = allOf(
552 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
553 // Matching using decls/type alias decls which are in named/anonymous/global
554 // namespace, these decls are always copied to new.h/cc. Those in classes,
555 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000556 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
557 usingDirectiveDecl(IsOldCCTopLevelDecl),
558 typeAliasDecl(IsOldCCTopLevelDecl)),
559 notInMacro())
560 .bind("using_decl"),
561 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000562
Haojian Wu67bb6512016-10-19 14:13:21 +0000563 // Match static functions/variable definitions which are defined in named
564 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000565 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
566 for (StringRef SymbolName : Context->Spec.Names) {
567 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
568 const auto HasName = hasName(("::" + GlobalSymbolName).str());
569 HasAnySymbolNames =
570 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
571 }
572
573 if (!HasAnySymbolNames) {
574 llvm::errs() << "No symbols being moved.\n";
575 return;
576 }
577 auto InMovedClass =
578 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000579
580 // Matchers for helper declarations in old.cc.
581 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000582 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
583 auto IsOldCCHelper =
584 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000585 // Match helper classes separately with helper functions/variables since we
586 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000587 //
588 // There could be forward declarations usage for helpers, especially for
589 // classes and functions. We need include these forward declarations.
590 //
591 // Forward declarations for variable helpers will be excluded as these
592 // declarations (with "extern") are not supposed in cpp file.
593 auto HelperFuncOrVar =
594 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
595 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000596 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000597 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000598 // Save all helper declarations in old.cc.
599 Finder->addMatcher(
600 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
601 this);
602
603 // Construct an AST-based call graph of helper declarations in old.cc.
604 // In the following matcheres, "dc" is a caller while "helper_decls" and
605 // "used_class" is a callee, so a new edge starting from caller to callee will
606 // be add in the graph.
607 //
608 // Find helper function/variable usages.
609 Finder->addMatcher(
610 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
611 .bind("func_ref"),
612 &RGBuilder);
613 // Find helper class usages.
614 Finder->addMatcher(
615 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
616 hasAncestor(decl().bind("dc"))),
617 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000618
619 //============================================================================
620 // Matchers for old files, including old.h/old.cc
621 //============================================================================
622 // Create a MatchCallback for class declarations.
623 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
624 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000625 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
626 isDefinition(), TopLevelDecl)
627 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000628 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
629 // Match moved class methods (static methods included) which are defined
630 // outside moved class declaration.
631 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000632 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000633 isDefinition())
634 .bind("class_method"),
635 MatchCallbacks.back().get());
636 // Match static member variable definition of the moved class.
637 Finder->addMatcher(
638 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
639 .bind("class_static_var_decl"),
640 MatchCallbacks.back().get());
641
Haojian Wu4543fec2016-11-16 13:05:19 +0000642 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000643 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000644 .bind("function"),
645 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000646
Haojian Wu4a920502017-02-27 13:19:13 +0000647 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
648 Finder->addMatcher(
649 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
650 MatchCallbacks.back().get());
651
Haojian Wud69d9072017-01-04 14:50:49 +0000652 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000653 // will not be moved for now no matter whether they are used or not.
654 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
655 Finder->addMatcher(
656 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
657 .bind("enum"),
658 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000659
660 // Match type alias in old.h, this includes "typedef" and "using" type alias
661 // declarations. Type alias helpers (which are defined in old.cc) will not be
662 // moved for now no matter whether they are used or not.
663 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
664 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
665 typeAliasDecl().bind("type_alias")),
666 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
667 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000668}
669
670void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000671 if (const auto *D =
672 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
673 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000674 } else if (const auto *FWD =
675 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000676 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000677 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000678 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000679 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000680 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000681 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000682 }
Haojian Wu357ef992016-09-21 13:18:19 +0000683 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000684 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
685 MovedDecls.push_back(ND);
686 HelperDeclarations.push_back(ND);
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000687 LLVM_DEBUG(llvm::dbgs() << "Add helper : " << ND->getNameAsString() << " ("
688 << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000689 } else if (const auto *UD =
690 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000691 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000692 }
693}
694
Haojian Wu2930be12016-11-08 19:55:13 +0000695std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000696 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000697}
698
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000699void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000700 llvm::StringRef SearchPath,
701 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000702 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000703 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000704 SmallVector<char, 128> HeaderWithSearchPath;
705 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000706 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000707 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000708 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000709 std::string IncludeLine =
710 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
711 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000712
Haojian Wufb68ca12018-01-31 12:12:29 +0000713 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000714 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
715 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000716 // Find old.h includes "old.h".
717 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
718 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
719 return;
720 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000721 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000722 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000723 // Find old.cc includes "old.h".
724 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
725 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
726 return;
727 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000728 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000729 }
Haojian Wu357ef992016-09-21 13:18:19 +0000730}
731
Haojian Wu08e402a2016-12-02 12:39:39 +0000732void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000733 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000734
735 // If old_header is not specified (only move declarations from old.cc), remain
736 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
737 // is empty in this case, there is no way to verify unused/used helpers.
738 if (!Context->Spec.OldHeader.empty()) {
739 std::vector<const NamedDecl *> UnremovedDecls;
740 for (const auto *D : UnremovedDeclsInOldHeader)
741 UnremovedDecls.push_back(D);
742
743 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
744
745 // We remove the helper declarations which are not used in the old.cc after
746 // moving the given declarations.
747 for (const auto *D : HelperDeclarations) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000748 LLVM_DEBUG(llvm::dbgs() << "Check helper is used: "
749 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu4775ce52017-01-17 13:22:37 +0000750 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
751 D->getCanonicalDecl()))) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000752 LLVM_DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
753 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000754 RemovedDecls.push_back(D);
755 }
756 }
757 }
758
Haojian Wu08e402a2016-12-02 12:39:39 +0000759 for (const auto *RemovedDecl : RemovedDecls) {
760 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
761 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000762 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000763 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000764 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000765 "");
766 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000767 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000768 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000769 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000770 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000771 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000772
773 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000774 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000775 StringRef FilePath = FileAndReplacements.first;
776 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000777 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000778 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000779 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000780 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000781 std::string IncludeNewH =
782 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000783 // This replacment for inserting header will be cleaned up at the end.
784 auto Err = FileAndReplacements.second.add(
785 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
786 if (Err)
787 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000788 }
Haojian Wu253d5962016-10-06 08:29:32 +0000789
Haojian Wu48ac3042016-11-23 10:04:19 +0000790 auto SI = FilePathToFileID.find(FilePath);
791 // Ignore replacements for new.h/cc.
792 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000793 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000794 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
795 if (!Style) {
796 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
797 continue;
798 }
Haojian Wu253d5962016-10-06 08:29:32 +0000799 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000800 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000801
802 if (!CleanReplacements) {
803 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
804 continue;
805 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000806 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000807 }
808}
809
Haojian Wu08e402a2016-12-02 12:39:39 +0000810void ClangMoveTool::moveDeclsToNewFiles() {
811 std::vector<const NamedDecl *> NewHeaderDecls;
812 std::vector<const NamedDecl *> NewCCDecls;
813 for (const auto *MovedDecl : MovedDecls) {
814 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000815 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000816 NewHeaderDecls.push_back(MovedDecl);
817 else
818 NewCCDecls.push_back(MovedDecl);
819 }
820
Haojian Wu36265162017-01-03 09:00:51 +0000821 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
822 std::vector<const NamedDecl *> ActualNewCCDecls;
823
824 // Filter out all unused helpers in NewCCDecls.
825 // We only move the used helpers (including transively used helpers) and the
826 // given symbols being moved.
827 for (const auto *D : NewCCDecls) {
828 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000829 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
830 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000831 continue;
832
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000833 LLVM_DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
834 << " " << D << "\n");
Haojian Wu36265162017-01-03 09:00:51 +0000835 ActualNewCCDecls.push_back(D);
836 }
837
Haojian Wub15c8da2016-11-24 10:17:17 +0000838 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000839 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000840 Context->Spec.NewDependOnOld
841 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
842 : "";
843 Context->FileToReplacements[Context->Spec.NewHeader] =
844 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
845 Context->Spec.NewHeader, /*IsHeader=*/true,
846 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000847 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000848 if (!Context->Spec.NewCC.empty())
849 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000850 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
851 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000852}
853
Haojian Wu2930be12016-11-08 19:55:13 +0000854// Move all contents from OldFile to NewFile.
855void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
856 StringRef NewFile) {
857 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
858 if (!FE) {
859 llvm::errs() << "Failed to get file: " << OldFile << "\n";
860 return;
861 }
862 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
863 auto Begin = SM.getLocForStartOfFile(ID);
864 auto End = SM.getLocForEndOfFile(ID);
865 clang::tooling::Replacement RemoveAll (
866 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
867 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000868 Context->FileToReplacements[FilePath] =
869 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000870
871 StringRef Code = SM.getBufferData(ID);
872 if (!NewFile.empty()) {
873 auto AllCode = clang::tooling::Replacements(
874 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000875 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
876 AllCode = AllCode.merge(clang::tooling::Replacements(
877 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
878 '"' + Context->Spec.NewHeader + '"')));
879 };
880 // Fix the case where old.h/old.cc includes "old.h", we replace the
881 // `#include "old.h"` with `#include "new.h"`.
882 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
883 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
884 else if (Context->Spec.NewHeader == NewFile &&
885 OldHeaderIncludeRangeInHeader.isValid())
886 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000887 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000888 }
889}
890
Haojian Wu357ef992016-09-21 13:18:19 +0000891void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000892 if (Context->DumpDeclarations) {
893 assert(Reporter);
894 for (const auto *Decl : UnremovedDeclsInOldHeader) {
895 auto Kind = Decl->getKind();
896 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000897 if (Kind == Decl::Kind::Var)
898 Reporter->reportDeclaration(QualifiedName, "Variable");
899 else if (Kind == Decl::Kind::Function ||
900 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000901 Reporter->reportDeclaration(QualifiedName, "Function");
902 else if (Kind == Decl::Kind::ClassTemplate ||
903 Kind == Decl::Kind::CXXRecord)
904 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000905 else if (Kind == Decl::Kind::Enum)
906 Reporter->reportDeclaration(QualifiedName, "Enum");
907 else if (Kind == Decl::Kind::Typedef ||
908 Kind == Decl::Kind::TypeAlias ||
909 Kind == Decl::Kind::TypeAliasTemplate)
910 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000911 }
912 return;
913 }
914
Haojian Wu357ef992016-09-21 13:18:19 +0000915 if (RemovedDecls.empty())
916 return;
Haojian Wud4786342018-02-09 15:57:30 +0000917 // Ignore symbols that are not supported when checking if there is unremoved
918 // symbol in old header. This makes sure that we always move old files to new
919 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000920 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
921 switch (Decl->getKind()) {
922 case Decl::Kind::Function:
923 case Decl::Kind::FunctionTemplate:
924 case Decl::Kind::ClassTemplate:
925 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000926 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000927 case Decl::Kind::Typedef:
928 case Decl::Kind::TypeAlias:
929 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000930 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000931 return true;
932 default:
933 return false;
934 }
935 };
936 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
937 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
938 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000939 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000940 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
941 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000942 return;
943 }
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000944 LLVM_DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000945 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000946 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000947}
948
949} // namespace move
950} // namespace clang