blob: 1c7bf50616cff0530cc1ee19f56f48536f51dbdd [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,
Haojian Wu220c7552016-10-14 13:01:36 +0000252 llvm::StringRef FileName,
253 bool IsHeader = false) {
Haojian Wu357ef992016-09-21 13:18:19 +0000254 clang::tooling::Replacements InsertedReplacements;
Haojian Wu220c7552016-10-14 13:01:36 +0000255 std::string GuardName(FileName);
256 if (IsHeader) {
257 std::replace(GuardName.begin(), GuardName.end(), '/', '_');
258 std::replace(GuardName.begin(), GuardName.end(), '.', '_');
259 std::replace(GuardName.begin(), GuardName.end(), '-', '_');
260
261 GuardName = StringRef(GuardName).upper();
262 std::string HeaderGuard = "#ifndef " + GuardName + "\n";
263 HeaderGuard += "#define " + GuardName + "\n";
264 clang::tooling::Replacement HeaderGuardInclude(FileName, 0, 0,
265 HeaderGuard);
266 addOrMergeReplacement(HeaderGuardInclude, &InsertedReplacements);
267 }
Haojian Wu357ef992016-09-21 13:18:19 +0000268
269 // Add #Includes.
270 std::string AllIncludesString;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000271 // FIXME: Add header guard.
Haojian Wu357ef992016-09-21 13:18:19 +0000272 for (const auto &Include : Includes)
273 AllIncludesString += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000274
275 if (!AllIncludesString.empty()) {
276 clang::tooling::Replacement InsertInclude(FileName, 0, 0,
277 AllIncludesString + "\n");
278 addOrMergeReplacement(InsertInclude, &InsertedReplacements);
279 }
Haojian Wu357ef992016-09-21 13:18:19 +0000280
281 // Add moved class definition and its related declarations. All declarations
282 // in same namespace are grouped together.
283 std::vector<std::string> CurrentNamespaces;
284 for (const auto &MovedDecl : Decls) {
285 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
286 auto CurrentIt = CurrentNamespaces.begin();
287 auto DeclIt = DeclNamespaces.begin();
288 while (CurrentIt != CurrentNamespaces.end() &&
289 DeclIt != DeclNamespaces.end()) {
290 if (*CurrentIt != *DeclIt)
291 break;
292 ++CurrentIt;
293 ++DeclIt;
294 }
295 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
296 CurrentIt);
297 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
298 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
299 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
300 --RemainingSize, ++It) {
301 assert(It < CurrentNamespaces.rend());
302 auto code = "} // namespace " + *It + "\n";
303 clang::tooling::Replacement InsertedReplacement(FileName, 0, 0, code);
304 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
305 }
306 while (DeclIt != DeclNamespaces.end()) {
307 clang::tooling::Replacement InsertedReplacement(
308 FileName, 0, 0, "namespace " + *DeclIt + " {\n");
309 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
310 ++DeclIt;
311 }
312
Haojian Wu357ef992016-09-21 13:18:19 +0000313 clang::tooling::Replacement InsertedReplacement(
314 FileName, 0, 0, getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM));
315 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
316
317 CurrentNamespaces = std::move(NextNamespaces);
318 }
319 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
320 for (const auto &NS : CurrentNamespaces) {
321 clang::tooling::Replacement InsertedReplacement(
322 FileName, 0, 0, "} // namespace " + NS + "\n");
323 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
324 }
Haojian Wu220c7552016-10-14 13:01:36 +0000325
326 if (IsHeader) {
327 clang::tooling::Replacement HeaderGuardEnd(FileName, 0, 0,
328 "#endif // " + GuardName + "\n");
329 addOrMergeReplacement(HeaderGuardEnd, &InsertedReplacements);
330 }
Haojian Wu357ef992016-09-21 13:18:19 +0000331 return InsertedReplacements;
332}
333
334} // namespace
335
336std::unique_ptr<clang::ASTConsumer>
337ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
338 StringRef /*InFile*/) {
339 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
340 &Compiler.getSourceManager(), &MoveTool));
341 return MatchFinder.newASTConsumer();
342}
343
Haojian Wu357ef992016-09-21 13:18:19 +0000344ClangMoveTool::ClangMoveTool(
Haojian Wu253d5962016-10-06 08:29:32 +0000345 const MoveDefinitionSpec &MoveSpec,
346 std::map<std::string, tooling::Replacements> &FileToReplacements,
347 llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle)
348 : Spec(MoveSpec), FileToReplacements(FileToReplacements),
349 OriginalRunningDirectory(OriginalRunningDirectory),
350 FallbackStyle(FallbackStyle) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000351 if (!Spec.NewHeader.empty())
352 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000353}
354
355void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000356 SmallVector<StringRef, 4> ClassNames;
357 llvm::StringRef(Spec.Names).split(ClassNames, ',');
358 Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames;
359 for (StringRef ClassName : ClassNames) {
360 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
361 const auto HasName = hasName(("::" + GlobalClassName).str());
362 InMovedClassNames =
363 InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName;
364 }
365 if (!InMovedClassNames) {
366 llvm::errs() << "No classes being moved.\n";
367 return;
368 }
369
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000370 auto InOldHeader = isExpansionInFile(
371 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader));
372 auto InOldCC = isExpansionInFile(
373 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000374 auto InOldFiles = anyOf(InOldHeader, InOldCC);
375 auto InMovedClass =
Haojian Wue77bcc72016-10-13 10:31:00 +0000376 hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames));
Haojian Wu357ef992016-09-21 13:18:19 +0000377
378 // Match moved class declarations.
379 auto MovedClass = cxxRecordDecl(
Haojian Wu9df3ac12016-10-13 08:48:42 +0000380 InOldFiles, *InMovedClassNames, isDefinition(),
Haojian Wu357ef992016-09-21 13:18:19 +0000381 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
382 Finder->addMatcher(MovedClass.bind("moved_class"), this);
383
384 // Match moved class methods (static methods included) which are defined
385 // outside moved class declaration.
Haojian Wue77bcc72016-10-13 10:31:00 +0000386 Finder->addMatcher(
387 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames),
388 isDefinition())
389 .bind("class_method"),
390 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000391
392 // Match static member variable definition of the moved class.
Haojian Wu7bd492c2016-10-14 10:07:58 +0000393 Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition(),
394 isStaticDataMember())
Haojian Wu357ef992016-09-21 13:18:19 +0000395 .bind("class_static_var_decl"),
396 this);
397
398 auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous()));
399 // Match functions/variables definitions which are defined in anonymous
400 // namespace in old cc.
401 Finder->addMatcher(
402 namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
403 inAnonymousNamespace)
404 .bind("decls_in_anonymous_ns"),
405 this);
406
407 // Match static functions/variabale definitions in old cc.
408 Finder->addMatcher(
409 namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass),
Haojian Wuef247cb2016-09-27 08:01:04 +0000410 isStaticStorageClass(), InOldCC),
411 varDecl(isDefinition(), unless(InMovedClass),
412 isStaticStorageClass(), InOldCC)))
Haojian Wu357ef992016-09-21 13:18:19 +0000413 .bind("static_decls"),
414 this);
415
416 // Match forward declarations in old header.
417 Finder->addMatcher(
418 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader)
419 .bind("fwd_decl"),
420 this);
421}
422
423void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
424 if (const auto *CMD =
425 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) {
426 // Skip inline class methods. isInline() ast matcher doesn't ignore this
427 // case.
428 if (!CMD->isInlined()) {
429 MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager());
430 RemovedDecls.push_back(MovedDecls.back());
431 }
432 } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
433 "class_static_var_decl")) {
434 MovedDecls.emplace_back(VD, &Result.Context->getSourceManager());
435 RemovedDecls.push_back(MovedDecls.back());
436 } else if (const auto *class_decl =
437 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) {
438 MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager());
439 RemovedDecls.push_back(MovedDecls.back());
440 } else if (const auto *FWD =
441 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
442 // Skip all forwad declarations which appear after moved class declaration.
443 if (RemovedDecls.empty())
444 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
445 } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>(
446 "decls_in_anonymous_ns")) {
447 MovedDecls.emplace_back(FD, &Result.Context->getSourceManager());
448 } else if (const auto *ND =
449 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
450 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
451 }
452}
453
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000454void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader,
455 bool IsAngled,
456 llvm::StringRef SearchPath,
457 llvm::StringRef FileName,
458 const SourceManager& SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000459 SmallVector<char, 128> HeaderWithSearchPath;
460 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
461 std::string AbsoluteOldHeader =
462 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000463 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
464 // old.h/c. For instance, when moved class uses another class defined in
465 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000466 if (AbsoluteOldHeader ==
467 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
468 HeaderWithSearchPath.size())))
Haojian Wudaf4cb82016-09-23 13:28:38 +0000469 return;
470
471 std::string IncludeLine =
472 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
473 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000474
Haojian Wudb726572016-10-12 15:50:30 +0000475 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
476 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000477 HeaderIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000478 } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) ==
Haojian Wudb726572016-10-12 15:50:30 +0000479 AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000480 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000481 }
Haojian Wu357ef992016-09-21 13:18:19 +0000482}
483
484void ClangMoveTool::removeClassDefinitionInOldFiles() {
485 for (const auto &MovedDecl : RemovedDecls) {
Haojian Wu253d5962016-10-06 08:29:32 +0000486 const auto &SM = *MovedDecl.SM;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000487 auto Range = GetFullRange(&SM, MovedDecl.Decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000488 clang::tooling::Replacement RemoveReplacement(
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000489 *MovedDecl.SM, clang::CharSourceRange::getCharRange(
490 Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000491 "");
492 std::string FilePath = RemoveReplacement.getFilePath().str();
493 addOrMergeReplacement(RemoveReplacement, &FileToReplacements[FilePath]);
Haojian Wu253d5962016-10-06 08:29:32 +0000494
495 llvm::StringRef Code =
496 SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation()));
497 format::FormatStyle Style =
498 format::getStyle("file", FilePath, FallbackStyle);
499 auto CleanReplacements = format::cleanupAroundReplacements(
500 Code, FileToReplacements[FilePath], Style);
501
502 if (!CleanReplacements) {
503 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
504 continue;
505 }
506 FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000507 }
508}
509
510void ClangMoveTool::moveClassDefinitionToNewFiles() {
511 std::vector<MovedDecl> NewHeaderDecls;
512 std::vector<MovedDecl> NewCCDecls;
513 for (const auto &MovedDecl : MovedDecls) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000514 if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory,
515 Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000516 NewHeaderDecls.push_back(MovedDecl);
517 else
518 NewCCDecls.push_back(MovedDecl);
519 }
520
521 if (!Spec.NewHeader.empty())
522 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
Haojian Wu220c7552016-10-14 13:01:36 +0000523 HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true);
Haojian Wu357ef992016-09-21 13:18:19 +0000524 if (!Spec.NewCC.empty())
525 FileToReplacements[Spec.NewCC] =
526 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
527}
528
529void ClangMoveTool::onEndOfTranslationUnit() {
530 if (RemovedDecls.empty())
531 return;
532 removeClassDefinitionInOldFiles();
533 moveClassDefinitionToNewFiles();
534}
535
536} // namespace move
537} // namespace clang