blob: e32e490ec6ba56acc475eb8c6e7bce1c2879a05a [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 Wu03c89632017-05-02 12:15:11 +0000507 auto classTemplateForwardDecls =
508 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
509 auto ForwardClassDecls = namedDecl(
510 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
511 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000512 auto TopLevelDecl =
513 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000514
515 //============================================================================
516 // Matchers for old header
517 //============================================================================
518 // Match all top-level named declarations (e.g. function, variable, enum) in
519 // old header, exclude forward class declarations and namespace declarations.
520 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000521 // We consider declarations inside a class belongs to the class. So these
522 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000523 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000524 unless(ForwardClassDecls), unless(namespaceDecl()),
525 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000526 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000527 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000528 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
529 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000530 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000531
532 // Don't register other matchers when dumping all declarations in header.
533 if (Context->DumpDeclarations)
534 return;
535
Haojian Wu2930be12016-11-08 19:55:13 +0000536 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000537 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000538 this);
539
540 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000541 // Matchers for old cc
542 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000543 auto IsOldCCTopLevelDecl = allOf(
544 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
545 // Matching using decls/type alias decls which are in named/anonymous/global
546 // namespace, these decls are always copied to new.h/cc. Those in classes,
547 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000548 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
549 usingDirectiveDecl(IsOldCCTopLevelDecl),
550 typeAliasDecl(IsOldCCTopLevelDecl)),
551 notInMacro())
552 .bind("using_decl"),
553 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000554
Haojian Wu67bb6512016-10-19 14:13:21 +0000555 // Match static functions/variable definitions which are defined in named
556 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000557 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
558 for (StringRef SymbolName : Context->Spec.Names) {
559 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
560 const auto HasName = hasName(("::" + GlobalSymbolName).str());
561 HasAnySymbolNames =
562 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
563 }
564
565 if (!HasAnySymbolNames) {
566 llvm::errs() << "No symbols being moved.\n";
567 return;
568 }
569 auto InMovedClass =
570 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000571
572 // Matchers for helper declarations in old.cc.
573 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000574 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
575 auto IsOldCCHelper =
576 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000577 // Match helper classes separately with helper functions/variables since we
578 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000579 //
580 // There could be forward declarations usage for helpers, especially for
581 // classes and functions. We need include these forward declarations.
582 //
583 // Forward declarations for variable helpers will be excluded as these
584 // declarations (with "extern") are not supposed in cpp file.
585 auto HelperFuncOrVar =
586 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
587 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000588 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000589 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000590 // Save all helper declarations in old.cc.
591 Finder->addMatcher(
592 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
593 this);
594
595 // Construct an AST-based call graph of helper declarations in old.cc.
596 // In the following matcheres, "dc" is a caller while "helper_decls" and
597 // "used_class" is a callee, so a new edge starting from caller to callee will
598 // be add in the graph.
599 //
600 // Find helper function/variable usages.
601 Finder->addMatcher(
602 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
603 .bind("func_ref"),
604 &RGBuilder);
605 // Find helper class usages.
606 Finder->addMatcher(
607 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
608 hasAncestor(decl().bind("dc"))),
609 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000610
611 //============================================================================
612 // Matchers for old files, including old.h/old.cc
613 //============================================================================
614 // Create a MatchCallback for class declarations.
615 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
616 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000617 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
618 isDefinition(), TopLevelDecl)
619 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000620 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
621 // Match moved class methods (static methods included) which are defined
622 // outside moved class declaration.
623 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000624 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000625 isDefinition())
626 .bind("class_method"),
627 MatchCallbacks.back().get());
628 // Match static member variable definition of the moved class.
629 Finder->addMatcher(
630 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
631 .bind("class_static_var_decl"),
632 MatchCallbacks.back().get());
633
Haojian Wu4543fec2016-11-16 13:05:19 +0000634 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000635 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000636 .bind("function"),
637 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000638
Haojian Wu4a920502017-02-27 13:19:13 +0000639 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
640 Finder->addMatcher(
641 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
642 MatchCallbacks.back().get());
643
Haojian Wud69d9072017-01-04 14:50:49 +0000644 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000645 // will not be moved for now no matter whether they are used or not.
646 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
647 Finder->addMatcher(
648 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
649 .bind("enum"),
650 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000651
652 // Match type alias in old.h, this includes "typedef" and "using" type alias
653 // declarations. Type alias helpers (which are defined in old.cc) will not be
654 // moved for now no matter whether they are used or not.
655 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
656 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
657 typeAliasDecl().bind("type_alias")),
658 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
659 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000660}
661
662void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000663 if (const auto *D =
664 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
665 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000666 } else if (const auto *FWD =
667 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000668 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000669 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000670 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000671 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000672 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000673 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000674 }
Haojian Wu357ef992016-09-21 13:18:19 +0000675 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000676 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
677 MovedDecls.push_back(ND);
678 HelperDeclarations.push_back(ND);
Haojian Wu4775ce52017-01-17 13:22:37 +0000679 DEBUG(llvm::dbgs() << "Add helper : "
680 << ND->getNameAsString() << " (" << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000681 } else if (const auto *UD =
682 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000683 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000684 }
685}
686
Haojian Wu2930be12016-11-08 19:55:13 +0000687std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000688 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000689}
690
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000691void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000692 llvm::StringRef SearchPath,
693 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000694 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000695 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000696 SmallVector<char, 128> HeaderWithSearchPath;
697 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000698 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000699 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000700 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000701 std::string IncludeLine =
702 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
703 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000704
Haojian Wufb68ca12018-01-31 12:12:29 +0000705 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000706 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
707 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000708 // Find old.h includes "old.h".
709 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
710 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
711 return;
712 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000713 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000714 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000715 // Find old.cc includes "old.h".
716 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
717 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
718 return;
719 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000720 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000721 }
Haojian Wu357ef992016-09-21 13:18:19 +0000722}
723
Haojian Wu08e402a2016-12-02 12:39:39 +0000724void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000725 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000726
727 // If old_header is not specified (only move declarations from old.cc), remain
728 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
729 // is empty in this case, there is no way to verify unused/used helpers.
730 if (!Context->Spec.OldHeader.empty()) {
731 std::vector<const NamedDecl *> UnremovedDecls;
732 for (const auto *D : UnremovedDeclsInOldHeader)
733 UnremovedDecls.push_back(D);
734
735 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
736
737 // We remove the helper declarations which are not used in the old.cc after
738 // moving the given declarations.
739 for (const auto *D : HelperDeclarations) {
Haojian Wu4775ce52017-01-17 13:22:37 +0000740 DEBUG(llvm::dbgs() << "Check helper is used: "
741 << D->getNameAsString() << " (" << D << ")\n");
742 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
743 D->getCanonicalDecl()))) {
Haojian Wu36265162017-01-03 09:00:51 +0000744 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
Haojian Wu4775ce52017-01-17 13:22:37 +0000745 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000746 RemovedDecls.push_back(D);
747 }
748 }
749 }
750
Haojian Wu08e402a2016-12-02 12:39:39 +0000751 for (const auto *RemovedDecl : RemovedDecls) {
752 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
753 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000754 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000755 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000756 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000757 "");
758 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000759 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000760 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000761 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000762 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000763 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000764
765 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000766 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000767 StringRef FilePath = FileAndReplacements.first;
768 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000769 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000770 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000771 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000772 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000773 std::string IncludeNewH =
774 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000775 // This replacment for inserting header will be cleaned up at the end.
776 auto Err = FileAndReplacements.second.add(
777 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
778 if (Err)
779 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000780 }
Haojian Wu253d5962016-10-06 08:29:32 +0000781
Haojian Wu48ac3042016-11-23 10:04:19 +0000782 auto SI = FilePathToFileID.find(FilePath);
783 // Ignore replacements for new.h/cc.
784 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000785 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000786 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
787 if (!Style) {
788 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
789 continue;
790 }
Haojian Wu253d5962016-10-06 08:29:32 +0000791 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000792 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000793
794 if (!CleanReplacements) {
795 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
796 continue;
797 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000798 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000799 }
800}
801
Haojian Wu08e402a2016-12-02 12:39:39 +0000802void ClangMoveTool::moveDeclsToNewFiles() {
803 std::vector<const NamedDecl *> NewHeaderDecls;
804 std::vector<const NamedDecl *> NewCCDecls;
805 for (const auto *MovedDecl : MovedDecls) {
806 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000807 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000808 NewHeaderDecls.push_back(MovedDecl);
809 else
810 NewCCDecls.push_back(MovedDecl);
811 }
812
Haojian Wu36265162017-01-03 09:00:51 +0000813 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
814 std::vector<const NamedDecl *> ActualNewCCDecls;
815
816 // Filter out all unused helpers in NewCCDecls.
817 // We only move the used helpers (including transively used helpers) and the
818 // given symbols being moved.
819 for (const auto *D : NewCCDecls) {
820 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000821 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
822 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000823 continue;
824
825 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
826 << " " << D << "\n");
827 ActualNewCCDecls.push_back(D);
828 }
829
Haojian Wub15c8da2016-11-24 10:17:17 +0000830 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000831 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000832 Context->Spec.NewDependOnOld
833 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
834 : "";
835 Context->FileToReplacements[Context->Spec.NewHeader] =
836 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
837 Context->Spec.NewHeader, /*IsHeader=*/true,
838 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000839 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000840 if (!Context->Spec.NewCC.empty())
841 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000842 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
843 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000844}
845
Haojian Wu2930be12016-11-08 19:55:13 +0000846// Move all contents from OldFile to NewFile.
847void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
848 StringRef NewFile) {
849 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
850 if (!FE) {
851 llvm::errs() << "Failed to get file: " << OldFile << "\n";
852 return;
853 }
854 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
855 auto Begin = SM.getLocForStartOfFile(ID);
856 auto End = SM.getLocForEndOfFile(ID);
857 clang::tooling::Replacement RemoveAll (
858 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
859 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000860 Context->FileToReplacements[FilePath] =
861 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000862
863 StringRef Code = SM.getBufferData(ID);
864 if (!NewFile.empty()) {
865 auto AllCode = clang::tooling::Replacements(
866 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000867 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
868 AllCode = AllCode.merge(clang::tooling::Replacements(
869 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
870 '"' + Context->Spec.NewHeader + '"')));
871 };
872 // Fix the case where old.h/old.cc includes "old.h", we replace the
873 // `#include "old.h"` with `#include "new.h"`.
874 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
875 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
876 else if (Context->Spec.NewHeader == NewFile &&
877 OldHeaderIncludeRangeInHeader.isValid())
878 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000879 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000880 }
881}
882
Haojian Wu357ef992016-09-21 13:18:19 +0000883void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000884 if (Context->DumpDeclarations) {
885 assert(Reporter);
886 for (const auto *Decl : UnremovedDeclsInOldHeader) {
887 auto Kind = Decl->getKind();
888 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000889 if (Kind == Decl::Kind::Var)
890 Reporter->reportDeclaration(QualifiedName, "Variable");
891 else if (Kind == Decl::Kind::Function ||
892 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000893 Reporter->reportDeclaration(QualifiedName, "Function");
894 else if (Kind == Decl::Kind::ClassTemplate ||
895 Kind == Decl::Kind::CXXRecord)
896 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000897 else if (Kind == Decl::Kind::Enum)
898 Reporter->reportDeclaration(QualifiedName, "Enum");
899 else if (Kind == Decl::Kind::Typedef ||
900 Kind == Decl::Kind::TypeAlias ||
901 Kind == Decl::Kind::TypeAliasTemplate)
902 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000903 }
904 return;
905 }
906
Haojian Wu357ef992016-09-21 13:18:19 +0000907 if (RemovedDecls.empty())
908 return;
Haojian Wud4786342018-02-09 15:57:30 +0000909 // Ignore symbols that are not supported when checking if there is unremoved
910 // symbol in old header. This makes sure that we always move old files to new
911 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000912 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
913 switch (Decl->getKind()) {
914 case Decl::Kind::Function:
915 case Decl::Kind::FunctionTemplate:
916 case Decl::Kind::ClassTemplate:
917 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000918 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000919 case Decl::Kind::Typedef:
920 case Decl::Kind::TypeAlias:
921 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000922 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000923 return true;
924 default:
925 return false;
926 }
927 };
928 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
929 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
930 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000931 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000932 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
933 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000934 return;
935 }
Haojian Wu36265162017-01-03 09:00:51 +0000936 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000937 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000938 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000939}
940
941} // namespace move
942} // namespace clang