blob: a741f559ece66ca340aa9db2bac3c80691e5575c [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 Wue77bcc72016-10-13 10:31:00 +000027AST_MATCHER_P(Decl, hasOutermostEnclosingClass,
28 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
29 const auto* Context = Node.getDeclContext();
30 if (!Context) return false;
31 while (const auto *NextContext = Context->getParent()) {
32 if (isa<NamespaceDecl>(NextContext) ||
33 isa<TranslationUnitDecl>(NextContext))
34 break;
35 Context = NextContext;
36 }
37 return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder,
38 Builder);
39}
40
41AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass,
42 ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) {
43 const CXXRecordDecl *Parent = Node.getParent();
44 if (!Parent) return false;
45 while (const auto *NextParent =
46 dyn_cast<CXXRecordDecl>(Parent->getParent())) {
47 Parent = NextParent;
48 }
49
50 return InnerMatcher.matches(*Parent, Finder, Builder);
51}
52
Haojian Wud2a6d7b2016-10-04 09:05:31 +000053// Make the Path absolute using the CurrentDir if the Path is not an absolute
54// path. An empty Path will result in an empty string.
55std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) {
56 if (Path.empty())
57 return "";
58 llvm::SmallString<128> InitialDirectory(CurrentDir);
59 llvm::SmallString<128> AbsolutePath(Path);
60 if (std::error_code EC =
61 llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath))
62 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
63 << '\n';
64 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wuc6f125e2016-10-04 09:49:20 +000065 llvm::sys::path::native(AbsolutePath);
Haojian Wud2a6d7b2016-10-04 09:05:31 +000066 return AbsolutePath.str();
67}
68
69// Make the Path absolute using the current working directory of the given
70// SourceManager if the Path is not an absolute path.
71//
72// The Path can be a path relative to the build directory, or retrieved from
73// the SourceManager.
74std::string MakeAbsolutePath(const SourceManager& SM, StringRef Path) {
75 llvm::SmallString<128> AbsolutePath(Path);
76 if (std::error_code EC =
77 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(AbsolutePath))
78 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
79 << '\n';
Haojian Wudb726572016-10-12 15:50:30 +000080 // Handle symbolic link path cases.
81 // We are trying to get the real file path of the symlink.
82 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
83 llvm::sys::path::parent_path(AbsolutePath.str()));
84 if (Dir) {
85 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
86 SmallVector<char, 128> AbsoluteFilename;
87 llvm::sys::path::append(AbsoluteFilename, DirName,
88 llvm::sys::path::filename(AbsolutePath.str()));
89 return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size())
90 .str();
91 }
Haojian Wud2a6d7b2016-10-04 09:05:31 +000092 return AbsolutePath.str();
93}
94
95// Matches AST nodes that are expanded within the given AbsoluteFilePath.
96AST_POLYMORPHIC_MATCHER_P(isExpansionInFile,
97 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
98 std::string, AbsoluteFilePath) {
99 auto &SourceManager = Finder->getASTContext().getSourceManager();
100 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
101 if (ExpansionLoc.isInvalid())
102 return false;
103 auto FileEntry =
104 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
105 if (!FileEntry)
106 return false;
107 return MakeAbsolutePath(SourceManager, FileEntry->getName()) ==
108 AbsoluteFilePath;
109}
110
Haojian Wu357ef992016-09-21 13:18:19 +0000111class FindAllIncludes : public clang::PPCallbacks {
112public:
113 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
114 : SM(*SM), MoveTool(MoveTool) {}
115
116 void InclusionDirective(clang::SourceLocation HashLoc,
117 const clang::Token & /*IncludeTok*/,
118 StringRef FileName, bool IsAngled,
119 clang::CharSourceRange /*FilenameRange*/,
120 const clang::FileEntry * /*File*/,
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000121 StringRef SearchPath, StringRef /*RelativePath*/,
Haojian Wu357ef992016-09-21 13:18:19 +0000122 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000123 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000124 MoveTool->addIncludes(FileName, IsAngled, SearchPath,
125 FileEntry->getName(), SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000126 }
127
128private:
129 const SourceManager &SM;
130 ClangMoveTool *const MoveTool;
131};
132
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000133// Expand to get the end location of the line where the EndLoc of the given
134// Decl.
135SourceLocation
136getLocForEndOfDecl(const clang::Decl *D, const SourceManager *SM,
137 const LangOptions &LangOpts = clang::LangOptions()) {
138 std::pair<FileID, unsigned> LocInfo = SM->getDecomposedLoc(D->getLocEnd());
139 // Try to load the file buffer.
140 bool InvalidTemp = false;
141 llvm::StringRef File = SM->getBufferData(LocInfo.first, &InvalidTemp);
142 if (InvalidTemp)
143 return SourceLocation();
144
145 const char *TokBegin = File.data() + LocInfo.second;
146 // Lex from the start of the given location.
147 Lexer Lex(SM->getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
148 TokBegin, File.end());
149
150 llvm::SmallVector<char, 16> Line;
151 // FIXME: this is a bit hacky to get ReadToEndOfLine work.
152 Lex.setParsingPreprocessorDirective(true);
153 Lex.ReadToEndOfLine(&Line);
154 SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size());
155 // If we already reach EOF, just return the EOF SourceLocation;
156 // otherwise, move 1 offset ahead to include the trailing newline character
157 // '\n'.
158 return SM->getLocForEndOfFile(LocInfo.first) == EndLoc
159 ? EndLoc
160 : EndLoc.getLocWithOffset(1);
161}
162
163// Get full range of a Decl including the comments associated with it.
164clang::CharSourceRange
165GetFullRange(const clang::SourceManager *SM, const clang::Decl *D,
166 const clang::LangOptions &options = clang::LangOptions()) {
167 clang::SourceRange Full = D->getSourceRange();
168 Full.setEnd(getLocForEndOfDecl(D, SM));
169 // Expand to comments that are associated with the Decl.
170 if (const auto* Comment =
171 D->getASTContext().getRawCommentForDeclNoCache(D)) {
172 if (SM->isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd()))
173 Full.setEnd(Comment->getLocEnd());
174 // FIXME: Don't delete a preceding comment, if there are no other entities
175 // it could refer to.
176 if (SM->isBeforeInTranslationUnit(Comment->getLocStart(),
177 Full.getBegin()))
178 Full.setBegin(Comment->getLocStart());
179 }
180
181 return clang::CharSourceRange::getCharRange(Full);
182}
183
184std::string getDeclarationSourceText(const clang::Decl *D,
185 const clang::SourceManager *SM) {
186 llvm::StringRef SourceText = clang::Lexer::getSourceText(
187 GetFullRange(SM, D), *SM, clang::LangOptions());
188 return SourceText.str();
189}
190
Haojian Wu357ef992016-09-21 13:18:19 +0000191clang::tooling::Replacement
192getReplacementInChangedCode(const clang::tooling::Replacements &Replacements,
193 const clang::tooling::Replacement &Replacement) {
194 unsigned Start = Replacements.getShiftedCodePosition(Replacement.getOffset());
195 unsigned End = Replacements.getShiftedCodePosition(Replacement.getOffset() +
196 Replacement.getLength());
197 return clang::tooling::Replacement(Replacement.getFilePath(), Start,
198 End - Start,
199 Replacement.getReplacementText());
200}
201
202void addOrMergeReplacement(const clang::tooling::Replacement &Replacement,
203 clang::tooling::Replacements *Replacements) {
204 auto Err = Replacements->add(Replacement);
205 if (Err) {
206 llvm::consumeError(std::move(Err));
207 auto Replace = getReplacementInChangedCode(*Replacements, Replacement);
208 *Replacements = Replacements->merge(clang::tooling::Replacements(Replace));
209 }
210}
211
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000212bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D,
213 llvm::StringRef OriginalRunningDirectory,
214 llvm::StringRef OldHeader) {
215 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000216 return false;
217 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
218 if (ExpansionLoc.isInvalid())
219 return false;
220
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000221 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
222 return MakeAbsolutePath(SM, FE->getName()) ==
223 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
224 }
Haojian Wu357ef992016-09-21 13:18:19 +0000225
226 return false;
227}
228
229std::vector<std::string> GetNamespaces(const clang::Decl *D) {
230 std::vector<std::string> Namespaces;
231 for (const auto *Context = D->getDeclContext(); Context;
232 Context = Context->getParent()) {
233 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
234 llvm::isa<clang::LinkageSpecDecl>(Context))
235 break;
236
237 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
238 Namespaces.push_back(ND->getName().str());
239 }
240 std::reverse(Namespaces.begin(), Namespaces.end());
241 return Namespaces;
242}
243
Haojian Wu357ef992016-09-21 13:18:19 +0000244clang::tooling::Replacements
245createInsertedReplacements(const std::vector<std::string> &Includes,
246 const std::vector<ClangMoveTool::MovedDecl> &Decls,
247 llvm::StringRef FileName) {
248 clang::tooling::Replacements InsertedReplacements;
249
250 // Add #Includes.
251 std::string AllIncludesString;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000252 // FIXME: Add header guard.
Haojian Wu357ef992016-09-21 13:18:19 +0000253 for (const auto &Include : Includes)
254 AllIncludesString += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000255
256 if (!AllIncludesString.empty()) {
257 clang::tooling::Replacement InsertInclude(FileName, 0, 0,
258 AllIncludesString + "\n");
259 addOrMergeReplacement(InsertInclude, &InsertedReplacements);
260 }
Haojian Wu357ef992016-09-21 13:18:19 +0000261
262 // Add moved class definition and its related declarations. All declarations
263 // in same namespace are grouped together.
264 std::vector<std::string> CurrentNamespaces;
265 for (const auto &MovedDecl : Decls) {
266 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
267 auto CurrentIt = CurrentNamespaces.begin();
268 auto DeclIt = DeclNamespaces.begin();
269 while (CurrentIt != CurrentNamespaces.end() &&
270 DeclIt != DeclNamespaces.end()) {
271 if (*CurrentIt != *DeclIt)
272 break;
273 ++CurrentIt;
274 ++DeclIt;
275 }
276 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
277 CurrentIt);
278 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
279 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
280 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
281 --RemainingSize, ++It) {
282 assert(It < CurrentNamespaces.rend());
283 auto code = "} // namespace " + *It + "\n";
284 clang::tooling::Replacement InsertedReplacement(FileName, 0, 0, code);
285 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
286 }
287 while (DeclIt != DeclNamespaces.end()) {
288 clang::tooling::Replacement InsertedReplacement(
289 FileName, 0, 0, "namespace " + *DeclIt + " {\n");
290 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
291 ++DeclIt;
292 }
293
Haojian Wu357ef992016-09-21 13:18:19 +0000294 clang::tooling::Replacement InsertedReplacement(
295 FileName, 0, 0, getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM));
296 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
297
298 CurrentNamespaces = std::move(NextNamespaces);
299 }
300 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
301 for (const auto &NS : CurrentNamespaces) {
302 clang::tooling::Replacement InsertedReplacement(
303 FileName, 0, 0, "} // namespace " + NS + "\n");
304 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
305 }
306 return InsertedReplacements;
307}
308
309} // namespace
310
311std::unique_ptr<clang::ASTConsumer>
312ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
313 StringRef /*InFile*/) {
314 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
315 &Compiler.getSourceManager(), &MoveTool));
316 return MatchFinder.newASTConsumer();
317}
318
Haojian Wu357ef992016-09-21 13:18:19 +0000319ClangMoveTool::ClangMoveTool(
Haojian Wu253d5962016-10-06 08:29:32 +0000320 const MoveDefinitionSpec &MoveSpec,
321 std::map<std::string, tooling::Replacements> &FileToReplacements,
322 llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle)
323 : Spec(MoveSpec), FileToReplacements(FileToReplacements),
324 OriginalRunningDirectory(OriginalRunningDirectory),
325 FallbackStyle(FallbackStyle) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000326 if (!Spec.NewHeader.empty())
327 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000328}
329
330void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000331 SmallVector<StringRef, 4> ClassNames;
332 llvm::StringRef(Spec.Names).split(ClassNames, ',');
333 Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames;
334 for (StringRef ClassName : ClassNames) {
335 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
336 const auto HasName = hasName(("::" + GlobalClassName).str());
337 InMovedClassNames =
338 InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName;
339 }
340 if (!InMovedClassNames) {
341 llvm::errs() << "No classes being moved.\n";
342 return;
343 }
344
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000345 auto InOldHeader = isExpansionInFile(
346 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader));
347 auto InOldCC = isExpansionInFile(
348 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000349 auto InOldFiles = anyOf(InOldHeader, InOldCC);
350 auto InMovedClass =
Haojian Wue77bcc72016-10-13 10:31:00 +0000351 hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames));
Haojian Wu357ef992016-09-21 13:18:19 +0000352
353 // Match moved class declarations.
354 auto MovedClass = cxxRecordDecl(
Haojian Wu9df3ac12016-10-13 08:48:42 +0000355 InOldFiles, *InMovedClassNames, isDefinition(),
Haojian Wu357ef992016-09-21 13:18:19 +0000356 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
357 Finder->addMatcher(MovedClass.bind("moved_class"), this);
358
359 // Match moved class methods (static methods included) which are defined
360 // outside moved class declaration.
Haojian Wue77bcc72016-10-13 10:31:00 +0000361 Finder->addMatcher(
362 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames),
363 isDefinition())
364 .bind("class_method"),
365 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000366
367 // Match static member variable definition of the moved class.
368 Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition())
369 .bind("class_static_var_decl"),
370 this);
371
372 auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous()));
373 // Match functions/variables definitions which are defined in anonymous
374 // namespace in old cc.
375 Finder->addMatcher(
376 namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
377 inAnonymousNamespace)
378 .bind("decls_in_anonymous_ns"),
379 this);
380
381 // Match static functions/variabale definitions in old cc.
382 Finder->addMatcher(
383 namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass),
Haojian Wuef247cb2016-09-27 08:01:04 +0000384 isStaticStorageClass(), InOldCC),
385 varDecl(isDefinition(), unless(InMovedClass),
386 isStaticStorageClass(), InOldCC)))
Haojian Wu357ef992016-09-21 13:18:19 +0000387 .bind("static_decls"),
388 this);
389
390 // Match forward declarations in old header.
391 Finder->addMatcher(
392 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader)
393 .bind("fwd_decl"),
394 this);
395}
396
397void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
398 if (const auto *CMD =
399 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) {
400 // Skip inline class methods. isInline() ast matcher doesn't ignore this
401 // case.
402 if (!CMD->isInlined()) {
403 MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager());
404 RemovedDecls.push_back(MovedDecls.back());
405 }
406 } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
407 "class_static_var_decl")) {
408 MovedDecls.emplace_back(VD, &Result.Context->getSourceManager());
409 RemovedDecls.push_back(MovedDecls.back());
410 } else if (const auto *class_decl =
411 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) {
412 MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager());
413 RemovedDecls.push_back(MovedDecls.back());
414 } else if (const auto *FWD =
415 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
416 // Skip all forwad declarations which appear after moved class declaration.
417 if (RemovedDecls.empty())
418 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
419 } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>(
420 "decls_in_anonymous_ns")) {
421 MovedDecls.emplace_back(FD, &Result.Context->getSourceManager());
422 } else if (const auto *ND =
423 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
424 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
425 }
426}
427
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000428void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader,
429 bool IsAngled,
430 llvm::StringRef SearchPath,
431 llvm::StringRef FileName,
432 const SourceManager& SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000433 SmallVector<char, 128> HeaderWithSearchPath;
434 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
435 std::string AbsoluteOldHeader =
436 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000437 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
438 // old.h/c. For instance, when moved class uses another class defined in
439 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000440 if (AbsoluteOldHeader ==
441 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
442 HeaderWithSearchPath.size())))
Haojian Wudaf4cb82016-09-23 13:28:38 +0000443 return;
444
445 std::string IncludeLine =
446 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
447 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000448
Haojian Wudb726572016-10-12 15:50:30 +0000449 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
450 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000451 HeaderIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000452 } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) ==
Haojian Wudb726572016-10-12 15:50:30 +0000453 AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000454 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000455 }
Haojian Wu357ef992016-09-21 13:18:19 +0000456}
457
458void ClangMoveTool::removeClassDefinitionInOldFiles() {
459 for (const auto &MovedDecl : RemovedDecls) {
Haojian Wu253d5962016-10-06 08:29:32 +0000460 const auto &SM = *MovedDecl.SM;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000461 auto Range = GetFullRange(&SM, MovedDecl.Decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000462 clang::tooling::Replacement RemoveReplacement(
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000463 *MovedDecl.SM, clang::CharSourceRange::getCharRange(
464 Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000465 "");
466 std::string FilePath = RemoveReplacement.getFilePath().str();
467 addOrMergeReplacement(RemoveReplacement, &FileToReplacements[FilePath]);
Haojian Wu253d5962016-10-06 08:29:32 +0000468
469 llvm::StringRef Code =
470 SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation()));
471 format::FormatStyle Style =
472 format::getStyle("file", FilePath, FallbackStyle);
473 auto CleanReplacements = format::cleanupAroundReplacements(
474 Code, FileToReplacements[FilePath], Style);
475
476 if (!CleanReplacements) {
477 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
478 continue;
479 }
480 FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000481 }
482}
483
484void ClangMoveTool::moveClassDefinitionToNewFiles() {
485 std::vector<MovedDecl> NewHeaderDecls;
486 std::vector<MovedDecl> NewCCDecls;
487 for (const auto &MovedDecl : MovedDecls) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000488 if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory,
489 Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000490 NewHeaderDecls.push_back(MovedDecl);
491 else
492 NewCCDecls.push_back(MovedDecl);
493 }
494
495 if (!Spec.NewHeader.empty())
496 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
497 HeaderIncludes, NewHeaderDecls, Spec.NewHeader);
498 if (!Spec.NewCC.empty())
499 FileToReplacements[Spec.NewCC] =
500 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
501}
502
503void ClangMoveTool::onEndOfTranslationUnit() {
504 if (RemovedDecls.empty())
505 return;
506 removeClassDefinitionInOldFiles();
507 moveClassDefinitionToNewFiles();
508}
509
510} // namespace move
511} // namespace clang