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