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" |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 19 | #include "llvm/Support/Path.h" |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 20 | |
| 21 | using namespace clang::ast_matchers; |
| 22 | |
| 23 | namespace clang { |
| 24 | namespace move { |
| 25 | namespace { |
| 26 | |
Haojian Wu | 7bd492c | 2016-10-14 10:07:58 +0000 | [diff] [blame] | 27 | // FIXME: Move to ASTMatchers. |
| 28 | AST_MATCHER(VarDecl, isStaticDataMember) { |
| 29 | return Node.isStaticDataMember(); |
| 30 | } |
| 31 | |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 32 | AST_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 | |
| 46 | AST_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 Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 58 | // 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. |
| 60 | std::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 Wu | c6f125e | 2016-10-04 09:49:20 +0000 | [diff] [blame] | 70 | llvm::sys::path::native(AbsolutePath); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 71 | 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. |
| 79 | std::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 Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 85 | // 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 Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 97 | return AbsolutePath.str(); |
| 98 | } |
| 99 | |
| 100 | // Matches AST nodes that are expanded within the given AbsoluteFilePath. |
| 101 | AST_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 Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 116 | class FindAllIncludes : public clang::PPCallbacks { |
| 117 | public: |
| 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 Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 126 | StringRef SearchPath, StringRef /*RelativePath*/, |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 127 | const clang::Module * /*Imported*/) override { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 128 | if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc))) |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 129 | MoveTool->addIncludes(FileName, IsAngled, SearchPath, |
| 130 | FileEntry->getName(), SM); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 131 | } |
| 132 | |
| 133 | private: |
| 134 | const SourceManager &SM; |
| 135 | ClangMoveTool *const MoveTool; |
| 136 | }; |
| 137 | |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 138 | // Expand to get the end location of the line where the EndLoc of the given |
| 139 | // Decl. |
| 140 | SourceLocation |
| 141 | getLocForEndOfDecl(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. |
| 169 | clang::CharSourceRange |
| 170 | GetFullRange(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 | |
| 189 | std::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 Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 196 | bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D, |
| 197 | llvm::StringRef OriginalRunningDirectory, |
| 198 | llvm::StringRef OldHeader) { |
| 199 | if (OldHeader.empty()) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 200 | return false; |
| 201 | auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart()); |
| 202 | if (ExpansionLoc.isInvalid()) |
| 203 | return false; |
| 204 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 205 | if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) { |
| 206 | return MakeAbsolutePath(SM, FE->getName()) == |
| 207 | MakeAbsolutePath(OriginalRunningDirectory, OldHeader); |
| 208 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 209 | |
| 210 | return false; |
| 211 | } |
| 212 | |
| 213 | std::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 Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 228 | clang::tooling::Replacements |
| 229 | createInsertedReplacements(const std::vector<std::string> &Includes, |
| 230 | const std::vector<ClangMoveTool::MovedDecl> &Decls, |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 231 | llvm::StringRef FileName, |
| 232 | bool IsHeader = false) { |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 233 | std::string NewCode; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 234 | std::string GuardName(FileName); |
| 235 | if (IsHeader) { |
Haojian Wu | ac97fc3 | 2016-10-17 15:26:34 +0000 | [diff] [blame] | 236 | for (size_t i = 0; i < GuardName.size(); ++i) { |
| 237 | if (!isAlphanumeric(GuardName[i])) |
| 238 | GuardName[i] = '_'; |
| 239 | } |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 240 | GuardName = StringRef(GuardName).upper(); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 241 | NewCode += "#ifndef " + GuardName + "\n"; |
| 242 | NewCode += "#define " + GuardName + "\n"; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 243 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 244 | |
| 245 | // Add #Includes. |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 246 | for (const auto &Include : Includes) |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 247 | NewCode += Include; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 248 | |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 249 | if (!Includes.empty()) |
| 250 | NewCode += "\n"; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 251 | |
| 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 Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 273 | NewCode += "} // namespace " + *It + "\n"; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 274 | } |
| 275 | while (DeclIt != DeclNamespaces.end()) { |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 276 | NewCode += "namespace " + *DeclIt + " {\n"; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 277 | ++DeclIt; |
| 278 | } |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 279 | NewCode += getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 280 | CurrentNamespaces = std::move(NextNamespaces); |
| 281 | } |
| 282 | std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end()); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 283 | for (const auto &NS : CurrentNamespaces) |
| 284 | NewCode += "} // namespace " + NS + "\n"; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 285 | |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 286 | if (IsHeader) |
| 287 | NewCode += "#endif // " + GuardName + "\n"; |
| 288 | return clang::tooling::Replacements( |
| 289 | clang::tooling::Replacement(FileName, 0, 0, NewCode)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 290 | } |
| 291 | |
| 292 | } // namespace |
| 293 | |
| 294 | std::unique_ptr<clang::ASTConsumer> |
| 295 | ClangMoveAction::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 Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 302 | ClangMoveTool::ClangMoveTool( |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 303 | 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 Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 309 | if (!Spec.NewHeader.empty()) |
| 310 | CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n"); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 311 | } |
| 312 | |
| 313 | void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) { |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 314 | Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames; |
Alexander Shaposhnikov | 5fe0678 | 2016-10-14 23:16:25 +0000 | [diff] [blame] | 315 | for (StringRef ClassName : Spec.Names) { |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 316 | 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 Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 326 | auto InOldHeader = isExpansionInFile( |
| 327 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader)); |
| 328 | auto InOldCC = isExpansionInFile( |
| 329 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 330 | auto InOldFiles = anyOf(InOldHeader, InOldCC); |
| 331 | auto InMovedClass = |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 332 | hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 333 | |
| 334 | // Match moved class declarations. |
| 335 | auto MovedClass = cxxRecordDecl( |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 336 | InOldFiles, *InMovedClassNames, isDefinition(), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 337 | 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 Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 342 | Finder->addMatcher( |
| 343 | cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames), |
| 344 | isDefinition()) |
| 345 | .bind("class_method"), |
| 346 | this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 347 | |
| 348 | // Match static member variable definition of the moved class. |
Haojian Wu | 7bd492c | 2016-10-14 10:07:58 +0000 | [diff] [blame] | 349 | Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition(), |
| 350 | isStaticDataMember()) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 351 | .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 Wu | ef247cb | 2016-09-27 08:01:04 +0000 | [diff] [blame] | 366 | isStaticStorageClass(), InOldCC), |
| 367 | varDecl(isDefinition(), unless(InMovedClass), |
| 368 | isStaticStorageClass(), InOldCC))) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 369 | .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 | |
| 379 | void 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 Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 410 | void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, |
| 411 | bool IsAngled, |
| 412 | llvm::StringRef SearchPath, |
| 413 | llvm::StringRef FileName, |
| 414 | const SourceManager& SM) { |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 415 | SmallVector<char, 128> HeaderWithSearchPath; |
| 416 | llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader); |
| 417 | std::string AbsoluteOldHeader = |
| 418 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader); |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 419 | // 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 Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 422 | if (AbsoluteOldHeader == |
| 423 | MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(), |
| 424 | HeaderWithSearchPath.size()))) |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 425 | return; |
| 426 | |
| 427 | std::string IncludeLine = |
| 428 | IsAngled ? ("#include <" + IncludeHeader + ">\n").str() |
| 429 | : ("#include \"" + IncludeHeader + "\"\n").str(); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 430 | |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 431 | std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName); |
| 432 | if (AbsoluteOldHeader == AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 433 | HeaderIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 434 | } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) == |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 435 | AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 436 | CCIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 437 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 438 | } |
| 439 | |
| 440 | void ClangMoveTool::removeClassDefinitionInOldFiles() { |
| 441 | for (const auto &MovedDecl : RemovedDecls) { |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 442 | const auto &SM = *MovedDecl.SM; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 443 | auto Range = GetFullRange(&SM, MovedDecl.Decl); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 444 | clang::tooling::Replacement RemoveReplacement( |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 445 | *MovedDecl.SM, clang::CharSourceRange::getCharRange( |
| 446 | Range.getBegin(), Range.getEnd()), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 447 | ""); |
| 448 | std::string FilePath = RemoveReplacement.getFilePath().str(); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 449 | auto Err = FileToReplacements[FilePath].add(RemoveReplacement); |
| 450 | if (Err) { |
| 451 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; |
| 452 | continue; |
| 453 | } |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 454 | |
| 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 Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 467 | } |
| 468 | } |
| 469 | |
| 470 | void ClangMoveTool::moveClassDefinitionToNewFiles() { |
| 471 | std::vector<MovedDecl> NewHeaderDecls; |
| 472 | std::vector<MovedDecl> NewCCDecls; |
| 473 | for (const auto &MovedDecl : MovedDecls) { |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 474 | if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory, |
| 475 | Spec.OldHeader)) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 476 | NewHeaderDecls.push_back(MovedDecl); |
| 477 | else |
| 478 | NewCCDecls.push_back(MovedDecl); |
| 479 | } |
| 480 | |
| 481 | if (!Spec.NewHeader.empty()) |
| 482 | FileToReplacements[Spec.NewHeader] = createInsertedReplacements( |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 483 | HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 484 | if (!Spec.NewCC.empty()) |
| 485 | FileToReplacements[Spec.NewCC] = |
| 486 | createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC); |
| 487 | } |
| 488 | |
| 489 | void ClangMoveTool::onEndOfTranslationUnit() { |
| 490 | if (RemovedDecls.empty()) |
| 491 | return; |
| 492 | removeClassDefinitionInOldFiles(); |
| 493 | moveClassDefinitionToNewFiles(); |
| 494 | } |
| 495 | |
| 496 | } // namespace move |
| 497 | } // namespace clang |