blob: 268d31dc4b9da86bbdc31c1a6bd287bc00e24f13 [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 Wud2a6d7b2016-10-04 09:05:31 +0000196bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D,
197 llvm::StringRef OriginalRunningDirectory,
198 llvm::StringRef OldHeader) {
199 if (OldHeader.empty())
Haojian Wu357ef992016-09-21 13:18:19 +0000200 return false;
201 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
202 if (ExpansionLoc.isInvalid())
203 return false;
204
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000205 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) {
206 return MakeAbsolutePath(SM, FE->getName()) ==
207 MakeAbsolutePath(OriginalRunningDirectory, OldHeader);
208 }
Haojian Wu357ef992016-09-21 13:18:19 +0000209
210 return false;
211}
212
213std::vector<std::string> GetNamespaces(const clang::Decl *D) {
214 std::vector<std::string> Namespaces;
215 for (const auto *Context = D->getDeclContext(); Context;
216 Context = Context->getParent()) {
217 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
218 llvm::isa<clang::LinkageSpecDecl>(Context))
219 break;
220
221 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
222 Namespaces.push_back(ND->getName().str());
223 }
224 std::reverse(Namespaces.begin(), Namespaces.end());
225 return Namespaces;
226}
227
Haojian Wu357ef992016-09-21 13:18:19 +0000228clang::tooling::Replacements
229createInsertedReplacements(const std::vector<std::string> &Includes,
230 const std::vector<ClangMoveTool::MovedDecl> &Decls,
Haojian Wu220c7552016-10-14 13:01:36 +0000231 llvm::StringRef FileName,
232 bool IsHeader = false) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000233 std::string NewCode;
Haojian Wu220c7552016-10-14 13:01:36 +0000234 std::string GuardName(FileName);
235 if (IsHeader) {
Haojian Wuac97fc32016-10-17 15:26:34 +0000236 for (size_t i = 0; i < GuardName.size(); ++i) {
237 if (!isAlphanumeric(GuardName[i]))
238 GuardName[i] = '_';
239 }
Haojian Wu220c7552016-10-14 13:01:36 +0000240 GuardName = StringRef(GuardName).upper();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000241 NewCode += "#ifndef " + GuardName + "\n";
242 NewCode += "#define " + GuardName + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000243 }
Haojian Wu357ef992016-09-21 13:18:19 +0000244
245 // Add #Includes.
Haojian Wu357ef992016-09-21 13:18:19 +0000246 for (const auto &Include : Includes)
Haojian Wu53eab1e2016-10-14 13:43:49 +0000247 NewCode += Include;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000248
Haojian Wu53eab1e2016-10-14 13:43:49 +0000249 if (!Includes.empty())
250 NewCode += "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000251
252 // Add moved class definition and its related declarations. All declarations
253 // in same namespace are grouped together.
254 std::vector<std::string> CurrentNamespaces;
255 for (const auto &MovedDecl : Decls) {
256 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
257 auto CurrentIt = CurrentNamespaces.begin();
258 auto DeclIt = DeclNamespaces.begin();
259 while (CurrentIt != CurrentNamespaces.end() &&
260 DeclIt != DeclNamespaces.end()) {
261 if (*CurrentIt != *DeclIt)
262 break;
263 ++CurrentIt;
264 ++DeclIt;
265 }
266 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
267 CurrentIt);
268 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
269 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
270 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
271 --RemainingSize, ++It) {
272 assert(It < CurrentNamespaces.rend());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000273 NewCode += "} // namespace " + *It + "\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000274 }
275 while (DeclIt != DeclNamespaces.end()) {
Haojian Wu53eab1e2016-10-14 13:43:49 +0000276 NewCode += "namespace " + *DeclIt + " {\n";
Haojian Wu357ef992016-09-21 13:18:19 +0000277 ++DeclIt;
278 }
Haojian Wu53eab1e2016-10-14 13:43:49 +0000279 NewCode += getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM);
Haojian Wu357ef992016-09-21 13:18:19 +0000280 CurrentNamespaces = std::move(NextNamespaces);
281 }
282 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
Haojian Wu53eab1e2016-10-14 13:43:49 +0000283 for (const auto &NS : CurrentNamespaces)
284 NewCode += "} // namespace " + NS + "\n";
Haojian Wu220c7552016-10-14 13:01:36 +0000285
Haojian Wu53eab1e2016-10-14 13:43:49 +0000286 if (IsHeader)
287 NewCode += "#endif // " + GuardName + "\n";
288 return clang::tooling::Replacements(
289 clang::tooling::Replacement(FileName, 0, 0, NewCode));
Haojian Wu357ef992016-09-21 13:18:19 +0000290}
291
292} // namespace
293
294std::unique_ptr<clang::ASTConsumer>
295ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
296 StringRef /*InFile*/) {
297 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
298 &Compiler.getSourceManager(), &MoveTool));
299 return MatchFinder.newASTConsumer();
300}
301
Haojian Wu357ef992016-09-21 13:18:19 +0000302ClangMoveTool::ClangMoveTool(
Haojian Wu253d5962016-10-06 08:29:32 +0000303 const MoveDefinitionSpec &MoveSpec,
304 std::map<std::string, tooling::Replacements> &FileToReplacements,
305 llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle)
306 : Spec(MoveSpec), FileToReplacements(FileToReplacements),
307 OriginalRunningDirectory(OriginalRunningDirectory),
308 FallbackStyle(FallbackStyle) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000309 if (!Spec.NewHeader.empty())
310 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000311}
312
313void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000314 Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames;
Alexander Shaposhnikov5fe06782016-10-14 23:16:25 +0000315 for (StringRef ClassName : Spec.Names) {
Haojian Wu9df3ac12016-10-13 08:48:42 +0000316 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
317 const auto HasName = hasName(("::" + GlobalClassName).str());
318 InMovedClassNames =
319 InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName;
320 }
321 if (!InMovedClassNames) {
322 llvm::errs() << "No classes being moved.\n";
323 return;
324 }
325
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000326 auto InOldHeader = isExpansionInFile(
327 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader));
328 auto InOldCC = isExpansionInFile(
329 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC));
Haojian Wu357ef992016-09-21 13:18:19 +0000330 auto InOldFiles = anyOf(InOldHeader, InOldCC);
331 auto InMovedClass =
Haojian Wue77bcc72016-10-13 10:31:00 +0000332 hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames));
Haojian Wu357ef992016-09-21 13:18:19 +0000333
334 // Match moved class declarations.
335 auto MovedClass = cxxRecordDecl(
Haojian Wu9df3ac12016-10-13 08:48:42 +0000336 InOldFiles, *InMovedClassNames, isDefinition(),
Haojian Wu357ef992016-09-21 13:18:19 +0000337 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
338 Finder->addMatcher(MovedClass.bind("moved_class"), this);
339
340 // Match moved class methods (static methods included) which are defined
341 // outside moved class declaration.
Haojian Wue77bcc72016-10-13 10:31:00 +0000342 Finder->addMatcher(
343 cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames),
344 isDefinition())
345 .bind("class_method"),
346 this);
Haojian Wu357ef992016-09-21 13:18:19 +0000347
348 // Match static member variable definition of the moved class.
Haojian Wu7bd492c2016-10-14 10:07:58 +0000349 Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition(),
350 isStaticDataMember())
Haojian Wu357ef992016-09-21 13:18:19 +0000351 .bind("class_static_var_decl"),
352 this);
353
354 auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous()));
355 // Match functions/variables definitions which are defined in anonymous
356 // namespace in old cc.
357 Finder->addMatcher(
358 namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
359 inAnonymousNamespace)
360 .bind("decls_in_anonymous_ns"),
361 this);
362
363 // Match static functions/variabale definitions in old cc.
364 Finder->addMatcher(
365 namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass),
Haojian Wuef247cb2016-09-27 08:01:04 +0000366 isStaticStorageClass(), InOldCC),
367 varDecl(isDefinition(), unless(InMovedClass),
368 isStaticStorageClass(), InOldCC)))
Haojian Wu357ef992016-09-21 13:18:19 +0000369 .bind("static_decls"),
370 this);
371
372 // Match forward declarations in old header.
373 Finder->addMatcher(
374 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader)
375 .bind("fwd_decl"),
376 this);
377}
378
379void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
380 if (const auto *CMD =
381 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) {
382 // Skip inline class methods. isInline() ast matcher doesn't ignore this
383 // case.
384 if (!CMD->isInlined()) {
385 MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager());
386 RemovedDecls.push_back(MovedDecls.back());
387 }
388 } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
389 "class_static_var_decl")) {
390 MovedDecls.emplace_back(VD, &Result.Context->getSourceManager());
391 RemovedDecls.push_back(MovedDecls.back());
392 } else if (const auto *class_decl =
393 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) {
394 MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager());
395 RemovedDecls.push_back(MovedDecls.back());
396 } else if (const auto *FWD =
397 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
398 // Skip all forwad declarations which appear after moved class declaration.
399 if (RemovedDecls.empty())
400 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
401 } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>(
402 "decls_in_anonymous_ns")) {
403 MovedDecls.emplace_back(FD, &Result.Context->getSourceManager());
404 } else if (const auto *ND =
405 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
406 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
407 }
408}
409
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000410void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader,
411 bool IsAngled,
412 llvm::StringRef SearchPath,
413 llvm::StringRef FileName,
414 const SourceManager& SM) {
Haojian Wudb726572016-10-12 15:50:30 +0000415 SmallVector<char, 128> HeaderWithSearchPath;
416 llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader);
417 std::string AbsoluteOldHeader =
418 MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader);
Haojian Wudaf4cb82016-09-23 13:28:38 +0000419 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
420 // old.h/c. For instance, when moved class uses another class defined in
421 // old.h, the old.h should be added in new.h.
Haojian Wudb726572016-10-12 15:50:30 +0000422 if (AbsoluteOldHeader ==
423 MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(),
424 HeaderWithSearchPath.size())))
Haojian Wudaf4cb82016-09-23 13:28:38 +0000425 return;
426
427 std::string IncludeLine =
428 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
429 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000430
Haojian Wudb726572016-10-12 15:50:30 +0000431 std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName);
432 if (AbsoluteOldHeader == AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000433 HeaderIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000434 } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) ==
Haojian Wudb726572016-10-12 15:50:30 +0000435 AbsoluteCurrentFile) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000436 CCIncludes.push_back(IncludeLine);
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000437 }
Haojian Wu357ef992016-09-21 13:18:19 +0000438}
439
440void ClangMoveTool::removeClassDefinitionInOldFiles() {
441 for (const auto &MovedDecl : RemovedDecls) {
Haojian Wu253d5962016-10-06 08:29:32 +0000442 const auto &SM = *MovedDecl.SM;
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000443 auto Range = GetFullRange(&SM, MovedDecl.Decl);
Haojian Wu357ef992016-09-21 13:18:19 +0000444 clang::tooling::Replacement RemoveReplacement(
Haojian Wu9abbeaa2016-10-06 08:59:24 +0000445 *MovedDecl.SM, clang::CharSourceRange::getCharRange(
446 Range.getBegin(), Range.getEnd()),
Haojian Wu357ef992016-09-21 13:18:19 +0000447 "");
448 std::string FilePath = RemoveReplacement.getFilePath().str();
Haojian Wu53eab1e2016-10-14 13:43:49 +0000449 auto Err = FileToReplacements[FilePath].add(RemoveReplacement);
450 if (Err) {
451 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
452 continue;
453 }
Haojian Wu253d5962016-10-06 08:29:32 +0000454
455 llvm::StringRef Code =
456 SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation()));
457 format::FormatStyle Style =
458 format::getStyle("file", FilePath, FallbackStyle);
459 auto CleanReplacements = format::cleanupAroundReplacements(
460 Code, FileToReplacements[FilePath], Style);
461
462 if (!CleanReplacements) {
463 llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n";
464 continue;
465 }
466 FileToReplacements[FilePath] = *CleanReplacements;
Haojian Wu357ef992016-09-21 13:18:19 +0000467 }
468}
469
470void ClangMoveTool::moveClassDefinitionToNewFiles() {
471 std::vector<MovedDecl> NewHeaderDecls;
472 std::vector<MovedDecl> NewCCDecls;
473 for (const auto &MovedDecl : MovedDecls) {
Haojian Wud2a6d7b2016-10-04 09:05:31 +0000474 if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory,
475 Spec.OldHeader))
Haojian Wu357ef992016-09-21 13:18:19 +0000476 NewHeaderDecls.push_back(MovedDecl);
477 else
478 NewCCDecls.push_back(MovedDecl);
479 }
480
481 if (!Spec.NewHeader.empty())
482 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
Haojian Wu220c7552016-10-14 13:01:36 +0000483 HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true);
Haojian Wu357ef992016-09-21 13:18:19 +0000484 if (!Spec.NewCC.empty())
485 FileToReplacements[Spec.NewCC] =
486 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
487}
488
489void ClangMoveTool::onEndOfTranslationUnit() {
490 if (RemovedDecls.empty())
491 return;
492 removeClassDefinitionInOldFiles();
493 moveClassDefinitionToNewFiles();
494}
495
496} // namespace move
497} // namespace clang