blob: d600daa22c55f6c93165eaa4daee5d148177c9cb [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();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000283 // If the expansion range is a character range, this is the location of
284 // the first character past the end. Otherwise it's the location of the
285 // first character in the final token in the range.
286 auto EndExpansionLoc = SM.getExpansionRange(D->getLocEnd()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000287 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000288 // Try to load the file buffer.
289 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000290 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000291 if (InvalidTemp)
292 return SourceLocation();
293
294 const char *TokBegin = File.data() + LocInfo.second;
295 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000296 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000297 TokBegin, File.end());
298
299 llvm::SmallVector<char, 16> Line;
300 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
301 Lex.setParsingPreprocessorDirective(true);
302 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000303 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000304 // If we already reach EOF, just return the EOF SourceLocation;
305 // otherwise, move 1 offset ahead to include the trailing newline character
306 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000307 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000308 ? EndLoc
309 : EndLoc.getLocWithOffset(1);
310}
311
312// Get full range of a Decl including the comments associated with it.
313clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000314getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000315 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000316 const auto &SM = D->getASTContext().getSourceManager();
317 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
318 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000319 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000320 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000321 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000322 Full.setEnd(Comment->getLocEnd());
323 // FIXME: Don't delete a preceding comment, if there are no other entities
324 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000325 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000326 Full.setBegin(Comment->getLocStart());
327 }
328
329 return clang::CharSourceRange::getCharRange(Full);
330}
331
Haojian Wu08e402a2016-12-02 12:39:39 +0000332std::string getDeclarationSourceText(const clang::Decl *D) {
333 const auto &SM = D->getASTContext().getSourceManager();
334 llvm::StringRef SourceText =
335 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000336 return SourceText.str();
337}
338
Haojian Wu08e402a2016-12-02 12:39:39 +0000339bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000340 llvm::StringRef OriginalRunningDirectory,
341 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000342 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000343 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000344 return false;
345 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
346 if (ExpansionLoc.isInvalid())
347 return false;
348
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000349 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
350 return MakeAbsolutePath(SM, FE->getName()) ==
351 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
352 }
Haojian Wu357ef992016-09-21 13:18:19 +0000353
354 return false;
355}
356
Haojian Wu08e402a2016-12-02 12:39:39 +0000357std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000358 std::vector<std::string> Namespaces;
359 for (const auto *Context = D->getDeclContext(); Context;
360 Context = Context->getParent()) {
361 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
362 llvm::isa<clang::LinkageSpecDecl>(Context))
363 break;
364
365 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
366 Namespaces.push_back(ND->getName().str());
367 }
368 std::reverse(Namespaces.begin(), Namespaces.end());
369 return Namespaces;
370}
371
Haojian Wu357ef992016-09-21 13:18:19 +0000372clang::tooling::Replacements
373createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000374 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000375 llvm::StringRef FileName, bool IsHeader = false,
376 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000377 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000378 std::string GuardName(FileName);
379 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000380 for (size_t i = 0; i < GuardName.size(); ++i) {
381 if (!isAlphanumeric(GuardName[i]))
382 GuardName[i] = '_';
383 }
Haojian Wu220c7552016-10-14 13:01:36 +0000384 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000385 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000386 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000387 }
Haojian Wu357ef992016-09-21 13:18:19 +0000388
Haojian Wu48ac3042016-11-23 10:04:19 +0000389 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000390 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000391 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000392 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000393
Haojian Wu53eab1e2016-10-14 13:43:49 +0000394 if (!Includes.empty())
395 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000396
397 // Add moved class definition and its related declarations. All declarations
398 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000399 //
400 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000401 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000402 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000403 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000404 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000405 auto CurrentIt = CurrentNamespaces.begin();
406 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000407 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000408 while (CurrentIt != CurrentNamespaces.end() &&
409 DeclIt != DeclNamespaces.end()) {
410 if (*CurrentIt != *DeclIt)
411 break;
412 ++CurrentIt;
413 ++DeclIt;
414 }
Haojian Wu53315a72016-11-15 09:06:59 +0000415 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
416 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000417 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
418 CurrentIt);
419 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000420
421
422 // End with CurrentNamespace.
423 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000424 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
425 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
426 --RemainingSize, ++It) {
427 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000428 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000429 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000430 }
Haojian Wu53315a72016-11-15 09:06:59 +0000431 // Add trailing '\n' after the nested namespace definition.
432 if (HasEndCurrentNamespace)
433 NewCode += "\n";
434
435 // If the moved declaration is not in CurrentNamespace, add extra namespace
436 // definitions.
437 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000438 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000439 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000440 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000441 ++DeclIt;
442 }
Haojian Wu53315a72016-11-15 09:06:59 +0000443 // If the moved declaration is in same namespace CurrentNamespace, add
444 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000445 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000446 if (!IsInNewNamespace)
447 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000448 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000449 CurrentNamespaces = std::move(NextNamespaces);
450 }
451 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000452 for (const auto &NS : CurrentNamespaces)
453 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000454
Haojian Wu53eab1e2016-10-14 13:43:49 +0000455 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000456 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000457 return clang::tooling::Replacements(
458 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000459}
460
Haojian Wu36265162017-01-03 09:00:51 +0000461// Return a set of all decls which are used/referenced by the given Decls.
462// Specically, given a class member declaration, this method will return all
463// decls which are used by the whole class.
464llvm::DenseSet<const Decl *>
465getUsedDecls(const HelperDeclRefGraph *RG,
466 const std::vector<const NamedDecl *> &Decls) {
467 assert(RG);
468 llvm::DenseSet<const CallGraphNode *> Nodes;
469 for (const auto *D : Decls) {
470 auto Result = RG->getReachableNodes(
471 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
472 Nodes.insert(Result.begin(), Result.end());
473 }
474 llvm::DenseSet<const Decl *> Results;
475 for (const auto *Node : Nodes)
476 Results.insert(Node->getDecl());
477 return Results;
478}
479
Haojian Wu357ef992016-09-21 13:18:19 +0000480} // namespace
481
482std::unique_ptr<clang::ASTConsumer>
483ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
484 StringRef /*InFile*/) {
485 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
486 &Compiler.getSourceManager(), &MoveTool));
487 return MatchFinder.newASTConsumer();
488}
489
Haojian Wub15c8da2016-11-24 10:17:17 +0000490ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
491 DeclarationReporter *const Reporter)
492 : Context(Context), Reporter(Reporter) {
493 if (!Context->Spec.NewHeader.empty())
494 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000495}
496
Haojian Wu08e402a2016-12-02 12:39:39 +0000497void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
498 const auto &SM = Decl->getASTContext().getSourceManager();
499 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000500 StringRef FilePath = SM.getFilename(Loc);
501 FilePathToFileID[FilePath] = SM.getFileID(Loc);
502 RemovedDecls.push_back(Decl);
503}
504
Haojian Wu357ef992016-09-21 13:18:19 +0000505void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000506 auto InOldHeader =
507 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
508 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000509 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000510 auto classTemplateForwardDecls =
511 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
512 auto ForwardClassDecls = namedDecl(
513 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
514 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000515 auto TopLevelDecl =
516 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000517
518 //============================================================================
519 // Matchers for old header
520 //============================================================================
521 // Match all top-level named declarations (e.g. function, variable, enum) in
522 // old header, exclude forward class declarations and namespace declarations.
523 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000524 // We consider declarations inside a class belongs to the class. So these
525 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000526 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000527 unless(ForwardClassDecls), unless(namespaceDecl()),
528 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000529 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000530 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000531 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
532 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000533 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000534
535 // Don't register other matchers when dumping all declarations in header.
536 if (Context->DumpDeclarations)
537 return;
538
Haojian Wu2930be12016-11-08 19:55:13 +0000539 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000540 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000541 this);
542
543 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000544 // Matchers for old cc
545 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000546 auto IsOldCCTopLevelDecl = allOf(
547 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
548 // Matching using decls/type alias decls which are in named/anonymous/global
549 // namespace, these decls are always copied to new.h/cc. Those in classes,
550 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000551 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
552 usingDirectiveDecl(IsOldCCTopLevelDecl),
553 typeAliasDecl(IsOldCCTopLevelDecl)),
554 notInMacro())
555 .bind("using_decl"),
556 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000557
Haojian Wu67bb6512016-10-19 14:13:21 +0000558 // Match static functions/variable definitions which are defined in named
559 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000560 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
561 for (StringRef SymbolName : Context->Spec.Names) {
562 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
563 const auto HasName = hasName(("::" + GlobalSymbolName).str());
564 HasAnySymbolNames =
565 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
566 }
567
568 if (!HasAnySymbolNames) {
569 llvm::errs() << "No symbols being moved.\n";
570 return;
571 }
572 auto InMovedClass =
573 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000574
575 // Matchers for helper declarations in old.cc.
576 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000577 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
578 auto IsOldCCHelper =
579 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000580 // Match helper classes separately with helper functions/variables since we
581 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000582 //
583 // There could be forward declarations usage for helpers, especially for
584 // classes and functions. We need include these forward declarations.
585 //
586 // Forward declarations for variable helpers will be excluded as these
587 // declarations (with "extern") are not supposed in cpp file.
588 auto HelperFuncOrVar =
589 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
590 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000591 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000592 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000593 // Save all helper declarations in old.cc.
594 Finder->addMatcher(
595 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
596 this);
597
598 // Construct an AST-based call graph of helper declarations in old.cc.
599 // In the following matcheres, "dc" is a caller while "helper_decls" and
600 // "used_class" is a callee, so a new edge starting from caller to callee will
601 // be add in the graph.
602 //
603 // Find helper function/variable usages.
604 Finder->addMatcher(
605 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
606 .bind("func_ref"),
607 &RGBuilder);
608 // Find helper class usages.
609 Finder->addMatcher(
610 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
611 hasAncestor(decl().bind("dc"))),
612 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000613
614 //============================================================================
615 // Matchers for old files, including old.h/old.cc
616 //============================================================================
617 // Create a MatchCallback for class declarations.
618 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
619 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000620 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
621 isDefinition(), TopLevelDecl)
622 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000623 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
624 // Match moved class methods (static methods included) which are defined
625 // outside moved class declaration.
626 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000627 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000628 isDefinition())
629 .bind("class_method"),
630 MatchCallbacks.back().get());
631 // Match static member variable definition of the moved class.
632 Finder->addMatcher(
633 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
634 .bind("class_static_var_decl"),
635 MatchCallbacks.back().get());
636
Haojian Wu4543fec2016-11-16 13:05:19 +0000637 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000638 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000639 .bind("function"),
640 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000641
Haojian Wu4a920502017-02-27 13:19:13 +0000642 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
643 Finder->addMatcher(
644 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
645 MatchCallbacks.back().get());
646
Haojian Wud69d9072017-01-04 14:50:49 +0000647 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000648 // will not be moved for now no matter whether they are used or not.
649 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
650 Finder->addMatcher(
651 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
652 .bind("enum"),
653 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000654
655 // Match type alias in old.h, this includes "typedef" and "using" type alias
656 // declarations. Type alias helpers (which are defined in old.cc) will not be
657 // moved for now no matter whether they are used or not.
658 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
659 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
660 typeAliasDecl().bind("type_alias")),
661 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
662 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000663}
664
665void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000666 if (const auto *D =
667 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
668 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000669 } else if (const auto *FWD =
670 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000671 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000672 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000673 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000674 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000675 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000676 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000677 }
Haojian Wu357ef992016-09-21 13:18:19 +0000678 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000679 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
680 MovedDecls.push_back(ND);
681 HelperDeclarations.push_back(ND);
Haojian Wu4775ce52017-01-17 13:22:37 +0000682 DEBUG(llvm::dbgs() << "Add helper : "
683 << ND->getNameAsString() << " (" << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000684 } else if (const auto *UD =
685 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000686 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000687 }
688}
689
Haojian Wu2930be12016-11-08 19:55:13 +0000690std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000691 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000692}
693
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000694void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000695 llvm::StringRef SearchPath,
696 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000697 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000698 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000699 SmallVector<char, 128> HeaderWithSearchPath;
700 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000701 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000702 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000703 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000704 std::string IncludeLine =
705 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
706 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000707
Haojian Wufb68ca12018-01-31 12:12:29 +0000708 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000709 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
710 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000711 // Find old.h includes "old.h".
712 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
713 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
714 return;
715 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000716 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000717 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000718 // Find old.cc includes "old.h".
719 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
720 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
721 return;
722 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000723 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000724 }
Haojian Wu357ef992016-09-21 13:18:19 +0000725}
726
Haojian Wu08e402a2016-12-02 12:39:39 +0000727void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000728 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000729
730 // If old_header is not specified (only move declarations from old.cc), remain
731 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
732 // is empty in this case, there is no way to verify unused/used helpers.
733 if (!Context->Spec.OldHeader.empty()) {
734 std::vector<const NamedDecl *> UnremovedDecls;
735 for (const auto *D : UnremovedDeclsInOldHeader)
736 UnremovedDecls.push_back(D);
737
738 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
739
740 // We remove the helper declarations which are not used in the old.cc after
741 // moving the given declarations.
742 for (const auto *D : HelperDeclarations) {
Haojian Wu4775ce52017-01-17 13:22:37 +0000743 DEBUG(llvm::dbgs() << "Check helper is used: "
744 << D->getNameAsString() << " (" << D << ")\n");
745 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
746 D->getCanonicalDecl()))) {
Haojian Wu36265162017-01-03 09:00:51 +0000747 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
Haojian Wu4775ce52017-01-17 13:22:37 +0000748 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000749 RemovedDecls.push_back(D);
750 }
751 }
752 }
753
Haojian Wu08e402a2016-12-02 12:39:39 +0000754 for (const auto *RemovedDecl : RemovedDecls) {
755 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
756 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000757 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000758 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000759 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000760 "");
761 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000762 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000763 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000764 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000765 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000766 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000767
768 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000769 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000770 StringRef FilePath = FileAndReplacements.first;
771 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000772 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000773 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000774 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000775 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000776 std::string IncludeNewH =
777 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000778 // This replacment for inserting header will be cleaned up at the end.
779 auto Err = FileAndReplacements.second.add(
780 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
781 if (Err)
782 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000783 }
Haojian Wu253d5962016-10-06 08:29:32 +0000784
Haojian Wu48ac3042016-11-23 10:04:19 +0000785 auto SI = FilePathToFileID.find(FilePath);
786 // Ignore replacements for new.h/cc.
787 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000788 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000789 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
790 if (!Style) {
791 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
792 continue;
793 }
Haojian Wu253d5962016-10-06 08:29:32 +0000794 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000795 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000796
797 if (!CleanReplacements) {
798 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
799 continue;
800 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000801 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000802 }
803}
804
Haojian Wu08e402a2016-12-02 12:39:39 +0000805void ClangMoveTool::moveDeclsToNewFiles() {
806 std::vector<const NamedDecl *> NewHeaderDecls;
807 std::vector<const NamedDecl *> NewCCDecls;
808 for (const auto *MovedDecl : MovedDecls) {
809 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000810 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000811 NewHeaderDecls.push_back(MovedDecl);
812 else
813 NewCCDecls.push_back(MovedDecl);
814 }
815
Haojian Wu36265162017-01-03 09:00:51 +0000816 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
817 std::vector<const NamedDecl *> ActualNewCCDecls;
818
819 // Filter out all unused helpers in NewCCDecls.
820 // We only move the used helpers (including transively used helpers) and the
821 // given symbols being moved.
822 for (const auto *D : NewCCDecls) {
823 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000824 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
825 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000826 continue;
827
828 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
829 << " " << D << "\n");
830 ActualNewCCDecls.push_back(D);
831 }
832
Haojian Wub15c8da2016-11-24 10:17:17 +0000833 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000834 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000835 Context->Spec.NewDependOnOld
836 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
837 : "";
838 Context->FileToReplacements[Context->Spec.NewHeader] =
839 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
840 Context->Spec.NewHeader, /*IsHeader=*/true,
841 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000842 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000843 if (!Context->Spec.NewCC.empty())
844 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000845 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
846 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000847}
848
Haojian Wu2930be12016-11-08 19:55:13 +0000849// Move all contents from OldFile to NewFile.
850void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
851 StringRef NewFile) {
852 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
853 if (!FE) {
854 llvm::errs() << "Failed to get file: " << OldFile << "\n";
855 return;
856 }
857 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
858 auto Begin = SM.getLocForStartOfFile(ID);
859 auto End = SM.getLocForEndOfFile(ID);
860 clang::tooling::Replacement RemoveAll (
861 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
862 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000863 Context->FileToReplacements[FilePath] =
864 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000865
866 StringRef Code = SM.getBufferData(ID);
867 if (!NewFile.empty()) {
868 auto AllCode = clang::tooling::Replacements(
869 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000870 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
871 AllCode = AllCode.merge(clang::tooling::Replacements(
872 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
873 '"' + Context->Spec.NewHeader + '"')));
874 };
875 // Fix the case where old.h/old.cc includes "old.h", we replace the
876 // `#include "old.h"` with `#include "new.h"`.
877 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
878 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
879 else if (Context->Spec.NewHeader == NewFile &&
880 OldHeaderIncludeRangeInHeader.isValid())
881 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000882 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000883 }
884}
885
Haojian Wu357ef992016-09-21 13:18:19 +0000886void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000887 if (Context->DumpDeclarations) {
888 assert(Reporter);
889 for (const auto *Decl : UnremovedDeclsInOldHeader) {
890 auto Kind = Decl->getKind();
891 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000892 if (Kind == Decl::Kind::Var)
893 Reporter->reportDeclaration(QualifiedName, "Variable");
894 else if (Kind == Decl::Kind::Function ||
895 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000896 Reporter->reportDeclaration(QualifiedName, "Function");
897 else if (Kind == Decl::Kind::ClassTemplate ||
898 Kind == Decl::Kind::CXXRecord)
899 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000900 else if (Kind == Decl::Kind::Enum)
901 Reporter->reportDeclaration(QualifiedName, "Enum");
902 else if (Kind == Decl::Kind::Typedef ||
903 Kind == Decl::Kind::TypeAlias ||
904 Kind == Decl::Kind::TypeAliasTemplate)
905 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000906 }
907 return;
908 }
909
Haojian Wu357ef992016-09-21 13:18:19 +0000910 if (RemovedDecls.empty())
911 return;
Haojian Wud4786342018-02-09 15:57:30 +0000912 // Ignore symbols that are not supported when checking if there is unremoved
913 // symbol in old header. This makes sure that we always move old files to new
914 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000915 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
916 switch (Decl->getKind()) {
917 case Decl::Kind::Function:
918 case Decl::Kind::FunctionTemplate:
919 case Decl::Kind::ClassTemplate:
920 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000921 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000922 case Decl::Kind::Typedef:
923 case Decl::Kind::TypeAlias:
924 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000925 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000926 return true;
927 default:
928 return false;
929 }
930 };
931 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
932 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
933 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000934 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000935 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
936 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000937 return;
938 }
Haojian Wu36265162017-01-03 09:00:51 +0000939 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000940 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000941 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000942}
943
944} // namespace move
945} // namespace clang