blob: 0f104e499eb8ad131e75eddfa0bf5c6950b51a90 [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
Haojian Wu357ef992016-09-21 13:18:19 +0000131class FindAllIncludes : public clang::PPCallbacks {
132public:
133 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
134 : SM(*SM), MoveTool(MoveTool) {}
135
136 void InclusionDirective(clang::SourceLocation HashLoc,
137 const clang::Token & /*IncludeTok*/,
138 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000139 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000140 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000141 StringRef SearchPath, StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +0000142 const clang::Module * /*Imported*/,
143 SrcMgr::CharacteristicKind /*FileType*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000144 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000145 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000146 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000147 }
148
149private:
150 const SourceManager &SM;
151 ClangMoveTool *const MoveTool;
152};
153
Haojian Wu32a552f2017-01-03 14:22:25 +0000154/// Add a declatration being moved to new.h/cc. Note that the declaration will
155/// also be deleted in old.h/cc.
156void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
157 MoveTool->getMovedDecls().push_back(D);
158 MoveTool->addRemovedDecl(D);
159 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
160}
161
Haojian Wu4543fec2016-11-16 13:05:19 +0000162class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
163public:
164 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
165 : MoveTool(MoveTool) {}
166
167 void run(const MatchFinder::MatchResult &Result) override {
168 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
169 assert(FD);
170 const clang::NamedDecl *D = FD;
171 if (const auto *FTD = FD->getDescribedFunctionTemplate())
172 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000173 MoveDeclFromOldFileToNewFile(MoveTool, D);
174 }
175
176private:
177 ClangMoveTool *MoveTool;
178};
179
Haojian Wu4a920502017-02-27 13:19:13 +0000180class VarDeclarationMatch : public MatchFinder::MatchCallback {
181public:
182 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
183 : MoveTool(MoveTool) {}
184
185 void run(const MatchFinder::MatchResult &Result) override {
186 const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>("var");
187 assert(VD);
188 MoveDeclFromOldFileToNewFile(MoveTool, VD);
189 }
190
191private:
192 ClangMoveTool *MoveTool;
193};
194
Haojian Wud69d9072017-01-04 14:50:49 +0000195class TypeAliasMatch : public MatchFinder::MatchCallback {
196public:
197 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
198 : MoveTool(MoveTool) {}
199
200 void run(const MatchFinder::MatchResult &Result) override {
201 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
202 MoveDeclFromOldFileToNewFile(MoveTool, TD);
203 else if (const auto *TAD =
204 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
205 const NamedDecl * D = TAD;
206 if (const auto * TD = TAD->getDescribedAliasTemplate())
207 D = TD;
208 MoveDeclFromOldFileToNewFile(MoveTool, D);
209 }
210 }
211
212private:
213 ClangMoveTool *MoveTool;
214};
215
Haojian Wu32a552f2017-01-03 14:22:25 +0000216class EnumDeclarationMatch : public MatchFinder::MatchCallback {
217public:
218 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
219 : MoveTool(MoveTool) {}
220
221 void run(const MatchFinder::MatchResult &Result) override {
222 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
223 assert(ED);
224 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000225 }
226
227private:
228 ClangMoveTool *MoveTool;
229};
230
Haojian Wu35ca9462016-11-14 14:15:44 +0000231class ClassDeclarationMatch : public MatchFinder::MatchCallback {
232public:
233 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
234 : MoveTool(MoveTool) {}
235 void run(const MatchFinder::MatchResult &Result) override {
236 clang::SourceManager* SM = &Result.Context->getSourceManager();
237 if (const auto *CMD =
238 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
239 MatchClassMethod(CMD, SM);
240 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
241 "class_static_var_decl"))
242 MatchClassStaticVariable(VD, SM);
243 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
244 "moved_class"))
245 MatchClassDeclaration(CD, SM);
246 }
247
248private:
249 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
250 clang::SourceManager* SM) {
251 // Skip inline class methods. isInline() ast matcher doesn't ignore this
252 // case.
253 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000254 MoveTool->getMovedDecls().push_back(CMD);
255 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000256 // Get template class method from its method declaration as
257 // UnremovedDecls stores template class method.
258 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
259 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
260 else
261 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
262 }
263 }
264
265 void MatchClassStaticVariable(const clang::NamedDecl *VD,
266 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000267 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000268 }
269
270 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
271 clang::SourceManager* SM) {
272 // Get class template from its class declaration as UnremovedDecls stores
273 // class template.
274 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000275 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000276 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000277 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000278 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000279 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000280 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000281 }
282
283 ClangMoveTool *MoveTool;
284};
285
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000286// Expand to get the end location of the line where the EndLoc of the given
287// Decl.
288SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000289getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000290 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000291 const auto &SM = D->getASTContext().getSourceManager();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000292 // If the expansion range is a character range, this is the location of
293 // the first character past the end. Otherwise it's the location of the
294 // first character in the final token in the range.
Stephen Kellyc09197e2018-08-09 22:43:02 +0000295 auto EndExpansionLoc = SM.getExpansionRange(D->getEndLoc()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000296 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000297 // Try to load the file buffer.
298 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000299 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000300 if (InvalidTemp)
301 return SourceLocation();
302
303 const char *TokBegin = File.data() + LocInfo.second;
304 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000305 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000306 TokBegin, File.end());
307
308 llvm::SmallVector<char, 16> Line;
309 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
310 Lex.setParsingPreprocessorDirective(true);
311 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000312 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000313 // If we already reach EOF, just return the EOF SourceLocation;
314 // otherwise, move 1 offset ahead to include the trailing newline character
315 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000316 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000317 ? EndLoc
318 : EndLoc.getLocWithOffset(1);
319}
320
321// Get full range of a Decl including the comments associated with it.
322clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000323getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000324 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000325 const auto &SM = D->getASTContext().getSourceManager();
Stephen Kelly43465bf2018-08-09 22:42:26 +0000326 clang::SourceRange Full(SM.getExpansionLoc(D->getBeginLoc()),
Haojian Wu08e402a2016-12-02 12:39:39 +0000327 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000328 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000329 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Stephen Kellyc09197e2018-08-09 22:43:02 +0000330 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getEndLoc()))
331 Full.setEnd(Comment->getEndLoc());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000332 // FIXME: Don't delete a preceding comment, if there are no other entities
333 // it could refer to.
Stephen Kelly43465bf2018-08-09 22:42:26 +0000334 if (SM.isBeforeInTranslationUnit(Comment->getBeginLoc(), Full.getBegin()))
335 Full.setBegin(Comment->getBeginLoc());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000336 }
337
338 return clang::CharSourceRange::getCharRange(Full);
339}
340
Haojian Wu08e402a2016-12-02 12:39:39 +0000341std::string getDeclarationSourceText(const clang::Decl *D) {
342 const auto &SM = D->getASTContext().getSourceManager();
343 llvm::StringRef SourceText =
344 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000345 return SourceText.str();
346}
347
Haojian Wu08e402a2016-12-02 12:39:39 +0000348bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000349 llvm::StringRef OriginalRunningDirectory,
350 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000351 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000352 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000353 return false;
Stephen Kelly43465bf2018-08-09 22:42:26 +0000354 auto ExpansionLoc = SM.getExpansionLoc(D->getBeginLoc());
Haojian Wu357ef992016-09-21 13:18:19 +0000355 if (ExpansionLoc.isInvalid())
356 return false;
357
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000358 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
359 return MakeAbsolutePath(SM, FE->getName()) ==
360 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
361 }
Haojian Wu357ef992016-09-21 13:18:19 +0000362
363 return false;
364}
365
Haojian Wu08e402a2016-12-02 12:39:39 +0000366std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000367 std::vector<std::string> Namespaces;
368 for (const auto *Context = D->getDeclContext(); Context;
369 Context = Context->getParent()) {
370 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
371 llvm::isa<clang::LinkageSpecDecl>(Context))
372 break;
373
374 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
375 Namespaces.push_back(ND->getName().str());
376 }
377 std::reverse(Namespaces.begin(), Namespaces.end());
378 return Namespaces;
379}
380
Haojian Wu357ef992016-09-21 13:18:19 +0000381clang::tooling::Replacements
382createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000383 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000384 llvm::StringRef FileName, bool IsHeader = false,
385 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000386 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000387 std::string GuardName(FileName);
388 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000389 for (size_t i = 0; i < GuardName.size(); ++i) {
390 if (!isAlphanumeric(GuardName[i]))
391 GuardName[i] = '_';
392 }
Haojian Wu220c7552016-10-14 13:01:36 +0000393 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000394 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000395 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000396 }
Haojian Wu357ef992016-09-21 13:18:19 +0000397
Haojian Wu48ac3042016-11-23 10:04:19 +0000398 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000399 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000400 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000401 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000402
Haojian Wu53eab1e2016-10-14 13:43:49 +0000403 if (!Includes.empty())
404 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000405
406 // Add moved class definition and its related declarations. All declarations
407 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000408 //
409 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000410 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000411 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000412 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000413 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000414 auto CurrentIt = CurrentNamespaces.begin();
415 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000416 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000417 while (CurrentIt != CurrentNamespaces.end() &&
418 DeclIt != DeclNamespaces.end()) {
419 if (*CurrentIt != *DeclIt)
420 break;
421 ++CurrentIt;
422 ++DeclIt;
423 }
Haojian Wu53315a72016-11-15 09:06:59 +0000424 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
425 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000426 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
427 CurrentIt);
428 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000429
430
431 // End with CurrentNamespace.
432 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000433 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
434 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
435 --RemainingSize, ++It) {
436 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000437 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000438 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000439 }
Haojian Wu53315a72016-11-15 09:06:59 +0000440 // Add trailing '\n' after the nested namespace definition.
441 if (HasEndCurrentNamespace)
442 NewCode += "\n";
443
444 // If the moved declaration is not in CurrentNamespace, add extra namespace
445 // definitions.
446 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000447 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000448 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000449 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000450 ++DeclIt;
451 }
Haojian Wu53315a72016-11-15 09:06:59 +0000452 // If the moved declaration is in same namespace CurrentNamespace, add
453 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000454 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000455 if (!IsInNewNamespace)
456 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000457 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000458 CurrentNamespaces = std::move(NextNamespaces);
459 }
460 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000461 for (const auto &NS : CurrentNamespaces)
462 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000463
Haojian Wu53eab1e2016-10-14 13:43:49 +0000464 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000465 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000466 return clang::tooling::Replacements(
467 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000468}
469
Haojian Wu36265162017-01-03 09:00:51 +0000470// Return a set of all decls which are used/referenced by the given Decls.
471// Specically, given a class member declaration, this method will return all
472// decls which are used by the whole class.
473llvm::DenseSet<const Decl *>
474getUsedDecls(const HelperDeclRefGraph *RG,
475 const std::vector<const NamedDecl *> &Decls) {
476 assert(RG);
477 llvm::DenseSet<const CallGraphNode *> Nodes;
478 for (const auto *D : Decls) {
479 auto Result = RG->getReachableNodes(
480 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
481 Nodes.insert(Result.begin(), Result.end());
482 }
483 llvm::DenseSet<const Decl *> Results;
484 for (const auto *Node : Nodes)
485 Results.insert(Node->getDecl());
486 return Results;
487}
488
Haojian Wu357ef992016-09-21 13:18:19 +0000489} // namespace
490
491std::unique_ptr<clang::ASTConsumer>
492ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
493 StringRef /*InFile*/) {
494 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
495 &Compiler.getSourceManager(), &MoveTool));
496 return MatchFinder.newASTConsumer();
497}
498
Haojian Wub15c8da2016-11-24 10:17:17 +0000499ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
500 DeclarationReporter *const Reporter)
501 : Context(Context), Reporter(Reporter) {
502 if (!Context->Spec.NewHeader.empty())
503 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000504}
505
Haojian Wu08e402a2016-12-02 12:39:39 +0000506void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
507 const auto &SM = Decl->getASTContext().getSourceManager();
508 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000509 StringRef FilePath = SM.getFilename(Loc);
510 FilePathToFileID[FilePath] = SM.getFileID(Loc);
511 RemovedDecls.push_back(Decl);
512}
513
Haojian Wu357ef992016-09-21 13:18:19 +0000514void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000515 auto InOldHeader =
516 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
517 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000518 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000519 auto classTemplateForwardDecls =
520 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
521 auto ForwardClassDecls = namedDecl(
522 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
523 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000524 auto TopLevelDecl =
525 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000526
527 //============================================================================
528 // Matchers for old header
529 //============================================================================
530 // Match all top-level named declarations (e.g. function, variable, enum) in
531 // old header, exclude forward class declarations and namespace declarations.
532 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000533 // We consider declarations inside a class belongs to the class. So these
534 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000535 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000536 unless(ForwardClassDecls), unless(namespaceDecl()),
537 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000538 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000539 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000540 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
541 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000542 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000543
544 // Don't register other matchers when dumping all declarations in header.
545 if (Context->DumpDeclarations)
546 return;
547
Haojian Wu2930be12016-11-08 19:55:13 +0000548 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000549 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000550 this);
551
552 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000553 // Matchers for old cc
554 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000555 auto IsOldCCTopLevelDecl = allOf(
556 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
557 // Matching using decls/type alias decls which are in named/anonymous/global
558 // namespace, these decls are always copied to new.h/cc. Those in classes,
559 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000560 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
Argyrios Kyrtzidis2b6ec652018-08-31 03:51:33 +0000561 usingDirectiveDecl(unless(isImplicit()),
562 IsOldCCTopLevelDecl),
Haojian Wub3d98882017-01-17 10:08:11 +0000563 typeAliasDecl(IsOldCCTopLevelDecl)),
564 notInMacro())
565 .bind("using_decl"),
566 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000567
Haojian Wu67bb6512016-10-19 14:13:21 +0000568 // Match static functions/variable definitions which are defined in named
569 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000570 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
571 for (StringRef SymbolName : Context->Spec.Names) {
572 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
573 const auto HasName = hasName(("::" + GlobalSymbolName).str());
574 HasAnySymbolNames =
575 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
576 }
577
578 if (!HasAnySymbolNames) {
579 llvm::errs() << "No symbols being moved.\n";
580 return;
581 }
582 auto InMovedClass =
583 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000584
585 // Matchers for helper declarations in old.cc.
586 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000587 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
588 auto IsOldCCHelper =
589 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000590 // Match helper classes separately with helper functions/variables since we
591 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000592 //
593 // There could be forward declarations usage for helpers, especially for
594 // classes and functions. We need include these forward declarations.
595 //
596 // Forward declarations for variable helpers will be excluded as these
597 // declarations (with "extern") are not supposed in cpp file.
598 auto HelperFuncOrVar =
599 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
600 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000601 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000602 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000603 // Save all helper declarations in old.cc.
604 Finder->addMatcher(
605 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
606 this);
607
608 // Construct an AST-based call graph of helper declarations in old.cc.
609 // In the following matcheres, "dc" is a caller while "helper_decls" and
610 // "used_class" is a callee, so a new edge starting from caller to callee will
611 // be add in the graph.
612 //
613 // Find helper function/variable usages.
614 Finder->addMatcher(
615 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
616 .bind("func_ref"),
617 &RGBuilder);
618 // Find helper class usages.
619 Finder->addMatcher(
620 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
621 hasAncestor(decl().bind("dc"))),
622 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000623
624 //============================================================================
625 // Matchers for old files, including old.h/old.cc
626 //============================================================================
627 // Create a MatchCallback for class declarations.
628 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
629 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000630 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
631 isDefinition(), TopLevelDecl)
632 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000633 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
634 // Match moved class methods (static methods included) which are defined
635 // outside moved class declaration.
636 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000637 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000638 isDefinition())
639 .bind("class_method"),
640 MatchCallbacks.back().get());
641 // Match static member variable definition of the moved class.
642 Finder->addMatcher(
643 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
644 .bind("class_static_var_decl"),
645 MatchCallbacks.back().get());
646
Haojian Wu4543fec2016-11-16 13:05:19 +0000647 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000648 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000649 .bind("function"),
650 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000651
Haojian Wu4a920502017-02-27 13:19:13 +0000652 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
653 Finder->addMatcher(
654 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
655 MatchCallbacks.back().get());
656
Haojian Wud69d9072017-01-04 14:50:49 +0000657 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000658 // will not be moved for now no matter whether they are used or not.
659 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
660 Finder->addMatcher(
661 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
662 .bind("enum"),
663 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000664
665 // Match type alias in old.h, this includes "typedef" and "using" type alias
666 // declarations. Type alias helpers (which are defined in old.cc) will not be
667 // moved for now no matter whether they are used or not.
668 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
669 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
670 typeAliasDecl().bind("type_alias")),
671 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
672 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000673}
674
675void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000676 if (const auto *D =
677 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
678 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000679 } else if (const auto *FWD =
680 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000681 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000682 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000683 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000684 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000685 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000686 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000687 }
Haojian Wu357ef992016-09-21 13:18:19 +0000688 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000689 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
690 MovedDecls.push_back(ND);
691 HelperDeclarations.push_back(ND);
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000692 LLVM_DEBUG(llvm::dbgs() << "Add helper : " << ND->getNameAsString() << " ("
693 << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000694 } else if (const auto *UD =
695 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000696 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000697 }
698}
699
Haojian Wu2930be12016-11-08 19:55:13 +0000700std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000701 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000702}
703
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000704void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000705 llvm::StringRef SearchPath,
706 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000707 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000708 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000709 SmallVector<char, 128> HeaderWithSearchPath;
710 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000711 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000712 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000713 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000714 std::string IncludeLine =
715 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
716 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000717
Haojian Wufb68ca12018-01-31 12:12:29 +0000718 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000719 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
720 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000721 // Find old.h includes "old.h".
722 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
723 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
724 return;
725 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000726 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000727 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000728 // Find old.cc includes "old.h".
729 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
730 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
731 return;
732 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000733 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000734 }
Haojian Wu357ef992016-09-21 13:18:19 +0000735}
736
Haojian Wu08e402a2016-12-02 12:39:39 +0000737void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000738 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000739
740 // If old_header is not specified (only move declarations from old.cc), remain
741 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
742 // is empty in this case, there is no way to verify unused/used helpers.
743 if (!Context->Spec.OldHeader.empty()) {
744 std::vector<const NamedDecl *> UnremovedDecls;
745 for (const auto *D : UnremovedDeclsInOldHeader)
746 UnremovedDecls.push_back(D);
747
748 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
749
750 // We remove the helper declarations which are not used in the old.cc after
751 // moving the given declarations.
752 for (const auto *D : HelperDeclarations) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000753 LLVM_DEBUG(llvm::dbgs() << "Check helper is used: "
754 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu4775ce52017-01-17 13:22:37 +0000755 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
756 D->getCanonicalDecl()))) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000757 LLVM_DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
758 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000759 RemovedDecls.push_back(D);
760 }
761 }
762 }
763
Haojian Wu08e402a2016-12-02 12:39:39 +0000764 for (const auto *RemovedDecl : RemovedDecls) {
765 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
766 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000767 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000768 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000769 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000770 "");
771 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000772 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000773 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000774 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000775 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000776 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000777
778 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000779 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000780 StringRef FilePath = FileAndReplacements.first;
781 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000782 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000783 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000784 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000785 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000786 std::string IncludeNewH =
787 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000788 // This replacment for inserting header will be cleaned up at the end.
789 auto Err = FileAndReplacements.second.add(
790 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
791 if (Err)
792 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000793 }
Haojian Wu253d5962016-10-06 08:29:32 +0000794
Haojian Wu48ac3042016-11-23 10:04:19 +0000795 auto SI = FilePathToFileID.find(FilePath);
796 // Ignore replacements for new.h/cc.
797 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000798 llvm::StringRef Code = SM.getBufferData(SI->second);
Eric Liufa63e982018-08-02 10:30:56 +0000799 auto Style = format::getStyle(format::DefaultFormatStyle, FilePath,
800 Context->FallbackStyle);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000801 if (!Style) {
802 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
803 continue;
804 }
Haojian Wu253d5962016-10-06 08:29:32 +0000805 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000806 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000807
808 if (!CleanReplacements) {
809 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
810 continue;
811 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000812 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000813 }
814}
815
Haojian Wu08e402a2016-12-02 12:39:39 +0000816void ClangMoveTool::moveDeclsToNewFiles() {
817 std::vector<const NamedDecl *> NewHeaderDecls;
818 std::vector<const NamedDecl *> NewCCDecls;
819 for (const auto *MovedDecl : MovedDecls) {
820 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000821 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000822 NewHeaderDecls.push_back(MovedDecl);
823 else
824 NewCCDecls.push_back(MovedDecl);
825 }
826
Haojian Wu36265162017-01-03 09:00:51 +0000827 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
828 std::vector<const NamedDecl *> ActualNewCCDecls;
829
830 // Filter out all unused helpers in NewCCDecls.
831 // We only move the used helpers (including transively used helpers) and the
832 // given symbols being moved.
833 for (const auto *D : NewCCDecls) {
834 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000835 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
836 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000837 continue;
838
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000839 LLVM_DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
840 << " " << D << "\n");
Haojian Wu36265162017-01-03 09:00:51 +0000841 ActualNewCCDecls.push_back(D);
842 }
843
Haojian Wub15c8da2016-11-24 10:17:17 +0000844 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000845 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000846 Context->Spec.NewDependOnOld
847 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
848 : "";
849 Context->FileToReplacements[Context->Spec.NewHeader] =
850 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
851 Context->Spec.NewHeader, /*IsHeader=*/true,
852 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000853 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000854 if (!Context->Spec.NewCC.empty())
855 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000856 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
857 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000858}
859
Haojian Wu2930be12016-11-08 19:55:13 +0000860// Move all contents from OldFile to NewFile.
861void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
862 StringRef NewFile) {
863 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
864 if (!FE) {
865 llvm::errs() << "Failed to get file: " << OldFile << "\n";
866 return;
867 }
868 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
869 auto Begin = SM.getLocForStartOfFile(ID);
870 auto End = SM.getLocForEndOfFile(ID);
871 clang::tooling::Replacement RemoveAll (
872 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
873 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000874 Context->FileToReplacements[FilePath] =
875 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000876
877 StringRef Code = SM.getBufferData(ID);
878 if (!NewFile.empty()) {
879 auto AllCode = clang::tooling::Replacements(
880 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000881 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
882 AllCode = AllCode.merge(clang::tooling::Replacements(
883 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
884 '"' + Context->Spec.NewHeader + '"')));
885 };
886 // Fix the case where old.h/old.cc includes "old.h", we replace the
887 // `#include "old.h"` with `#include "new.h"`.
888 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
889 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
890 else if (Context->Spec.NewHeader == NewFile &&
891 OldHeaderIncludeRangeInHeader.isValid())
892 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000893 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000894 }
895}
896
Haojian Wu357ef992016-09-21 13:18:19 +0000897void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000898 if (Context->DumpDeclarations) {
899 assert(Reporter);
900 for (const auto *Decl : UnremovedDeclsInOldHeader) {
901 auto Kind = Decl->getKind();
Eric Liubce181c2018-10-08 17:22:50 +0000902 bool Templated = Decl->isTemplated();
Haojian Wub15c8da2016-11-24 10:17:17 +0000903 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000904 if (Kind == Decl::Kind::Var)
Eric Liubce181c2018-10-08 17:22:50 +0000905 Reporter->reportDeclaration(QualifiedName, "Variable", Templated);
Haojian Wu4a920502017-02-27 13:19:13 +0000906 else if (Kind == Decl::Kind::Function ||
907 Kind == Decl::Kind::FunctionTemplate)
Eric Liubce181c2018-10-08 17:22:50 +0000908 Reporter->reportDeclaration(QualifiedName, "Function", Templated);
Haojian Wub15c8da2016-11-24 10:17:17 +0000909 else if (Kind == Decl::Kind::ClassTemplate ||
910 Kind == Decl::Kind::CXXRecord)
Eric Liubce181c2018-10-08 17:22:50 +0000911 Reporter->reportDeclaration(QualifiedName, "Class", Templated);
Haojian Wu85867722017-01-16 09:34:07 +0000912 else if (Kind == Decl::Kind::Enum)
Eric Liubce181c2018-10-08 17:22:50 +0000913 Reporter->reportDeclaration(QualifiedName, "Enum", Templated);
914 else if (Kind == Decl::Kind::Typedef || Kind == Decl::Kind::TypeAlias ||
Haojian Wu85867722017-01-16 09:34:07 +0000915 Kind == Decl::Kind::TypeAliasTemplate)
Eric Liubce181c2018-10-08 17:22:50 +0000916 Reporter->reportDeclaration(QualifiedName, "TypeAlias", Templated);
Haojian Wub15c8da2016-11-24 10:17:17 +0000917 }
918 return;
919 }
920
Haojian Wu357ef992016-09-21 13:18:19 +0000921 if (RemovedDecls.empty())
922 return;
Haojian Wud4786342018-02-09 15:57:30 +0000923 // Ignore symbols that are not supported when checking if there is unremoved
924 // symbol in old header. This makes sure that we always move old files to new
925 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000926 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
927 switch (Decl->getKind()) {
928 case Decl::Kind::Function:
929 case Decl::Kind::FunctionTemplate:
930 case Decl::Kind::ClassTemplate:
931 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000932 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000933 case Decl::Kind::Typedef:
934 case Decl::Kind::TypeAlias:
935 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000936 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000937 return true;
938 default:
939 return false;
940 }
941 };
942 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
943 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
944 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000945 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000946 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
947 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000948 return;
949 }
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000950 LLVM_DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000951 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000952 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000953}
954
955} // namespace move
956} // namespace clang