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. |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 28 | AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); } |
Haojian Wu | 7bd492c | 2016-10-14 10:07:58 +0000 | [diff] [blame] | 29 | |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 30 | AST_MATCHER_P(Decl, hasOutermostEnclosingClass, |
| 31 | ast_matchers::internal::Matcher<Decl>, InnerMatcher) { |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 32 | const auto *Context = Node.getDeclContext(); |
| 33 | if (!Context) |
| 34 | return false; |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 35 | while (const auto *NextContext = Context->getParent()) { |
| 36 | if (isa<NamespaceDecl>(NextContext) || |
| 37 | isa<TranslationUnitDecl>(NextContext)) |
| 38 | break; |
| 39 | Context = NextContext; |
| 40 | } |
| 41 | return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder, |
| 42 | Builder); |
| 43 | } |
| 44 | |
| 45 | AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass, |
| 46 | ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) { |
| 47 | const CXXRecordDecl *Parent = Node.getParent(); |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 48 | if (!Parent) |
| 49 | return false; |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 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)) |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 67 | llvm::errs() << "Warning: could not make absolute file: '" << EC.message() |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 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. |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 79 | std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) { |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 80 | llvm::SmallString<128> AbsolutePath(Path); |
| 81 | if (std::error_code EC = |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 82 | SM.getFileManager().getVirtualFileSystem()->makeAbsolute( |
| 83 | AbsolutePath)) |
| 84 | llvm::errs() << "Warning: could not make absolute file: '" << EC.message() |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 85 | << '\n'; |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 86 | // Handle symbolic link path cases. |
| 87 | // We are trying to get the real file path of the symlink. |
| 88 | const DirectoryEntry *Dir = SM.getFileManager().getDirectory( |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 89 | llvm::sys::path::parent_path(AbsolutePath.str())); |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 90 | if (Dir) { |
| 91 | StringRef DirName = SM.getFileManager().getCanonicalName(Dir); |
| 92 | SmallVector<char, 128> AbsoluteFilename; |
| 93 | llvm::sys::path::append(AbsoluteFilename, DirName, |
| 94 | llvm::sys::path::filename(AbsolutePath.str())); |
| 95 | return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size()) |
| 96 | .str(); |
| 97 | } |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 98 | return AbsolutePath.str(); |
| 99 | } |
| 100 | |
| 101 | // Matches AST nodes that are expanded within the given AbsoluteFilePath. |
| 102 | AST_POLYMORPHIC_MATCHER_P(isExpansionInFile, |
| 103 | AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), |
| 104 | std::string, AbsoluteFilePath) { |
| 105 | auto &SourceManager = Finder->getASTContext().getSourceManager(); |
| 106 | auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart()); |
| 107 | if (ExpansionLoc.isInvalid()) |
| 108 | return false; |
| 109 | auto FileEntry = |
| 110 | SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc)); |
| 111 | if (!FileEntry) |
| 112 | return false; |
| 113 | return MakeAbsolutePath(SourceManager, FileEntry->getName()) == |
| 114 | AbsoluteFilePath; |
| 115 | } |
| 116 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 117 | class FindAllIncludes : public clang::PPCallbacks { |
| 118 | public: |
| 119 | explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool) |
| 120 | : SM(*SM), MoveTool(MoveTool) {} |
| 121 | |
| 122 | void InclusionDirective(clang::SourceLocation HashLoc, |
| 123 | const clang::Token & /*IncludeTok*/, |
| 124 | StringRef FileName, bool IsAngled, |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 125 | clang::CharSourceRange FilenameRange, |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 126 | const clang::FileEntry * /*File*/, |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 127 | StringRef SearchPath, StringRef /*RelativePath*/, |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 128 | const clang::Module * /*Imported*/) override { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 129 | if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc))) |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 130 | MoveTool->addIncludes(FileName, IsAngled, SearchPath, |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 131 | FileEntry->getName(), FilenameRange, SM); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 132 | } |
| 133 | |
| 134 | private: |
| 135 | const SourceManager &SM; |
| 136 | ClangMoveTool *const MoveTool; |
| 137 | }; |
| 138 | |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 139 | // Expand to get the end location of the line where the EndLoc of the given |
| 140 | // Decl. |
| 141 | SourceLocation |
| 142 | getLocForEndOfDecl(const clang::Decl *D, const SourceManager *SM, |
| 143 | const LangOptions &LangOpts = clang::LangOptions()) { |
| 144 | std::pair<FileID, unsigned> LocInfo = SM->getDecomposedLoc(D->getLocEnd()); |
| 145 | // Try to load the file buffer. |
| 146 | bool InvalidTemp = false; |
| 147 | llvm::StringRef File = SM->getBufferData(LocInfo.first, &InvalidTemp); |
| 148 | if (InvalidTemp) |
| 149 | return SourceLocation(); |
| 150 | |
| 151 | const char *TokBegin = File.data() + LocInfo.second; |
| 152 | // Lex from the start of the given location. |
| 153 | Lexer Lex(SM->getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(), |
| 154 | TokBegin, File.end()); |
| 155 | |
| 156 | llvm::SmallVector<char, 16> Line; |
| 157 | // FIXME: this is a bit hacky to get ReadToEndOfLine work. |
| 158 | Lex.setParsingPreprocessorDirective(true); |
| 159 | Lex.ReadToEndOfLine(&Line); |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 160 | SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size()); |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 161 | // If we already reach EOF, just return the EOF SourceLocation; |
| 162 | // otherwise, move 1 offset ahead to include the trailing newline character |
| 163 | // '\n'. |
| 164 | return SM->getLocForEndOfFile(LocInfo.first) == EndLoc |
| 165 | ? EndLoc |
| 166 | : EndLoc.getLocWithOffset(1); |
| 167 | } |
| 168 | |
| 169 | // Get full range of a Decl including the comments associated with it. |
| 170 | clang::CharSourceRange |
| 171 | GetFullRange(const clang::SourceManager *SM, const clang::Decl *D, |
| 172 | const clang::LangOptions &options = clang::LangOptions()) { |
| 173 | clang::SourceRange Full = D->getSourceRange(); |
| 174 | Full.setEnd(getLocForEndOfDecl(D, SM)); |
| 175 | // Expand to comments that are associated with the Decl. |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 176 | if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) { |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 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. |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 181 | if (SM->isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin())) |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 182 | Full.setBegin(Comment->getLocStart()); |
| 183 | } |
| 184 | |
| 185 | return clang::CharSourceRange::getCharRange(Full); |
| 186 | } |
| 187 | |
| 188 | std::string getDeclarationSourceText(const clang::Decl *D, |
| 189 | const clang::SourceManager *SM) { |
| 190 | llvm::StringRef SourceText = clang::Lexer::getSourceText( |
| 191 | GetFullRange(SM, D), *SM, clang::LangOptions()); |
| 192 | return SourceText.str(); |
| 193 | } |
| 194 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 195 | bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D, |
| 196 | llvm::StringRef OriginalRunningDirectory, |
| 197 | llvm::StringRef OldHeader) { |
| 198 | if (OldHeader.empty()) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 199 | return false; |
| 200 | auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart()); |
| 201 | if (ExpansionLoc.isInvalid()) |
| 202 | return false; |
| 203 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 204 | if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) { |
| 205 | return MakeAbsolutePath(SM, FE->getName()) == |
| 206 | MakeAbsolutePath(OriginalRunningDirectory, OldHeader); |
| 207 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 208 | |
| 209 | return false; |
| 210 | } |
| 211 | |
| 212 | std::vector<std::string> GetNamespaces(const clang::Decl *D) { |
| 213 | std::vector<std::string> Namespaces; |
| 214 | for (const auto *Context = D->getDeclContext(); Context; |
| 215 | Context = Context->getParent()) { |
| 216 | if (llvm::isa<clang::TranslationUnitDecl>(Context) || |
| 217 | llvm::isa<clang::LinkageSpecDecl>(Context)) |
| 218 | break; |
| 219 | |
| 220 | if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context)) |
| 221 | Namespaces.push_back(ND->getName().str()); |
| 222 | } |
| 223 | std::reverse(Namespaces.begin(), Namespaces.end()); |
| 224 | return Namespaces; |
| 225 | } |
| 226 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 227 | clang::tooling::Replacements |
| 228 | createInsertedReplacements(const std::vector<std::string> &Includes, |
| 229 | const std::vector<ClangMoveTool::MovedDecl> &Decls, |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 230 | llvm::StringRef FileName, bool IsHeader = false) { |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 231 | std::string NewCode; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 232 | std::string GuardName(FileName); |
| 233 | if (IsHeader) { |
Haojian Wu | ac97fc3 | 2016-10-17 15:26:34 +0000 | [diff] [blame] | 234 | for (size_t i = 0; i < GuardName.size(); ++i) { |
| 235 | if (!isAlphanumeric(GuardName[i])) |
| 236 | GuardName[i] = '_'; |
| 237 | } |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 238 | GuardName = StringRef(GuardName).upper(); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 239 | NewCode += "#ifndef " + GuardName + "\n"; |
| 240 | NewCode += "#define " + GuardName + "\n"; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 241 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 242 | |
| 243 | // Add #Includes. |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 244 | for (const auto &Include : Includes) |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 245 | NewCode += Include; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 246 | |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 247 | if (!Includes.empty()) |
| 248 | NewCode += "\n"; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 249 | |
| 250 | // Add moved class definition and its related declarations. All declarations |
| 251 | // in same namespace are grouped together. |
| 252 | std::vector<std::string> CurrentNamespaces; |
| 253 | for (const auto &MovedDecl : Decls) { |
| 254 | std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl); |
| 255 | auto CurrentIt = CurrentNamespaces.begin(); |
| 256 | auto DeclIt = DeclNamespaces.begin(); |
| 257 | while (CurrentIt != CurrentNamespaces.end() && |
| 258 | DeclIt != DeclNamespaces.end()) { |
| 259 | if (*CurrentIt != *DeclIt) |
| 260 | break; |
| 261 | ++CurrentIt; |
| 262 | ++DeclIt; |
| 263 | } |
| 264 | std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(), |
| 265 | CurrentIt); |
| 266 | NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end()); |
| 267 | auto RemainingSize = CurrentNamespaces.end() - CurrentIt; |
| 268 | for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0; |
| 269 | --RemainingSize, ++It) { |
| 270 | assert(It < CurrentNamespaces.rend()); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 271 | NewCode += "} // namespace " + *It + "\n"; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 272 | } |
| 273 | while (DeclIt != DeclNamespaces.end()) { |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 274 | NewCode += "namespace " + *DeclIt + " {\n"; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 275 | ++DeclIt; |
| 276 | } |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 277 | NewCode += getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 278 | CurrentNamespaces = std::move(NextNamespaces); |
| 279 | } |
| 280 | std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end()); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 281 | for (const auto &NS : CurrentNamespaces) |
| 282 | NewCode += "} // namespace " + NS + "\n"; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 283 | |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 284 | if (IsHeader) |
| 285 | NewCode += "#endif // " + GuardName + "\n"; |
| 286 | return clang::tooling::Replacements( |
| 287 | clang::tooling::Replacement(FileName, 0, 0, NewCode)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 288 | } |
| 289 | |
| 290 | } // namespace |
| 291 | |
| 292 | std::unique_ptr<clang::ASTConsumer> |
| 293 | ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler, |
| 294 | StringRef /*InFile*/) { |
| 295 | Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>( |
| 296 | &Compiler.getSourceManager(), &MoveTool)); |
| 297 | return MatchFinder.newASTConsumer(); |
| 298 | } |
| 299 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 300 | ClangMoveTool::ClangMoveTool( |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 301 | const MoveDefinitionSpec &MoveSpec, |
| 302 | std::map<std::string, tooling::Replacements> &FileToReplacements, |
| 303 | llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle) |
| 304 | : Spec(MoveSpec), FileToReplacements(FileToReplacements), |
| 305 | OriginalRunningDirectory(OriginalRunningDirectory), |
| 306 | FallbackStyle(FallbackStyle) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 307 | if (!Spec.NewHeader.empty()) |
| 308 | CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n"); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 309 | } |
| 310 | |
| 311 | void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) { |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 312 | Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames; |
Alexander Shaposhnikov | 5fe0678 | 2016-10-14 23:16:25 +0000 | [diff] [blame] | 313 | for (StringRef ClassName : Spec.Names) { |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 314 | llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':'); |
| 315 | const auto HasName = hasName(("::" + GlobalClassName).str()); |
| 316 | InMovedClassNames = |
| 317 | InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName; |
| 318 | } |
| 319 | if (!InMovedClassNames) { |
| 320 | llvm::errs() << "No classes being moved.\n"; |
| 321 | return; |
| 322 | } |
| 323 | |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 324 | auto InOldHeader = isExpansionInFile(makeAbsolutePath(Spec.OldHeader)); |
| 325 | auto InOldCC = isExpansionInFile(makeAbsolutePath(Spec.OldCC)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 326 | auto InOldFiles = anyOf(InOldHeader, InOldCC); |
| 327 | auto InMovedClass = |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 328 | hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 329 | |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 330 | auto ForwardDecls = |
| 331 | cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition()))); |
| 332 | |
| 333 | //============================================================================ |
| 334 | // Matchers for old header |
| 335 | //============================================================================ |
| 336 | // Match all top-level named declarations (e.g. function, variable, enum) in |
| 337 | // old header, exclude forward class declarations and namespace declarations. |
| 338 | // |
| 339 | // The old header which contains only one declaration being moved and forward |
| 340 | // declarations is considered to be moved totally. |
| 341 | auto AllDeclsInHeader = namedDecl( |
| 342 | unless(ForwardDecls), unless(namespaceDecl()), |
| 343 | unless(usingDirectiveDecl()), // using namespace decl. |
| 344 | unless(classTemplateDecl(has(ForwardDecls))), // template forward decl. |
| 345 | InOldHeader, |
| 346 | hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl())))); |
| 347 | Finder->addMatcher(AllDeclsInHeader.bind("decls_in_header"), this); |
| 348 | // Match forward declarations in old header. |
| 349 | Finder->addMatcher(namedDecl(ForwardDecls, InOldHeader).bind("fwd_decl"), |
| 350 | this); |
| 351 | |
| 352 | //============================================================================ |
| 353 | // Matchers for old files, including old.h/old.cc |
| 354 | //============================================================================ |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 355 | // Match moved class declarations. |
| 356 | auto MovedClass = cxxRecordDecl( |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 357 | InOldFiles, *InMovedClassNames, isDefinition(), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 358 | hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()))); |
| 359 | Finder->addMatcher(MovedClass.bind("moved_class"), this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 360 | // Match moved class methods (static methods included) which are defined |
| 361 | // outside moved class declaration. |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 362 | Finder->addMatcher( |
| 363 | cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames), |
| 364 | isDefinition()) |
| 365 | .bind("class_method"), |
| 366 | this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 367 | |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 368 | //============================================================================ |
| 369 | // Matchers for old cc |
| 370 | //============================================================================ |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 371 | // Match static member variable definition of the moved class. |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 372 | Finder->addMatcher( |
| 373 | varDecl(InMovedClass, InOldCC, isDefinition(), isStaticDataMember()) |
| 374 | .bind("class_static_var_decl"), |
| 375 | this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 376 | |
Haojian Wu | 67bb651 | 2016-10-19 14:13:21 +0000 | [diff] [blame] | 377 | auto InOldCCNamedNamespace = |
| 378 | allOf(hasParent(namespaceDecl(unless(isAnonymous()))), InOldCC); |
| 379 | // Matching using decls/type alias decls which are in named namespace. Those |
| 380 | // in classes, functions and anonymous namespaces are covered in other |
| 381 | // matchers. |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 382 | Finder->addMatcher( |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 383 | namedDecl(anyOf(usingDecl(InOldCCNamedNamespace), |
| 384 | usingDirectiveDecl(InOldCC, InOldCCNamedNamespace), |
| 385 | typeAliasDecl(InOldCC, InOldCCNamedNamespace))) |
Haojian Wu | 67bb651 | 2016-10-19 14:13:21 +0000 | [diff] [blame] | 386 | .bind("using_decl"), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 387 | this); |
| 388 | |
Haojian Wu | 67bb651 | 2016-10-19 14:13:21 +0000 | [diff] [blame] | 389 | // Match anonymous namespace decl in old cc. |
| 390 | Finder->addMatcher(namespaceDecl(isAnonymous(), InOldCC).bind("anonymous_ns"), |
| 391 | this); |
| 392 | |
| 393 | // Match static functions/variable definitions which are defined in named |
| 394 | // namespaces. |
| 395 | auto IsOldCCStaticDefinition = |
| 396 | allOf(isDefinition(), unless(InMovedClass), InOldCCNamedNamespace, |
| 397 | isStaticStorageClass()); |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 398 | Finder->addMatcher(namedDecl(anyOf(functionDecl(IsOldCCStaticDefinition), |
| 399 | varDecl(IsOldCCStaticDefinition))) |
| 400 | .bind("static_decls"), |
| 401 | this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 402 | } |
| 403 | |
| 404 | void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) { |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 405 | if (const auto *D = |
| 406 | Result.Nodes.getNodeAs<clang::NamedDecl>("decls_in_header")) { |
| 407 | UnremovedDeclsInOldHeader.insert(D); |
| 408 | } else if (const auto *CMD = |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 409 | Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) { |
| 410 | // Skip inline class methods. isInline() ast matcher doesn't ignore this |
| 411 | // case. |
| 412 | if (!CMD->isInlined()) { |
| 413 | MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager()); |
| 414 | RemovedDecls.push_back(MovedDecls.back()); |
| 415 | } |
| 416 | } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>( |
| 417 | "class_static_var_decl")) { |
| 418 | MovedDecls.emplace_back(VD, &Result.Context->getSourceManager()); |
| 419 | RemovedDecls.push_back(MovedDecls.back()); |
| 420 | } else if (const auto *class_decl = |
| 421 | Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) { |
| 422 | MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager()); |
| 423 | RemovedDecls.push_back(MovedDecls.back()); |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 424 | UnremovedDeclsInOldHeader.erase(class_decl); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 425 | } else if (const auto *FWD = |
| 426 | Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) { |
| 427 | // Skip all forwad declarations which appear after moved class declaration. |
Haojian Wu | 29c38f7 | 2016-10-21 19:26:43 +0000 | [diff] [blame] | 428 | if (RemovedDecls.empty()) { |
| 429 | if (const auto *DCT = FWD->getDescribedClassTemplate()) { |
| 430 | MovedDecls.emplace_back(DCT, &Result.Context->getSourceManager()); |
| 431 | } else { |
| 432 | MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager()); |
| 433 | } |
| 434 | } |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 435 | } else if (const auto *ANS = |
| 436 | Result.Nodes.getNodeAs<clang::NamespaceDecl>("anonymous_ns")) { |
Haojian Wu | 67bb651 | 2016-10-19 14:13:21 +0000 | [diff] [blame] | 437 | MovedDecls.emplace_back(ANS, &Result.Context->getSourceManager()); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 438 | } else if (const auto *ND = |
| 439 | Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) { |
| 440 | MovedDecls.emplace_back(ND, &Result.Context->getSourceManager()); |
Haojian Wu | 67bb651 | 2016-10-19 14:13:21 +0000 | [diff] [blame] | 441 | } else if (const auto *UD = |
| 442 | Result.Nodes.getNodeAs<clang::NamedDecl>("using_decl")) { |
| 443 | MovedDecls.emplace_back(UD, &Result.Context->getSourceManager()); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 444 | } |
| 445 | } |
| 446 | |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 447 | std::string ClangMoveTool::makeAbsolutePath(StringRef Path) { |
| 448 | return MakeAbsolutePath(OriginalRunningDirectory, Path); |
| 449 | } |
| 450 | |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 451 | void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled, |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 452 | llvm::StringRef SearchPath, |
| 453 | llvm::StringRef FileName, |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 454 | clang::CharSourceRange IncludeFilenameRange, |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 455 | const SourceManager &SM) { |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 456 | SmallVector<char, 128> HeaderWithSearchPath; |
| 457 | llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader); |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 458 | std::string AbsoluteOldHeader = makeAbsolutePath(Spec.OldHeader); |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 459 | // FIXME: Add old.h to the new.cc/h when the new target has dependencies on |
| 460 | // old.h/c. For instance, when moved class uses another class defined in |
| 461 | // old.h, the old.h should be added in new.h. |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 462 | if (AbsoluteOldHeader == |
| 463 | MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(), |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 464 | HeaderWithSearchPath.size()))) { |
| 465 | OldHeaderIncludeRange = IncludeFilenameRange; |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 466 | return; |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 467 | } |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 468 | |
| 469 | std::string IncludeLine = |
| 470 | IsAngled ? ("#include <" + IncludeHeader + ">\n").str() |
| 471 | : ("#include \"" + IncludeHeader + "\"\n").str(); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 472 | |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 473 | std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName); |
| 474 | if (AbsoluteOldHeader == AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 475 | HeaderIncludes.push_back(IncludeLine); |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 476 | } else if (makeAbsolutePath(Spec.OldCC) == AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 477 | CCIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 478 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 479 | } |
| 480 | |
| 481 | void ClangMoveTool::removeClassDefinitionInOldFiles() { |
| 482 | for (const auto &MovedDecl : RemovedDecls) { |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 483 | const auto &SM = *MovedDecl.SM; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 484 | auto Range = GetFullRange(&SM, MovedDecl.Decl); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 485 | clang::tooling::Replacement RemoveReplacement( |
Mandeep Singh Grang | 7c7ea7d | 2016-11-08 07:50:19 +0000 | [diff] [blame] | 486 | *MovedDecl.SM, |
| 487 | clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 488 | ""); |
| 489 | std::string FilePath = RemoveReplacement.getFilePath().str(); |
Haojian Wu | 53eab1e | 2016-10-14 13:43:49 +0000 | [diff] [blame] | 490 | auto Err = FileToReplacements[FilePath].add(RemoveReplacement); |
| 491 | if (Err) { |
| 492 | llvm::errs() << llvm::toString(std::move(Err)) << "\n"; |
| 493 | continue; |
| 494 | } |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 495 | |
| 496 | llvm::StringRef Code = |
| 497 | SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation())); |
| 498 | format::FormatStyle Style = |
| 499 | format::getStyle("file", FilePath, FallbackStyle); |
| 500 | auto CleanReplacements = format::cleanupAroundReplacements( |
| 501 | Code, FileToReplacements[FilePath], Style); |
| 502 | |
| 503 | if (!CleanReplacements) { |
| 504 | llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n"; |
| 505 | continue; |
| 506 | } |
| 507 | FileToReplacements[FilePath] = *CleanReplacements; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 508 | } |
| 509 | } |
| 510 | |
| 511 | void ClangMoveTool::moveClassDefinitionToNewFiles() { |
| 512 | std::vector<MovedDecl> NewHeaderDecls; |
| 513 | std::vector<MovedDecl> NewCCDecls; |
| 514 | for (const auto &MovedDecl : MovedDecls) { |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 515 | if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory, |
| 516 | Spec.OldHeader)) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 517 | NewHeaderDecls.push_back(MovedDecl); |
| 518 | else |
| 519 | NewCCDecls.push_back(MovedDecl); |
| 520 | } |
| 521 | |
| 522 | if (!Spec.NewHeader.empty()) |
| 523 | FileToReplacements[Spec.NewHeader] = createInsertedReplacements( |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame] | 524 | HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 525 | if (!Spec.NewCC.empty()) |
| 526 | FileToReplacements[Spec.NewCC] = |
| 527 | createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC); |
| 528 | } |
| 529 | |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 530 | // Move all contents from OldFile to NewFile. |
| 531 | void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile, |
| 532 | StringRef NewFile) { |
| 533 | const FileEntry *FE = SM.getFileManager().getFile(makeAbsolutePath(OldFile)); |
| 534 | if (!FE) { |
| 535 | llvm::errs() << "Failed to get file: " << OldFile << "\n"; |
| 536 | return; |
| 537 | } |
| 538 | FileID ID = SM.getOrCreateFileID(FE, SrcMgr::C_User); |
| 539 | auto Begin = SM.getLocForStartOfFile(ID); |
| 540 | auto End = SM.getLocForEndOfFile(ID); |
| 541 | clang::tooling::Replacement RemoveAll ( |
| 542 | SM, clang::CharSourceRange::getCharRange(Begin, End), ""); |
| 543 | std::string FilePath = RemoveAll.getFilePath().str(); |
| 544 | FileToReplacements[FilePath] = clang::tooling::Replacements(RemoveAll); |
| 545 | |
| 546 | StringRef Code = SM.getBufferData(ID); |
| 547 | if (!NewFile.empty()) { |
| 548 | auto AllCode = clang::tooling::Replacements( |
| 549 | clang::tooling::Replacement(NewFile, 0, 0, Code)); |
| 550 | // If we are moving from old.cc, an extra step is required: excluding |
| 551 | // the #include of "old.h", instead, we replace it with #include of "new.h". |
| 552 | if (Spec.NewCC == NewFile && OldHeaderIncludeRange.isValid()) { |
| 553 | AllCode = AllCode.merge( |
| 554 | clang::tooling::Replacements(clang::tooling::Replacement( |
| 555 | SM, OldHeaderIncludeRange, '"' + Spec.NewHeader + '"'))); |
| 556 | } |
| 557 | FileToReplacements[NewFile] = std::move(AllCode); |
| 558 | } |
| 559 | } |
| 560 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 561 | void ClangMoveTool::onEndOfTranslationUnit() { |
| 562 | if (RemovedDecls.empty()) |
| 563 | return; |
Haojian Wu | 2930be1 | 2016-11-08 19:55:13 +0000 | [diff] [blame] | 564 | if (UnremovedDeclsInOldHeader.empty() && !Spec.OldHeader.empty()) { |
| 565 | auto &SM = *RemovedDecls[0].SM; |
| 566 | moveAll(SM, Spec.OldHeader, Spec.NewHeader); |
| 567 | moveAll(SM, Spec.OldCC, Spec.NewCC); |
| 568 | return; |
| 569 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 570 | removeClassDefinitionInOldFiles(); |
| 571 | moveClassDefinitionToNewFiles(); |
| 572 | } |
| 573 | |
| 574 | } // namespace move |
| 575 | } // namespace clang |