blob: af1711ce5e21cb479ae1eb9dd9a4407eb67fccc0 [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.
28AST_MATCHER(VarDecl, isStaticDataMember) {
29 return Node.isStaticDataMember();
30}
31
Haojian Wue77bcc72016-10-13 10:31:00 +000032AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
33 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
34 const auto* Context = Node.getDeclContext();
35 if (!Context) return false;
36 while (const auto *NextContext = Context->getParent()) {
37 if (isa<NamespaceDecl>(NextContext) ||
38 isa<TranslationUnitDecl>(NextContext))
39 break;
40 Context = NextContext;
41 }
42 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
43 Builder);
44}
45
46AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
47 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
48 const CXXRecordDecl *Parent = Node.getParent();
49 if (!Parent) return false;
50 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))
67 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
68 << '\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.
79std::string MakeAbsolutePath(const SourceManager& SM, StringRef Path) {
80 llvm::SmallString<128> AbsolutePath(Path);
81 if (std::error_code EC =
82 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(AbsolutePath))
83 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
84 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000085 // Handle symbolic link path cases.
86 // We are trying to get the real file path of the symlink.
87 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
88 llvm::sys::path::parent_path(AbsolutePath.str()));
89 if (Dir) {
90 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
91 SmallVector<char, 128> AbsoluteFilename;
92 llvm::sys::path::append(AbsoluteFilename, DirName,
93 llvm::sys::path::filename(AbsolutePath.str()));
94 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
95 .str();
96 }
Haojian Wud2a6d7b2016-10-04 09:05:31 +000097 return AbsolutePath.str();
98}
99
100// Matches AST nodes that are expanded within the given AbsoluteFilePath.
101AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
102 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
103 std::string, AbsoluteFilePath) {
104 auto &SourceManager = Finder->getASTContext().getSourceManager();
105 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
106 if (ExpansionLoc.isInvalid())
107 return false;
108 auto FileEntry =
109 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
110 if (!FileEntry)
111 return false;
112 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
113 AbsoluteFilePath;
114}
115
Haojian Wu357ef992016-09-21 13:18:19 +0000116class FindAllIncludes : public clang::PPCallbacks {
117public:
118 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
119 : SM(*SM), MoveTool(MoveTool) {}
120
121 void InclusionDirective(clang::SourceLocation HashLoc,
122 const clang::Token & /*IncludeTok*/,
123 StringRef FileName, bool IsAngled,
124 clang::CharSourceRange /*FilenameRange*/,
125 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000126 StringRef SearchPath, StringRef /*RelativePath*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000127 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000128 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000129 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
130 FileEntry->getName(), SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000131 }
132
133private:
134 const SourceManager &SM;
135 ClangMoveTool *const MoveTool;
136};
137
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000138// Expand to get the end location of the line where the EndLoc of the given
139// Decl.
140SourceLocation
141getLocForEndOfDecl(const clang::Decl *D, const SourceManager *SM,
142 const LangOptions &LangOpts = clang::LangOptions()) {
143 std::pair<FileID, unsigned> LocInfo = SM->getDecomposedLoc(D->getLocEnd());
144 // Try to load the file buffer.
145 bool InvalidTemp = false;
146 llvm::StringRef File = SM->getBufferData(LocInfo.first, &InvalidTemp);
147 if (InvalidTemp)
148 return SourceLocation();
149
150 const char *TokBegin = File.data() + LocInfo.second;
151 // Lex from the start of the given location.
152 Lexer Lex(SM->getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
153 TokBegin, File.end());
154
155 llvm::SmallVector<char, 16> Line;
156 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
157 Lex.setParsingPreprocessorDirective(true);
158 Lex.ReadToEndOfLine(&Line);
159 SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size());
160 // If we already reach EOF, just return the EOF SourceLocation;
161 // otherwise, move 1 offset ahead to include the trailing newline character
162 // '\n'.
163 return SM->getLocForEndOfFile(LocInfo.first) == EndLoc
164 ? EndLoc
165 : EndLoc.getLocWithOffset(1);
166}
167
168// Get full range of a Decl including the comments associated with it.
169clang::CharSourceRange
170GetFullRange(const clang::SourceManager *SM, const clang::Decl *D,
171 const clang::LangOptions &options = clang::LangOptions()) {
172 clang::SourceRange Full = D->getSourceRange();
173 Full.setEnd(getLocForEndOfDecl(D, SM));
174 // Expand to comments that are associated with the Decl.
175 if (const auto* Comment =
176 D->getASTContext().getRawCommentForDeclNoCache(D)) {
177 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.
181 if (SM->isBeforeInTranslationUnit(Comment->getLocStart(),
182 Full.getBegin()))
183 Full.setBegin(Comment->getLocStart());
184 }
185
186 return clang::CharSourceRange::getCharRange(Full);
187}
188
189std::string getDeclarationSourceText(const clang::Decl *D,
190 const clang::SourceManager *SM) {
191 llvm::StringRef SourceText = clang::Lexer::getSourceText(
192 GetFullRange(SM, D), *SM, clang::LangOptions());
193 return SourceText.str();
194}
195
Haojian Wu357ef992016-09-21 13:18:19 +0000196clang::tooling::Replacement
197getReplacementInChangedCode(const clang::tooling::Replacements &Replacements,
198 const clang::tooling::Replacement &Replacement) {
199 unsigned Start = Replacements.getShiftedCodePosition(Replacement.getOffset());
200 unsigned End = Replacements.getShiftedCodePosition(Replacement.getOffset() +
201 Replacement.getLength());
202 return clang::tooling::Replacement(Replacement.getFilePath(), Start,
203 End - Start,
204 Replacement.getReplacementText());
205}
206
207void addOrMergeReplacement(const clang::tooling::Replacement &Replacement,
208 clang::tooling::Replacements *Replacements) {
209 auto Err = Replacements->add(Replacement);
210 if (Err) {
211 llvm::consumeError(std::move(Err));
212 auto Replace = getReplacementInChangedCode(*Replacements, Replacement);
213 *Replacements = Replacements->merge(clang::tooling::Replacements(Replace));
214 }
215}
216
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000217bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D,
218 llvm::StringRef OriginalRunningDirectory,
219 llvm::StringRef OldHeader) {
220 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000221 return false;
222 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
223 if (ExpansionLoc.isInvalid())
224 return false;
225
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000226 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
227 return MakeAbsolutePath(SM, FE->getName()) ==
228 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
229 }
Haojian Wu357ef992016-09-21 13:18:19 +0000230
231 return false;
232}
233
234std::vector<std::string> GetNamespaces(const clang::Decl *D) {
235 std::vector<std::string> Namespaces;
236 for (const auto *Context = D->getDeclContext(); Context;
237 Context = Context->getParent()) {
238 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
239 llvm::isa<clang::LinkageSpecDecl>(Context))
240 break;
241
242 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
243 Namespaces.push_back(ND->getName().str());
244 }
245 std::reverse(Namespaces.begin(), Namespaces.end());
246 return Namespaces;
247}
248
Haojian Wu357ef992016-09-21 13:18:19 +0000249clang::tooling::Replacements
250createInsertedReplacements(const std::vector<std::string> &Includes,
251 const std::vector<ClangMoveTool::MovedDecl> &Decls,
252 llvm::StringRef FileName) {
253 clang::tooling::Replacements InsertedReplacements;
254
255 // Add #Includes.
256 std::string AllIncludesString;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000257 // FIXME: Add header guard.
Haojian Wu357ef992016-09-21 13:18:19 +0000258 for (const auto &Include : Includes)
259 AllIncludesString += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000260
261 if (!AllIncludesString.empty()) {
262 clang::tooling::Replacement InsertInclude(FileName, 0, 0,
263 AllIncludesString + "\n");
264 addOrMergeReplacement(InsertInclude, &InsertedReplacements);
265 }
Haojian Wu357ef992016-09-21 13:18:19 +0000266
267 // Add moved class definition and its related declarations. All declarations
268 // in same namespace are grouped together.
269 std::vector<std::string> CurrentNamespaces;
270 for (const auto &MovedDecl : Decls) {
271 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
272 auto CurrentIt = CurrentNamespaces.begin();
273 auto DeclIt = DeclNamespaces.begin();
274 while (CurrentIt != CurrentNamespaces.end() &&
275 DeclIt != DeclNamespaces.end()) {
276 if (*CurrentIt != *DeclIt)
277 break;
278 ++CurrentIt;
279 ++DeclIt;
280 }
281 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
282 CurrentIt);
283 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
284 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
285 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
286 --RemainingSize, ++It) {
287 assert(It < CurrentNamespaces.rend());
288 auto code = "} // namespace " + *It + "\n";
289 clang::tooling::Replacement InsertedReplacement(FileName, 0, 0, code);
290 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
291 }
292 while (DeclIt != DeclNamespaces.end()) {
293 clang::tooling::Replacement InsertedReplacement(
294 FileName, 0, 0, "namespace " + *DeclIt + " {\n");
295 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
296 ++DeclIt;
297 }
298
Haojian Wu357ef992016-09-21 13:18:19 +0000299 clang::tooling::Replacement InsertedReplacement(
300 FileName, 0, 0, getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM));
301 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
302
303 CurrentNamespaces = std::move(NextNamespaces);
304 }
305 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
306 for (const auto &NS : CurrentNamespaces) {
307 clang::tooling::Replacement InsertedReplacement(
308 FileName, 0, 0, "} // namespace " + NS + "\n");
309 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
310 }
311 return InsertedReplacements;
312}
313
314} // namespace
315
316std::unique_ptr<clang::ASTConsumer>
317ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
318 StringRef /*InFile*/) {
319 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
320 &Compiler.getSourceManager(), &MoveTool));
321 return MatchFinder.newASTConsumer();
322}
323
Haojian Wu357ef992016-09-21 13:18:19 +0000324ClangMoveTool::ClangMoveTool(
Haojian Wu253d5962016-10-06 08:29:32 +0000325 const MoveDefinitionSpec &MoveSpec,
326 std::map<std::string, tooling::Replacements> &FileToReplacements,
327 llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle)
328 : Spec(MoveSpec), FileToReplacements(FileToReplacements),
329 OriginalRunningDirectory(OriginalRunningDirectory),
330 FallbackStyle(FallbackStyle) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000331 if (!Spec.NewHeader.empty())
332 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000333}
334
335void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000336 SmallVector<StringRef, 4> ClassNames;
337 llvm::StringRef(Spec.Names).split(ClassNames, ',');
338 Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames;
339 for (StringRef ClassName : ClassNames) {
340 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
341 const auto HasName = hasName(("::" + GlobalClassName).str());
342 InMovedClassNames =
343 InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName;
344 }
345 if (!InMovedClassNames) {
346 llvm::errs() << "No classes being moved.\n";
347 return;
348 }
349
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000350 auto InOldHeader = isExpansionInFile(
351 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader));
352 auto InOldCC = isExpansionInFile(
353 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000354 auto InOldFiles = anyOf(InOldHeader, InOldCC);
355 auto InMovedClass =
Haojian Wue77bcc72016-10-13 10:31:00 +0000356 hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames));
Haojian Wu357ef992016-09-21 13:18:19 +0000357
358 // Match moved class declarations.
359 auto MovedClass = cxxRecordDecl(
Haojian Wu9df3ac12016-10-13 08:48:42 +0000360 InOldFiles, *InMovedClassNames, isDefinition(),
Haojian Wu357ef992016-09-21 13:18:19 +0000361 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
362 Finder->addMatcher(MovedClass.bind("moved_class"), this);
363
364 // Match moved class methods (static methods included) which are defined
365 // outside moved class declaration.
Haojian Wue77bcc72016-10-13 10:31:00 +0000366 Finder->addMatcher(
367 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames),
368 isDefinition())
369 .bind("class_method"),
370 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000371
372 // Match static member variable definition of the moved class.
Haojian Wu7bd492c2016-10-14 10:07:58 +0000373 Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition(),
374 isStaticDataMember())
Haojian Wu357ef992016-09-21 13:18:19 +0000375 .bind("class_static_var_decl"),
376 this);
377
378 auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous()));
379 // Match functions/variables definitions which are defined in anonymous
380 // namespace in old cc.
381 Finder->addMatcher(
382 namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
383 inAnonymousNamespace)
384 .bind("decls_in_anonymous_ns"),
385 this);
386
387 // Match static functions/variabale definitions in old cc.
388 Finder->addMatcher(
389 namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass),
Haojian Wuef247cb2016-09-27 08:01:04 +0000390 isStaticStorageClass(), InOldCC),
391 varDecl(isDefinition(), unless(InMovedClass),
392 isStaticStorageClass(), InOldCC)))
Haojian Wu357ef992016-09-21 13:18:19 +0000393 .bind("static_decls"),
394 this);
395
396 // Match forward declarations in old header.
397 Finder->addMatcher(
398 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader)
399 .bind("fwd_decl"),
400 this);
401}
402
403void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
404 if (const auto *CMD =
405 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) {
406 // Skip inline class methods. isInline() ast matcher doesn't ignore this
407 // case.
408 if (!CMD->isInlined()) {
409 MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager());
410 RemovedDecls.push_back(MovedDecls.back());
411 }
412 } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
413 "class_static_var_decl")) {
414 MovedDecls.emplace_back(VD, &Result.Context->getSourceManager());
415 RemovedDecls.push_back(MovedDecls.back());
416 } else if (const auto *class_decl =
417 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) {
418 MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager());
419 RemovedDecls.push_back(MovedDecls.back());
420 } else if (const auto *FWD =
421 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
422 // Skip all forwad declarations which appear after moved class declaration.
423 if (RemovedDecls.empty())
424 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
425 } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>(
426 "decls_in_anonymous_ns")) {
427 MovedDecls.emplace_back(FD, &Result.Context->getSourceManager());
428 } else if (const auto *ND =
429 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
430 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
431 }
432}
433
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000434void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader,
435 bool IsAngled,
436 llvm::StringRef SearchPath,
437 llvm::StringRef FileName,
438 const SourceManager& SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000439 SmallVector<char, 128> HeaderWithSearchPath;
440 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
441 std::string AbsoluteOldHeader =
442 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000443 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
444 // old.h/c. For instance, when moved class uses another class defined in
445 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000446 if (AbsoluteOldHeader ==
447 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
448 HeaderWithSearchPath.size())))
Haojian Wudaf4cb82016-09-23 13:28:38 +0000449 return;
450
451 std::string IncludeLine =
452 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
453 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000454
Haojian Wudb726572016-10-12 15:50:30 +0000455 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
456 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000457 HeaderIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000458 } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) ==
Haojian Wudb726572016-10-12 15:50:30 +0000459 AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000460 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000461 }
Haojian Wu357ef992016-09-21 13:18:19 +0000462}
463
464void ClangMoveTool::removeClassDefinitionInOldFiles() {
465 for (const auto &MovedDecl : RemovedDecls) {
Haojian Wu253d5962016-10-06 08:29:32 +0000466 const auto &SM = *MovedDecl.SM;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000467 auto Range = GetFullRange(&SM, MovedDecl.Decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000468 clang::tooling::Replacement RemoveReplacement(
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000469 *MovedDecl.SM, clang::CharSourceRange::getCharRange(
470 Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000471 "");
472 std::string FilePath = RemoveReplacement.getFilePath().str();
473 addOrMergeReplacement(RemoveReplacement, &FileToReplacements[FilePath]);
Haojian Wu253d5962016-10-06 08:29:32 +0000474
475 llvm::StringRef Code =
476 SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation()));
477 format::FormatStyle Style =
478 format::getStyle("file", FilePath, FallbackStyle);
479 auto CleanReplacements = format::cleanupAroundReplacements(
480 Code, FileToReplacements[FilePath], Style);
481
482 if (!CleanReplacements) {
483 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
484 continue;
485 }
486 FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000487 }
488}
489
490void ClangMoveTool::moveClassDefinitionToNewFiles() {
491 std::vector<MovedDecl> NewHeaderDecls;
492 std::vector<MovedDecl> NewCCDecls;
493 for (const auto &MovedDecl : MovedDecls) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000494 if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory,
495 Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000496 NewHeaderDecls.push_back(MovedDecl);
497 else
498 NewCCDecls.push_back(MovedDecl);
499 }
500
501 if (!Spec.NewHeader.empty())
502 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
503 HeaderIncludes, NewHeaderDecls, Spec.NewHeader);
504 if (!Spec.NewCC.empty())
505 FileToReplacements[Spec.NewCC] =
506 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
507}
508
509void ClangMoveTool::onEndOfTranslationUnit() {
510 if (RemovedDecls.empty())
511 return;
512 removeClassDefinitionInOldFiles();
513 moveClassDefinitionToNewFiles();
514}
515
516} // namespace move
517} // namespace clang