blob: e1f20b70009c10326ca54a4909b1b6685ba3a285 [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 Wud69d9072017-01-04 14:50:49 +0000171class TypeAliasMatch : public MatchFinder::MatchCallback {
172public:
173 explicit TypeAliasMatch(ClangMoveTool *MoveTool)
174 : MoveTool(MoveTool) {}
175
176 void run(const MatchFinder::MatchResult &Result) override {
177 if (const auto *TD = Result.Nodes.getNodeAs<clang::TypedefDecl>("typedef"))
178 MoveDeclFromOldFileToNewFile(MoveTool, TD);
179 else if (const auto *TAD =
180 Result.Nodes.getNodeAs<clang::TypeAliasDecl>("type_alias")) {
181 const NamedDecl * D = TAD;
182 if (const auto * TD = TAD->getDescribedAliasTemplate())
183 D = TD;
184 MoveDeclFromOldFileToNewFile(MoveTool, D);
185 }
186 }
187
188private:
189 ClangMoveTool *MoveTool;
190};
191
Haojian Wu32a552f2017-01-03 14:22:25 +0000192class EnumDeclarationMatch : public MatchFinder::MatchCallback {
193public:
194 explicit EnumDeclarationMatch(ClangMoveTool *MoveTool)
195 : MoveTool(MoveTool) {}
196
197 void run(const MatchFinder::MatchResult &Result) override {
198 const auto *ED = Result.Nodes.getNodeAs<clang::EnumDecl>("enum");
199 assert(ED);
200 MoveDeclFromOldFileToNewFile(MoveTool, ED);
Haojian Wu4543fec2016-11-16 13:05:19 +0000201 }
202
203private:
204 ClangMoveTool *MoveTool;
205};
206
Haojian Wu35ca9462016-11-14 14:15:44 +0000207class ClassDeclarationMatch : public MatchFinder::MatchCallback {
208public:
209 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
210 : MoveTool(MoveTool) {}
211 void run(const MatchFinder::MatchResult &Result) override {
212 clang::SourceManager* SM = &Result.Context->getSourceManager();
213 if (const auto *CMD =
214 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
215 MatchClassMethod(CMD, SM);
216 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
217 "class_static_var_decl"))
218 MatchClassStaticVariable(VD, SM);
219 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
220 "moved_class"))
221 MatchClassDeclaration(CD, SM);
222 }
223
224private:
225 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
226 clang::SourceManager* SM) {
227 // Skip inline class methods. isInline() ast matcher doesn't ignore this
228 // case.
229 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000230 MoveTool->getMovedDecls().push_back(CMD);
231 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000232 // Get template class method from its method declaration as
233 // UnremovedDecls stores template class method.
234 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
235 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
236 else
237 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
238 }
239 }
240
241 void MatchClassStaticVariable(const clang::NamedDecl *VD,
242 clang::SourceManager* SM) {
Haojian Wu32a552f2017-01-03 14:22:25 +0000243 MoveDeclFromOldFileToNewFile(MoveTool, VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000244 }
245
246 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
247 clang::SourceManager* SM) {
248 // Get class template from its class declaration as UnremovedDecls stores
249 // class template.
250 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000251 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000252 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000253 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000254 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000255 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000256 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000257 }
258
259 ClangMoveTool *MoveTool;
260};
261
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000262// Expand to get the end location of the line where the EndLoc of the given
263// Decl.
264SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000265getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000266 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000267 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wudc4edba2016-12-13 15:35:47 +0000268 auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
269 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000270 // Try to load the file buffer.
271 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000272 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000273 if (InvalidTemp)
274 return SourceLocation();
275
276 const char *TokBegin = File.data() + LocInfo.second;
277 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000278 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000279 TokBegin, File.end());
280
281 llvm::SmallVector<char, 16> Line;
282 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
283 Lex.setParsingPreprocessorDirective(true);
284 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000285 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000286 // If we already reach EOF, just return the EOF SourceLocation;
287 // otherwise, move 1 offset ahead to include the trailing newline character
288 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000289 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000290 ? EndLoc
291 : EndLoc.getLocWithOffset(1);
292}
293
294// Get full range of a Decl including the comments associated with it.
295clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000296getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000297 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000298 const auto &SM = D->getASTContext().getSourceManager();
299 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
300 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000301 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000302 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000303 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000304 Full.setEnd(Comment->getLocEnd());
305 // FIXME: Don't delete a preceding comment, if there are no other entities
306 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000307 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000308 Full.setBegin(Comment->getLocStart());
309 }
310
311 return clang::CharSourceRange::getCharRange(Full);
312}
313
Haojian Wu08e402a2016-12-02 12:39:39 +0000314std::string getDeclarationSourceText(const clang::Decl *D) {
315 const auto &SM = D->getASTContext().getSourceManager();
316 llvm::StringRef SourceText =
317 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000318 return SourceText.str();
319}
320
Haojian Wu08e402a2016-12-02 12:39:39 +0000321bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000322 llvm::StringRef OriginalRunningDirectory,
323 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000324 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000325 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000326 return false;
327 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
328 if (ExpansionLoc.isInvalid())
329 return false;
330
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000331 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
332 return MakeAbsolutePath(SM, FE->getName()) ==
333 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
334 }
Haojian Wu357ef992016-09-21 13:18:19 +0000335
336 return false;
337}
338
Haojian Wu08e402a2016-12-02 12:39:39 +0000339std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000340 std::vector<std::string> Namespaces;
341 for (const auto *Context = D->getDeclContext(); Context;
342 Context = Context->getParent()) {
343 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
344 llvm::isa<clang::LinkageSpecDecl>(Context))
345 break;
346
347 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
348 Namespaces.push_back(ND->getName().str());
349 }
350 std::reverse(Namespaces.begin(), Namespaces.end());
351 return Namespaces;
352}
353
Haojian Wu357ef992016-09-21 13:18:19 +0000354clang::tooling::Replacements
355createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000356 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000357 llvm::StringRef FileName, bool IsHeader = false,
358 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000359 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000360 std::string GuardName(FileName);
361 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000362 for (size_t i = 0; i < GuardName.size(); ++i) {
363 if (!isAlphanumeric(GuardName[i]))
364 GuardName[i] = '_';
365 }
Haojian Wu220c7552016-10-14 13:01:36 +0000366 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000367 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000368 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000369 }
Haojian Wu357ef992016-09-21 13:18:19 +0000370
Haojian Wu48ac3042016-11-23 10:04:19 +0000371 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000372 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000373 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000374 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000375
Haojian Wu53eab1e2016-10-14 13:43:49 +0000376 if (!Includes.empty())
377 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000378
379 // Add moved class definition and its related declarations. All declarations
380 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000381 //
382 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000383 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000384 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000385 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000386 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000387 auto CurrentIt = CurrentNamespaces.begin();
388 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000389 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000390 while (CurrentIt != CurrentNamespaces.end() &&
391 DeclIt != DeclNamespaces.end()) {
392 if (*CurrentIt != *DeclIt)
393 break;
394 ++CurrentIt;
395 ++DeclIt;
396 }
Haojian Wu53315a72016-11-15 09:06:59 +0000397 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
398 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000399 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
400 CurrentIt);
401 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000402
403
404 // End with CurrentNamespace.
405 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000406 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
407 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
408 --RemainingSize, ++It) {
409 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000410 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000411 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000412 }
Haojian Wu53315a72016-11-15 09:06:59 +0000413 // Add trailing '\n' after the nested namespace definition.
414 if (HasEndCurrentNamespace)
415 NewCode += "\n";
416
417 // If the moved declaration is not in CurrentNamespace, add extra namespace
418 // definitions.
419 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000420 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000421 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000422 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000423 ++DeclIt;
424 }
Haojian Wu53315a72016-11-15 09:06:59 +0000425 // If the moved declaration is in same namespace CurrentNamespace, add
426 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000427 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000428 if (!IsInNewNamespace)
429 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000430 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000431 CurrentNamespaces = std::move(NextNamespaces);
432 }
433 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000434 for (const auto &NS : CurrentNamespaces)
435 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000436
Haojian Wu53eab1e2016-10-14 13:43:49 +0000437 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000438 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000439 return clang::tooling::Replacements(
440 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000441}
442
Haojian Wu36265162017-01-03 09:00:51 +0000443// Return a set of all decls which are used/referenced by the given Decls.
444// Specically, given a class member declaration, this method will return all
445// decls which are used by the whole class.
446llvm::DenseSet<const Decl *>
447getUsedDecls(const HelperDeclRefGraph *RG,
448 const std::vector<const NamedDecl *> &Decls) {
449 assert(RG);
450 llvm::DenseSet<const CallGraphNode *> Nodes;
451 for (const auto *D : Decls) {
452 auto Result = RG->getReachableNodes(
453 HelperDeclRGBuilder::getOutmostClassOrFunDecl(D));
454 Nodes.insert(Result.begin(), Result.end());
455 }
456 llvm::DenseSet<const Decl *> Results;
457 for (const auto *Node : Nodes)
458 Results.insert(Node->getDecl());
459 return Results;
460}
461
Haojian Wu357ef992016-09-21 13:18:19 +0000462} // namespace
463
464std::unique_ptr<clang::ASTConsumer>
465ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
466 StringRef /*InFile*/) {
467 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
468 &Compiler.getSourceManager(), &MoveTool));
469 return MatchFinder.newASTConsumer();
470}
471
Haojian Wub15c8da2016-11-24 10:17:17 +0000472ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
473 DeclarationReporter *const Reporter)
474 : Context(Context), Reporter(Reporter) {
475 if (!Context->Spec.NewHeader.empty())
476 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000477}
478
Haojian Wu08e402a2016-12-02 12:39:39 +0000479void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
480 const auto &SM = Decl->getASTContext().getSourceManager();
481 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000482 StringRef FilePath = SM.getFilename(Loc);
483 FilePathToFileID[FilePath] = SM.getFileID(Loc);
484 RemovedDecls.push_back(Decl);
485}
486
Haojian Wu357ef992016-09-21 13:18:19 +0000487void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000488 auto InOldHeader =
489 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
490 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000491 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000492 auto ForwardDecls =
493 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
Haojian Wu32a552f2017-01-03 14:22:25 +0000494 auto TopLevelDecl =
495 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
Haojian Wu2930be12016-11-08 19:55:13 +0000496
497 //============================================================================
498 // Matchers for old header
499 //============================================================================
500 // Match all top-level named declarations (e.g. function, variable, enum) in
501 // old header, exclude forward class declarations and namespace declarations.
502 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000503 // We consider declarations inside a class belongs to the class. So these
504 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000505 auto AllDeclsInHeader = namedDecl(
506 unless(ForwardDecls), unless(namespaceDecl()),
Haojian Wub15c8da2016-11-24 10:17:17 +0000507 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wu2930be12016-11-08 19:55:13 +0000508 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
509 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000510 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
511 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000512 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000513
514 // Don't register other matchers when dumping all declarations in header.
515 if (Context->DumpDeclarations)
516 return;
517
Haojian Wu2930be12016-11-08 19:55:13 +0000518 // Match forward declarations in old header.
519 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
520 this);
521
522 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000523 // Matchers for old cc
524 //============================================================================
Haojian Wu36265162017-01-03 09:00:51 +0000525 auto IsOldCCTopLevelDecl = allOf(
526 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), InOldCC);
527 // Matching using decls/type alias decls which are in named/anonymous/global
528 // namespace, these decls are always copied to new.h/cc. Those in classes,
529 // functions are covered in other matchers.
Haojian Wub3d98882017-01-17 10:08:11 +0000530 Finder->addMatcher(namedDecl(anyOf(usingDecl(IsOldCCTopLevelDecl),
531 usingDirectiveDecl(IsOldCCTopLevelDecl),
532 typeAliasDecl(IsOldCCTopLevelDecl)),
533 notInMacro())
534 .bind("using_decl"),
535 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000536
Haojian Wu67bb6512016-10-19 14:13:21 +0000537 // Match static functions/variable definitions which are defined in named
538 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000539 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
540 for (StringRef SymbolName : Context->Spec.Names) {
541 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
542 const auto HasName = hasName(("::" + GlobalSymbolName).str());
543 HasAnySymbolNames =
544 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
545 }
546
547 if (!HasAnySymbolNames) {
548 llvm::errs() << "No symbols being moved.\n";
549 return;
550 }
551 auto InMovedClass =
552 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu36265162017-01-03 09:00:51 +0000553
554 // Matchers for helper declarations in old.cc.
555 auto InAnonymousNS = hasParent(namespaceDecl(isAnonymous()));
556 auto DefinitionInOldCC = allOf(isDefinition(), unless(InMovedClass), InOldCC);
557 auto IsOldCCHelperDefinition =
558 allOf(DefinitionInOldCC, anyOf(isStaticStorageClass(), InAnonymousNS));
559 // Match helper classes separately with helper functions/variables since we
560 // want to reuse these matchers in finding helpers usage below.
Haojian Wub3d98882017-01-17 10:08:11 +0000561 auto HelperFuncOrVar =
562 namedDecl(notInMacro(), anyOf(functionDecl(IsOldCCHelperDefinition),
563 varDecl(IsOldCCHelperDefinition)));
564 auto HelperClasses =
565 cxxRecordDecl(notInMacro(), DefinitionInOldCC, InAnonymousNS);
Haojian Wu36265162017-01-03 09:00:51 +0000566 // Save all helper declarations in old.cc.
567 Finder->addMatcher(
568 namedDecl(anyOf(HelperFuncOrVar, HelperClasses)).bind("helper_decls"),
569 this);
570
571 // Construct an AST-based call graph of helper declarations in old.cc.
572 // In the following matcheres, "dc" is a caller while "helper_decls" and
573 // "used_class" is a callee, so a new edge starting from caller to callee will
574 // be add in the graph.
575 //
576 // Find helper function/variable usages.
577 Finder->addMatcher(
578 declRefExpr(to(HelperFuncOrVar), hasAncestor(decl().bind("dc")))
579 .bind("func_ref"),
580 &RGBuilder);
581 // Find helper class usages.
582 Finder->addMatcher(
583 typeLoc(loc(recordType(hasDeclaration(HelperClasses.bind("used_class")))),
584 hasAncestor(decl().bind("dc"))),
585 &RGBuilder);
Haojian Wu35ca9462016-11-14 14:15:44 +0000586
587 //============================================================================
588 // Matchers for old files, including old.h/old.cc
589 //============================================================================
590 // Create a MatchCallback for class declarations.
591 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
592 // Match moved class declarations.
Haojian Wu32a552f2017-01-03 14:22:25 +0000593 auto MovedClass = cxxRecordDecl(InOldFiles, *HasAnySymbolNames,
594 isDefinition(), TopLevelDecl)
595 .bind("moved_class");
Haojian Wu35ca9462016-11-14 14:15:44 +0000596 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
597 // Match moved class methods (static methods included) which are defined
598 // outside moved class declaration.
599 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000600 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000601 isDefinition())
602 .bind("class_method"),
603 MatchCallbacks.back().get());
604 // Match static member variable definition of the moved class.
605 Finder->addMatcher(
606 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
607 .bind("class_static_var_decl"),
608 MatchCallbacks.back().get());
609
Haojian Wu4543fec2016-11-16 13:05:19 +0000610 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
Haojian Wu32a552f2017-01-03 14:22:25 +0000611 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames, TopLevelDecl)
Haojian Wu4543fec2016-11-16 13:05:19 +0000612 .bind("function"),
613 MatchCallbacks.back().get());
Haojian Wu32a552f2017-01-03 14:22:25 +0000614
Haojian Wud69d9072017-01-04 14:50:49 +0000615 // Match enum definition in old.h. Enum helpers (which are defined in old.cc)
Haojian Wu32a552f2017-01-03 14:22:25 +0000616 // will not be moved for now no matter whether they are used or not.
617 MatchCallbacks.push_back(llvm::make_unique<EnumDeclarationMatch>(this));
618 Finder->addMatcher(
619 enumDecl(InOldHeader, *HasAnySymbolNames, isDefinition(), TopLevelDecl)
620 .bind("enum"),
621 MatchCallbacks.back().get());
Haojian Wud69d9072017-01-04 14:50:49 +0000622
623 // Match type alias in old.h, this includes "typedef" and "using" type alias
624 // declarations. Type alias helpers (which are defined in old.cc) will not be
625 // moved for now no matter whether they are used or not.
626 MatchCallbacks.push_back(llvm::make_unique<TypeAliasMatch>(this));
627 Finder->addMatcher(namedDecl(anyOf(typedefDecl().bind("typedef"),
628 typeAliasDecl().bind("type_alias")),
629 InOldHeader, *HasAnySymbolNames, TopLevelDecl),
630 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000631}
632
633void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000634 if (const auto *D =
635 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
636 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000637 } else if (const auto *FWD =
638 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000639 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000640 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000641 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000642 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000643 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000644 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000645 }
Haojian Wu357ef992016-09-21 13:18:19 +0000646 } else if (const auto *ND =
647 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000648 MovedDecls.push_back(ND);
Haojian Wu36265162017-01-03 09:00:51 +0000649 } else if (const auto *ND =
650 Result.Nodes.getNodeAs<clang::NamedDecl>("helper_decls")) {
651 MovedDecls.push_back(ND);
652 HelperDeclarations.push_back(ND);
Haojian Wu67bb6512016-10-19 14:13:21 +0000653 } else if (const auto *UD =
654 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000655 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000656 }
657}
658
Haojian Wu2930be12016-11-08 19:55:13 +0000659std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000660 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000661}
662
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000663void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000664 llvm::StringRef SearchPath,
665 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000666 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000667 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000668 SmallVector<char, 128> HeaderWithSearchPath;
669 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000670 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudb726572016-10-12 15:50:30 +0000671 if (AbsoluteOldHeader ==
672 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000673 HeaderWithSearchPath.size()))) {
674 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000675 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000676 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000677
678 std::string IncludeLine =
679 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
680 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000681
Haojian Wudb726572016-10-12 15:50:30 +0000682 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
683 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000684 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000685 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000686 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000687 }
Haojian Wu357ef992016-09-21 13:18:19 +0000688}
689
Haojian Wu08e402a2016-12-02 12:39:39 +0000690void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000691 if (RemovedDecls.empty()) return;
Haojian Wu36265162017-01-03 09:00:51 +0000692
693 // If old_header is not specified (only move declarations from old.cc), remain
694 // all the helper function declarations in old.cc as UnremovedDeclsInOldHeader
695 // is empty in this case, there is no way to verify unused/used helpers.
696 if (!Context->Spec.OldHeader.empty()) {
697 std::vector<const NamedDecl *> UnremovedDecls;
698 for (const auto *D : UnremovedDeclsInOldHeader)
699 UnremovedDecls.push_back(D);
700
701 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), UnremovedDecls);
702
703 // We remove the helper declarations which are not used in the old.cc after
704 // moving the given declarations.
705 for (const auto *D : HelperDeclarations) {
706 if (!UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D))) {
707 DEBUG(llvm::dbgs() << "Helper removed in old.cc: "
708 << D->getNameAsString() << " " << D << "\n");
709 RemovedDecls.push_back(D);
710 }
711 }
712 }
713
Haojian Wu08e402a2016-12-02 12:39:39 +0000714 for (const auto *RemovedDecl : RemovedDecls) {
715 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
716 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000717 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000718 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000719 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000720 "");
721 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000722 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000723 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000724 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000725 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000726 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000727
728 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000729 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000730 StringRef FilePath = FileAndReplacements.first;
731 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000732 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000733 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000734 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000735 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000736 std::string IncludeNewH =
737 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000738 // This replacment for inserting header will be cleaned up at the end.
739 auto Err = FileAndReplacements.second.add(
740 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
741 if (Err)
742 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000743 }
Haojian Wu253d5962016-10-06 08:29:32 +0000744
Haojian Wu48ac3042016-11-23 10:04:19 +0000745 auto SI = FilePathToFileID.find(FilePath);
746 // Ignore replacements for new.h/cc.
747 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000748 llvm::StringRef Code = SM.getBufferData(SI->second);
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000749 auto Style = format::getStyle("file", FilePath, Context->FallbackStyle);
750 if (!Style) {
751 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
752 continue;
753 }
Haojian Wu253d5962016-10-06 08:29:32 +0000754 auto CleanReplacements = format::cleanupAroundReplacements(
Antonio Maiorano0d7d9c22017-01-17 00:13:32 +0000755 Code, Context->FileToReplacements[FilePath], *Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000756
757 if (!CleanReplacements) {
758 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
759 continue;
760 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000761 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000762 }
763}
764
Haojian Wu08e402a2016-12-02 12:39:39 +0000765void ClangMoveTool::moveDeclsToNewFiles() {
766 std::vector<const NamedDecl *> NewHeaderDecls;
767 std::vector<const NamedDecl *> NewCCDecls;
768 for (const auto *MovedDecl : MovedDecls) {
769 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000770 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000771 NewHeaderDecls.push_back(MovedDecl);
772 else
773 NewCCDecls.push_back(MovedDecl);
774 }
775
Haojian Wu36265162017-01-03 09:00:51 +0000776 auto UsedDecls = getUsedDecls(RGBuilder.getGraph(), RemovedDecls);
777 std::vector<const NamedDecl *> ActualNewCCDecls;
778
779 // Filter out all unused helpers in NewCCDecls.
780 // We only move the used helpers (including transively used helpers) and the
781 // given symbols being moved.
782 for (const auto *D : NewCCDecls) {
783 if (llvm::is_contained(HelperDeclarations, D) &&
784 !UsedDecls.count(HelperDeclRGBuilder::getOutmostClassOrFunDecl(D)))
785 continue;
786
787 DEBUG(llvm::dbgs() << "Helper used in new.cc: " << D->getNameAsString()
788 << " " << D << "\n");
789 ActualNewCCDecls.push_back(D);
790 }
791
Haojian Wub15c8da2016-11-24 10:17:17 +0000792 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000793 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000794 Context->Spec.NewDependOnOld
795 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
796 : "";
797 Context->FileToReplacements[Context->Spec.NewHeader] =
798 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
799 Context->Spec.NewHeader, /*IsHeader=*/true,
800 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000801 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000802 if (!Context->Spec.NewCC.empty())
803 Context->FileToReplacements[Context->Spec.NewCC] =
Haojian Wu36265162017-01-03 09:00:51 +0000804 createInsertedReplacements(CCIncludes, ActualNewCCDecls,
805 Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000806}
807
Haojian Wu2930be12016-11-08 19:55:13 +0000808// Move all contents from OldFile to NewFile.
809void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
810 StringRef NewFile) {
811 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
812 if (!FE) {
813 llvm::errs() << "Failed to get file: " << OldFile << "\n";
814 return;
815 }
816 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
817 auto Begin = SM.getLocForStartOfFile(ID);
818 auto End = SM.getLocForEndOfFile(ID);
819 clang::tooling::Replacement RemoveAll (
820 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
821 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000822 Context->FileToReplacements[FilePath] =
823 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000824
825 StringRef Code = SM.getBufferData(ID);
826 if (!NewFile.empty()) {
827 auto AllCode = clang::tooling::Replacements(
828 clang::tooling::Replacement(NewFile, 0, 0, Code));
829 // If we are moving from old.cc, an extra step is required: excluding
830 // the #include of "old.h", instead, we replace it with #include of "new.h".
Haojian Wub15c8da2016-11-24 10:17:17 +0000831 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
Haojian Wu2930be12016-11-08 19:55:13 +0000832 AllCode = AllCode.merge(
833 clang::tooling::Replacements(clang::tooling::Replacement(
Haojian Wub15c8da2016-11-24 10:17:17 +0000834 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wu2930be12016-11-08 19:55:13 +0000835 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000836 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000837 }
838}
839
Haojian Wu357ef992016-09-21 13:18:19 +0000840void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000841 if (Context->DumpDeclarations) {
842 assert(Reporter);
843 for (const auto *Decl : UnremovedDeclsInOldHeader) {
844 auto Kind = Decl->getKind();
845 const std::string QualifiedName = Decl->getQualifiedNameAsString();
846 if (Kind == Decl::Kind::Function || Kind == Decl::Kind::FunctionTemplate)
847 Reporter->reportDeclaration(QualifiedName, "Function");
848 else if (Kind == Decl::Kind::ClassTemplate ||
849 Kind == Decl::Kind::CXXRecord)
850 Reporter->reportDeclaration(QualifiedName, "Class");
Haojian Wu85867722017-01-16 09:34:07 +0000851 else if (Kind == Decl::Kind::Enum)
852 Reporter->reportDeclaration(QualifiedName, "Enum");
853 else if (Kind == Decl::Kind::Typedef ||
854 Kind == Decl::Kind::TypeAlias ||
855 Kind == Decl::Kind::TypeAliasTemplate)
856 Reporter->reportDeclaration(QualifiedName, "TypeAlias");
Haojian Wub15c8da2016-11-24 10:17:17 +0000857 }
858 return;
859 }
860
Haojian Wu357ef992016-09-21 13:18:19 +0000861 if (RemovedDecls.empty())
862 return;
Eric Liu47a42d52016-12-06 10:12:23 +0000863 // Ignore symbols that are not supported (e.g. typedef and enum) when
864 // checking if there is unremoved symbol in old header. This makes sure that
865 // we always move old files to new files when all symbols produced from
866 // dump_decls are moved.
867 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
868 switch (Decl->getKind()) {
869 case Decl::Kind::Function:
870 case Decl::Kind::FunctionTemplate:
871 case Decl::Kind::ClassTemplate:
872 case Decl::Kind::CXXRecord:
Haojian Wu32a552f2017-01-03 14:22:25 +0000873 case Decl::Kind::Enum:
Haojian Wud69d9072017-01-04 14:50:49 +0000874 case Decl::Kind::Typedef:
875 case Decl::Kind::TypeAlias:
876 case Decl::Kind::TypeAliasTemplate:
Eric Liu47a42d52016-12-06 10:12:23 +0000877 return true;
878 default:
879 return false;
880 }
881 };
882 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
883 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
884 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000885 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000886 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
887 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000888 return;
889 }
Haojian Wu36265162017-01-03 09:00:51 +0000890 DEBUG(RGBuilder.getGraph()->dump());
Haojian Wu08e402a2016-12-02 12:39:39 +0000891 moveDeclsToNewFiles();
Haojian Wu36265162017-01-03 09:00:51 +0000892 removeDeclsInOldFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000893}
894
895} // namespace move
896} // namespace clang