blob: be3fca0dff5a6ad979793ff6739113b58fcd066b [file] [log] [blame]
Haojian Wu357ef992016-09-21 13:18:19 +00001//===-- ClangMove.cpp - Implement ClangMove functationalities ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ClangMove.h"
Haojian Wu36265162017-01-03 09:00:51 +000011#include "HelperDeclRefGraph.h"
Haojian Wu357ef992016-09-21 13:18:19 +000012#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Basic/SourceManager.h"
14#include "clang/Format/Format.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Lex/Lexer.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Rewrite/Core/Rewriter.h"
19#include "clang/Tooling/Core/Replacement.h"
Haojian Wu36265162017-01-03 09:00:51 +000020#include "llvm/Support/Debug.h"
Haojian Wud2a6d7b2016-10-04 09:05:31 +000021#include "llvm/Support/Path.h"
Haojian Wu357ef992016-09-21 13:18:19 +000022
Haojian Wu36265162017-01-03 09:00:51 +000023#define DEBUG_TYPE "clang-move"
24
Haojian Wu357ef992016-09-21 13:18:19 +000025using namespace clang::ast_matchers;
26
27namespace clang {
28namespace move {
29namespace {
30
Haojian Wu7bd492c2016-10-14 10:07:58 +000031// FIXME: Move to ASTMatchers.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000032AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
Haojian Wu7bd492c2016-10-14 10:07:58 +000033
Haojian Wue77bcc72016-10-13 10:31:00 +000034AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
35 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000036 const auto *Context = Node.getDeclContext();
37 if (!Context)
38 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000039 while (const auto *NextContext = Context->getParent()) {
40 if (isa<NamespaceDecl>(NextContext) ||
41 isa<TranslationUnitDecl>(NextContext))
42 break;
43 Context = NextContext;
44 }
45 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
46 Builder);
47}
48
49AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
50 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
51 const CXXRecordDecl *Parent = Node.getParent();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000052 if (!Parent)
53 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000054 while (const auto *NextParent =
55 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
56 Parent = NextParent;
57 }
58
59 return InnerMatcher.matches(*Parent, Finder, Builder);
60}
61
Haojian Wud2a6d7b2016-10-04 09:05:31 +000062// Make the Path absolute using the CurrentDir if the Path is not an absolute
63// path. An empty Path will result in an empty string.
64std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
65 if (Path.empty())
66 return "";
67 llvm::SmallString<128> InitialDirectory(CurrentDir);
68 llvm::SmallString<128> AbsolutePath(Path);
69 if (std::error_code EC =
70 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000071 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000072 << '\n';
73 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wuc6f125e2016-10-04 09:49:20 +000074 llvm::sys::path::native(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +000075 return AbsolutePath.str();
76}
77
78// Make the Path absolute using the current working directory of the given
79// SourceManager if the Path is not an absolute path.
80//
81// The Path can be a path relative to the build directory, or retrieved from
82// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000083std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000084 llvm::SmallString<128> AbsolutePath(Path);
85 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000086 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
87 AbsolutePath))
88 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000089 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000090 // Handle symbolic link path cases.
91 // We are trying to get the real file path of the symlink.
92 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000093 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +000094 if (Dir) {
95 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
96 SmallVector<char, 128> AbsoluteFilename;
97 llvm::sys::path::append(AbsoluteFilename, DirName,
98 llvm::sys::path::filename(AbsolutePath.str()));
99 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
100 .str();
101 }
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000102 return AbsolutePath.str();
103}
104
105// Matches AST nodes that are expanded within the given AbsoluteFilePath.
106AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
107 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
108 std::string, AbsoluteFilePath) {
109 auto &SourceManager = Finder->getASTContext().getSourceManager();
110 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
111 if (ExpansionLoc.isInvalid())
112 return false;
113 auto FileEntry =
114 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
115 if (!FileEntry)
116 return false;
117 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
118 AbsoluteFilePath;
119}
120
Haojian Wu357ef992016-09-21 13:18:19 +0000121class FindAllIncludes : public clang::PPCallbacks {
122public:
123 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
124 : SM(*SM), MoveTool(MoveTool) {}
125
126 void InclusionDirective(clang::SourceLocation HashLoc,
127 const clang::Token & /*IncludeTok*/,
128 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000129 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000130 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000131 StringRef SearchPath, StringRef /*RelativePath*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000132 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000133 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000134 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000135 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000136 }
137
138private:
139 const SourceManager &SM;
140 ClangMoveTool *const MoveTool;
141};
142
Haojian Wu32a552f2017-01-03 14:22:25 +0000143/// Add a declatration being moved to new.h/cc. Note that the declaration will
144/// also be deleted in old.h/cc.
145void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
146 MoveTool->getMovedDecls().push_back(D);
147 MoveTool->addRemovedDecl(D);
148 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
149}
150
Haojian Wu4543fec2016-11-16 13:05:19 +0000151class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
152public:
153 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
154 : MoveTool(MoveTool) {}
155
156 void run(const MatchFinder::MatchResult &Result) override {
157 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
158 assert(FD);
159 const clang::NamedDecl *D = FD;
160 if (const auto *FTD = FD->getDescribedFunctionTemplate())
161 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000162 MoveDeclFromOldFileToNewFile(MoveTool, D);
163 }
164
165private:
166 ClangMoveTool *MoveTool;
167};
168
Haojian Wud69d9072017-01-04 14:50:49 +0000169class TypeAliasMatch : public MatchFinder::MatchCallback {
170public:
171 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
172 : MoveTool(MoveTool) {}
173
174 void run(const MatchFinder::MatchResult &Result) override {
175 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
176 MoveDeclFromOldFileToNewFile(MoveTool, TD);
177 else if (const auto *TAD =
178 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
179 const NamedDecl * D = TAD;
180 if (const auto * TD = TAD->getDescribedAliasTemplate())
181 D = TD;
182 MoveDeclFromOldFileToNewFile(MoveTool, D);
183 }
184 }
185
186private:
187 ClangMoveTool *MoveTool;
188};
189
Haojian Wu32a552f2017-01-03 14:22:25 +0000190class EnumDeclarationMatch : public MatchFinder::MatchCallback {
191public:
192 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
193 : MoveTool(MoveTool) {}
194
195 void run(const MatchFinder::MatchResult &Result) override {
196 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
197 assert(ED);
198 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000199 }
200
201private:
202 ClangMoveTool *MoveTool;
203};
204
Haojian Wu35ca9462016-11-14 14:15:44 +0000205class ClassDeclarationMatch : public MatchFinder::MatchCallback {
206public:
207 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
208 : MoveTool(MoveTool) {}
209 void run(const MatchFinder::MatchResult &Result) override {
210 clang::SourceManager* SM = &Result.Context->getSourceManager();
211 if (const auto *CMD =
212 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
213 MatchClassMethod(CMD, SM);
214 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
215 "class_static_var_decl"))
216 MatchClassStaticVariable(VD, SM);
217 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
218 "moved_class"))
219 MatchClassDeclaration(CD, SM);
220 }
221
222private:
223 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
224 clang::SourceManager* SM) {
225 // Skip inline class methods. isInline() ast matcher doesn't ignore this
226 // case.
227 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000228 MoveTool->getMovedDecls().push_back(CMD);
229 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000230 // Get template class method from its method declaration as
231 // UnremovedDecls stores template class method.
232 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
233 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
234 else
235 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
236 }
237 }
238
239 void MatchClassStaticVariable(const clang::NamedDecl *VD,
240 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000241 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000242 }
243
244 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
245 clang::SourceManager* SM) {
246 // Get class template from its class declaration as UnremovedDecls stores
247 // class template.
248 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000249 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000250 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000251 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000252 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000253 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000254 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000255 }
256
257 ClangMoveTool *MoveTool;
258};
259
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000260// Expand to get the end location of the line where the EndLoc of the given
261// Decl.
262SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000263getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000264 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000265 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wudc4edba2016-12-13 15:35:47 +0000266 auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
267 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000268 // Try to load the file buffer.
269 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000270 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000271 if (InvalidTemp)
272 return SourceLocation();
273
274 const char *TokBegin = File.data() + LocInfo.second;
275 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000276 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000277 TokBegin, File.end());
278
279 llvm::SmallVector<char, 16> Line;
280 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
281 Lex.setParsingPreprocessorDirective(true);
282 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000283 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000284 // If we already reach EOF, just return the EOF SourceLocation;
285 // otherwise, move 1 offset ahead to include the trailing newline character
286 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000287 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000288 ? EndLoc
289 : EndLoc.getLocWithOffset(1);
290}
291
292// Get full range of a Decl including the comments associated with it.
293clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000294getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000295 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000296 const auto &SM = D->getASTContext().getSourceManager();
297 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
298 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000299 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000300 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000301 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000302 Full.setEnd(Comment->getLocEnd());
303 // FIXME: Don't delete a preceding comment, if there are no other entities
304 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000305 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000306 Full.setBegin(Comment->getLocStart());
307 }
308
309 return clang::CharSourceRange::getCharRange(Full);
310}
311
Haojian Wu08e402a2016-12-02 12:39:39 +0000312std::string getDeclarationSourceText(const clang::Decl *D) {
313 const auto &SM = D->getASTContext().getSourceManager();
314 llvm::StringRef SourceText =
315 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000316 return SourceText.str();
317}
318
Haojian Wu08e402a2016-12-02 12:39:39 +0000319bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000320 llvm::StringRef OriginalRunningDirectory,
321 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000322 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000323 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000324 return false;
325 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
326 if (ExpansionLoc.isInvalid())
327 return false;
328
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000329 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
330 return MakeAbsolutePath(SM, FE->getName()) ==
331 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
332 }
Haojian Wu357ef992016-09-21 13:18:19 +0000333
334 return false;
335}
336
Haojian Wu08e402a2016-12-02 12:39:39 +0000337std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000338 std::vector<std::string> Namespaces;
339 for (const auto *Context = D->getDeclContext(); Context;
340 Context = Context->getParent()) {
341 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
342 llvm::isa<clang::LinkageSpecDecl>(Context))
343 break;
344
345 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
346 Namespaces.push_back(ND->getName().str());
347 }
348 std::reverse(Namespaces.begin(), Namespaces.end());
349 return Namespaces;
350}
351
Haojian Wu357ef992016-09-21 13:18:19 +0000352clang::tooling::Replacements
353createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000354 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000355 llvm::StringRef FileName, bool IsHeader = false,
356 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000357 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000358 std::string GuardName(FileName);
359 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000360 for (size_t i = 0; i < GuardName.size(); ++i) {
361 if (!isAlphanumeric(GuardName[i]))
362 GuardName[i] = '_';
363 }
Haojian Wu220c7552016-10-14 13:01:36 +0000364 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000365 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000366 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000367 }
Haojian Wu357ef992016-09-21 13:18:19 +0000368
Haojian Wu48ac3042016-11-23 10:04:19 +0000369 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000370 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000371 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000372 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000373
Haojian Wu53eab1e2016-10-14 13:43:49 +0000374 if (!Includes.empty())
375 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000376
377 // Add moved class definition and its related declarations. All declarations
378 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000379 //
380 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000381 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000382 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000383 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000384 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000385 auto CurrentIt = CurrentNamespaces.begin();
386 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000387 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000388 while (CurrentIt != CurrentNamespaces.end() &&
389 DeclIt != DeclNamespaces.end()) {
390 if (*CurrentIt != *DeclIt)
391 break;
392 ++CurrentIt;
393 ++DeclIt;
394 }
Haojian Wu53315a72016-11-15 09:06:59 +0000395 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
396 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000397 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
398 CurrentIt);
399 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000400
401
402 // End with CurrentNamespace.
403 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000404 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
405 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
406 --RemainingSize, ++It) {
407 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000408 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000409 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000410 }
Haojian Wu53315a72016-11-15 09:06:59 +0000411 // Add trailing '\n' after the nested namespace definition.
412 if (HasEndCurrentNamespace)
413 NewCode += "\n";
414
415 // If the moved declaration is not in CurrentNamespace, add extra namespace
416 // definitions.
417 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000418 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000419 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000420 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000421 ++DeclIt;
422 }
Haojian Wu53315a72016-11-15 09:06:59 +0000423 // If the moved declaration is in same namespace CurrentNamespace, add
424 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000425 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000426 if (!IsInNewNamespace)
427 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000428 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000429 CurrentNamespaces = std::move(NextNamespaces);
430 }
431 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000432 for (const auto &NS : CurrentNamespaces)
433 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000434
Haojian Wu53eab1e2016-10-14 13:43:49 +0000435 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000436 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000437 return clang::tooling::Replacements(
438 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000439}
440
Haojian Wu36265162017-01-03 09:00:51 +0000441// Return a set of all decls which are used/referenced by the given Decls.
442// Specically, given a class member declaration, this method will return all
443// decls which are used by the whole class.
444llvm::DenseSet<const Decl *>
445getUsedDecls(const HelperDeclRefGraph *RG,
446 const std::vector<const NamedDecl *> &Decls) {
447 assert(RG);
448 llvm::DenseSet<const CallGraphNode *> Nodes;
449 for (const auto *D : Decls) {
450 auto Result = RG->getReachableNodes(
451 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
452 Nodes.insert(Result.begin(), Result.end());
453 }
454 llvm::DenseSet<const Decl *> Results;
455 for (const auto *Node : Nodes)
456 Results.insert(Node->getDecl());
457 return Results;
458}
459
Haojian Wu357ef992016-09-21 13:18:19 +0000460} // namespace
461
462std::unique_ptr<clang::ASTConsumer>
463ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
464 StringRef /*InFile*/) {
465 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
466 &Compiler.getSourceManager(), &MoveTool));
467 return MatchFinder.newASTConsumer();
468}
469
Haojian Wub15c8da2016-11-24 10:17:17 +0000470ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
471 DeclarationReporter *const Reporter)
472 : Context(Context), Reporter(Reporter) {
473 if (!Context->Spec.NewHeader.empty())
474 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000475}
476
Haojian Wu08e402a2016-12-02 12:39:39 +0000477void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
478 const auto &SM = Decl->getASTContext().getSourceManager();
479 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000480 StringRef FilePath = SM.getFilename(Loc);
481 FilePathToFileID[FilePath] = SM.getFileID(Loc);
482 RemovedDecls.push_back(Decl);
483}
484
Haojian Wu357ef992016-09-21 13:18:19 +0000485void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000486 auto InOldHeader =
487 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
488 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000489 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000490 auto ForwardDecls =
491 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
Haojian Wu32a552f2017-01-03 14:22:25 +0000492 auto TopLevelDecl =
493 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000494
495 //============================================================================
496 // Matchers for old header
497 //============================================================================
498 // Match all top-level named declarations (e.g. function, variable, enum) in
499 // old header, exclude forward class declarations and namespace declarations.
500 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000501 // We consider declarations inside a class belongs to the class. So these
502 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000503 auto AllDeclsInHeader = namedDecl(
504 unless(ForwardDecls), unless(namespaceDecl()),
Haojian Wub15c8da2016-11-24 10:17:17 +0000505 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wu2930be12016-11-08 19:55:13 +0000506 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
507 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000508 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
509 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000510 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000511
512 // Don't register other matchers when dumping all declarations in header.
513 if (Context->DumpDeclarations)
514 return;
515
Haojian Wu2930be12016-11-08 19:55:13 +0000516 // Match forward declarations in old header.
517 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
518 this);
519
520 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000521 // Matchers for old cc
522 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000523 auto IsOldCCTopLevelDecl = allOf(
524 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
525 // Matching using decls/type alias decls which are in named/anonymous/global
526 // namespace, these decls are always copied to new.h/cc. Those in classes,
527 // functions are covered in other matchers.
Haojian Wu357ef992016-09-21 13:18:19 +0000528 Finder->addMatcher(
Haojian Wu36265162017-01-03 09:00:51 +0000529 namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
530 usingDirectiveDecl(IsOldCCTopLevelDecl),
531 typeAliasDecl(IsOldCCTopLevelDecl)))
Haojian Wu67bb6512016-10-19 14:13:21 +0000532 .bind("using_decl"),
Haojian Wu357ef992016-09-21 13:18:19 +0000533 this);
534
Haojian Wu67bb6512016-10-19 14:13:21 +0000535 // Match static functions/variable definitions which are defined in named
536 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000537 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
538 for (StringRef SymbolName : Context->Spec.Names) {
539 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
540 const auto HasName = hasName(("::" + GlobalSymbolName).str());
541 HasAnySymbolNames =
542 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
543 }
544
545 if (!HasAnySymbolNames) {
546 llvm::errs() << "No symbols being moved.\n";
547 return;
548 }
549 auto InMovedClass =
550 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000551
552 // Matchers for helper declarations in old.cc.
553 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
554 auto DefinitionInOldCC = allOf(isDefinition(), unless(InMovedClass), InOldCC);
555 auto IsOldCCHelperDefinition =
556 allOf(DefinitionInOldCC, anyOf(isStaticStorageClass(), InAnonymousNS));
557 // Match helper classes separately with helper functions/variables since we
558 // want to reuse these matchers in finding helpers usage below.
559 auto HelperFuncOrVar = namedDecl(anyOf(functionDecl(IsOldCCHelperDefinition),
560 varDecl(IsOldCCHelperDefinition)));
561 auto HelperClasses = cxxRecordDecl(DefinitionInOldCC, InAnonymousNS);
562 // Save all helper declarations in old.cc.
563 Finder->addMatcher(
564 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
565 this);
566
567 // Construct an AST-based call graph of helper declarations in old.cc.
568 // In the following matcheres, "dc" is a caller while "helper_decls" and
569 // "used_class" is a callee, so a new edge starting from caller to callee will
570 // be add in the graph.
571 //
572 // Find helper function/variable usages.
573 Finder->addMatcher(
574 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
575 .bind("func_ref"),
576 &RGBuilder);
577 // Find helper class usages.
578 Finder->addMatcher(
579 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
580 hasAncestor(decl().bind("dc"))),
581 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000582
583 //============================================================================
584 // Matchers for old files, including old.h/old.cc
585 //============================================================================
586 // Create a MatchCallback for class declarations.
587 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
588 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000589 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
590 isDefinition(), TopLevelDecl)
591 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000592 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
593 // Match moved class methods (static methods included) which are defined
594 // outside moved class declaration.
595 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000596 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000597 isDefinition())
598 .bind("class_method"),
599 MatchCallbacks.back().get());
600 // Match static member variable definition of the moved class.
601 Finder->addMatcher(
602 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
603 .bind("class_static_var_decl"),
604 MatchCallbacks.back().get());
605
Haojian Wu4543fec2016-11-16 13:05:19 +0000606 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000607 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000608 .bind("function"),
609 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000610
Haojian Wud69d9072017-01-04 14:50:49 +0000611 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000612 // will not be moved for now no matter whether they are used or not.
613 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
614 Finder->addMatcher(
615 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
616 .bind("enum"),
617 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000618
619 // Match type alias in old.h, this includes "typedef" and "using" type alias
620 // declarations. Type alias helpers (which are defined in old.cc) will not be
621 // moved for now no matter whether they are used or not.
622 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
623 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
624 typeAliasDecl().bind("type_alias")),
625 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
626 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000627}
628
629void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000630 if (const auto *D =
631 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
632 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000633 } else if (const auto *FWD =
634 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000635 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000636 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000637 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000638 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000639 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000640 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000641 }
Haojian Wu357ef992016-09-21 13:18:19 +0000642 } else if (const auto *ND =
643 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000644 MovedDecls.push_back(ND);
Haojian Wu36265162017-01-03 09:00:51 +0000645 } else if (const auto *ND =
646 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
647 MovedDecls.push_back(ND);
648 HelperDeclarations.push_back(ND);
Haojian Wu67bb6512016-10-19 14:13:21 +0000649 } else if (const auto *UD =
650 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000651 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000652 }
653}
654
Haojian Wu2930be12016-11-08 19:55:13 +0000655std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000656 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000657}
658
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000659void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000660 llvm::StringRef SearchPath,
661 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000662 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000663 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000664 SmallVector<char, 128> HeaderWithSearchPath;
665 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000666 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000667 if (AbsoluteOldHeader ==
668 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000669 HeaderWithSearchPath.size()))) {
670 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000671 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000672 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000673
674 std::string IncludeLine =
675 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
676 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000677
Haojian Wudb726572016-10-12 15:50:30 +0000678 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
679 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000680 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000681 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000682 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000683 }
Haojian Wu357ef992016-09-21 13:18:19 +0000684}
685
Haojian Wu08e402a2016-12-02 12:39:39 +0000686void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000687 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000688
689 // If old_header is not specified (only move declarations from old.cc), remain
690 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
691 // is empty in this case, there is no way to verify unused/used helpers.
692 if (!Context->Spec.OldHeader.empty()) {
693 std::vector<const NamedDecl *> UnremovedDecls;
694 for (const auto *D : UnremovedDeclsInOldHeader)
695 UnremovedDecls.push_back(D);
696
697 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
698
699 // We remove the helper declarations which are not used in the old.cc after
700 // moving the given declarations.
701 for (const auto *D : HelperDeclarations) {
702 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D))) {
703 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
704 << D->getNameAsString() << " " << D << "\n");
705 RemovedDecls.push_back(D);
706 }
707 }
708 }
709
Haojian Wu08e402a2016-12-02 12:39:39 +0000710 for (const auto *RemovedDecl : RemovedDecls) {
711 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
712 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000713 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000714 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000715 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000716 "");
717 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000718 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000719 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000720 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000721 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000722 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000723
724 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000725 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000726 StringRef FilePath = FileAndReplacements.first;
727 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000728 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000729 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000730 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000731 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000732 std::string IncludeNewH =
733 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000734 // This replacment for inserting header will be cleaned up at the end.
735 auto Err = FileAndReplacements.second.add(
736 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
737 if (Err)
738 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000739 }
Haojian Wu253d5962016-10-06 08:29:32 +0000740
Haojian Wu48ac3042016-11-23 10:04:19 +0000741 auto SI = FilePathToFileID.find(FilePath);
742 // Ignore replacements for new.h/cc.
743 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000744 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000745 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
746 if (!Style) {
747 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
748 continue;
749 }
Haojian Wu253d5962016-10-06 08:29:32 +0000750 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000751 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000752
753 if (!CleanReplacements) {
754 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
755 continue;
756 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000757 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000758 }
759}
760
Haojian Wu08e402a2016-12-02 12:39:39 +0000761void ClangMoveTool::moveDeclsToNewFiles() {
762 std::vector<const NamedDecl *> NewHeaderDecls;
763 std::vector<const NamedDecl *> NewCCDecls;
764 for (const auto *MovedDecl : MovedDecls) {
765 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000766 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000767 NewHeaderDecls.push_back(MovedDecl);
768 else
769 NewCCDecls.push_back(MovedDecl);
770 }
771
Haojian Wu36265162017-01-03 09:00:51 +0000772 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
773 std::vector<const NamedDecl *> ActualNewCCDecls;
774
775 // Filter out all unused helpers in NewCCDecls.
776 // We only move the used helpers (including transively used helpers) and the
777 // given symbols being moved.
778 for (const auto *D : NewCCDecls) {
779 if (llvm::is_contained(HelperDeclarations, D) &&
780 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D)))
781 continue;
782
783 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
784 << " " << D << "\n");
785 ActualNewCCDecls.push_back(D);
786 }
787
Haojian Wub15c8da2016-11-24 10:17:17 +0000788 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000789 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000790 Context->Spec.NewDependOnOld
791 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
792 : "";
793 Context->FileToReplacements[Context->Spec.NewHeader] =
794 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
795 Context->Spec.NewHeader, /*IsHeader=*/true,
796 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000797 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000798 if (!Context->Spec.NewCC.empty())
799 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000800 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
801 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000802}
803
Haojian Wu2930be12016-11-08 19:55:13 +0000804// Move all contents from OldFile to NewFile.
805void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
806 StringRef NewFile) {
807 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
808 if (!FE) {
809 llvm::errs() << "Failed to get file: " << OldFile << "\n";
810 return;
811 }
812 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
813 auto Begin = SM.getLocForStartOfFile(ID);
814 auto End = SM.getLocForEndOfFile(ID);
815 clang::tooling::Replacement RemoveAll (
816 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
817 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000818 Context->FileToReplacements[FilePath] =
819 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000820
821 StringRef Code = SM.getBufferData(ID);
822 if (!NewFile.empty()) {
823 auto AllCode = clang::tooling::Replacements(
824 clang::tooling::Replacement(NewFile, 0, 0, Code));
825 // If we are moving from old.cc, an extra step is required: excluding
826 // the #include of "old.h", instead, we replace it with #include of "new.h".
Haojian Wub15c8da2016-11-24 10:17:17 +0000827 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
Haojian Wu2930be12016-11-08 19:55:13 +0000828 AllCode = AllCode.merge(
829 clang::tooling::Replacements(clang::tooling::Replacement(
Haojian Wub15c8da2016-11-24 10:17:17 +0000830 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wu2930be12016-11-08 19:55:13 +0000831 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000832 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000833 }
834}
835
Haojian Wu357ef992016-09-21 13:18:19 +0000836void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000837 if (Context->DumpDeclarations) {
838 assert(Reporter);
839 for (const auto *Decl : UnremovedDeclsInOldHeader) {
840 auto Kind = Decl->getKind();
841 const std::string QualifiedName = Decl->getQualifiedNameAsString();
842 if (Kind == Decl::Kind::Function || Kind == Decl::Kind::FunctionTemplate)
843 Reporter->reportDeclaration(QualifiedName, "Function");
844 else if (Kind == Decl::Kind::ClassTemplate ||
845 Kind == Decl::Kind::CXXRecord)
846 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000847 else if (Kind == Decl::Kind::Enum)
848 Reporter->reportDeclaration(QualifiedName, "Enum");
849 else if (Kind == Decl::Kind::Typedef ||
850 Kind == Decl::Kind::TypeAlias ||
851 Kind == Decl::Kind::TypeAliasTemplate)
852 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000853 }
854 return;
855 }
856
Haojian Wu357ef992016-09-21 13:18:19 +0000857 if (RemovedDecls.empty())
858 return;
Eric Liu47a42d52016-12-06 10:12:23 +0000859 // Ignore symbols that are not supported (e.g. typedef and enum) when
860 // checking if there is unremoved symbol in old header. This makes sure that
861 // we always move old files to new files when all symbols produced from
862 // dump_decls are moved.
863 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
864 switch (Decl->getKind()) {
865 case Decl::Kind::Function:
866 case Decl::Kind::FunctionTemplate:
867 case Decl::Kind::ClassTemplate:
868 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000869 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000870 case Decl::Kind::Typedef:
871 case Decl::Kind::TypeAlias:
872 case Decl::Kind::TypeAliasTemplate:
Eric Liu47a42d52016-12-06 10:12:23 +0000873 return true;
874 default:
875 return false;
876 }
877 };
878 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
879 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
880 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000881 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000882 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
883 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000884 return;
885 }
Haojian Wu36265162017-01-03 09:00:51 +0000886 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000887 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000888 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000889}
890
891} // namespace move
892} // namespace clang