blob: 8dbeaead097e34b3fb5752e7522fd51bf802a7a4 [file] [log] [blame]
Haojian Wu357ef992016-09-21 13:18:19 +00001//===-- ClangMove.cpp - Implement ClangMove functationalities ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ClangMove.h"
Haojian Wu36265162017-01-03 09:00:51 +000011#include "HelperDeclRefGraph.h"
Haojian Wu357ef992016-09-21 13:18:19 +000012#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Basic/SourceManager.h"
14#include "clang/Format/Format.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Lex/Lexer.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Rewrite/Core/Rewriter.h"
19#include "clang/Tooling/Core/Replacement.h"
Haojian Wu36265162017-01-03 09:00:51 +000020#include "llvm/Support/Debug.h"
Haojian Wud2a6d7b2016-10-04 09:05:31 +000021#include "llvm/Support/Path.h"
Haojian Wu357ef992016-09-21 13:18:19 +000022
Haojian Wu36265162017-01-03 09:00:51 +000023#define DEBUG_TYPE "clang-move"
24
Haojian Wu357ef992016-09-21 13:18:19 +000025using namespace clang::ast_matchers;
26
27namespace clang {
28namespace move {
29namespace {
30
Haojian Wu7bd492c2016-10-14 10:07:58 +000031// FIXME: Move to ASTMatchers.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000032AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
Haojian Wu7bd492c2016-10-14 10:07:58 +000033
Haojian Wub3d98882017-01-17 10:08:11 +000034AST_MATCHER(NamedDecl, notInMacro) { return !Node.getLocation().isMacroID(); }
35
Haojian Wue77bcc72016-10-13 10:31:00 +000036AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
37 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000038 const auto *Context = Node.getDeclContext();
39 if (!Context)
40 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000041 while (const auto *NextContext = Context->getParent()) {
42 if (isa<NamespaceDecl>(NextContext) ||
43 isa<TranslationUnitDecl>(NextContext))
44 break;
45 Context = NextContext;
46 }
47 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
48 Builder);
49}
50
51AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
52 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
53 const CXXRecordDecl *Parent = Node.getParent();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000054 if (!Parent)
55 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000056 while (const auto *NextParent =
57 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
58 Parent = NextParent;
59 }
60
61 return InnerMatcher.matches(*Parent, Finder, Builder);
62}
63
Haojian Wud2a6d7b2016-10-04 09:05:31 +000064// Make the Path absolute using the CurrentDir if the Path is not an absolute
65// path. An empty Path will result in an empty string.
66std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
67 if (Path.empty())
68 return "";
69 llvm::SmallString<128> InitialDirectory(CurrentDir);
70 llvm::SmallString<128> AbsolutePath(Path);
71 if (std::error_code EC =
72 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000073 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000074 << '\n';
75 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wuc6f125e2016-10-04 09:49:20 +000076 llvm::sys::path::native(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +000077 return AbsolutePath.str();
78}
79
80// Make the Path absolute using the current working directory of the given
81// SourceManager if the Path is not an absolute path.
82//
83// The Path can be a path relative to the build directory, or retrieved from
84// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000085std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000086 llvm::SmallString<128> AbsolutePath(Path);
87 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000088 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
89 AbsolutePath))
90 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000091 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000092 // Handle symbolic link path cases.
93 // We are trying to get the real file path of the symlink.
94 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000095 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +000096 if (Dir) {
97 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
98 SmallVector<char, 128> AbsoluteFilename;
99 llvm::sys::path::append(AbsoluteFilename, DirName,
100 llvm::sys::path::filename(AbsolutePath.str()));
101 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
102 .str();
103 }
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000104 return AbsolutePath.str();
105}
106
107// Matches AST nodes that are expanded within the given AbsoluteFilePath.
108AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
109 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
110 std::string, AbsoluteFilePath) {
111 auto &SourceManager = Finder->getASTContext().getSourceManager();
112 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
113 if (ExpansionLoc.isInvalid())
114 return false;
115 auto FileEntry =
116 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
117 if (!FileEntry)
118 return false;
119 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
120 AbsoluteFilePath;
121}
122
Haojian Wu357ef992016-09-21 13:18:19 +0000123class FindAllIncludes : public clang::PPCallbacks {
124public:
125 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
126 : SM(*SM), MoveTool(MoveTool) {}
127
128 void InclusionDirective(clang::SourceLocation HashLoc,
129 const clang::Token & /*IncludeTok*/,
130 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000131 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000132 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000133 StringRef SearchPath, StringRef /*RelativePath*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000134 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000135 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000136 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000137 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000138 }
139
140private:
141 const SourceManager &SM;
142 ClangMoveTool *const MoveTool;
143};
144
Haojian Wu32a552f2017-01-03 14:22:25 +0000145/// Add a declatration being moved to new.h/cc. Note that the declaration will
146/// also be deleted in old.h/cc.
147void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
148 MoveTool->getMovedDecls().push_back(D);
149 MoveTool->addRemovedDecl(D);
150 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
151}
152
Haojian Wu4543fec2016-11-16 13:05:19 +0000153class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
154public:
155 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
156 : MoveTool(MoveTool) {}
157
158 void run(const MatchFinder::MatchResult &Result) override {
159 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
160 assert(FD);
161 const clang::NamedDecl *D = FD;
162 if (const auto *FTD = FD->getDescribedFunctionTemplate())
163 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000164 MoveDeclFromOldFileToNewFile(MoveTool, D);
165 }
166
167private:
168 ClangMoveTool *MoveTool;
169};
170
Haojian Wu4a920502017-02-27 13:19:13 +0000171class VarDeclarationMatch : public MatchFinder::MatchCallback {
172public:
173 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
174 : MoveTool(MoveTool) {}
175
176 void run(const MatchFinder::MatchResult &Result) override {
177 const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>("var");
178 assert(VD);
179 MoveDeclFromOldFileToNewFile(MoveTool, VD);
180 }
181
182private:
183 ClangMoveTool *MoveTool;
184};
185
Haojian Wud69d9072017-01-04 14:50:49 +0000186class TypeAliasMatch : public MatchFinder::MatchCallback {
187public:
188 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
189 : MoveTool(MoveTool) {}
190
191 void run(const MatchFinder::MatchResult &Result) override {
192 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
193 MoveDeclFromOldFileToNewFile(MoveTool, TD);
194 else if (const auto *TAD =
195 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
196 const NamedDecl * D = TAD;
197 if (const auto * TD = TAD->getDescribedAliasTemplate())
198 D = TD;
199 MoveDeclFromOldFileToNewFile(MoveTool, D);
200 }
201 }
202
203private:
204 ClangMoveTool *MoveTool;
205};
206
Haojian Wu32a552f2017-01-03 14:22:25 +0000207class EnumDeclarationMatch : public MatchFinder::MatchCallback {
208public:
209 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
210 : MoveTool(MoveTool) {}
211
212 void run(const MatchFinder::MatchResult &Result) override {
213 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
214 assert(ED);
215 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000216 }
217
218private:
219 ClangMoveTool *MoveTool;
220};
221
Haojian Wu35ca9462016-11-14 14:15:44 +0000222class ClassDeclarationMatch : public MatchFinder::MatchCallback {
223public:
224 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
225 : MoveTool(MoveTool) {}
226 void run(const MatchFinder::MatchResult &Result) override {
227 clang::SourceManager* SM = &Result.Context->getSourceManager();
228 if (const auto *CMD =
229 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
230 MatchClassMethod(CMD, SM);
231 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
232 "class_static_var_decl"))
233 MatchClassStaticVariable(VD, SM);
234 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
235 "moved_class"))
236 MatchClassDeclaration(CD, SM);
237 }
238
239private:
240 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
241 clang::SourceManager* SM) {
242 // Skip inline class methods. isInline() ast matcher doesn't ignore this
243 // case.
244 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000245 MoveTool->getMovedDecls().push_back(CMD);
246 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000247 // Get template class method from its method declaration as
248 // UnremovedDecls stores template class method.
249 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
250 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
251 else
252 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
253 }
254 }
255
256 void MatchClassStaticVariable(const clang::NamedDecl *VD,
257 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000258 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000259 }
260
261 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
262 clang::SourceManager* SM) {
263 // Get class template from its class declaration as UnremovedDecls stores
264 // class template.
265 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000266 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000267 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000268 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000269 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000270 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000271 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000272 }
273
274 ClangMoveTool *MoveTool;
275};
276
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000277// Expand to get the end location of the line where the EndLoc of the given
278// Decl.
279SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000280getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000281 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000282 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wudc4edba2016-12-13 15:35:47 +0000283 auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
284 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000285 // Try to load the file buffer.
286 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000287 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000288 if (InvalidTemp)
289 return SourceLocation();
290
291 const char *TokBegin = File.data() + LocInfo.second;
292 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000293 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000294 TokBegin, File.end());
295
296 llvm::SmallVector<char, 16> Line;
297 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
298 Lex.setParsingPreprocessorDirective(true);
299 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000300 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000301 // If we already reach EOF, just return the EOF SourceLocation;
302 // otherwise, move 1 offset ahead to include the trailing newline character
303 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000304 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000305 ? EndLoc
306 : EndLoc.getLocWithOffset(1);
307}
308
309// Get full range of a Decl including the comments associated with it.
310clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000311getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000312 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000313 const auto &SM = D->getASTContext().getSourceManager();
314 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
315 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000316 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000317 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000318 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000319 Full.setEnd(Comment->getLocEnd());
320 // FIXME: Don't delete a preceding comment, if there are no other entities
321 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000322 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000323 Full.setBegin(Comment->getLocStart());
324 }
325
326 return clang::CharSourceRange::getCharRange(Full);
327}
328
Haojian Wu08e402a2016-12-02 12:39:39 +0000329std::string getDeclarationSourceText(const clang::Decl *D) {
330 const auto &SM = D->getASTContext().getSourceManager();
331 llvm::StringRef SourceText =
332 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000333 return SourceText.str();
334}
335
Haojian Wu08e402a2016-12-02 12:39:39 +0000336bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000337 llvm::StringRef OriginalRunningDirectory,
338 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000339 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000340 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000341 return false;
342 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
343 if (ExpansionLoc.isInvalid())
344 return false;
345
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000346 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
347 return MakeAbsolutePath(SM, FE->getName()) ==
348 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
349 }
Haojian Wu357ef992016-09-21 13:18:19 +0000350
351 return false;
352}
353
Haojian Wu08e402a2016-12-02 12:39:39 +0000354std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000355 std::vector<std::string> Namespaces;
356 for (const auto *Context = D->getDeclContext(); Context;
357 Context = Context->getParent()) {
358 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
359 llvm::isa<clang::LinkageSpecDecl>(Context))
360 break;
361
362 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
363 Namespaces.push_back(ND->getName().str());
364 }
365 std::reverse(Namespaces.begin(), Namespaces.end());
366 return Namespaces;
367}
368
Haojian Wu357ef992016-09-21 13:18:19 +0000369clang::tooling::Replacements
370createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000371 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000372 llvm::StringRef FileName, bool IsHeader = false,
373 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000374 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000375 std::string GuardName(FileName);
376 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000377 for (size_t i = 0; i < GuardName.size(); ++i) {
378 if (!isAlphanumeric(GuardName[i]))
379 GuardName[i] = '_';
380 }
Haojian Wu220c7552016-10-14 13:01:36 +0000381 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000382 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000383 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000384 }
Haojian Wu357ef992016-09-21 13:18:19 +0000385
Haojian Wu48ac3042016-11-23 10:04:19 +0000386 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000387 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000388 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000389 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000390
Haojian Wu53eab1e2016-10-14 13:43:49 +0000391 if (!Includes.empty())
392 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000393
394 // Add moved class definition and its related declarations. All declarations
395 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000396 //
397 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000398 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000399 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000400 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000401 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000402 auto CurrentIt = CurrentNamespaces.begin();
403 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000404 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000405 while (CurrentIt != CurrentNamespaces.end() &&
406 DeclIt != DeclNamespaces.end()) {
407 if (*CurrentIt != *DeclIt)
408 break;
409 ++CurrentIt;
410 ++DeclIt;
411 }
Haojian Wu53315a72016-11-15 09:06:59 +0000412 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
413 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000414 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
415 CurrentIt);
416 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000417
418
419 // End with CurrentNamespace.
420 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000421 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
422 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
423 --RemainingSize, ++It) {
424 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000425 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000426 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000427 }
Haojian Wu53315a72016-11-15 09:06:59 +0000428 // Add trailing '\n' after the nested namespace definition.
429 if (HasEndCurrentNamespace)
430 NewCode += "\n";
431
432 // If the moved declaration is not in CurrentNamespace, add extra namespace
433 // definitions.
434 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000435 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000436 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000437 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000438 ++DeclIt;
439 }
Haojian Wu53315a72016-11-15 09:06:59 +0000440 // If the moved declaration is in same namespace CurrentNamespace, add
441 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000442 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000443 if (!IsInNewNamespace)
444 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000445 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000446 CurrentNamespaces = std::move(NextNamespaces);
447 }
448 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000449 for (const auto &NS : CurrentNamespaces)
450 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000451
Haojian Wu53eab1e2016-10-14 13:43:49 +0000452 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000453 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000454 return clang::tooling::Replacements(
455 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000456}
457
Haojian Wu36265162017-01-03 09:00:51 +0000458// Return a set of all decls which are used/referenced by the given Decls.
459// Specically, given a class member declaration, this method will return all
460// decls which are used by the whole class.
461llvm::DenseSet<const Decl *>
462getUsedDecls(const HelperDeclRefGraph *RG,
463 const std::vector<const NamedDecl *> &Decls) {
464 assert(RG);
465 llvm::DenseSet<const CallGraphNode *> Nodes;
466 for (const auto *D : Decls) {
467 auto Result = RG->getReachableNodes(
468 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
469 Nodes.insert(Result.begin(), Result.end());
470 }
471 llvm::DenseSet<const Decl *> Results;
472 for (const auto *Node : Nodes)
473 Results.insert(Node->getDecl());
474 return Results;
475}
476
Haojian Wu357ef992016-09-21 13:18:19 +0000477} // namespace
478
479std::unique_ptr<clang::ASTConsumer>
480ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
481 StringRef /*InFile*/) {
482 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
483 &Compiler.getSourceManager(), &MoveTool));
484 return MatchFinder.newASTConsumer();
485}
486
Haojian Wub15c8da2016-11-24 10:17:17 +0000487ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
488 DeclarationReporter *const Reporter)
489 : Context(Context), Reporter(Reporter) {
490 if (!Context->Spec.NewHeader.empty())
491 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000492}
493
Haojian Wu08e402a2016-12-02 12:39:39 +0000494void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
495 const auto &SM = Decl->getASTContext().getSourceManager();
496 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000497 StringRef FilePath = SM.getFilename(Loc);
498 FilePathToFileID[FilePath] = SM.getFileID(Loc);
499 RemovedDecls.push_back(Decl);
500}
501
Haojian Wu357ef992016-09-21 13:18:19 +0000502void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000503 auto InOldHeader =
504 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
505 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000506 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000507 auto ForwardDecls =
508 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
Haojian Wu32a552f2017-01-03 14:22:25 +0000509 auto TopLevelDecl =
510 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000511
512 //============================================================================
513 // Matchers for old header
514 //============================================================================
515 // Match all top-level named declarations (e.g. function, variable, enum) in
516 // old header, exclude forward class declarations and namespace declarations.
517 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000518 // We consider declarations inside a class belongs to the class. So these
519 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000520 auto AllDeclsInHeader = namedDecl(
521 unless(ForwardDecls), unless(namespaceDecl()),
Haojian Wub15c8da2016-11-24 10:17:17 +0000522 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wu2930be12016-11-08 19:55:13 +0000523 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
524 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000525 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
526 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000527 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000528
529 // Don't register other matchers when dumping all declarations in header.
530 if (Context->DumpDeclarations)
531 return;
532
Haojian Wu2930be12016-11-08 19:55:13 +0000533 // Match forward declarations in old header.
534 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
535 this);
536
537 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000538 // Matchers for old cc
539 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000540 auto IsOldCCTopLevelDecl = allOf(
541 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
542 // Matching using decls/type alias decls which are in named/anonymous/global
543 // namespace, these decls are always copied to new.h/cc. Those in classes,
544 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000545 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
546 usingDirectiveDecl(IsOldCCTopLevelDecl),
547 typeAliasDecl(IsOldCCTopLevelDecl)),
548 notInMacro())
549 .bind("using_decl"),
550 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000551
Haojian Wu67bb6512016-10-19 14:13:21 +0000552 // Match static functions/variable definitions which are defined in named
553 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000554 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
555 for (StringRef SymbolName : Context->Spec.Names) {
556 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
557 const auto HasName = hasName(("::" + GlobalSymbolName).str());
558 HasAnySymbolNames =
559 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
560 }
561
562 if (!HasAnySymbolNames) {
563 llvm::errs() << "No symbols being moved.\n";
564 return;
565 }
566 auto InMovedClass =
567 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000568
569 // Matchers for helper declarations in old.cc.
570 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000571 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
572 auto IsOldCCHelper =
573 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000574 // Match helper classes separately with helper functions/variables since we
575 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000576 //
577 // There could be forward declarations usage for helpers, especially for
578 // classes and functions. We need include these forward declarations.
579 //
580 // Forward declarations for variable helpers will be excluded as these
581 // declarations (with "extern") are not supposed in cpp file.
582 auto HelperFuncOrVar =
583 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
584 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000585 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000586 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000587 // Save all helper declarations in old.cc.
588 Finder->addMatcher(
589 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
590 this);
591
592 // Construct an AST-based call graph of helper declarations in old.cc.
593 // In the following matcheres, "dc" is a caller while "helper_decls" and
594 // "used_class" is a callee, so a new edge starting from caller to callee will
595 // be add in the graph.
596 //
597 // Find helper function/variable usages.
598 Finder->addMatcher(
599 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
600 .bind("func_ref"),
601 &RGBuilder);
602 // Find helper class usages.
603 Finder->addMatcher(
604 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
605 hasAncestor(decl().bind("dc"))),
606 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000607
608 //============================================================================
609 // Matchers for old files, including old.h/old.cc
610 //============================================================================
611 // Create a MatchCallback for class declarations.
612 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
613 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000614 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
615 isDefinition(), TopLevelDecl)
616 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000617 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
618 // Match moved class methods (static methods included) which are defined
619 // outside moved class declaration.
620 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000621 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000622 isDefinition())
623 .bind("class_method"),
624 MatchCallbacks.back().get());
625 // Match static member variable definition of the moved class.
626 Finder->addMatcher(
627 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
628 .bind("class_static_var_decl"),
629 MatchCallbacks.back().get());
630
Haojian Wu4543fec2016-11-16 13:05:19 +0000631 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000632 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000633 .bind("function"),
634 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000635
Haojian Wu4a920502017-02-27 13:19:13 +0000636 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
637 Finder->addMatcher(
638 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
639 MatchCallbacks.back().get());
640
Haojian Wud69d9072017-01-04 14:50:49 +0000641 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000642 // will not be moved for now no matter whether they are used or not.
643 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
644 Finder->addMatcher(
645 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
646 .bind("enum"),
647 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000648
649 // Match type alias in old.h, this includes "typedef" and "using" type alias
650 // declarations. Type alias helpers (which are defined in old.cc) will not be
651 // moved for now no matter whether they are used or not.
652 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
653 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
654 typeAliasDecl().bind("type_alias")),
655 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
656 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000657}
658
659void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000660 if (const auto *D =
661 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
662 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000663 } else if (const auto *FWD =
664 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000665 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000666 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000667 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000668 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000669 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000670 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000671 }
Haojian Wu357ef992016-09-21 13:18:19 +0000672 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000673 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
674 MovedDecls.push_back(ND);
675 HelperDeclarations.push_back(ND);
Haojian Wu4775ce52017-01-17 13:22:37 +0000676 DEBUG(llvm::dbgs() << "Add helper : "
677 << ND->getNameAsString() << " (" << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000678 } else if (const auto *UD =
679 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000680 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000681 }
682}
683
Haojian Wu2930be12016-11-08 19:55:13 +0000684std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000685 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000686}
687
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000688void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000689 llvm::StringRef SearchPath,
690 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000691 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000692 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000693 SmallVector<char, 128> HeaderWithSearchPath;
694 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000695 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000696 if (AbsoluteOldHeader ==
697 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000698 HeaderWithSearchPath.size()))) {
699 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000700 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000701 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000702
703 std::string IncludeLine =
704 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
705 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000706
Haojian Wudb726572016-10-12 15:50:30 +0000707 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
708 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000709 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000710 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000711 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000712 }
Haojian Wu357ef992016-09-21 13:18:19 +0000713}
714
Haojian Wu08e402a2016-12-02 12:39:39 +0000715void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000716 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000717
718 // If old_header is not specified (only move declarations from old.cc), remain
719 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
720 // is empty in this case, there is no way to verify unused/used helpers.
721 if (!Context->Spec.OldHeader.empty()) {
722 std::vector<const NamedDecl *> UnremovedDecls;
723 for (const auto *D : UnremovedDeclsInOldHeader)
724 UnremovedDecls.push_back(D);
725
726 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
727
728 // We remove the helper declarations which are not used in the old.cc after
729 // moving the given declarations.
730 for (const auto *D : HelperDeclarations) {
Haojian Wu4775ce52017-01-17 13:22:37 +0000731 DEBUG(llvm::dbgs() << "Check helper is used: "
732 << D->getNameAsString() << " (" << D << ")\n");
733 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
734 D->getCanonicalDecl()))) {
Haojian Wu36265162017-01-03 09:00:51 +0000735 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
Haojian Wu4775ce52017-01-17 13:22:37 +0000736 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000737 RemovedDecls.push_back(D);
738 }
739 }
740 }
741
Haojian Wu08e402a2016-12-02 12:39:39 +0000742 for (const auto *RemovedDecl : RemovedDecls) {
743 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
744 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000745 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000746 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000747 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000748 "");
749 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000750 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000751 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000752 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000753 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000754 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000755
756 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000757 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000758 StringRef FilePath = FileAndReplacements.first;
759 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000760 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000761 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000762 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000763 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000764 std::string IncludeNewH =
765 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000766 // This replacment for inserting header will be cleaned up at the end.
767 auto Err = FileAndReplacements.second.add(
768 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
769 if (Err)
770 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000771 }
Haojian Wu253d5962016-10-06 08:29:32 +0000772
Haojian Wu48ac3042016-11-23 10:04:19 +0000773 auto SI = FilePathToFileID.find(FilePath);
774 // Ignore replacements for new.h/cc.
775 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000776 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000777 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
778 if (!Style) {
779 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
780 continue;
781 }
Haojian Wu253d5962016-10-06 08:29:32 +0000782 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000783 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000784
785 if (!CleanReplacements) {
786 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
787 continue;
788 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000789 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000790 }
791}
792
Haojian Wu08e402a2016-12-02 12:39:39 +0000793void ClangMoveTool::moveDeclsToNewFiles() {
794 std::vector<const NamedDecl *> NewHeaderDecls;
795 std::vector<const NamedDecl *> NewCCDecls;
796 for (const auto *MovedDecl : MovedDecls) {
797 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000798 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000799 NewHeaderDecls.push_back(MovedDecl);
800 else
801 NewCCDecls.push_back(MovedDecl);
802 }
803
Haojian Wu36265162017-01-03 09:00:51 +0000804 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
805 std::vector<const NamedDecl *> ActualNewCCDecls;
806
807 // Filter out all unused helpers in NewCCDecls.
808 // We only move the used helpers (including transively used helpers) and the
809 // given symbols being moved.
810 for (const auto *D : NewCCDecls) {
811 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000812 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
813 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000814 continue;
815
816 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
817 << " " << D << "\n");
818 ActualNewCCDecls.push_back(D);
819 }
820
Haojian Wub15c8da2016-11-24 10:17:17 +0000821 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000822 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000823 Context->Spec.NewDependOnOld
824 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
825 : "";
826 Context->FileToReplacements[Context->Spec.NewHeader] =
827 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
828 Context->Spec.NewHeader, /*IsHeader=*/true,
829 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000830 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000831 if (!Context->Spec.NewCC.empty())
832 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000833 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
834 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000835}
836
Haojian Wu2930be12016-11-08 19:55:13 +0000837// Move all contents from OldFile to NewFile.
838void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
839 StringRef NewFile) {
840 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
841 if (!FE) {
842 llvm::errs() << "Failed to get file: " << OldFile << "\n";
843 return;
844 }
845 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
846 auto Begin = SM.getLocForStartOfFile(ID);
847 auto End = SM.getLocForEndOfFile(ID);
848 clang::tooling::Replacement RemoveAll (
849 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
850 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000851 Context->FileToReplacements[FilePath] =
852 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000853
854 StringRef Code = SM.getBufferData(ID);
855 if (!NewFile.empty()) {
856 auto AllCode = clang::tooling::Replacements(
857 clang::tooling::Replacement(NewFile, 0, 0, Code));
858 // If we are moving from old.cc, an extra step is required: excluding
859 // the #include of "old.h", instead, we replace it with #include of "new.h".
Haojian Wub15c8da2016-11-24 10:17:17 +0000860 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
Haojian Wu2930be12016-11-08 19:55:13 +0000861 AllCode = AllCode.merge(
862 clang::tooling::Replacements(clang::tooling::Replacement(
Haojian Wub15c8da2016-11-24 10:17:17 +0000863 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wu2930be12016-11-08 19:55:13 +0000864 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000865 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000866 }
867}
868
Haojian Wu357ef992016-09-21 13:18:19 +0000869void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000870 if (Context->DumpDeclarations) {
871 assert(Reporter);
872 for (const auto *Decl : UnremovedDeclsInOldHeader) {
873 auto Kind = Decl->getKind();
874 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000875 if (Kind == Decl::Kind::Var)
876 Reporter->reportDeclaration(QualifiedName, "Variable");
877 else if (Kind == Decl::Kind::Function ||
878 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000879 Reporter->reportDeclaration(QualifiedName, "Function");
880 else if (Kind == Decl::Kind::ClassTemplate ||
881 Kind == Decl::Kind::CXXRecord)
882 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000883 else if (Kind == Decl::Kind::Enum)
884 Reporter->reportDeclaration(QualifiedName, "Enum");
885 else if (Kind == Decl::Kind::Typedef ||
886 Kind == Decl::Kind::TypeAlias ||
887 Kind == Decl::Kind::TypeAliasTemplate)
888 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000889 }
890 return;
891 }
892
Haojian Wu357ef992016-09-21 13:18:19 +0000893 if (RemovedDecls.empty())
894 return;
Eric Liu47a42d52016-12-06 10:12:23 +0000895 // Ignore symbols that are not supported (e.g. typedef and enum) when
896 // checking if there is unremoved symbol in old header. This makes sure that
897 // we always move old files to new files when all symbols produced from
898 // dump_decls are moved.
899 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
900 switch (Decl->getKind()) {
901 case Decl::Kind::Function:
902 case Decl::Kind::FunctionTemplate:
903 case Decl::Kind::ClassTemplate:
904 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000905 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000906 case Decl::Kind::Typedef:
907 case Decl::Kind::TypeAlias:
908 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000909 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000910 return true;
911 default:
912 return false;
913 }
914 };
915 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
916 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
917 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000918 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000919 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
920 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000921 return;
922 }
Haojian Wu36265162017-01-03 09:00:51 +0000923 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000924 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000925 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000926}
927
928} // namespace move
929} // namespace clang