blob: 9219c7ff4a80d7f691a2d79179be915af12595c4 [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"
11#include "clang/ASTMatchers/ASTMatchers.h"
12#include "clang/Basic/SourceManager.h"
13#include "clang/Format/Format.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/Lexer.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Rewrite/Core/Rewriter.h"
18#include "clang/Tooling/Core/Replacement.h"
Haojian Wud2a6d7b2016-10-04 09:05:31 +000019#include "llvm/Support/Path.h"
Haojian Wu357ef992016-09-21 13:18:19 +000020
21using namespace clang::ast_matchers;
22
23namespace clang {
24namespace move {
25namespace {
26
Haojian Wu7bd492c2016-10-14 10:07:58 +000027// FIXME: Move to ASTMatchers.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000028AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); }
Haojian Wu7bd492c2016-10-14 10:07:58 +000029
Haojian Wue77bcc72016-10-13 10:31:00 +000030AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
31 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000032 const auto *Context = Node.getDeclContext();
33 if (!Context)
34 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000035 while (const auto *NextContext = Context->getParent()) {
36 if (isa<NamespaceDecl>(NextContext) ||
37 isa<TranslationUnitDecl>(NextContext))
38 break;
39 Context = NextContext;
40 }
41 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
42 Builder);
43}
44
45AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
46 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
47 const CXXRecordDecl *Parent = Node.getParent();
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000048 if (!Parent)
49 return false;
Haojian Wue77bcc72016-10-13 10:31:00 +000050 while (const auto *NextParent =
51 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
52 Parent = NextParent;
53 }
54
55 return InnerMatcher.matches(*Parent, Finder, Builder);
56}
57
Haojian Wud2a6d7b2016-10-04 09:05:31 +000058// Make the Path absolute using the CurrentDir if the Path is not an absolute
59// path. An empty Path will result in an empty string.
60std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
61 if (Path.empty())
62 return "";
63 llvm::SmallString<128> InitialDirectory(CurrentDir);
64 llvm::SmallString<128> AbsolutePath(Path);
65 if (std::error_code EC =
66 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000067 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000068 << '\n';
69 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wuc6f125e2016-10-04 09:49:20 +000070 llvm::sys::path::native(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +000071 return AbsolutePath.str();
72}
73
74// Make the Path absolute using the current working directory of the given
75// SourceManager if the Path is not an absolute path.
76//
77// The Path can be a path relative to the build directory, or retrieved from
78// the SourceManager.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000079std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +000080 llvm::SmallString<128> AbsolutePath(Path);
81 if (std::error_code EC =
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000082 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
83 AbsolutePath))
84 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
Haojian Wud2a6d7b2016-10-04 09:05:31 +000085 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000086 // Handle symbolic link path cases.
87 // We are trying to get the real file path of the symlink.
88 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000089 llvm::sys::path::parent_path(AbsolutePath.str()));
Haojian Wudb726572016-10-12 15:50:30 +000090 if (Dir) {
91 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
92 SmallVector<char, 128> AbsoluteFilename;
93 llvm::sys::path::append(AbsoluteFilename, DirName,
94 llvm::sys::path::filename(AbsolutePath.str()));
95 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
96 .str();
97 }
Haojian Wud2a6d7b2016-10-04 09:05:31 +000098 return AbsolutePath.str();
99}
100
101// Matches AST nodes that are expanded within the given AbsoluteFilePath.
102AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
103 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
104 std::string, AbsoluteFilePath) {
105 auto &SourceManager = Finder->getASTContext().getSourceManager();
106 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
107 if (ExpansionLoc.isInvalid())
108 return false;
109 auto FileEntry =
110 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
111 if (!FileEntry)
112 return false;
113 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
114 AbsoluteFilePath;
115}
116
Haojian Wu357ef992016-09-21 13:18:19 +0000117class FindAllIncludes : public clang::PPCallbacks {
118public:
119 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
120 : SM(*SM), MoveTool(MoveTool) {}
121
122 void InclusionDirective(clang::SourceLocation HashLoc,
123 const clang::Token & /*IncludeTok*/,
124 StringRef FileName, bool IsAngled,
Haojian Wu2930be12016-11-08 19:55:13 +0000125 clang::CharSourceRange FilenameRange,
Haojian Wu357ef992016-09-21 13:18:19 +0000126 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000127 StringRef SearchPath, StringRef /*RelativePath*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000128 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000129 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000130 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
Haojian Wu2930be12016-11-08 19:55:13 +0000131 FileEntry->getName(), FilenameRange, SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000132 }
133
134private:
135 const SourceManager &SM;
136 ClangMoveTool *const MoveTool;
137};
138
Haojian Wu4543fec2016-11-16 13:05:19 +0000139class FunctionDeclarationMatch : public MatchFinder::MatchCallback {
140public:
141 explicit FunctionDeclarationMatch(ClangMoveTool *MoveTool)
142 : MoveTool(MoveTool) {}
143
144 void run(const MatchFinder::MatchResult &Result) override {
145 const auto *FD = Result.Nodes.getNodeAs<clang::FunctionDecl>("function");
146 assert(FD);
147 const clang::NamedDecl *D = FD;
148 if (const auto *FTD = FD->getDescribedFunctionTemplate())
149 D = FTD;
Haojian Wu08e402a2016-12-02 12:39:39 +0000150 MoveTool->getMovedDecls().push_back(D);
Haojian Wu4543fec2016-11-16 13:05:19 +0000151 MoveTool->getUnremovedDeclsInOldHeader().erase(D);
Haojian Wu08e402a2016-12-02 12:39:39 +0000152 MoveTool->addRemovedDecl(D);
Haojian Wu4543fec2016-11-16 13:05:19 +0000153 }
154
155private:
156 ClangMoveTool *MoveTool;
157};
158
Haojian Wu35ca9462016-11-14 14:15:44 +0000159class ClassDeclarationMatch : public MatchFinder::MatchCallback {
160public:
161 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
162 : MoveTool(MoveTool) {}
163 void run(const MatchFinder::MatchResult &Result) override {
164 clang::SourceManager* SM = &Result.Context->getSourceManager();
165 if (const auto *CMD =
166 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
167 MatchClassMethod(CMD, SM);
168 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
169 "class_static_var_decl"))
170 MatchClassStaticVariable(VD, SM);
171 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
172 "moved_class"))
173 MatchClassDeclaration(CD, SM);
174 }
175
176private:
177 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
178 clang::SourceManager* SM) {
179 // Skip inline class methods. isInline() ast matcher doesn't ignore this
180 // case.
181 if (!CMD->isInlined()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000182 MoveTool->getMovedDecls().push_back(CMD);
183 MoveTool->addRemovedDecl(CMD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000184 // Get template class method from its method declaration as
185 // UnremovedDecls stores template class method.
186 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
187 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
188 else
189 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
190 }
191 }
192
193 void MatchClassStaticVariable(const clang::NamedDecl *VD,
194 clang::SourceManager* SM) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000195 MoveTool->getMovedDecls().push_back(VD);
196 MoveTool->addRemovedDecl(VD);
Haojian Wu35ca9462016-11-14 14:15:44 +0000197 MoveTool->getUnremovedDeclsInOldHeader().erase(VD);
198 }
199
200 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
201 clang::SourceManager* SM) {
202 // Get class template from its class declaration as UnremovedDecls stores
203 // class template.
204 if (const auto *TC = CD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000205 MoveTool->getMovedDecls().push_back(TC);
Haojian Wu35ca9462016-11-14 14:15:44 +0000206 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000207 MoveTool->getMovedDecls().push_back(CD);
Haojian Wu48ac3042016-11-23 10:04:19 +0000208 MoveTool->addRemovedDecl(MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000209 MoveTool->getUnremovedDeclsInOldHeader().erase(
Haojian Wu08e402a2016-12-02 12:39:39 +0000210 MoveTool->getMovedDecls().back());
Haojian Wu35ca9462016-11-14 14:15:44 +0000211 }
212
213 ClangMoveTool *MoveTool;
214};
215
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000216// Expand to get the end location of the line where the EndLoc of the given
217// Decl.
218SourceLocation
Haojian Wu08e402a2016-12-02 12:39:39 +0000219getLocForEndOfDecl(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000220 const LangOptions &LangOpts = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000221 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wudc4edba2016-12-13 15:35:47 +0000222 auto EndExpansionLoc = SM.getExpansionLoc(D->getLocEnd());
223 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(EndExpansionLoc);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000224 // Try to load the file buffer.
225 bool InvalidTemp = false;
Haojian Wu08e402a2016-12-02 12:39:39 +0000226 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000227 if (InvalidTemp)
228 return SourceLocation();
229
230 const char *TokBegin = File.data() + LocInfo.second;
231 // Lex from the start of the given location.
Haojian Wu08e402a2016-12-02 12:39:39 +0000232 Lexer Lex(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000233 TokBegin, File.end());
234
235 llvm::SmallVector<char, 16> Line;
236 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
237 Lex.setParsingPreprocessorDirective(true);
238 Lex.ReadToEndOfLine(&Line);
Haojian Wudc4edba2016-12-13 15:35:47 +0000239 SourceLocation EndLoc = EndExpansionLoc.getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000240 // If we already reach EOF, just return the EOF SourceLocation;
241 // otherwise, move 1 offset ahead to include the trailing newline character
242 // '\n'.
Haojian Wu08e402a2016-12-02 12:39:39 +0000243 return SM.getLocForEndOfFile(LocInfo.first) == EndLoc
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000244 ? EndLoc
245 : EndLoc.getLocWithOffset(1);
246}
247
248// Get full range of a Decl including the comments associated with it.
249clang::CharSourceRange
Haojian Wu08e402a2016-12-02 12:39:39 +0000250getFullRange(const clang::Decl *D,
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000251 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000252 const auto &SM = D->getASTContext().getSourceManager();
253 clang::SourceRange Full(SM.getExpansionLoc(D->getLocStart()),
254 getLocForEndOfDecl(D));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000255 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000256 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000257 if (SM.isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000258 Full.setEnd(Comment->getLocEnd());
259 // FIXME: Don't delete a preceding comment, if there are no other entities
260 // it could refer to.
Haojian Wu08e402a2016-12-02 12:39:39 +0000261 if (SM.isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000262 Full.setBegin(Comment->getLocStart());
263 }
264
265 return clang::CharSourceRange::getCharRange(Full);
266}
267
Haojian Wu08e402a2016-12-02 12:39:39 +0000268std::string getDeclarationSourceText(const clang::Decl *D) {
269 const auto &SM = D->getASTContext().getSourceManager();
270 llvm::StringRef SourceText =
271 clang::Lexer::getSourceText(getFullRange(D), SM, clang::LangOptions());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000272 return SourceText.str();
273}
274
Haojian Wu08e402a2016-12-02 12:39:39 +0000275bool isInHeaderFile(const clang::Decl *D,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000276 llvm::StringRef OriginalRunningDirectory,
277 llvm::StringRef OldHeader) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000278 const auto &SM = D->getASTContext().getSourceManager();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000279 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000280 return false;
281 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
282 if (ExpansionLoc.isInvalid())
283 return false;
284
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000285 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
286 return MakeAbsolutePath(SM, FE->getName()) ==
287 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
288 }
Haojian Wu357ef992016-09-21 13:18:19 +0000289
290 return false;
291}
292
Haojian Wu08e402a2016-12-02 12:39:39 +0000293std::vector<std::string> getNamespaces(const clang::Decl *D) {
Haojian Wu357ef992016-09-21 13:18:19 +0000294 std::vector<std::string> Namespaces;
295 for (const auto *Context = D->getDeclContext(); Context;
296 Context = Context->getParent()) {
297 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
298 llvm::isa<clang::LinkageSpecDecl>(Context))
299 break;
300
301 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
302 Namespaces.push_back(ND->getName().str());
303 }
304 std::reverse(Namespaces.begin(), Namespaces.end());
305 return Namespaces;
306}
307
Haojian Wu357ef992016-09-21 13:18:19 +0000308clang::tooling::Replacements
309createInsertedReplacements(const std::vector<std::string> &Includes,
Haojian Wu08e402a2016-12-02 12:39:39 +0000310 const std::vector<const NamedDecl *> &Decls,
Haojian Wu48ac3042016-11-23 10:04:19 +0000311 llvm::StringRef FileName, bool IsHeader = false,
312 StringRef OldHeaderInclude = "") {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000313 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000314 std::string GuardName(FileName);
315 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000316 for (size_t i = 0; i < GuardName.size(); ++i) {
317 if (!isAlphanumeric(GuardName[i]))
318 GuardName[i] = '_';
319 }
Haojian Wu220c7552016-10-14 13:01:36 +0000320 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000321 NewCode += "#ifndef " + GuardName + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000322 NewCode += "#define " + GuardName + "\n\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000323 }
Haojian Wu357ef992016-09-21 13:18:19 +0000324
Haojian Wu48ac3042016-11-23 10:04:19 +0000325 NewCode += OldHeaderInclude;
Haojian Wu357ef992016-09-21 13:18:19 +0000326 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000327 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000328 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000329
Haojian Wu53eab1e2016-10-14 13:43:49 +0000330 if (!Includes.empty())
331 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000332
333 // Add moved class definition and its related declarations. All declarations
334 // in same namespace are grouped together.
Haojian Wu53315a72016-11-15 09:06:59 +0000335 //
336 // Record namespaces where the current position is in.
Haojian Wu357ef992016-09-21 13:18:19 +0000337 std::vector<std::string> CurrentNamespaces;
Haojian Wu08e402a2016-12-02 12:39:39 +0000338 for (const auto *MovedDecl : Decls) {
Haojian Wu53315a72016-11-15 09:06:59 +0000339 // The namespaces of the declaration being moved.
Haojian Wu08e402a2016-12-02 12:39:39 +0000340 std::vector<std::string> DeclNamespaces = getNamespaces(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000341 auto CurrentIt = CurrentNamespaces.begin();
342 auto DeclIt = DeclNamespaces.begin();
Haojian Wu53315a72016-11-15 09:06:59 +0000343 // Skip the common prefix.
Haojian Wu357ef992016-09-21 13:18:19 +0000344 while (CurrentIt != CurrentNamespaces.end() &&
345 DeclIt != DeclNamespaces.end()) {
346 if (*CurrentIt != *DeclIt)
347 break;
348 ++CurrentIt;
349 ++DeclIt;
350 }
Haojian Wu53315a72016-11-15 09:06:59 +0000351 // Calculate the new namespaces after adding MovedDecl in CurrentNamespace,
352 // which is used for next iteration of this loop.
Haojian Wu357ef992016-09-21 13:18:19 +0000353 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
354 CurrentIt);
355 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
Haojian Wu53315a72016-11-15 09:06:59 +0000356
357
358 // End with CurrentNamespace.
359 bool HasEndCurrentNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000360 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
361 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
362 --RemainingSize, ++It) {
363 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000364 NewCode += "} // namespace " + *It + "\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000365 HasEndCurrentNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000366 }
Haojian Wu53315a72016-11-15 09:06:59 +0000367 // Add trailing '\n' after the nested namespace definition.
368 if (HasEndCurrentNamespace)
369 NewCode += "\n";
370
371 // If the moved declaration is not in CurrentNamespace, add extra namespace
372 // definitions.
373 bool IsInNewNamespace = false;
Haojian Wu357ef992016-09-21 13:18:19 +0000374 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000375 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu53315a72016-11-15 09:06:59 +0000376 IsInNewNamespace = true;
Haojian Wu357ef992016-09-21 13:18:19 +0000377 ++DeclIt;
378 }
Haojian Wu53315a72016-11-15 09:06:59 +0000379 // If the moved declaration is in same namespace CurrentNamespace, add
380 // a preceeding `\n' before the moved declaration.
Haojian Wu50a45d92016-11-18 10:51:16 +0000381 // FIXME: Don't add empty lines between using declarations.
Haojian Wu53315a72016-11-15 09:06:59 +0000382 if (!IsInNewNamespace)
383 NewCode += "\n";
Haojian Wu08e402a2016-12-02 12:39:39 +0000384 NewCode += getDeclarationSourceText(MovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000385 CurrentNamespaces = std::move(NextNamespaces);
386 }
387 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000388 for (const auto &NS : CurrentNamespaces)
389 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000390
Haojian Wu53eab1e2016-10-14 13:43:49 +0000391 if (IsHeader)
Haojian Wu53315a72016-11-15 09:06:59 +0000392 NewCode += "\n#endif // " + GuardName + "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000393 return clang::tooling::Replacements(
394 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000395}
396
397} // namespace
398
399std::unique_ptr<clang::ASTConsumer>
400ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
401 StringRef /*InFile*/) {
402 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
403 &Compiler.getSourceManager(), &MoveTool));
404 return MatchFinder.newASTConsumer();
405}
406
Haojian Wub15c8da2016-11-24 10:17:17 +0000407ClangMoveTool::ClangMoveTool(ClangMoveContext *const Context,
408 DeclarationReporter *const Reporter)
409 : Context(Context), Reporter(Reporter) {
410 if (!Context->Spec.NewHeader.empty())
411 CCIncludes.push_back("#include \"" + Context->Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000412}
413
Haojian Wu08e402a2016-12-02 12:39:39 +0000414void ClangMoveTool::addRemovedDecl(const NamedDecl *Decl) {
415 const auto &SM = Decl->getASTContext().getSourceManager();
416 auto Loc = Decl->getLocation();
Haojian Wu48ac3042016-11-23 10:04:19 +0000417 StringRef FilePath = SM.getFilename(Loc);
418 FilePathToFileID[FilePath] = SM.getFileID(Loc);
419 RemovedDecls.push_back(Decl);
420}
421
Haojian Wu357ef992016-09-21 13:18:19 +0000422void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000423 auto InOldHeader =
424 isExpansionInFile(makeAbsolutePath(Context->Spec.OldHeader));
425 auto InOldCC = isExpansionInFile(makeAbsolutePath(Context->Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000426 auto InOldFiles = anyOf(InOldHeader, InOldCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000427 auto ForwardDecls =
428 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
429
430 //============================================================================
431 // Matchers for old header
432 //============================================================================
433 // Match all top-level named declarations (e.g. function, variable, enum) in
434 // old header, exclude forward class declarations and namespace declarations.
435 //
Haojian Wub15c8da2016-11-24 10:17:17 +0000436 // We consider declarations inside a class belongs to the class. So these
437 // declarations will be ignored.
Haojian Wu2930be12016-11-08 19:55:13 +0000438 auto AllDeclsInHeader = namedDecl(
439 unless(ForwardDecls), unless(namespaceDecl()),
Haojian Wub15c8da2016-11-24 10:17:17 +0000440 unless(usingDirectiveDecl()), // using namespace decl.
Haojian Wu2930be12016-11-08 19:55:13 +0000441 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
442 InOldHeader,
Haojian Wub15c8da2016-11-24 10:17:17 +0000443 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))),
444 hasDeclContext(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
Haojian Wu2930be12016-11-08 19:55:13 +0000445 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
Haojian Wub15c8da2016-11-24 10:17:17 +0000446
447 // Don't register other matchers when dumping all declarations in header.
448 if (Context->DumpDeclarations)
449 return;
450
Haojian Wu2930be12016-11-08 19:55:13 +0000451 // Match forward declarations in old header.
452 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
453 this);
454
455 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000456 // Matchers for old cc
457 //============================================================================
Haojian Wu50a45d92016-11-18 10:51:16 +0000458 auto InOldCCNamedOrGlobalNamespace =
459 allOf(hasParent(decl(anyOf(namespaceDecl(unless(isAnonymous())),
460 translationUnitDecl()))),
461 InOldCC);
462 // Matching using decls/type alias decls which are in named namespace or
463 // global namespace. Those in classes, functions and anonymous namespaces are
464 // covered in other matchers.
Haojian Wu357ef992016-09-21 13:18:19 +0000465 Finder->addMatcher(
Haojian Wu50a45d92016-11-18 10:51:16 +0000466 namedDecl(anyOf(usingDecl(InOldCCNamedOrGlobalNamespace),
467 usingDirectiveDecl(InOldCCNamedOrGlobalNamespace),
468 typeAliasDecl( InOldCCNamedOrGlobalNamespace)))
Haojian Wu67bb6512016-10-19 14:13:21 +0000469 .bind("using_decl"),
Haojian Wu357ef992016-09-21 13:18:19 +0000470 this);
471
Haojian Wu67bb6512016-10-19 14:13:21 +0000472 // Match anonymous namespace decl in old cc.
473 Finder->addMatcher(namespaceDecl(isAnonymous(), InOldCC).bind("anonymous_ns"),
474 this);
475
476 // Match static functions/variable definitions which are defined in named
477 // namespaces.
Haojian Wub15c8da2016-11-24 10:17:17 +0000478 Optional<ast_matchers::internal::Matcher<NamedDecl>> HasAnySymbolNames;
479 for (StringRef SymbolName : Context->Spec.Names) {
480 llvm::StringRef GlobalSymbolName = SymbolName.trim().ltrim(':');
481 const auto HasName = hasName(("::" + GlobalSymbolName).str());
482 HasAnySymbolNames =
483 HasAnySymbolNames ? anyOf(*HasAnySymbolNames, HasName) : HasName;
484 }
485
486 if (!HasAnySymbolNames) {
487 llvm::errs() << "No symbols being moved.\n";
488 return;
489 }
490 auto InMovedClass =
491 hasOutermostEnclosingClass(cxxRecordDecl(*HasAnySymbolNames));
Haojian Wu67bb6512016-10-19 14:13:21 +0000492 auto IsOldCCStaticDefinition =
Haojian Wu50a45d92016-11-18 10:51:16 +0000493 allOf(isDefinition(), unless(InMovedClass), InOldCCNamedOrGlobalNamespace,
Haojian Wu67bb6512016-10-19 14:13:21 +0000494 isStaticStorageClass());
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000495 Finder->addMatcher(namedDecl(anyOf(functionDecl(IsOldCCStaticDefinition),
496 varDecl(IsOldCCStaticDefinition)))
497 .bind("static_decls"),
498 this);
Haojian Wu35ca9462016-11-14 14:15:44 +0000499
500 //============================================================================
501 // Matchers for old files, including old.h/old.cc
502 //============================================================================
503 // Create a MatchCallback for class declarations.
504 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
505 // Match moved class declarations.
506 auto MovedClass =
507 cxxRecordDecl(
Haojian Wu4543fec2016-11-16 13:05:19 +0000508 InOldFiles, *HasAnySymbolNames, isDefinition(),
Haojian Wu35ca9462016-11-14 14:15:44 +0000509 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())))
510 .bind("moved_class");
511 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
512 // Match moved class methods (static methods included) which are defined
513 // outside moved class declaration.
514 Finder->addMatcher(
Haojian Wu4543fec2016-11-16 13:05:19 +0000515 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*HasAnySymbolNames),
Haojian Wu35ca9462016-11-14 14:15:44 +0000516 isDefinition())
517 .bind("class_method"),
518 MatchCallbacks.back().get());
519 // Match static member variable definition of the moved class.
520 Finder->addMatcher(
521 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
522 .bind("class_static_var_decl"),
523 MatchCallbacks.back().get());
524
Haojian Wu4543fec2016-11-16 13:05:19 +0000525 MatchCallbacks.push_back(llvm::make_unique<FunctionDeclarationMatch>(this));
526 Finder->addMatcher(functionDecl(InOldFiles, *HasAnySymbolNames,
527 anyOf(hasDeclContext(namespaceDecl()),
528 hasDeclContext(translationUnitDecl())))
529 .bind("function"),
530 MatchCallbacks.back().get());
Haojian Wu357ef992016-09-21 13:18:19 +0000531}
532
533void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000534 if (const auto *D =
535 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
536 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000537 } else if (const auto *FWD =
538 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000539 // Skip all forward declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000540 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000541 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu08e402a2016-12-02 12:39:39 +0000542 MovedDecls.push_back(DCT);
Haojian Wub53ec462016-11-10 05:33:26 +0000543 else
Haojian Wu08e402a2016-12-02 12:39:39 +0000544 MovedDecls.push_back(FWD);
Haojian Wu29c38f72016-10-21 19:26:43 +0000545 }
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000546 } else if (const auto *ANS =
547 Result.Nodes.getNodeAs<clang::NamespaceDecl>("anonymous_ns")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000548 MovedDecls.push_back(ANS);
Haojian Wu357ef992016-09-21 13:18:19 +0000549 } else if (const auto *ND =
550 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000551 MovedDecls.push_back(ND);
Haojian Wu67bb6512016-10-19 14:13:21 +0000552 } else if (const auto *UD =
553 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000554 MovedDecls.push_back(UD);
Haojian Wu357ef992016-09-21 13:18:19 +0000555 }
556}
557
Haojian Wu2930be12016-11-08 19:55:13 +0000558std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
Haojian Wub15c8da2016-11-24 10:17:17 +0000559 return MakeAbsolutePath(Context->OriginalRunningDirectory, Path);
Haojian Wu2930be12016-11-08 19:55:13 +0000560}
561
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000562void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000563 llvm::StringRef SearchPath,
564 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000565 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000566 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000567 SmallVector<char, 128> HeaderWithSearchPath;
568 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wub15c8da2016-11-24 10:17:17 +0000569 std::string AbsoluteOldHeader = makeAbsolutePath(Context->Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000570 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
571 // old.h/c. For instance, when moved class uses another class defined in
572 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000573 if (AbsoluteOldHeader ==
574 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000575 HeaderWithSearchPath.size()))) {
576 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000577 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000578 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000579
580 std::string IncludeLine =
581 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
582 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000583
Haojian Wudb726572016-10-12 15:50:30 +0000584 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
585 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000586 HeaderIncludes.push_back(IncludeLine);
Haojian Wub15c8da2016-11-24 10:17:17 +0000587 } else if (makeAbsolutePath(Context->Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000588 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000589 }
Haojian Wu357ef992016-09-21 13:18:19 +0000590}
591
Haojian Wu08e402a2016-12-02 12:39:39 +0000592void ClangMoveTool::removeDeclsInOldFiles() {
Haojian Wu48ac3042016-11-23 10:04:19 +0000593 if (RemovedDecls.empty()) return;
Haojian Wu08e402a2016-12-02 12:39:39 +0000594 for (const auto *RemovedDecl : RemovedDecls) {
595 const auto &SM = RemovedDecl->getASTContext().getSourceManager();
596 auto Range = getFullRange(RemovedDecl);
Haojian Wu357ef992016-09-21 13:18:19 +0000597 clang::tooling::Replacement RemoveReplacement(
Haojian Wu48ac3042016-11-23 10:04:19 +0000598 SM,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000599 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000600 "");
601 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000602 auto Err = Context->FileToReplacements[FilePath].add(RemoveReplacement);
Haojian Wu48ac3042016-11-23 10:04:19 +0000603 if (Err)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000604 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000605 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000606 const auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wu48ac3042016-11-23 10:04:19 +0000607
608 // Post process of cleanup around all the replacements.
Haojian Wub15c8da2016-11-24 10:17:17 +0000609 for (auto &FileAndReplacements : Context->FileToReplacements) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000610 StringRef FilePath = FileAndReplacements.first;
611 // Add #include of new header to old header.
Haojian Wub15c8da2016-11-24 10:17:17 +0000612 if (Context->Spec.OldDependOnNew &&
Haojian Wu08e402a2016-12-02 12:39:39 +0000613 MakeAbsolutePath(SM, FilePath) ==
Haojian Wub15c8da2016-11-24 10:17:17 +0000614 makeAbsolutePath(Context->Spec.OldHeader)) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000615 // FIXME: Minimize the include path like include-fixer.
Haojian Wub15c8da2016-11-24 10:17:17 +0000616 std::string IncludeNewH =
617 "#include \"" + Context->Spec.NewHeader + "\"\n";
Haojian Wu48ac3042016-11-23 10:04:19 +0000618 // This replacment for inserting header will be cleaned up at the end.
619 auto Err = FileAndReplacements.second.add(
620 tooling::Replacement(FilePath, UINT_MAX, 0, IncludeNewH));
621 if (Err)
622 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
Haojian Wu53eab1e2016-10-14 13:43:49 +0000623 }
Haojian Wu253d5962016-10-06 08:29:32 +0000624
Haojian Wu48ac3042016-11-23 10:04:19 +0000625 auto SI = FilePathToFileID.find(FilePath);
626 // Ignore replacements for new.h/cc.
627 if (SI == FilePathToFileID.end()) continue;
Haojian Wu08e402a2016-12-02 12:39:39 +0000628 llvm::StringRef Code = SM.getBufferData(SI->second);
Haojian Wu253d5962016-10-06 08:29:32 +0000629 format::FormatStyle Style =
Haojian Wub15c8da2016-11-24 10:17:17 +0000630 format::getStyle("file", FilePath, Context->FallbackStyle);
Haojian Wu253d5962016-10-06 08:29:32 +0000631 auto CleanReplacements = format::cleanupAroundReplacements(
Haojian Wub15c8da2016-11-24 10:17:17 +0000632 Code, Context->FileToReplacements[FilePath], Style);
Haojian Wu253d5962016-10-06 08:29:32 +0000633
634 if (!CleanReplacements) {
635 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
636 continue;
637 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000638 Context->FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000639 }
640}
641
Haojian Wu08e402a2016-12-02 12:39:39 +0000642void ClangMoveTool::moveDeclsToNewFiles() {
643 std::vector<const NamedDecl *> NewHeaderDecls;
644 std::vector<const NamedDecl *> NewCCDecls;
645 for (const auto *MovedDecl : MovedDecls) {
646 if (isInHeaderFile(MovedDecl, Context->OriginalRunningDirectory,
Haojian Wub15c8da2016-11-24 10:17:17 +0000647 Context->Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000648 NewHeaderDecls.push_back(MovedDecl);
649 else
650 NewCCDecls.push_back(MovedDecl);
651 }
652
Haojian Wub15c8da2016-11-24 10:17:17 +0000653 if (!Context->Spec.NewHeader.empty()) {
Haojian Wu48ac3042016-11-23 10:04:19 +0000654 std::string OldHeaderInclude =
Haojian Wub15c8da2016-11-24 10:17:17 +0000655 Context->Spec.NewDependOnOld
656 ? "#include \"" + Context->Spec.OldHeader + "\"\n"
657 : "";
658 Context->FileToReplacements[Context->Spec.NewHeader] =
659 createInsertedReplacements(HeaderIncludes, NewHeaderDecls,
660 Context->Spec.NewHeader, /*IsHeader=*/true,
661 OldHeaderInclude);
Haojian Wu48ac3042016-11-23 10:04:19 +0000662 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000663 if (!Context->Spec.NewCC.empty())
664 Context->FileToReplacements[Context->Spec.NewCC] =
665 createInsertedReplacements(CCIncludes, NewCCDecls, Context->Spec.NewCC);
Haojian Wu357ef992016-09-21 13:18:19 +0000666}
667
Haojian Wu2930be12016-11-08 19:55:13 +0000668// Move all contents from OldFile to NewFile.
669void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
670 StringRef NewFile) {
671 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
672 if (!FE) {
673 llvm::errs() << "Failed to get file: " << OldFile << "\n";
674 return;
675 }
676 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
677 auto Begin = SM.getLocForStartOfFile(ID);
678 auto End = SM.getLocForEndOfFile(ID);
679 clang::tooling::Replacement RemoveAll (
680 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
681 std::string FilePath = RemoveAll.getFilePath().str();
Haojian Wub15c8da2016-11-24 10:17:17 +0000682 Context->FileToReplacements[FilePath] =
683 clang::tooling::Replacements(RemoveAll);
Haojian Wu2930be12016-11-08 19:55:13 +0000684
685 StringRef Code = SM.getBufferData(ID);
686 if (!NewFile.empty()) {
687 auto AllCode = clang::tooling::Replacements(
688 clang::tooling::Replacement(NewFile, 0, 0, Code));
689 // If we are moving from old.cc, an extra step is required: excluding
690 // the #include of "old.h", instead, we replace it with #include of "new.h".
Haojian Wub15c8da2016-11-24 10:17:17 +0000691 if (Context->Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
Haojian Wu2930be12016-11-08 19:55:13 +0000692 AllCode = AllCode.merge(
693 clang::tooling::Replacements(clang::tooling::Replacement(
Haojian Wub15c8da2016-11-24 10:17:17 +0000694 SM, OldHeaderIncludeRange, '"' + Context->Spec.NewHeader + '"')));
Haojian Wu2930be12016-11-08 19:55:13 +0000695 }
Haojian Wub15c8da2016-11-24 10:17:17 +0000696 Context->FileToReplacements[NewFile] = std::move(AllCode);
Haojian Wu2930be12016-11-08 19:55:13 +0000697 }
698}
699
Haojian Wu357ef992016-09-21 13:18:19 +0000700void ClangMoveTool::onEndOfTranslationUnit() {
Haojian Wub15c8da2016-11-24 10:17:17 +0000701 if (Context->DumpDeclarations) {
702 assert(Reporter);
703 for (const auto *Decl : UnremovedDeclsInOldHeader) {
704 auto Kind = Decl->getKind();
705 const std::string QualifiedName = Decl->getQualifiedNameAsString();
706 if (Kind == Decl::Kind::Function || Kind == Decl::Kind::FunctionTemplate)
707 Reporter->reportDeclaration(QualifiedName, "Function");
708 else if (Kind == Decl::Kind::ClassTemplate ||
709 Kind == Decl::Kind::CXXRecord)
710 Reporter->reportDeclaration(QualifiedName, "Class");
711 }
712 return;
713 }
714
Haojian Wu357ef992016-09-21 13:18:19 +0000715 if (RemovedDecls.empty())
716 return;
Eric Liu47a42d52016-12-06 10:12:23 +0000717 // Ignore symbols that are not supported (e.g. typedef and enum) when
718 // checking if there is unremoved symbol in old header. This makes sure that
719 // we always move old files to new files when all symbols produced from
720 // dump_decls are moved.
721 auto IsSupportedKind = [](const clang::NamedDecl *Decl) {
722 switch (Decl->getKind()) {
723 case Decl::Kind::Function:
724 case Decl::Kind::FunctionTemplate:
725 case Decl::Kind::ClassTemplate:
726 case Decl::Kind::CXXRecord:
727 return true;
728 default:
729 return false;
730 }
731 };
732 if (std::none_of(UnremovedDeclsInOldHeader.begin(),
733 UnremovedDeclsInOldHeader.end(), IsSupportedKind) &&
734 !Context->Spec.OldHeader.empty()) {
Haojian Wu08e402a2016-12-02 12:39:39 +0000735 auto &SM = RemovedDecls[0]->getASTContext().getSourceManager();
Haojian Wub15c8da2016-11-24 10:17:17 +0000736 moveAll(SM, Context->Spec.OldHeader, Context->Spec.NewHeader);
737 moveAll(SM, Context->Spec.OldCC, Context->Spec.NewCC);
Haojian Wu2930be12016-11-08 19:55:13 +0000738 return;
739 }
Haojian Wu08e402a2016-12-02 12:39:39 +0000740 removeDeclsInOldFiles();
741 moveDeclsToNewFiles();
Haojian Wu357ef992016-09-21 13:18:19 +0000742}
743
744} // namespace move
745} // namespace clang