blob: 7f02bdcf2f2ebceb78b05473cdd1049380214ac1 [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"
19
20using namespace clang::ast_matchers;
21
22namespace clang {
23namespace move {
24namespace {
25
Haojian Wu357ef992016-09-21 13:18:19 +000026class FindAllIncludes : public clang::PPCallbacks {
27public:
28 explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool)
29 : SM(*SM), MoveTool(MoveTool) {}
30
31 void InclusionDirective(clang::SourceLocation HashLoc,
32 const clang::Token & /*IncludeTok*/,
33 StringRef FileName, bool IsAngled,
34 clang::CharSourceRange /*FilenameRange*/,
35 const clang::FileEntry * /*File*/,
36 StringRef /*SearchPath*/, StringRef /*RelativePath*/,
37 const clang::Module * /*Imported*/) override {
Haojian Wudaf4cb82016-09-23 13:28:38 +000038 if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc)))
39 MoveTool->addIncludes(FileName, IsAngled, FileEntry->getName());
Haojian Wu357ef992016-09-21 13:18:19 +000040 }
41
42private:
43 const SourceManager &SM;
44 ClangMoveTool *const MoveTool;
45};
46
47clang::tooling::Replacement
48getReplacementInChangedCode(const clang::tooling::Replacements &Replacements,
49 const clang::tooling::Replacement &Replacement) {
50 unsigned Start = Replacements.getShiftedCodePosition(Replacement.getOffset());
51 unsigned End = Replacements.getShiftedCodePosition(Replacement.getOffset() +
52 Replacement.getLength());
53 return clang::tooling::Replacement(Replacement.getFilePath(), Start,
54 End - Start,
55 Replacement.getReplacementText());
56}
57
58void addOrMergeReplacement(const clang::tooling::Replacement &Replacement,
59 clang::tooling::Replacements *Replacements) {
60 auto Err = Replacements->add(Replacement);
61 if (Err) {
62 llvm::consumeError(std::move(Err));
63 auto Replace = getReplacementInChangedCode(*Replacements, Replacement);
64 *Replacements = Replacements->merge(clang::tooling::Replacements(Replace));
65 }
66}
67
68bool IsInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D,
69 llvm::StringRef HeaderFile) {
70 if (HeaderFile.empty())
71 return false;
72 auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart());
73 if (ExpansionLoc.isInvalid())
74 return false;
75
76 if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc)))
77 return llvm::StringRef(FE->getName()).endswith(HeaderFile);
78
79 return false;
80}
81
82std::vector<std::string> GetNamespaces(const clang::Decl *D) {
83 std::vector<std::string> Namespaces;
84 for (const auto *Context = D->getDeclContext(); Context;
85 Context = Context->getParent()) {
86 if (llvm::isa<clang::TranslationUnitDecl>(Context) ||
87 llvm::isa<clang::LinkageSpecDecl>(Context))
88 break;
89
90 if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context))
91 Namespaces.push_back(ND->getName().str());
92 }
93 std::reverse(Namespaces.begin(), Namespaces.end());
94 return Namespaces;
95}
96
97SourceLocation getLocForEndOfDecl(const clang::Decl *D,
98 const clang::SourceManager *SM) {
99 auto End = D->getLocEnd();
100 clang::SourceLocation AfterSemi = clang::Lexer::findLocationAfterToken(
101 End, clang::tok::semi, *SM, clang::LangOptions(),
102 /*SkipTrailingWhitespaceAndNewLine=*/true);
103 if (AfterSemi.isValid())
104 End = AfterSemi.getLocWithOffset(-1);
105 return End;
106}
107
108std::string getDeclarationSourceText(const clang::Decl *D,
109 const clang::SourceManager *SM) {
110 auto EndLoc = getLocForEndOfDecl(D, SM);
111 llvm::StringRef SourceText = clang::Lexer::getSourceText(
112 clang::CharSourceRange::getTokenRange(D->getLocStart(), EndLoc), *SM,
113 clang::LangOptions());
114 return SourceText.str() + "\n";
115}
116
117clang::tooling::Replacements
118createInsertedReplacements(const std::vector<std::string> &Includes,
119 const std::vector<ClangMoveTool::MovedDecl> &Decls,
120 llvm::StringRef FileName) {
121 clang::tooling::Replacements InsertedReplacements;
122
123 // Add #Includes.
124 std::string AllIncludesString;
Haojian Wudaf4cb82016-09-23 13:28:38 +0000125 // FIXME: Add header guard.
Haojian Wu357ef992016-09-21 13:18:19 +0000126 for (const auto &Include : Includes)
127 AllIncludesString += Include;
128 clang::tooling::Replacement InsertInclude(FileName, 0, 0, AllIncludesString);
129 addOrMergeReplacement(InsertInclude, &InsertedReplacements);
130
131 // Add moved class definition and its related declarations. All declarations
132 // in same namespace are grouped together.
133 std::vector<std::string> CurrentNamespaces;
134 for (const auto &MovedDecl : Decls) {
135 std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl);
136 auto CurrentIt = CurrentNamespaces.begin();
137 auto DeclIt = DeclNamespaces.begin();
138 while (CurrentIt != CurrentNamespaces.end() &&
139 DeclIt != DeclNamespaces.end()) {
140 if (*CurrentIt != *DeclIt)
141 break;
142 ++CurrentIt;
143 ++DeclIt;
144 }
145 std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(),
146 CurrentIt);
147 NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end());
148 auto RemainingSize = CurrentNamespaces.end() - CurrentIt;
149 for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0;
150 --RemainingSize, ++It) {
151 assert(It < CurrentNamespaces.rend());
152 auto code = "} // namespace " + *It + "\n";
153 clang::tooling::Replacement InsertedReplacement(FileName, 0, 0, code);
154 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
155 }
156 while (DeclIt != DeclNamespaces.end()) {
157 clang::tooling::Replacement InsertedReplacement(
158 FileName, 0, 0, "namespace " + *DeclIt + " {\n");
159 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
160 ++DeclIt;
161 }
162
163 // FIXME: consider moving comments of the moved declaration.
164 clang::tooling::Replacement InsertedReplacement(
165 FileName, 0, 0, getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM));
166 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
167
168 CurrentNamespaces = std::move(NextNamespaces);
169 }
170 std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end());
171 for (const auto &NS : CurrentNamespaces) {
172 clang::tooling::Replacement InsertedReplacement(
173 FileName, 0, 0, "} // namespace " + NS + "\n");
174 addOrMergeReplacement(InsertedReplacement, &InsertedReplacements);
175 }
176 return InsertedReplacements;
177}
178
179} // namespace
180
181std::unique_ptr<clang::ASTConsumer>
182ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler,
183 StringRef /*InFile*/) {
184 Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>(
185 &Compiler.getSourceManager(), &MoveTool));
186 return MatchFinder.newASTConsumer();
187}
188
189
190ClangMoveTool::ClangMoveTool(
191 const MoveDefinitionSpec &MoveSpec,
192 std::map<std::string, tooling::Replacements> &FileToReplacements)
193 : Spec(MoveSpec), FileToReplacements(FileToReplacements) {
194 Spec.Name = llvm::StringRef(Spec.Name).ltrim(':');
Haojian Wudaf4cb82016-09-23 13:28:38 +0000195 if (!Spec.NewHeader.empty())
196 CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n");
Haojian Wu357ef992016-09-21 13:18:19 +0000197}
198
199void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
200 std::string FullyQualifiedName = "::" + Spec.Name;
201 auto InOldHeader = isExpansionInFileMatching(Spec.OldHeader);
202 auto InOldCC = isExpansionInFileMatching(Spec.OldCC);
203 auto InOldFiles = anyOf(InOldHeader, InOldCC);
204 auto InMovedClass =
205 hasDeclContext(cxxRecordDecl(hasName(FullyQualifiedName)));
206
207 // Match moved class declarations.
208 auto MovedClass = cxxRecordDecl(
209 InOldFiles, hasName(FullyQualifiedName), isDefinition(),
210 hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
211 Finder->addMatcher(MovedClass.bind("moved_class"), this);
212
213 // Match moved class methods (static methods included) which are defined
214 // outside moved class declaration.
215 Finder->addMatcher(cxxMethodDecl(InOldFiles,
216 ofClass(hasName(FullyQualifiedName)),
217 isDefinition())
218 .bind("class_method"),
219 this);
220
221 // Match static member variable definition of the moved class.
222 Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition())
223 .bind("class_static_var_decl"),
224 this);
225
226 auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous()));
227 // Match functions/variables definitions which are defined in anonymous
228 // namespace in old cc.
229 Finder->addMatcher(
230 namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())),
231 inAnonymousNamespace)
232 .bind("decls_in_anonymous_ns"),
233 this);
234
235 // Match static functions/variabale definitions in old cc.
236 Finder->addMatcher(
237 namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass),
Haojian Wuef247cb2016-09-27 08:01:04 +0000238 isStaticStorageClass(), InOldCC),
239 varDecl(isDefinition(), unless(InMovedClass),
240 isStaticStorageClass(), InOldCC)))
Haojian Wu357ef992016-09-21 13:18:19 +0000241 .bind("static_decls"),
242 this);
243
244 // Match forward declarations in old header.
245 Finder->addMatcher(
246 cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader)
247 .bind("fwd_decl"),
248 this);
249}
250
251void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) {
252 if (const auto *CMD =
253 Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) {
254 // Skip inline class methods. isInline() ast matcher doesn't ignore this
255 // case.
256 if (!CMD->isInlined()) {
257 MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager());
258 RemovedDecls.push_back(MovedDecls.back());
259 }
260 } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>(
261 "class_static_var_decl")) {
262 MovedDecls.emplace_back(VD, &Result.Context->getSourceManager());
263 RemovedDecls.push_back(MovedDecls.back());
264 } else if (const auto *class_decl =
265 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) {
266 MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager());
267 RemovedDecls.push_back(MovedDecls.back());
268 } else if (const auto *FWD =
269 Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) {
270 // Skip all forwad declarations which appear after moved class declaration.
271 if (RemovedDecls.empty())
272 MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager());
273 } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>(
274 "decls_in_anonymous_ns")) {
275 MovedDecls.emplace_back(FD, &Result.Context->getSourceManager());
276 } else if (const auto *ND =
277 Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) {
278 MovedDecls.emplace_back(ND, &Result.Context->getSourceManager());
279 }
280}
281
Haojian Wudaf4cb82016-09-23 13:28:38 +0000282void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled,
Haojian Wu357ef992016-09-21 13:18:19 +0000283 llvm::StringRef FileName) {
Haojian Wudaf4cb82016-09-23 13:28:38 +0000284 // FIXME: Add old.h to the new.cc/h when the new target has dependencies on
285 // old.h/c. For instance, when moved class uses another class defined in
286 // old.h, the old.h should be added in new.h.
287 if (!Spec.OldHeader.empty() &&
288 llvm::StringRef(Spec.OldHeader).endswith(IncludeHeader))
289 return;
290
291 std::string IncludeLine =
292 IsAngled ? ("#include <" + IncludeHeader + ">\n").str()
293 : ("#include \"" + IncludeHeader + "\"\n").str();
Haojian Wu357ef992016-09-21 13:18:19 +0000294 if (!Spec.OldHeader.empty() && FileName.endswith(Spec.OldHeader))
Haojian Wudaf4cb82016-09-23 13:28:38 +0000295 HeaderIncludes.push_back(IncludeLine);
Haojian Wu357ef992016-09-21 13:18:19 +0000296 else if (!Spec.OldCC.empty() && FileName.endswith(Spec.OldCC))
Haojian Wudaf4cb82016-09-23 13:28:38 +0000297 CCIncludes.push_back(IncludeLine);
Haojian Wu357ef992016-09-21 13:18:19 +0000298}
299
300void ClangMoveTool::removeClassDefinitionInOldFiles() {
301 for (const auto &MovedDecl : RemovedDecls) {
302 auto EndLoc = getLocForEndOfDecl(MovedDecl.Decl, MovedDecl.SM);
303 clang::tooling::Replacement RemoveReplacement(
304 *MovedDecl.SM, clang::CharSourceRange::getTokenRange(
305 MovedDecl.Decl->getLocStart(), EndLoc),
306 "");
307 std::string FilePath = RemoveReplacement.getFilePath().str();
308 addOrMergeReplacement(RemoveReplacement, &FileToReplacements[FilePath]);
309 }
310}
311
312void ClangMoveTool::moveClassDefinitionToNewFiles() {
313 std::vector<MovedDecl> NewHeaderDecls;
314 std::vector<MovedDecl> NewCCDecls;
315 for (const auto &MovedDecl : MovedDecls) {
316 if (IsInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, Spec.OldHeader))
317 NewHeaderDecls.push_back(MovedDecl);
318 else
319 NewCCDecls.push_back(MovedDecl);
320 }
321
322 if (!Spec.NewHeader.empty())
323 FileToReplacements[Spec.NewHeader] = createInsertedReplacements(
324 HeaderIncludes, NewHeaderDecls, Spec.NewHeader);
325 if (!Spec.NewCC.empty())
326 FileToReplacements[Spec.NewCC] =
327 createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC);
328}
329
330void ClangMoveTool::onEndOfTranslationUnit() {
331 if (RemovedDecls.empty())
332 return;
333 removeClassDefinitionInOldFiles();
334 moveClassDefinitionToNewFiles();
335}
336
337} // namespace move
338} // namespace clang