blob: 16b0f72350961080501faf6fed868f576c1bbffd [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*/,
Julie Hockett546943f2018-05-10 19:13:14 +0000134 const clang::Module * /*Imported*/,
135 SrcMgr::CharacteristicKind /*FileType*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000136 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000137 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000138 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000139 }
140
141private:
142 const SourceManager &SM;
143 ClangMoveTool *const MoveTool;
144};
145
Haojian Wu32a552f2017-01-03 14:22:25 +0000146/// Add a declatration being moved to new.h/cc. Note that the declaration will
147/// also be deleted in old.h/cc.
148void MoveDeclFromOldFileToNewFile(ClangMoveTool *MoveTool, const NamedDecl *D) {
149 MoveTool->getMovedDecls().push_back(D);
150 MoveTool->addRemovedDecl(D);
151 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
152}
153
Haojian Wu4543fec2016-11-16 13:05:19 +0000154class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
155public:
156 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
157 : MoveTool(MoveTool) {}
158
159 void run(const MatchFinder::MatchResult &Result) override {
160 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
161 assert(FD);
162 const clang::NamedDecl *D = FD;
163 if (const auto *FTD = FD->getDescribedFunctionTemplate())
164 D = FTD;
Haojian Wu32a552f2017-01-03 14:22:25 +0000165 MoveDeclFromOldFileToNewFile(MoveTool, D);
166 }
167
168private:
169 ClangMoveTool *MoveTool;
170};
171
Haojian Wu4a920502017-02-27 13:19:13 +0000172class VarDeclarationMatch : public MatchFinder::MatchCallback {
173public:
174 explicit VarDeclarationMatch(ClangMoveTool *MoveTool)
175 : MoveTool(MoveTool) {}
176
177 void run(const MatchFinder::MatchResult &Result) override {
178 const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>("var");
179 assert(VD);
180 MoveDeclFromOldFileToNewFile(MoveTool, VD);
181 }
182
183private:
184 ClangMoveTool *MoveTool;
185};
186
Haojian Wud69d9072017-01-04 14:50:49 +0000187class TypeAliasMatch : public MatchFinder::MatchCallback {
188public:
189 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
190 : MoveTool(MoveTool) {}
191
192 void run(const MatchFinder::MatchResult &Result) override {
193 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
194 MoveDeclFromOldFileToNewFile(MoveTool, TD);
195 else if (const auto *TAD =
196 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
197 const NamedDecl * D = TAD;
198 if (const auto * TD = TAD->getDescribedAliasTemplate())
199 D = TD;
200 MoveDeclFromOldFileToNewFile(MoveTool, D);
201 }
202 }
203
204private:
205 ClangMoveTool *MoveTool;
206};
207
Haojian Wu32a552f2017-01-03 14:22:25 +0000208class EnumDeclarationMatch : public MatchFinder::MatchCallback {
209public:
210 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
211 : MoveTool(MoveTool) {}
212
213 void run(const MatchFinder::MatchResult &Result) override {
214 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
215 assert(ED);
216 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000217 }
218
219private:
220 ClangMoveTool *MoveTool;
221};
222
Haojian Wu35ca9462016-11-14 14:15:44 +0000223class ClassDeclarationMatch : public MatchFinder::MatchCallback {
224public:
225 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
226 : MoveTool(MoveTool) {}
227 void run(const MatchFinder::MatchResult &Result) override {
228 clang::SourceManager* SM = &Result.Context->getSourceManager();
229 if (const auto *CMD =
230 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
231 MatchClassMethod(CMD, SM);
232 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
233 "class_static_var_decl"))
234 MatchClassStaticVariable(VD, SM);
235 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
236 "moved_class"))
237 MatchClassDeclaration(CD, SM);
238 }
239
240private:
241 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
242 clang::SourceManager* SM) {
243 // Skip inline class methods. isInline() ast matcher doesn't ignore this
244 // case.
245 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000246 MoveTool->getMovedDecls().push_back(CMD);
247 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000248 // Get template class method from its method declaration as
249 // UnremovedDecls stores template class method.
250 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
251 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
252 else
253 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
254 }
255 }
256
257 void MatchClassStaticVariable(const clang::NamedDecl *VD,
258 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000259 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000260 }
261
262 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
263 clang::SourceManager* SM) {
264 // Get class template from its class declaration as UnremovedDecls stores
265 // class template.
266 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000267 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000268 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000269 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000270 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000271 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000272 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000273 }
274
275 ClangMoveTool *MoveTool;
276};
277
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000278// Expand to get the end location of the line where the EndLoc of the given
279// Decl.
280SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000281getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000282 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000283 const auto &SM = D->getASTContext().getSourceManager();
Richard Smith4bb15ab2018-04-30 05:26:07 +0000284 // If the expansion range is a character range, this is the location of
285 // the first character past the end. Otherwise it's the location of the
286 // first character in the final token in the range.
287 auto EndExpansionLoc = SM.getExpansionRange(D->getLocEnd()).getEnd();
Haojian Wudc4edba2016-12-13 15:35:47 +0000288 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000289 // Try to load the file buffer.
290 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000291 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000292 if (InvalidTemp)
293 return SourceLocation();
294
295 const char *TokBegin = File.data() + LocInfo.second;
296 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000297 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000298 TokBegin, File.end());
299
300 llvm::SmallVector<char, 16> Line;
301 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
302 Lex.setParsingPreprocessorDirective(true);
303 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000304 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000305 // If we already reach EOF, just return the EOF SourceLocation;
306 // otherwise, move 1 offset ahead to include the trailing newline character
307 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000308 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000309 ? EndLoc
310 : EndLoc.getLocWithOffset(1);
311}
312
313// Get full range of a Decl including the comments associated with it.
314clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000315getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000316 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000317 const auto &SM = D->getASTContext().getSourceManager();
318 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
319 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000320 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000321 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000322 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000323 Full.setEnd(Comment->getLocEnd());
324 // FIXME: Don't delete a preceding comment, if there are no other entities
325 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000326 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000327 Full.setBegin(Comment->getLocStart());
328 }
329
330 return clang::CharSourceRange::getCharRange(Full);
331}
332
Haojian Wu08e402a2016-12-02 12:39:39 +0000333std::string getDeclarationSourceText(const clang::Decl *D) {
334 const auto &SM = D->getASTContext().getSourceManager();
335 llvm::StringRef SourceText =
336 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000337 return SourceText.str();
338}
339
Haojian Wu08e402a2016-12-02 12:39:39 +0000340bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000341 llvm::StringRef OriginalRunningDirectory,
342 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000343 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000344 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000345 return false;
346 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
347 if (ExpansionLoc.isInvalid())
348 return false;
349
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000350 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
351 return MakeAbsolutePath(SM, FE->getName()) ==
352 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
353 }
Haojian Wu357ef992016-09-21 13:18:19 +0000354
355 return false;
356}
357
Haojian Wu08e402a2016-12-02 12:39:39 +0000358std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000359 std::vector<std::string> Namespaces;
360 for (const auto *Context = D->getDeclContext(); Context;
361 Context = Context->getParent()) {
362 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
363 llvm::isa<clang::LinkageSpecDecl>(Context))
364 break;
365
366 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
367 Namespaces.push_back(ND->getName().str());
368 }
369 std::reverse(Namespaces.begin(), Namespaces.end());
370 return Namespaces;
371}
372
Haojian Wu357ef992016-09-21 13:18:19 +0000373clang::tooling::Replacements
374createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000375 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000376 llvm::StringRef FileName, bool IsHeader = false,
377 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000378 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000379 std::string GuardName(FileName);
380 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000381 for (size_t i = 0; i < GuardName.size(); ++i) {
382 if (!isAlphanumeric(GuardName[i]))
383 GuardName[i] = '_';
384 }
Haojian Wu220c7552016-10-14 13:01:36 +0000385 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000386 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000387 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000388 }
Haojian Wu357ef992016-09-21 13:18:19 +0000389
Haojian Wu48ac3042016-11-23 10:04:19 +0000390 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000391 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000392 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000393 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000394
Haojian Wu53eab1e2016-10-14 13:43:49 +0000395 if (!Includes.empty())
396 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000397
398 // Add moved class definition and its related declarations. All declarations
399 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000400 //
401 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000402 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000403 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000404 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000405 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000406 auto CurrentIt = CurrentNamespaces.begin();
407 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000408 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000409 while (CurrentIt != CurrentNamespaces.end() &&
410 DeclIt != DeclNamespaces.end()) {
411 if (*CurrentIt != *DeclIt)
412 break;
413 ++CurrentIt;
414 ++DeclIt;
415 }
Haojian Wu53315a72016-11-15 09:06:59 +0000416 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
417 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000418 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
419 CurrentIt);
420 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000421
422
423 // End with CurrentNamespace.
424 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000425 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
426 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
427 --RemainingSize, ++It) {
428 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000429 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000430 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000431 }
Haojian Wu53315a72016-11-15 09:06:59 +0000432 // Add trailing '\n' after the nested namespace definition.
433 if (HasEndCurrentNamespace)
434 NewCode += "\n";
435
436 // If the moved declaration is not in CurrentNamespace, add extra namespace
437 // definitions.
438 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000439 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000440 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000441 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000442 ++DeclIt;
443 }
Haojian Wu53315a72016-11-15 09:06:59 +0000444 // If the moved declaration is in same namespace CurrentNamespace, add
445 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000446 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000447 if (!IsInNewNamespace)
448 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000449 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000450 CurrentNamespaces = std::move(NextNamespaces);
451 }
452 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000453 for (const auto &NS : CurrentNamespaces)
454 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000455
Haojian Wu53eab1e2016-10-14 13:43:49 +0000456 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000457 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000458 return clang::tooling::Replacements(
459 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000460}
461
Haojian Wu36265162017-01-03 09:00:51 +0000462// Return a set of all decls which are used/referenced by the given Decls.
463// Specically, given a class member declaration, this method will return all
464// decls which are used by the whole class.
465llvm::DenseSet<const Decl *>
466getUsedDecls(const HelperDeclRefGraph *RG,
467 const std::vector<const NamedDecl *> &Decls) {
468 assert(RG);
469 llvm::DenseSet<const CallGraphNode *> Nodes;
470 for (const auto *D : Decls) {
471 auto Result = RG->getReachableNodes(
472 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
473 Nodes.insert(Result.begin(), Result.end());
474 }
475 llvm::DenseSet<const Decl *> Results;
476 for (const auto *Node : Nodes)
477 Results.insert(Node->getDecl());
478 return Results;
479}
480
Haojian Wu357ef992016-09-21 13:18:19 +0000481} // namespace
482
483std::unique_ptr<clang::ASTConsumer>
484ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
485 StringRef /*InFile*/) {
486 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
487 &Compiler.getSourceManager(), &MoveTool));
488 return MatchFinder.newASTConsumer();
489}
490
Haojian Wub15c8da2016-11-24 10:17:17 +0000491ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
492 DeclarationReporter *const Reporter)
493 : Context(Context), Reporter(Reporter) {
494 if (!Context->Spec.NewHeader.empty())
495 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000496}
497
Haojian Wu08e402a2016-12-02 12:39:39 +0000498void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
499 const auto &SM = Decl->getASTContext().getSourceManager();
500 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000501 StringRef FilePath = SM.getFilename(Loc);
502 FilePathToFileID[FilePath] = SM.getFileID(Loc);
503 RemovedDecls.push_back(Decl);
504}
505
Haojian Wu357ef992016-09-21 13:18:19 +0000506void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000507 auto InOldHeader =
508 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
509 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000510 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu03c89632017-05-02 12:15:11 +0000511 auto classTemplateForwardDecls =
512 classTemplateDecl(unless(has(cxxRecordDecl(isDefinition()))));
513 auto ForwardClassDecls = namedDecl(
514 anyOf(cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))),
515 classTemplateForwardDecls));
Haojian Wu32a552f2017-01-03 14:22:25 +0000516 auto TopLevelDecl =
517 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000518
519 //============================================================================
520 // Matchers for old header
521 //============================================================================
522 // Match all top-level named declarations (e.g. function, variable, enum) in
523 // old header, exclude forward class declarations and namespace declarations.
524 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000525 // We consider declarations inside a class belongs to the class. So these
526 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000527 auto AllDeclsInHeader = namedDecl(
Haojian Wu03c89632017-05-02 12:15:11 +0000528 unless(ForwardClassDecls), unless(namespaceDecl()),
529 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wud4786342018-02-09 15:57:30 +0000530 notInMacro(),
Haojian Wu2930be12016-11-08 19:55:13 +0000531 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000532 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
533 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000534 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000535
536 // Don't register other matchers when dumping all declarations in header.
537 if (Context->DumpDeclarations)
538 return;
539
Haojian Wu2930be12016-11-08 19:55:13 +0000540 // Match forward declarations in old header.
Haojian Wu03c89632017-05-02 12:15:11 +0000541 Finder->addMatcher(namedDecl(ForwardClassDecls, InOldHeader).bind("fwd_decl"),
Haojian Wu2930be12016-11-08 19:55:13 +0000542 this);
543
544 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000545 // Matchers for old cc
546 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000547 auto IsOldCCTopLevelDecl = allOf(
548 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
549 // Matching using decls/type alias decls which are in named/anonymous/global
550 // namespace, these decls are always copied to new.h/cc. Those in classes,
551 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000552 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
553 usingDirectiveDecl(IsOldCCTopLevelDecl),
554 typeAliasDecl(IsOldCCTopLevelDecl)),
555 notInMacro())
556 .bind("using_decl"),
557 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000558
Haojian Wu67bb6512016-10-19 14:13:21 +0000559 // Match static functions/variable definitions which are defined in named
560 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000561 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
562 for (StringRef SymbolName : Context->Spec.Names) {
563 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
564 const auto HasName = hasName(("::" + GlobalSymbolName).str());
565 HasAnySymbolNames =
566 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
567 }
568
569 if (!HasAnySymbolNames) {
570 llvm::errs() << "No symbols being moved.\n";
571 return;
572 }
573 auto InMovedClass =
574 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000575
576 // Matchers for helper declarations in old.cc.
577 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
Haojian Wu4775ce52017-01-17 13:22:37 +0000578 auto NotInMovedClass= allOf(unless(InMovedClass), InOldCC);
579 auto IsOldCCHelper =
580 allOf(NotInMovedClass, anyOf(isStaticStorageClass(), InAnonymousNS));
Haojian Wu36265162017-01-03 09:00:51 +0000581 // Match helper classes separately with helper functions/variables since we
582 // want to reuse these matchers in finding helpers usage below.
Haojian Wu4775ce52017-01-17 13:22:37 +0000583 //
584 // There could be forward declarations usage for helpers, especially for
585 // classes and functions. We need include these forward declarations.
586 //
587 // Forward declarations for variable helpers will be excluded as these
588 // declarations (with "extern") are not supposed in cpp file.
589 auto HelperFuncOrVar =
590 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelper),
591 varDecl(isDefinition(), IsOldCCHelper)));
Haojian Wub3d98882017-01-17 10:08:11 +0000592 auto HelperClasses =
Haojian Wu4775ce52017-01-17 13:22:37 +0000593 cxxRecordDecl(notInMacro(), NotInMovedClass, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000594 // Save all helper declarations in old.cc.
595 Finder->addMatcher(
596 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
597 this);
598
599 // Construct an AST-based call graph of helper declarations in old.cc.
600 // In the following matcheres, "dc" is a caller while "helper_decls" and
601 // "used_class" is a callee, so a new edge starting from caller to callee will
602 // be add in the graph.
603 //
604 // Find helper function/variable usages.
605 Finder->addMatcher(
606 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
607 .bind("func_ref"),
608 &RGBuilder);
609 // Find helper class usages.
610 Finder->addMatcher(
611 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
612 hasAncestor(decl().bind("dc"))),
613 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000614
615 //============================================================================
616 // Matchers for old files, including old.h/old.cc
617 //============================================================================
618 // Create a MatchCallback for class declarations.
619 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
620 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000621 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
622 isDefinition(), TopLevelDecl)
623 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000624 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
625 // Match moved class methods (static methods included) which are defined
626 // outside moved class declaration.
627 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000628 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000629 isDefinition())
630 .bind("class_method"),
631 MatchCallbacks.back().get());
632 // Match static member variable definition of the moved class.
633 Finder->addMatcher(
634 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
635 .bind("class_static_var_decl"),
636 MatchCallbacks.back().get());
637
Haojian Wu4543fec2016-11-16 13:05:19 +0000638 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000639 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000640 .bind("function"),
641 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000642
Haojian Wu4a920502017-02-27 13:19:13 +0000643 MatchCallbacks.push_back(llvm::make_unique<VarDeclarationMatch>(this));
644 Finder->addMatcher(
645 varDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl).bind("var"),
646 MatchCallbacks.back().get());
647
Haojian Wud69d9072017-01-04 14:50:49 +0000648 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000649 // will not be moved for now no matter whether they are used or not.
650 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
651 Finder->addMatcher(
652 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
653 .bind("enum"),
654 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000655
656 // Match type alias in old.h, this includes "typedef" and "using" type alias
657 // declarations. Type alias helpers (which are defined in old.cc) will not be
658 // moved for now no matter whether they are used or not.
659 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
660 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
661 typeAliasDecl().bind("type_alias")),
662 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
663 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000664}
665
666void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000667 if (const auto *D =
668 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
669 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000670 } else if (const auto *FWD =
671 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000672 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000673 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000674 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000675 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000676 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000677 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000678 }
Haojian Wu357ef992016-09-21 13:18:19 +0000679 } else if (const auto *ND =
Haojian Wu36265162017-01-03 09:00:51 +0000680 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
681 MovedDecls.push_back(ND);
682 HelperDeclarations.push_back(ND);
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000683 LLVM_DEBUG(llvm::dbgs() << "Add helper : " << ND->getNameAsString() << " ("
684 << ND << ")\n");
Haojian Wu67bb6512016-10-19 14:13:21 +0000685 } else if (const auto *UD =
686 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000687 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000688 }
689}
690
Haojian Wu2930be12016-11-08 19:55:13 +0000691std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000692 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000693}
694
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000695void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000696 llvm::StringRef SearchPath,
697 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000698 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000699 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000700 SmallVector<char, 128> HeaderWithSearchPath;
701 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wufb68ca12018-01-31 12:12:29 +0000702 std::string AbsoluteIncludeHeader =
Haojian Wudb726572016-10-12 15:50:30 +0000703 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wufb68ca12018-01-31 12:12:29 +0000704 HeaderWithSearchPath.size()));
Haojian Wudaf4cb82016-09-23 13:28:38 +0000705 std::string IncludeLine =
706 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
707 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000708
Haojian Wufb68ca12018-01-31 12:12:29 +0000709 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000710 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
711 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000712 // Find old.h includes "old.h".
713 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
714 OldHeaderIncludeRangeInHeader = IncludeFilenameRange;
715 return;
716 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000717 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000718 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wufb68ca12018-01-31 12:12:29 +0000719 // Find old.cc includes "old.h".
720 if (AbsoluteOldHeader == AbsoluteIncludeHeader) {
721 OldHeaderIncludeRangeInCC = IncludeFilenameRange;
722 return;
723 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000724 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000725 }
Haojian Wu357ef992016-09-21 13:18:19 +0000726}
727
Haojian Wu08e402a2016-12-02 12:39:39 +0000728void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000729 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000730
731 // If old_header is not specified (only move declarations from old.cc), remain
732 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
733 // is empty in this case, there is no way to verify unused/used helpers.
734 if (!Context->Spec.OldHeader.empty()) {
735 std::vector<const NamedDecl *> UnremovedDecls;
736 for (const auto *D : UnremovedDeclsInOldHeader)
737 UnremovedDecls.push_back(D);
738
739 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
740
741 // We remove the helper declarations which are not used in the old.cc after
742 // moving the given declarations.
743 for (const auto *D : HelperDeclarations) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000744 LLVM_DEBUG(llvm::dbgs() << "Check helper is used: "
745 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu4775ce52017-01-17 13:22:37 +0000746 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
747 D->getCanonicalDecl()))) {
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000748 LLVM_DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
749 << D->getNameAsString() << " (" << D << ")\n");
Haojian Wu36265162017-01-03 09:00:51 +0000750 RemovedDecls.push_back(D);
751 }
752 }
753 }
754
Haojian Wu08e402a2016-12-02 12:39:39 +0000755 for (const auto *RemovedDecl : RemovedDecls) {
756 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
757 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000758 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000759 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000760 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000761 "");
762 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000763 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000764 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000765 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000766 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000767 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000768
769 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000770 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000771 StringRef FilePath = FileAndReplacements.first;
772 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000773 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000774 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000775 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000776 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000777 std::string IncludeNewH =
778 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000779 // This replacment for inserting header will be cleaned up at the end.
780 auto Err = FileAndReplacements.second.add(
781 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
782 if (Err)
783 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000784 }
Haojian Wu253d5962016-10-06 08:29:32 +0000785
Haojian Wu48ac3042016-11-23 10:04:19 +0000786 auto SI = FilePathToFileID.find(FilePath);
787 // Ignore replacements for new.h/cc.
788 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000789 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000790 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
791 if (!Style) {
792 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
793 continue;
794 }
Haojian Wu253d5962016-10-06 08:29:32 +0000795 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000796 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000797
798 if (!CleanReplacements) {
799 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
800 continue;
801 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000802 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000803 }
804}
805
Haojian Wu08e402a2016-12-02 12:39:39 +0000806void ClangMoveTool::moveDeclsToNewFiles() {
807 std::vector<const NamedDecl *> NewHeaderDecls;
808 std::vector<const NamedDecl *> NewCCDecls;
809 for (const auto *MovedDecl : MovedDecls) {
810 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000811 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000812 NewHeaderDecls.push_back(MovedDecl);
813 else
814 NewCCDecls.push_back(MovedDecl);
815 }
816
Haojian Wu36265162017-01-03 09:00:51 +0000817 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
818 std::vector<const NamedDecl *> ActualNewCCDecls;
819
820 // Filter out all unused helpers in NewCCDecls.
821 // We only move the used helpers (including transively used helpers) and the
822 // given symbols being moved.
823 for (const auto *D : NewCCDecls) {
824 if (llvm::is_contained(HelperDeclarations, D) &&
Haojian Wu4775ce52017-01-17 13:22:37 +0000825 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(
826 D->getCanonicalDecl())))
Haojian Wu36265162017-01-03 09:00:51 +0000827 continue;
828
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000829 LLVM_DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
830 << " " << D << "\n");
Haojian Wu36265162017-01-03 09:00:51 +0000831 ActualNewCCDecls.push_back(D);
832 }
833
Haojian Wub15c8da2016-11-24 10:17:17 +0000834 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000835 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000836 Context->Spec.NewDependOnOld
837 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
838 : "";
839 Context->FileToReplacements[Context->Spec.NewHeader] =
840 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
841 Context->Spec.NewHeader, /*IsHeader=*/true,
842 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000843 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000844 if (!Context->Spec.NewCC.empty())
845 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000846 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
847 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000848}
849
Haojian Wu2930be12016-11-08 19:55:13 +0000850// Move all contents from OldFile to NewFile.
851void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
852 StringRef NewFile) {
853 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
854 if (!FE) {
855 llvm::errs() << "Failed to get file: " << OldFile << "\n";
856 return;
857 }
858 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
859 auto Begin = SM.getLocForStartOfFile(ID);
860 auto End = SM.getLocForEndOfFile(ID);
861 clang::tooling::Replacement RemoveAll (
862 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
863 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000864 Context->FileToReplacements[FilePath] =
865 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000866
867 StringRef Code = SM.getBufferData(ID);
868 if (!NewFile.empty()) {
869 auto AllCode = clang::tooling::Replacements(
870 clang::tooling::Replacement(NewFile, 0, 0, Code));
Haojian Wufb68ca12018-01-31 12:12:29 +0000871 auto ReplaceOldInclude = [&](clang::CharSourceRange OldHeaderIncludeRange) {
872 AllCode = AllCode.merge(clang::tooling::Replacements(
873 clang::tooling::Replacement(SM, OldHeaderIncludeRange,
874 '"' + Context->Spec.NewHeader + '"')));
875 };
876 // Fix the case where old.h/old.cc includes "old.h", we replace the
877 // `#include "old.h"` with `#include "new.h"`.
878 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRangeInCC.isValid())
879 ReplaceOldInclude(OldHeaderIncludeRangeInCC);
880 else if (Context->Spec.NewHeader == NewFile &&
881 OldHeaderIncludeRangeInHeader.isValid())
882 ReplaceOldInclude(OldHeaderIncludeRangeInHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000883 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000884 }
885}
886
Haojian Wu357ef992016-09-21 13:18:19 +0000887void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000888 if (Context->DumpDeclarations) {
889 assert(Reporter);
890 for (const auto *Decl : UnremovedDeclsInOldHeader) {
891 auto Kind = Decl->getKind();
892 const std::string QualifiedName = Decl->getQualifiedNameAsString();
Haojian Wu4a920502017-02-27 13:19:13 +0000893 if (Kind == Decl::Kind::Var)
894 Reporter->reportDeclaration(QualifiedName, "Variable");
895 else if (Kind == Decl::Kind::Function ||
896 Kind == Decl::Kind::FunctionTemplate)
Haojian Wub15c8da2016-11-24 10:17:17 +0000897 Reporter->reportDeclaration(QualifiedName, "Function");
898 else if (Kind == Decl::Kind::ClassTemplate ||
899 Kind == Decl::Kind::CXXRecord)
900 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000901 else if (Kind == Decl::Kind::Enum)
902 Reporter->reportDeclaration(QualifiedName, "Enum");
903 else if (Kind == Decl::Kind::Typedef ||
904 Kind == Decl::Kind::TypeAlias ||
905 Kind == Decl::Kind::TypeAliasTemplate)
906 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000907 }
908 return;
909 }
910
Haojian Wu357ef992016-09-21 13:18:19 +0000911 if (RemovedDecls.empty())
912 return;
Haojian Wud4786342018-02-09 15:57:30 +0000913 // Ignore symbols that are not supported when checking if there is unremoved
914 // symbol in old header. This makes sure that we always move old files to new
915 // files when all symbols produced from dump_decls are moved.
Eric Liu47a42d52016-12-06 10:12:23 +0000916 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
917 switch (Decl->getKind()) {
918 case Decl::Kind::Function:
919 case Decl::Kind::FunctionTemplate:
920 case Decl::Kind::ClassTemplate:
921 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000922 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000923 case Decl::Kind::Typedef:
924 case Decl::Kind::TypeAlias:
925 case Decl::Kind::TypeAliasTemplate:
Haojian Wu4a920502017-02-27 13:19:13 +0000926 case Decl::Kind::Var:
Eric Liu47a42d52016-12-06 10:12:23 +0000927 return true;
928 default:
929 return false;
930 }
931 };
932 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
933 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
934 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000935 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000936 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
937 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000938 return;
939 }
Nicola Zaghen0efd5242018-05-15 16:37:45 +0000940 LLVM_DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000941 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000942 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000943}
944
945} // namespace move
946} // namespace clang