blob: e23db7474b438740da1f8590c58c1f4214a72848 [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 Wu9abbeaa2016-10-06 08:59:24 +0000139// Expand to get the end location of the line where the EndLoc of the given
140// Decl.
141SourceLocation
142getLocForEndOfDecl(const clang::Decl *D, const SourceManager *SM,
143 const LangOptions &LangOpts = clang::LangOptions()) {
144 std::pair<FileID, unsigned> LocInfo = SM->getDecomposedLoc(D->getLocEnd());
145 // Try to load the file buffer.
146 bool InvalidTemp = false;
147 llvm::StringRef File = SM->getBufferData(LocInfo.first, &InvalidTemp);
148 if (InvalidTemp)
149 return SourceLocation();
150
151 const char *TokBegin = File.data() + LocInfo.second;
152 // Lex from the start of the given location.
153 Lexer Lex(SM->getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
154 TokBegin, File.end());
155
156 llvm::SmallVector<char, 16> Line;
157 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
158 Lex.setParsingPreprocessorDirective(true);
159 Lex.ReadToEndOfLine(&Line);
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000160 SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size());
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000161 // If we already reach EOF, just return the EOF SourceLocation;
162 // otherwise, move 1 offset ahead to include the trailing newline character
163 // '\n'.
164 return SM->getLocForEndOfFile(LocInfo.first) == EndLoc
165 ? EndLoc
166 : EndLoc.getLocWithOffset(1);
167}
168
169// Get full range of a Decl including the comments associated with it.
170clang::CharSourceRange
171GetFullRange(const clang::SourceManager *SM, const clang::Decl *D,
172 const clang::LangOptions &options = clang::LangOptions()) {
173 clang::SourceRange Full = D->getSourceRange();
174 Full.setEnd(getLocForEndOfDecl(D, SM));
175 // Expand to comments that are associated with the Decl.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000176 if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) {
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000177 if (SM->isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
178 Full.setEnd(Comment->getLocEnd());
179 // FIXME: Don't delete a preceding comment, if there are no other entities
180 // it could refer to.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000181 if (SM->isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin()))
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000182 Full.setBegin(Comment->getLocStart());
183 }
184
185 return clang::CharSourceRange::getCharRange(Full);
186}
187
188std::string getDeclarationSourceText(const clang::Decl *D,
189 const clang::SourceManager *SM) {
190 llvm::StringRef SourceText = clang::Lexer::getSourceText(
191 GetFullRange(SM, D), *SM, clang::LangOptions());
192 return SourceText.str();
193}
194
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000195bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D,
196 llvm::StringRef OriginalRunningDirectory,
197 llvm::StringRef OldHeader) {
198 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000199 return false;
200 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
201 if (ExpansionLoc.isInvalid())
202 return false;
203
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000204 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
205 return MakeAbsolutePath(SM, FE->getName()) ==
206 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
207 }
Haojian Wu357ef992016-09-21 13:18:19 +0000208
209 return false;
210}
211
212std::vector<std::string> GetNamespaces(const clang::Decl *D) {
213 std::vector<std::string> Namespaces;
214 for (const auto *Context = D->getDeclContext(); Context;
215 Context = Context->getParent()) {
216 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
217 llvm::isa<clang::LinkageSpecDecl>(Context))
218 break;
219
220 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
221 Namespaces.push_back(ND->getName().str());
222 }
223 std::reverse(Namespaces.begin(), Namespaces.end());
224 return Namespaces;
225}
226
Haojian Wu357ef992016-09-21 13:18:19 +0000227clang::tooling::Replacements
228createInsertedReplacements(const std::vector<std::string> &Includes,
229 const std::vector<ClangMoveTool::MovedDecl> &Decls,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000230 llvm::StringRef FileName, bool IsHeader = false) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000231 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000232 std::string GuardName(FileName);
233 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000234 for (size_t i = 0; i < GuardName.size(); ++i) {
235 if (!isAlphanumeric(GuardName[i]))
236 GuardName[i] = '_';
237 }
Haojian Wu220c7552016-10-14 13:01:36 +0000238 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000239 NewCode += "#ifndef " + GuardName + "\n";
240 NewCode += "#define " + GuardName + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000241 }
Haojian Wu357ef992016-09-21 13:18:19 +0000242
243 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000244 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000245 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000246
Haojian Wu53eab1e2016-10-14 13:43:49 +0000247 if (!Includes.empty())
248 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000249
250 // Add moved class definition and its related declarations. All declarations
251 // in same namespace are grouped together.
252 std::vector<std::string> CurrentNamespaces;
253 for (const auto &MovedDecl : Decls) {
254 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
255 auto CurrentIt = CurrentNamespaces.begin();
256 auto DeclIt = DeclNamespaces.begin();
257 while (CurrentIt != CurrentNamespaces.end() &&
258 DeclIt != DeclNamespaces.end()) {
259 if (*CurrentIt != *DeclIt)
260 break;
261 ++CurrentIt;
262 ++DeclIt;
263 }
264 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
265 CurrentIt);
266 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
267 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
268 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
269 --RemainingSize, ++It) {
270 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000271 NewCode += "} // namespace " + *It + "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000272 }
273 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000274 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000275 ++DeclIt;
276 }
Haojian Wu53eab1e2016-10-14 13:43:49 +0000277 NewCode += getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000278 CurrentNamespaces = std::move(NextNamespaces);
279 }
280 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000281 for (const auto &NS : CurrentNamespaces)
282 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000283
Haojian Wu53eab1e2016-10-14 13:43:49 +0000284 if (IsHeader)
285 NewCode += "#endif // " + GuardName + "\n";
286 return clang::tooling::Replacements(
287 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000288}
289
290} // namespace
291
292std::unique_ptr<clang::ASTConsumer>
293ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
294 StringRef /*InFile*/) {
295 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
296 &Compiler.getSourceManager(), &MoveTool));
297 return MatchFinder.newASTConsumer();
298}
299
Haojian Wu357ef992016-09-21 13:18:19 +0000300ClangMoveTool::ClangMoveTool(
Haojian Wu253d5962016-10-06 08:29:32 +0000301 const MoveDefinitionSpec &MoveSpec,
302 std::map<std::string, tooling::Replacements> &FileToReplacements,
303 llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle)
304 : Spec(MoveSpec), FileToReplacements(FileToReplacements),
305 OriginalRunningDirectory(OriginalRunningDirectory),
306 FallbackStyle(FallbackStyle) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000307 if (!Spec.NewHeader.empty())
308 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000309}
310
311void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000312 Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames;
Alexander Shaposhnikov5fe06782016-10-14 23:16:25 +0000313 for (StringRef ClassName : Spec.Names) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000314 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
315 const auto HasName = hasName(("::" + GlobalClassName).str());
316 InMovedClassNames =
317 InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName;
318 }
319 if (!InMovedClassNames) {
320 llvm::errs() << "No classes being moved.\n";
321 return;
322 }
323
Haojian Wu2930be12016-11-08 19:55:13 +0000324 auto InOldHeader = isExpansionInFile(makeAbsolutePath(Spec.OldHeader));
325 auto InOldCC = isExpansionInFile(makeAbsolutePath(Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000326 auto InOldFiles = anyOf(InOldHeader, InOldCC);
327 auto InMovedClass =
Haojian Wue77bcc72016-10-13 10:31:00 +0000328 hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames));
Haojian Wu357ef992016-09-21 13:18:19 +0000329
Haojian Wu2930be12016-11-08 19:55:13 +0000330 auto ForwardDecls =
331 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())));
332
333 //============================================================================
334 // Matchers for old header
335 //============================================================================
336 // Match all top-level named declarations (e.g. function, variable, enum) in
337 // old header, exclude forward class declarations and namespace declarations.
338 //
339 // The old header which contains only one declaration being moved and forward
340 // declarations is considered to be moved totally.
341 auto AllDeclsInHeader = namedDecl(
342 unless(ForwardDecls), unless(namespaceDecl()),
343 unless(usingDirectiveDecl()), // using namespace decl.
344 unless(classTemplateDecl(has(ForwardDecls))), // template forward decl.
345 InOldHeader,
346 hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))));
347 Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this);
348 // Match forward declarations in old header.
349 Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"),
350 this);
351
352 //============================================================================
353 // Matchers for old files, including old.h/old.cc
354 //============================================================================
Haojian Wu357ef992016-09-21 13:18:19 +0000355 // Match moved class declarations.
356 auto MovedClass = cxxRecordDecl(
Haojian Wu9df3ac12016-10-13 08:48:42 +0000357 InOldFiles, *InMovedClassNames, isDefinition(),
Haojian Wu357ef992016-09-21 13:18:19 +0000358 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
359 Finder->addMatcher(MovedClass.bind("moved_class"), this);
Haojian Wu357ef992016-09-21 13:18:19 +0000360 // Match moved class methods (static methods included) which are defined
361 // outside moved class declaration.
Haojian Wue77bcc72016-10-13 10:31:00 +0000362 Finder->addMatcher(
363 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames),
364 isDefinition())
365 .bind("class_method"),
366 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000367
Haojian Wu2930be12016-11-08 19:55:13 +0000368 //============================================================================
369 // Matchers for old cc
370 //============================================================================
Haojian Wu357ef992016-09-21 13:18:19 +0000371 // Match static member variable definition of the moved class.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000372 Finder->addMatcher(
373 varDecl(InMovedClass, InOldCC, isDefinition(), isStaticDataMember())
374 .bind("class_static_var_decl"),
375 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000376
Haojian Wu67bb6512016-10-19 14:13:21 +0000377 auto InOldCCNamedNamespace =
378 allOf(hasParent(namespaceDecl(unless(isAnonymous()))), InOldCC);
379 // Matching using decls/type alias decls which are in named namespace. Those
380 // in classes, functions and anonymous namespaces are covered in other
381 // matchers.
Haojian Wu357ef992016-09-21 13:18:19 +0000382 Finder->addMatcher(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000383 namedDecl(anyOf(usingDecl(InOldCCNamedNamespace),
384 usingDirectiveDecl(InOldCC, InOldCCNamedNamespace),
385 typeAliasDecl(InOldCC, InOldCCNamedNamespace)))
Haojian Wu67bb6512016-10-19 14:13:21 +0000386 .bind("using_decl"),
Haojian Wu357ef992016-09-21 13:18:19 +0000387 this);
388
Haojian Wu67bb6512016-10-19 14:13:21 +0000389 // Match anonymous namespace decl in old cc.
390 Finder->addMatcher(namespaceDecl(isAnonymous(), InOldCC).bind("anonymous_ns"),
391 this);
392
393 // Match static functions/variable definitions which are defined in named
394 // namespaces.
395 auto IsOldCCStaticDefinition =
396 allOf(isDefinition(), unless(InMovedClass), InOldCCNamedNamespace,
397 isStaticStorageClass());
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000398 Finder->addMatcher(namedDecl(anyOf(functionDecl(IsOldCCStaticDefinition),
399 varDecl(IsOldCCStaticDefinition)))
400 .bind("static_decls"),
401 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000402}
403
404void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
Haojian Wu2930be12016-11-08 19:55:13 +0000405 if (const auto *D =
406 Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) {
407 UnremovedDeclsInOldHeader.insert(D);
408 } else if (const auto *CMD =
Haojian Wu357ef992016-09-21 13:18:19 +0000409 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) {
410 // Skip inline class methods. isInline() ast matcher doesn't ignore this
411 // case.
412 if (!CMD->isInlined()) {
413 MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager());
414 RemovedDecls.push_back(MovedDecls.back());
415 }
416 } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
417 "class_static_var_decl")) {
418 MovedDecls.emplace_back(VD, &Result.Context->getSourceManager());
419 RemovedDecls.push_back(MovedDecls.back());
420 } else if (const auto *class_decl =
421 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) {
422 MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager());
423 RemovedDecls.push_back(MovedDecls.back());
Haojian Wu2930be12016-11-08 19:55:13 +0000424 UnremovedDeclsInOldHeader.erase(class_decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000425 } else if (const auto *FWD =
426 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
427 // Skip all forwad declarations which appear after moved class declaration.
Haojian Wu29c38f72016-10-21 19:26:43 +0000428 if (RemovedDecls.empty()) {
429 if (const auto *DCT = FWD->getDescribedClassTemplate()) {
430 MovedDecls.emplace_back(DCT, &Result.Context->getSourceManager());
431 } else {
432 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
433 }
434 }
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000435 } else if (const auto *ANS =
436 Result.Nodes.getNodeAs<clang::NamespaceDecl>("anonymous_ns")) {
Haojian Wu67bb6512016-10-19 14:13:21 +0000437 MovedDecls.emplace_back(ANS, &Result.Context->getSourceManager());
Haojian Wu357ef992016-09-21 13:18:19 +0000438 } else if (const auto *ND =
439 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
440 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
Haojian Wu67bb6512016-10-19 14:13:21 +0000441 } else if (const auto *UD =
442 Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) {
443 MovedDecls.emplace_back(UD, &Result.Context->getSourceManager());
Haojian Wu357ef992016-09-21 13:18:19 +0000444 }
445}
446
Haojian Wu2930be12016-11-08 19:55:13 +0000447std::string ClangMoveTool::makeAbsolutePath(StringRef Path) {
448 return MakeAbsolutePath(OriginalRunningDirectory, Path);
449}
450
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000451void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000452 llvm::StringRef SearchPath,
453 llvm::StringRef FileName,
Haojian Wu2930be12016-11-08 19:55:13 +0000454 clang::CharSourceRange IncludeFilenameRange,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000455 const SourceManager &SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000456 SmallVector<char, 128> HeaderWithSearchPath;
457 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
Haojian Wu2930be12016-11-08 19:55:13 +0000458 std::string AbsoluteOldHeader = makeAbsolutePath(Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000459 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
460 // old.h/c. For instance, when moved class uses another class defined in
461 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000462 if (AbsoluteOldHeader ==
463 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
Haojian Wu2930be12016-11-08 19:55:13 +0000464 HeaderWithSearchPath.size()))) {
465 OldHeaderIncludeRange = IncludeFilenameRange;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000466 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000467 }
Haojian Wudaf4cb82016-09-23 13:28:38 +0000468
469 std::string IncludeLine =
470 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
471 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000472
Haojian Wudb726572016-10-12 15:50:30 +0000473 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
474 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000475 HeaderIncludes.push_back(IncludeLine);
Haojian Wu2930be12016-11-08 19:55:13 +0000476 } else if (makeAbsolutePath(Spec.OldCC) == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000477 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000478 }
Haojian Wu357ef992016-09-21 13:18:19 +0000479}
480
481void ClangMoveTool::removeClassDefinitionInOldFiles() {
482 for (const auto &MovedDecl : RemovedDecls) {
Haojian Wu253d5962016-10-06 08:29:32 +0000483 const auto &SM = *MovedDecl.SM;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000484 auto Range = GetFullRange(&SM, MovedDecl.Decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000485 clang::tooling::Replacement RemoveReplacement(
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000486 *MovedDecl.SM,
487 clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000488 "");
489 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000490 auto Err = FileToReplacements[FilePath].add(RemoveReplacement);
491 if (Err) {
492 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
493 continue;
494 }
Haojian Wu253d5962016-10-06 08:29:32 +0000495
496 llvm::StringRef Code =
497 SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation()));
498 format::FormatStyle Style =
499 format::getStyle("file", FilePath, FallbackStyle);
500 auto CleanReplacements = format::cleanupAroundReplacements(
501 Code, FileToReplacements[FilePath], Style);
502
503 if (!CleanReplacements) {
504 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
505 continue;
506 }
507 FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000508 }
509}
510
511void ClangMoveTool::moveClassDefinitionToNewFiles() {
512 std::vector<MovedDecl> NewHeaderDecls;
513 std::vector<MovedDecl> NewCCDecls;
514 for (const auto &MovedDecl : MovedDecls) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000515 if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory,
516 Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000517 NewHeaderDecls.push_back(MovedDecl);
518 else
519 NewCCDecls.push_back(MovedDecl);
520 }
521
522 if (!Spec.NewHeader.empty())
523 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
Haojian Wu220c7552016-10-14 13:01:36 +0000524 HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true);
Haojian Wu357ef992016-09-21 13:18:19 +0000525 if (!Spec.NewCC.empty())
526 FileToReplacements[Spec.NewCC] =
527 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
528}
529
Haojian Wu2930be12016-11-08 19:55:13 +0000530// Move all contents from OldFile to NewFile.
531void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile,
532 StringRef NewFile) {
533 const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile));
534 if (!FE) {
535 llvm::errs() << "Failed to get file: " << OldFile << "\n";
536 return;
537 }
538 FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User);
539 auto Begin = SM.getLocForStartOfFile(ID);
540 auto End = SM.getLocForEndOfFile(ID);
541 clang::tooling::Replacement RemoveAll (
542 SM, clang::CharSourceRange::getCharRange(Begin, End), "");
543 std::string FilePath = RemoveAll.getFilePath().str();
544 FileToReplacements[FilePath] = clang::tooling::Replacements(RemoveAll);
545
546 StringRef Code = SM.getBufferData(ID);
547 if (!NewFile.empty()) {
548 auto AllCode = clang::tooling::Replacements(
549 clang::tooling::Replacement(NewFile, 0, 0, Code));
550 // If we are moving from old.cc, an extra step is required: excluding
551 // the #include of "old.h", instead, we replace it with #include of "new.h".
552 if (Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) {
553 AllCode = AllCode.merge(
554 clang::tooling::Replacements(clang::tooling::Replacement(
555 SM, OldHeaderIncludeRange, '"' + Spec.NewHeader + '"')));
556 }
557 FileToReplacements[NewFile] = std::move(AllCode);
558 }
559}
560
Haojian Wu357ef992016-09-21 13:18:19 +0000561void ClangMoveTool::onEndOfTranslationUnit() {
562 if (RemovedDecls.empty())
563 return;
Haojian Wu2930be12016-11-08 19:55:13 +0000564 if (UnremovedDeclsInOldHeader.empty() && !Spec.OldHeader.empty()) {
565 auto &SM = *RemovedDecls[0].SM;
566 moveAll(SM, Spec.OldHeader, Spec.NewHeader);
567 moveAll(SM, Spec.OldCC, Spec.NewCC);
568 return;
569 }
Haojian Wu357ef992016-09-21 13:18:19 +0000570 removeClassDefinitionInOldFiles();
571 moveClassDefinitionToNewFiles();
572}
573
574} // namespace move
575} // namespace clang