blob: 9b5bd03e4969af151592030a3703dab05b6e78f7 [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 Wu35ca9462016-11-14 14:15:44 +0000139class ClassDeclarationMatch : public MatchFinder::MatchCallback {
140public:
141 explicit ClassDeclarationMatch(ClangMoveTool *MoveTool)
142 : MoveTool(MoveTool) {}
143 void run(const MatchFinder::MatchResult &Result) override {
144 clang::SourceManager* SM = &Result.Context->getSourceManager();
145 if (const auto *CMD =
146 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method"))
147 MatchClassMethod(CMD, SM);
148 else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
149 "class_static_var_decl"))
150 MatchClassStaticVariable(VD, SM);
151 else if (const auto *CD = Result.Nodes.getNodeAs<clang::CXXRecordDecl>(
152 "moved_class"))
153 MatchClassDeclaration(CD, SM);
154 }
155
156private:
157 void MatchClassMethod(const clang::CXXMethodDecl* CMD,
158 clang::SourceManager* SM) {
159 // Skip inline class methods. isInline() ast matcher doesn't ignore this
160 // case.
161 if (!CMD->isInlined()) {
162 MoveTool->getMovedDecls().emplace_back(CMD, SM);
163 MoveTool->getRemovedDecls().push_back(MoveTool->getMovedDecls().back());
164 // Get template class method from its method declaration as
165 // UnremovedDecls stores template class method.
166 if (const auto *FTD = CMD->getDescribedFunctionTemplate())
167 MoveTool->getUnremovedDeclsInOldHeader().erase(FTD);
168 else
169 MoveTool->getUnremovedDeclsInOldHeader().erase(CMD);
170 }
171 }
172
173 void MatchClassStaticVariable(const clang::NamedDecl *VD,
174 clang::SourceManager* SM) {
175 MoveTool->getMovedDecls().emplace_back(VD, SM);
176 MoveTool->getRemovedDecls().push_back(MoveTool->getMovedDecls().back());
177 MoveTool->getUnremovedDeclsInOldHeader().erase(VD);
178 }
179
180 void MatchClassDeclaration(const clang::CXXRecordDecl *CD,
181 clang::SourceManager* SM) {
182 // Get class template from its class declaration as UnremovedDecls stores
183 // class template.
184 if (const auto *TC = CD->getDescribedClassTemplate())
185 MoveTool->getMovedDecls().emplace_back(TC, SM);
186 else
187 MoveTool->getMovedDecls().emplace_back(CD, SM);
188 MoveTool->getRemovedDecls().push_back(MoveTool->getMovedDecls().back());
189 MoveTool->getUnremovedDeclsInOldHeader().erase(
190 MoveTool->getMovedDecls().back().Decl);
191 }
192
193 ClangMoveTool *MoveTool;
194};
195
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000196// Expand to get the end location of the line where the EndLoc of the given
197// Decl.
198SourceLocation
199getLocForEndOfDecl(const clang::Decl *D, const SourceManager *SM,
200 const LangOptions &LangOpts = clang::LangOptions()) {
201 std::pair<FileID, unsigned> LocInfo = SM->getDecomposedLoc(D->getLocEnd());
202 // Try to load the file buffer.
203 bool InvalidTemp = false;
204 llvm::StringRef File = SM->getBufferData(LocInfo.first, &InvalidTemp);
205 if (InvalidTemp)
206 return SourceLocation();
207
208 const char *TokBegin = File.data() + LocInfo.second;
209 // Lex from the start of the given location.
210 Lexer Lex(SM->getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
211 TokBegin, File.end());
212
213 llvm::SmallVector<char, 16> Line;
214 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
215 Lex.setParsingPreprocessorDirective(true);
216 Lex.ReadToEndOfLine(&Line);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000217 SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000218 // If we already reach EOF, just return the EOF SourceLocation;
219 // otherwise, move 1 offset ahead to include the trailing newline character
220 // '\n'.
221 return SM->getLocForEndOfFile(LocInfo.first) == EndLoc
222 ? EndLoc
223 : EndLoc.getLocWithOffset(1);
224}
225
226// Get full range of a Decl including the comments associated with it.
227clang::CharSourceRange
228GetFullRange(const clang::SourceManager *SM, const clang::Decl *D,
229 const clang::LangOptions &options = clang::LangOptions()) {
Haojian Wu24675392016-11-14 14:46:48 +0000230 clang::SourceRange Full(SM->getExpansionLoc(D->getLocStart()),
231 getLocForEndOfDecl(D, SM));
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000232 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000233 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000234 if (SM->isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
235 Full.setEnd(Comment->getLocEnd());
236 // FIXME: Don't delete a preceding comment, if there are no other entities
237 // it could refer to.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000238 if (SM->isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000239 Full.setBegin(Comment->getLocStart());
240 }
241
242 return clang::CharSourceRange::getCharRange(Full);
243}
244
245std::string getDeclarationSourceText(const clang::Decl *D,
246 const clang::SourceManager *SM) {
247 llvm::StringRef SourceText = clang::Lexer::getSourceText(
248 GetFullRange(SM, D), *SM, clang::LangOptions());
249 return SourceText.str();
250}
251
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000252bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D,
253 llvm::StringRef OriginalRunningDirectory,
254 llvm::StringRef OldHeader) {
255 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000256 return false;
257 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
258 if (ExpansionLoc.isInvalid())
259 return false;
260
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000261 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
262 return MakeAbsolutePath(SM, FE->getName()) ==
263 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
264 }
Haojian Wu357ef992016-09-21 13:18:19 +0000265
266 return false;
267}
268
269std::vector<std::string> GetNamespaces(const clang::Decl *D) {
270 std::vector<std::string> Namespaces;
271 for (const auto *Context = D->getDeclContext(); Context;
272 Context = Context->getParent()) {
273 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
274 llvm::isa<clang::LinkageSpecDecl>(Context))
275 break;
276
277 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
278 Namespaces.push_back(ND->getName().str());
279 }
280 std::reverse(Namespaces.begin(), Namespaces.end());
281 return Namespaces;
282}
283
Haojian Wu357ef992016-09-21 13:18:19 +0000284clang::tooling::Replacements
285createInsertedReplacements(const std::vector<std::string> &Includes,
286 const std::vector<ClangMoveTool::MovedDecl> &Decls,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000287 llvm::StringRef FileName, bool IsHeader = false) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000288 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000289 std::string GuardName(FileName);
290 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000291 for (size_t i = 0; i < GuardName.size(); ++i) {
292 if (!isAlphanumeric(GuardName[i]))
293 GuardName[i] = '_';
294 }
Haojian Wu220c7552016-10-14 13:01:36 +0000295 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000296 NewCode += "#ifndef " + GuardName + "\n";
297 NewCode += "#define " + GuardName + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000298 }
Haojian Wu357ef992016-09-21 13:18:19 +0000299
300 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000301 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000302 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000303
Haojian Wu53eab1e2016-10-14 13:43:49 +0000304 if (!Includes.empty())
305 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000306
307 // Add moved class definition and its related declarations. All declarations
308 // in same namespace are grouped together.
309 std::vector<std::string> CurrentNamespaces;
310 for (const auto &MovedDecl : Decls) {
311 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
312 auto CurrentIt = CurrentNamespaces.begin();
313 auto DeclIt = DeclNamespaces.begin();
314 while (CurrentIt != CurrentNamespaces.end() &&
315 DeclIt != DeclNamespaces.end()) {
316 if (*CurrentIt != *DeclIt)
317 break;
318 ++CurrentIt;
319 ++DeclIt;
320 }
321 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
322 CurrentIt);
323 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
324 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
325 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
326 --RemainingSize, ++It) {
327 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000328 NewCode += "} // namespace " + *It + "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000329 }
330 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000331 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000332 ++DeclIt;
333 }
Haojian Wu53eab1e2016-10-14 13:43:49 +0000334 NewCode += getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000335 CurrentNamespaces = std::move(NextNamespaces);
336 }
337 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000338 for (const auto &NS : CurrentNamespaces)
339 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000340
Haojian Wu53eab1e2016-10-14 13:43:49 +0000341 if (IsHeader)
342 NewCode += "#endif // " + GuardName + "\n";
343 return clang::tooling::Replacements(
344 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000345}
346
347} // namespace
348
349std::unique_ptr<clang::ASTConsumer>
350ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
351 StringRef /*InFile*/) {
352 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
353 &Compiler.getSourceManager(), &MoveTool));
354 return MatchFinder.newASTConsumer();
355}
356
Haojian Wu357ef992016-09-21 13:18:19 +0000357ClangMoveTool::ClangMoveTool(
Haojian Wu253d5962016-10-06 08:29:32 +0000358 const MoveDefinitionSpec &MoveSpec,
359 std::map<std::string, tooling::Replacements> &FileToReplacements,
360 llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle)
361 : Spec(MoveSpec), FileToReplacements(FileToReplacements),
362 OriginalRunningDirectory(OriginalRunningDirectory),
363 FallbackStyle(FallbackStyle) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000364 if (!Spec.NewHeader.empty())
365 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000366}
367
368void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000369 Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames;
Alexander Shaposhnikov5fe06782016-10-14 23:16:25 +0000370 for (StringRef ClassName : Spec.Names) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000371 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
372 const auto HasName = hasName(("::" + GlobalClassName).str());
373 InMovedClassNames =
374 InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName;
375 }
376 if (!InMovedClassNames) {
377 llvm::errs() << "No classes being moved.\n";
378 return;
379 }
380
Haojian Wu2930be12016-11-08 19:55:13 +0000381 auto InOldHeader = isExpansionInFile(makeAbsolutePath(Spec.OldHeader));
382 auto InOldCC = isExpansionInFile(makeAbsolutePath(Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000383 auto InOldFiles = anyOf(InOldHeader, InOldCC);
384 auto InMovedClass =
Haojian Wue77bcc72016-10-13 10:31:00 +0000385 hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames));
Haojian Wu357ef992016-09-21 13:18:19 +0000386
Haojian Wu2930be12016-11-08 19:55:13 +0000387 auto ForwardDecls =
388 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
389
390 //============================================================================
391 // Matchers for old header
392 //============================================================================
393 // Match all top-level named declarations (e.g. function, variable, enum) in
394 // old header, exclude forward class declarations and namespace declarations.
395 //
396 // The old header which contains only one declaration being moved and forward
397 // declarations is considered to be moved totally.
398 auto AllDeclsInHeader = namedDecl(
399 unless(ForwardDecls), unless(namespaceDecl()),
400 unless(usingDirectiveDecl()), // using namespace decl.
401 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
402 InOldHeader,
403 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
404 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
405 // Match forward declarations in old header.
406 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
407 this);
408
409 //============================================================================
Haojian Wu2930be12016-11-08 19:55:13 +0000410 // Matchers for old cc
411 //============================================================================
Haojian Wu67bb6512016-10-19 14:13:21 +0000412 auto InOldCCNamedNamespace =
413 allOf(hasParent(namespaceDecl(unless(isAnonymous()))), InOldCC);
414 // Matching using decls/type alias decls which are in named namespace. Those
415 // in classes, functions and anonymous namespaces are covered in other
416 // matchers.
Haojian Wu357ef992016-09-21 13:18:19 +0000417 Finder->addMatcher(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000418 namedDecl(anyOf(usingDecl(InOldCCNamedNamespace),
419 usingDirectiveDecl(InOldCC, InOldCCNamedNamespace),
420 typeAliasDecl(InOldCC, InOldCCNamedNamespace)))
Haojian Wu67bb6512016-10-19 14:13:21 +0000421 .bind("using_decl"),
Haojian Wu357ef992016-09-21 13:18:19 +0000422 this);
423
Haojian Wu67bb6512016-10-19 14:13:21 +0000424 // Match anonymous namespace decl in old cc.
425 Finder->addMatcher(namespaceDecl(isAnonymous(), InOldCC).bind("anonymous_ns"),
426 this);
427
428 // Match static functions/variable definitions which are defined in named
429 // namespaces.
430 auto IsOldCCStaticDefinition =
431 allOf(isDefinition(), unless(InMovedClass), InOldCCNamedNamespace,
432 isStaticStorageClass());
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000433 Finder->addMatcher(namedDecl(anyOf(functionDecl(IsOldCCStaticDefinition),
434 varDecl(IsOldCCStaticDefinition)))
435 .bind("static_decls"),
436 this);
Haojian Wu35ca9462016-11-14 14:15:44 +0000437
438 //============================================================================
439 // Matchers for old files, including old.h/old.cc
440 //============================================================================
441 // Create a MatchCallback for class declarations.
442 MatchCallbacks.push_back(llvm::make_unique<ClassDeclarationMatch>(this));
443 // Match moved class declarations.
444 auto MovedClass =
445 cxxRecordDecl(
446 InOldFiles, *InMovedClassNames, isDefinition(),
447 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())))
448 .bind("moved_class");
449 Finder->addMatcher(MovedClass, MatchCallbacks.back().get());
450 // Match moved class methods (static methods included) which are defined
451 // outside moved class declaration.
452 Finder->addMatcher(
453 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames),
454 isDefinition())
455 .bind("class_method"),
456 MatchCallbacks.back().get());
457 // Match static member variable definition of the moved class.
458 Finder->addMatcher(
459 varDecl(InMovedClass, InOldFiles, isDefinition(), isStaticDataMember())
460 .bind("class_static_var_decl"),
461 MatchCallbacks.back().get());
462
Haojian Wu357ef992016-09-21 13:18:19 +0000463}
464
465void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000466 if (const auto *D =
467 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
468 UnremovedDeclsInOldHeader.insert(D);
Haojian Wu357ef992016-09-21 13:18:19 +0000469 } else if (const auto *FWD =
470 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
471 // Skip all forwad declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000472 if (RemovedDecls.empty()) {
Haojian Wub53ec462016-11-10 05:33:26 +0000473 if (const auto *DCT = FWD->getDescribedClassTemplate())
Haojian Wu29c38f72016-10-21 19:26:43 +0000474 MovedDecls.emplace_back(DCT, &Result.Context->getSourceManager());
Haojian Wub53ec462016-11-10 05:33:26 +0000475 else
Haojian Wu29c38f72016-10-21 19:26:43 +0000476 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
Haojian Wu29c38f72016-10-21 19:26:43 +0000477 }
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000478 } else if (const auto *ANS =
479 Result.Nodes.getNodeAs<clang::NamespaceDecl>("anonymous_ns")) {
Haojian Wu67bb6512016-10-19 14:13:21 +0000480 MovedDecls.emplace_back(ANS, &Result.Context->getSourceManager());
Haojian Wu357ef992016-09-21 13:18:19 +0000481 } else if (const auto *ND =
482 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
483 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
Haojian Wu67bb6512016-10-19 14:13:21 +0000484 } else if (const auto *UD =
485 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
486 MovedDecls.emplace_back(UD, &Result.Context->getSourceManager());
Haojian Wu357ef992016-09-21 13:18:19 +0000487 }
488}
489
Haojian Wu2930be12016-11-08 19:55:13 +0000490std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
491 return MakeAbsolutePath(OriginalRunningDirectory, Path);
492}
493
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000494void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000495 llvm::StringRef SearchPath,
496 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000497 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000498 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000499 SmallVector<char, 128> HeaderWithSearchPath;
500 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wu2930be12016-11-08 19:55:13 +0000501 std::string AbsoluteOldHeader = makeAbsolutePath(Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000502 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
503 // old.h/c. For instance, when moved class uses another class defined in
504 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000505 if (AbsoluteOldHeader ==
506 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000507 HeaderWithSearchPath.size()))) {
508 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000509 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000510 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000511
512 std::string IncludeLine =
513 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
514 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000515
Haojian Wudb726572016-10-12 15:50:30 +0000516 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
517 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000518 HeaderIncludes.push_back(IncludeLine);
Haojian Wu2930be12016-11-08 19:55:13 +0000519 } else if (makeAbsolutePath(Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000520 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000521 }
Haojian Wu357ef992016-09-21 13:18:19 +0000522}
523
524void ClangMoveTool::removeClassDefinitionInOldFiles() {
525 for (const auto &MovedDecl : RemovedDecls) {
Haojian Wu253d5962016-10-06 08:29:32 +0000526 const auto &SM = *MovedDecl.SM;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000527 auto Range = GetFullRange(&SM, MovedDecl.Decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000528 clang::tooling::Replacement RemoveReplacement(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000529 *MovedDecl.SM,
530 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000531 "");
532 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000533 auto Err = FileToReplacements[FilePath].add(RemoveReplacement);
534 if (Err) {
535 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
536 continue;
537 }
Haojian Wu253d5962016-10-06 08:29:32 +0000538
539 llvm::StringRef Code =
540 SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation()));
541 format::FormatStyle Style =
542 format::getStyle("file", FilePath, FallbackStyle);
543 auto CleanReplacements = format::cleanupAroundReplacements(
544 Code, FileToReplacements[FilePath], Style);
545
546 if (!CleanReplacements) {
547 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
548 continue;
549 }
550 FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000551 }
552}
553
554void ClangMoveTool::moveClassDefinitionToNewFiles() {
555 std::vector<MovedDecl> NewHeaderDecls;
556 std::vector<MovedDecl> NewCCDecls;
557 for (const auto &MovedDecl : MovedDecls) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000558 if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory,
559 Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000560 NewHeaderDecls.push_back(MovedDecl);
561 else
562 NewCCDecls.push_back(MovedDecl);
563 }
564
565 if (!Spec.NewHeader.empty())
566 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
Haojian Wu220c7552016-10-14 13:01:36 +0000567 HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true);
Haojian Wu357ef992016-09-21 13:18:19 +0000568 if (!Spec.NewCC.empty())
569 FileToReplacements[Spec.NewCC] =
570 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
571}
572
Haojian Wu2930be12016-11-08 19:55:13 +0000573// Move all contents from OldFile to NewFile.
574void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
575 StringRef NewFile) {
576 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
577 if (!FE) {
578 llvm::errs() << "Failed to get file: " << OldFile << "\n";
579 return;
580 }
581 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
582 auto Begin = SM.getLocForStartOfFile(ID);
583 auto End = SM.getLocForEndOfFile(ID);
584 clang::tooling::Replacement RemoveAll (
585 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
586 std::string FilePath = RemoveAll.getFilePath().str();
587 FileToReplacements[FilePath] = clang::tooling::Replacements(RemoveAll);
588
589 StringRef Code = SM.getBufferData(ID);
590 if (!NewFile.empty()) {
591 auto AllCode = clang::tooling::Replacements(
592 clang::tooling::Replacement(NewFile, 0, 0, Code));
593 // If we are moving from old.cc, an extra step is required: excluding
594 // the #include of "old.h", instead, we replace it with #include of "new.h".
595 if (Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
596 AllCode = AllCode.merge(
597 clang::tooling::Replacements(clang::tooling::Replacement(
598 SM, OldHeaderIncludeRange, '"' + Spec.NewHeader + '"')));
599 }
600 FileToReplacements[NewFile] = std::move(AllCode);
601 }
602}
603
Haojian Wu357ef992016-09-21 13:18:19 +0000604void ClangMoveTool::onEndOfTranslationUnit() {
605 if (RemovedDecls.empty())
606 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000607 if (UnremovedDeclsInOldHeader.empty() && !Spec.OldHeader.empty()) {
608 auto &SM = *RemovedDecls[0].SM;
609 moveAll(SM, Spec.OldHeader, Spec.NewHeader);
610 moveAll(SM, Spec.OldCC, Spec.NewCC);
611 return;
612 }
Haojian Wu357ef992016-09-21 13:18:19 +0000613 removeClassDefinitionInOldFiles();
614 moveClassDefinitionToNewFiles();
615}
616
617} // namespace move
618} // namespace clang