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 | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 27 | AST_MATCHER_P(Decl, hasOutermostEnclosingClass, |
| 28 | ast_matchers::internal::Matcher<Decl>, InnerMatcher) { |
| 29 | const auto* Context = Node.getDeclContext(); |
| 30 | if (!Context) return false; |
| 31 | while (const auto *NextContext = Context->getParent()) { |
| 32 | if (isa<NamespaceDecl>(NextContext) || |
| 33 | isa<TranslationUnitDecl>(NextContext)) |
| 34 | break; |
| 35 | Context = NextContext; |
| 36 | } |
| 37 | return InnerMatcher.matches(*Decl::castFromDeclContext(Context), Finder, |
| 38 | Builder); |
| 39 | } |
| 40 | |
| 41 | AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass, |
| 42 | ast_matchers::internal::Matcher<CXXRecordDecl>, InnerMatcher) { |
| 43 | const CXXRecordDecl *Parent = Node.getParent(); |
| 44 | if (!Parent) return false; |
| 45 | while (const auto *NextParent = |
| 46 | dyn_cast<CXXRecordDecl>(Parent->getParent())) { |
| 47 | Parent = NextParent; |
| 48 | } |
| 49 | |
| 50 | return InnerMatcher.matches(*Parent, Finder, Builder); |
| 51 | } |
| 52 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 53 | // Make the Path absolute using the CurrentDir if the Path is not an absolute |
| 54 | // path. An empty Path will result in an empty string. |
| 55 | std::string MakeAbsolutePath(StringRef CurrentDir, StringRef Path) { |
| 56 | if (Path.empty()) |
| 57 | return ""; |
| 58 | llvm::SmallString<128> InitialDirectory(CurrentDir); |
| 59 | llvm::SmallString<128> AbsolutePath(Path); |
| 60 | if (std::error_code EC = |
| 61 | llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath)) |
| 62 | llvm::errs() << "Warning: could not make absolute file: '" << EC.message() |
| 63 | << '\n'; |
| 64 | llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true); |
Haojian Wu | c6f125e | 2016-10-04 09:49:20 +0000 | [diff] [blame] | 65 | llvm::sys::path::native(AbsolutePath); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 66 | return AbsolutePath.str(); |
| 67 | } |
| 68 | |
| 69 | // Make the Path absolute using the current working directory of the given |
| 70 | // SourceManager if the Path is not an absolute path. |
| 71 | // |
| 72 | // The Path can be a path relative to the build directory, or retrieved from |
| 73 | // the SourceManager. |
| 74 | std::string MakeAbsolutePath(const SourceManager& SM, StringRef Path) { |
| 75 | llvm::SmallString<128> AbsolutePath(Path); |
| 76 | if (std::error_code EC = |
| 77 | SM.getFileManager().getVirtualFileSystem()->makeAbsolute(AbsolutePath)) |
| 78 | llvm::errs() << "Warning: could not make absolute file: '" << EC.message() |
| 79 | << '\n'; |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 80 | // Handle symbolic link path cases. |
| 81 | // We are trying to get the real file path of the symlink. |
| 82 | const DirectoryEntry *Dir = SM.getFileManager().getDirectory( |
| 83 | llvm::sys::path::parent_path(AbsolutePath.str())); |
| 84 | if (Dir) { |
| 85 | StringRef DirName = SM.getFileManager().getCanonicalName(Dir); |
| 86 | SmallVector<char, 128> AbsoluteFilename; |
| 87 | llvm::sys::path::append(AbsoluteFilename, DirName, |
| 88 | llvm::sys::path::filename(AbsolutePath.str())); |
| 89 | return llvm::StringRef(AbsoluteFilename.data(), AbsoluteFilename.size()) |
| 90 | .str(); |
| 91 | } |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 92 | return AbsolutePath.str(); |
| 93 | } |
| 94 | |
| 95 | // Matches AST nodes that are expanded within the given AbsoluteFilePath. |
| 96 | AST_POLYMORPHIC_MATCHER_P(isExpansionInFile, |
| 97 | AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), |
| 98 | std::string, AbsoluteFilePath) { |
| 99 | auto &SourceManager = Finder->getASTContext().getSourceManager(); |
| 100 | auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart()); |
| 101 | if (ExpansionLoc.isInvalid()) |
| 102 | return false; |
| 103 | auto FileEntry = |
| 104 | SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc)); |
| 105 | if (!FileEntry) |
| 106 | return false; |
| 107 | return MakeAbsolutePath(SourceManager, FileEntry->getName()) == |
| 108 | AbsoluteFilePath; |
| 109 | } |
| 110 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 111 | class FindAllIncludes : public clang::PPCallbacks { |
| 112 | public: |
| 113 | explicit FindAllIncludes(SourceManager *SM, ClangMoveTool *const MoveTool) |
| 114 | : SM(*SM), MoveTool(MoveTool) {} |
| 115 | |
| 116 | void InclusionDirective(clang::SourceLocation HashLoc, |
| 117 | const clang::Token & /*IncludeTok*/, |
| 118 | StringRef FileName, bool IsAngled, |
| 119 | clang::CharSourceRange /*FilenameRange*/, |
| 120 | const clang::FileEntry * /*File*/, |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 121 | StringRef SearchPath, StringRef /*RelativePath*/, |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 122 | const clang::Module * /*Imported*/) override { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 123 | if (const auto *FileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc))) |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 124 | MoveTool->addIncludes(FileName, IsAngled, SearchPath, |
| 125 | FileEntry->getName(), SM); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 126 | } |
| 127 | |
| 128 | private: |
| 129 | const SourceManager &SM; |
| 130 | ClangMoveTool *const MoveTool; |
| 131 | }; |
| 132 | |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 133 | // Expand to get the end location of the line where the EndLoc of the given |
| 134 | // Decl. |
| 135 | SourceLocation |
| 136 | getLocForEndOfDecl(const clang::Decl *D, const SourceManager *SM, |
| 137 | const LangOptions &LangOpts = clang::LangOptions()) { |
| 138 | std::pair<FileID, unsigned> LocInfo = SM->getDecomposedLoc(D->getLocEnd()); |
| 139 | // Try to load the file buffer. |
| 140 | bool InvalidTemp = false; |
| 141 | llvm::StringRef File = SM->getBufferData(LocInfo.first, &InvalidTemp); |
| 142 | if (InvalidTemp) |
| 143 | return SourceLocation(); |
| 144 | |
| 145 | const char *TokBegin = File.data() + LocInfo.second; |
| 146 | // Lex from the start of the given location. |
| 147 | Lexer Lex(SM->getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(), |
| 148 | TokBegin, File.end()); |
| 149 | |
| 150 | llvm::SmallVector<char, 16> Line; |
| 151 | // FIXME: this is a bit hacky to get ReadToEndOfLine work. |
| 152 | Lex.setParsingPreprocessorDirective(true); |
| 153 | Lex.ReadToEndOfLine(&Line); |
| 154 | SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size()); |
| 155 | // If we already reach EOF, just return the EOF SourceLocation; |
| 156 | // otherwise, move 1 offset ahead to include the trailing newline character |
| 157 | // '\n'. |
| 158 | return SM->getLocForEndOfFile(LocInfo.first) == EndLoc |
| 159 | ? EndLoc |
| 160 | : EndLoc.getLocWithOffset(1); |
| 161 | } |
| 162 | |
| 163 | // Get full range of a Decl including the comments associated with it. |
| 164 | clang::CharSourceRange |
| 165 | GetFullRange(const clang::SourceManager *SM, const clang::Decl *D, |
| 166 | const clang::LangOptions &options = clang::LangOptions()) { |
| 167 | clang::SourceRange Full = D->getSourceRange(); |
| 168 | Full.setEnd(getLocForEndOfDecl(D, SM)); |
| 169 | // Expand to comments that are associated with the Decl. |
| 170 | if (const auto* Comment = |
| 171 | D->getASTContext().getRawCommentForDeclNoCache(D)) { |
| 172 | if (SM->isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd())) |
| 173 | Full.setEnd(Comment->getLocEnd()); |
| 174 | // FIXME: Don't delete a preceding comment, if there are no other entities |
| 175 | // it could refer to. |
| 176 | if (SM->isBeforeInTranslationUnit(Comment->getLocStart(), |
| 177 | Full.getBegin())) |
| 178 | Full.setBegin(Comment->getLocStart()); |
| 179 | } |
| 180 | |
| 181 | return clang::CharSourceRange::getCharRange(Full); |
| 182 | } |
| 183 | |
| 184 | std::string getDeclarationSourceText(const clang::Decl *D, |
| 185 | const clang::SourceManager *SM) { |
| 186 | llvm::StringRef SourceText = clang::Lexer::getSourceText( |
| 187 | GetFullRange(SM, D), *SM, clang::LangOptions()); |
| 188 | return SourceText.str(); |
| 189 | } |
| 190 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 191 | clang::tooling::Replacement |
| 192 | getReplacementInChangedCode(const clang::tooling::Replacements &Replacements, |
| 193 | const clang::tooling::Replacement &Replacement) { |
| 194 | unsigned Start = Replacements.getShiftedCodePosition(Replacement.getOffset()); |
| 195 | unsigned End = Replacements.getShiftedCodePosition(Replacement.getOffset() + |
| 196 | Replacement.getLength()); |
| 197 | return clang::tooling::Replacement(Replacement.getFilePath(), Start, |
| 198 | End - Start, |
| 199 | Replacement.getReplacementText()); |
| 200 | } |
| 201 | |
| 202 | void addOrMergeReplacement(const clang::tooling::Replacement &Replacement, |
| 203 | clang::tooling::Replacements *Replacements) { |
| 204 | auto Err = Replacements->add(Replacement); |
| 205 | if (Err) { |
| 206 | llvm::consumeError(std::move(Err)); |
| 207 | auto Replace = getReplacementInChangedCode(*Replacements, Replacement); |
| 208 | *Replacements = Replacements->merge(clang::tooling::Replacements(Replace)); |
| 209 | } |
| 210 | } |
| 211 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 212 | bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D, |
| 213 | llvm::StringRef OriginalRunningDirectory, |
| 214 | llvm::StringRef OldHeader) { |
| 215 | if (OldHeader.empty()) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 216 | return false; |
| 217 | auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart()); |
| 218 | if (ExpansionLoc.isInvalid()) |
| 219 | return false; |
| 220 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 221 | if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) { |
| 222 | return MakeAbsolutePath(SM, FE->getName()) == |
| 223 | MakeAbsolutePath(OriginalRunningDirectory, OldHeader); |
| 224 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 225 | |
| 226 | return false; |
| 227 | } |
| 228 | |
| 229 | std::vector<std::string> GetNamespaces(const clang::Decl *D) { |
| 230 | std::vector<std::string> Namespaces; |
| 231 | for (const auto *Context = D->getDeclContext(); Context; |
| 232 | Context = Context->getParent()) { |
| 233 | if (llvm::isa<clang::TranslationUnitDecl>(Context) || |
| 234 | llvm::isa<clang::LinkageSpecDecl>(Context)) |
| 235 | break; |
| 236 | |
| 237 | if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context)) |
| 238 | Namespaces.push_back(ND->getName().str()); |
| 239 | } |
| 240 | std::reverse(Namespaces.begin(), Namespaces.end()); |
| 241 | return Namespaces; |
| 242 | } |
| 243 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 244 | clang::tooling::Replacements |
| 245 | createInsertedReplacements(const std::vector<std::string> &Includes, |
| 246 | const std::vector<ClangMoveTool::MovedDecl> &Decls, |
| 247 | llvm::StringRef FileName) { |
| 248 | clang::tooling::Replacements InsertedReplacements; |
| 249 | |
| 250 | // Add #Includes. |
| 251 | std::string AllIncludesString; |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 252 | // FIXME: Add header guard. |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 253 | for (const auto &Include : Includes) |
| 254 | AllIncludesString += Include; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 255 | |
| 256 | if (!AllIncludesString.empty()) { |
| 257 | clang::tooling::Replacement InsertInclude(FileName, 0, 0, |
| 258 | AllIncludesString + "\n"); |
| 259 | addOrMergeReplacement(InsertInclude, &InsertedReplacements); |
| 260 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 261 | |
| 262 | // Add moved class definition and its related declarations. All declarations |
| 263 | // in same namespace are grouped together. |
| 264 | std::vector<std::string> CurrentNamespaces; |
| 265 | for (const auto &MovedDecl : Decls) { |
| 266 | std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl); |
| 267 | auto CurrentIt = CurrentNamespaces.begin(); |
| 268 | auto DeclIt = DeclNamespaces.begin(); |
| 269 | while (CurrentIt != CurrentNamespaces.end() && |
| 270 | DeclIt != DeclNamespaces.end()) { |
| 271 | if (*CurrentIt != *DeclIt) |
| 272 | break; |
| 273 | ++CurrentIt; |
| 274 | ++DeclIt; |
| 275 | } |
| 276 | std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(), |
| 277 | CurrentIt); |
| 278 | NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end()); |
| 279 | auto RemainingSize = CurrentNamespaces.end() - CurrentIt; |
| 280 | for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0; |
| 281 | --RemainingSize, ++It) { |
| 282 | assert(It < CurrentNamespaces.rend()); |
| 283 | auto code = "} // namespace " + *It + "\n"; |
| 284 | clang::tooling::Replacement InsertedReplacement(FileName, 0, 0, code); |
| 285 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 286 | } |
| 287 | while (DeclIt != DeclNamespaces.end()) { |
| 288 | clang::tooling::Replacement InsertedReplacement( |
| 289 | FileName, 0, 0, "namespace " + *DeclIt + " {\n"); |
| 290 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 291 | ++DeclIt; |
| 292 | } |
| 293 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 294 | clang::tooling::Replacement InsertedReplacement( |
| 295 | FileName, 0, 0, getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM)); |
| 296 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 297 | |
| 298 | CurrentNamespaces = std::move(NextNamespaces); |
| 299 | } |
| 300 | std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end()); |
| 301 | for (const auto &NS : CurrentNamespaces) { |
| 302 | clang::tooling::Replacement InsertedReplacement( |
| 303 | FileName, 0, 0, "} // namespace " + NS + "\n"); |
| 304 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 305 | } |
| 306 | return InsertedReplacements; |
| 307 | } |
| 308 | |
| 309 | } // namespace |
| 310 | |
| 311 | std::unique_ptr<clang::ASTConsumer> |
| 312 | ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler, |
| 313 | StringRef /*InFile*/) { |
| 314 | Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>( |
| 315 | &Compiler.getSourceManager(), &MoveTool)); |
| 316 | return MatchFinder.newASTConsumer(); |
| 317 | } |
| 318 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 319 | ClangMoveTool::ClangMoveTool( |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 320 | const MoveDefinitionSpec &MoveSpec, |
| 321 | std::map<std::string, tooling::Replacements> &FileToReplacements, |
| 322 | llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle) |
| 323 | : Spec(MoveSpec), FileToReplacements(FileToReplacements), |
| 324 | OriginalRunningDirectory(OriginalRunningDirectory), |
| 325 | FallbackStyle(FallbackStyle) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 326 | if (!Spec.NewHeader.empty()) |
| 327 | CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n"); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 328 | } |
| 329 | |
| 330 | void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) { |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 331 | SmallVector<StringRef, 4> ClassNames; |
| 332 | llvm::StringRef(Spec.Names).split(ClassNames, ','); |
| 333 | Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames; |
| 334 | for (StringRef ClassName : ClassNames) { |
| 335 | llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':'); |
| 336 | const auto HasName = hasName(("::" + GlobalClassName).str()); |
| 337 | InMovedClassNames = |
| 338 | InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName; |
| 339 | } |
| 340 | if (!InMovedClassNames) { |
| 341 | llvm::errs() << "No classes being moved.\n"; |
| 342 | return; |
| 343 | } |
| 344 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 345 | auto InOldHeader = isExpansionInFile( |
| 346 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader)); |
| 347 | auto InOldCC = isExpansionInFile( |
| 348 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 349 | auto InOldFiles = anyOf(InOldHeader, InOldCC); |
| 350 | auto InMovedClass = |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 351 | hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 352 | |
| 353 | // Match moved class declarations. |
| 354 | auto MovedClass = cxxRecordDecl( |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 355 | InOldFiles, *InMovedClassNames, isDefinition(), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 356 | hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()))); |
| 357 | Finder->addMatcher(MovedClass.bind("moved_class"), this); |
| 358 | |
| 359 | // Match moved class methods (static methods included) which are defined |
| 360 | // outside moved class declaration. |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 361 | Finder->addMatcher( |
| 362 | cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames), |
| 363 | isDefinition()) |
| 364 | .bind("class_method"), |
| 365 | this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 366 | |
| 367 | // Match static member variable definition of the moved class. |
| 368 | Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition()) |
| 369 | .bind("class_static_var_decl"), |
| 370 | this); |
| 371 | |
| 372 | auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous())); |
| 373 | // Match functions/variables definitions which are defined in anonymous |
| 374 | // namespace in old cc. |
| 375 | Finder->addMatcher( |
| 376 | namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())), |
| 377 | inAnonymousNamespace) |
| 378 | .bind("decls_in_anonymous_ns"), |
| 379 | this); |
| 380 | |
| 381 | // Match static functions/variabale definitions in old cc. |
| 382 | Finder->addMatcher( |
| 383 | namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass), |
Haojian Wu | ef247cb | 2016-09-27 08:01:04 +0000 | [diff] [blame] | 384 | isStaticStorageClass(), InOldCC), |
| 385 | varDecl(isDefinition(), unless(InMovedClass), |
| 386 | isStaticStorageClass(), InOldCC))) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 387 | .bind("static_decls"), |
| 388 | this); |
| 389 | |
| 390 | // Match forward declarations in old header. |
| 391 | Finder->addMatcher( |
| 392 | cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader) |
| 393 | .bind("fwd_decl"), |
| 394 | this); |
| 395 | } |
| 396 | |
| 397 | void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) { |
| 398 | if (const auto *CMD = |
| 399 | Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) { |
| 400 | // Skip inline class methods. isInline() ast matcher doesn't ignore this |
| 401 | // case. |
| 402 | if (!CMD->isInlined()) { |
| 403 | MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager()); |
| 404 | RemovedDecls.push_back(MovedDecls.back()); |
| 405 | } |
| 406 | } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>( |
| 407 | "class_static_var_decl")) { |
| 408 | MovedDecls.emplace_back(VD, &Result.Context->getSourceManager()); |
| 409 | RemovedDecls.push_back(MovedDecls.back()); |
| 410 | } else if (const auto *class_decl = |
| 411 | Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) { |
| 412 | MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager()); |
| 413 | RemovedDecls.push_back(MovedDecls.back()); |
| 414 | } else if (const auto *FWD = |
| 415 | Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) { |
| 416 | // Skip all forwad declarations which appear after moved class declaration. |
| 417 | if (RemovedDecls.empty()) |
| 418 | MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager()); |
| 419 | } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>( |
| 420 | "decls_in_anonymous_ns")) { |
| 421 | MovedDecls.emplace_back(FD, &Result.Context->getSourceManager()); |
| 422 | } else if (const auto *ND = |
| 423 | Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) { |
| 424 | MovedDecls.emplace_back(ND, &Result.Context->getSourceManager()); |
| 425 | } |
| 426 | } |
| 427 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 428 | void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, |
| 429 | bool IsAngled, |
| 430 | llvm::StringRef SearchPath, |
| 431 | llvm::StringRef FileName, |
| 432 | const SourceManager& SM) { |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 433 | SmallVector<char, 128> HeaderWithSearchPath; |
| 434 | llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader); |
| 435 | std::string AbsoluteOldHeader = |
| 436 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader); |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 437 | // FIXME: Add old.h to the new.cc/h when the new target has dependencies on |
| 438 | // old.h/c. For instance, when moved class uses another class defined in |
| 439 | // old.h, the old.h should be added in new.h. |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 440 | if (AbsoluteOldHeader == |
| 441 | MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(), |
| 442 | HeaderWithSearchPath.size()))) |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 443 | return; |
| 444 | |
| 445 | std::string IncludeLine = |
| 446 | IsAngled ? ("#include <" + IncludeHeader + ">\n").str() |
| 447 | : ("#include \"" + IncludeHeader + "\"\n").str(); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 448 | |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 449 | std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName); |
| 450 | if (AbsoluteOldHeader == AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 451 | HeaderIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 452 | } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) == |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 453 | AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 454 | CCIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 455 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 456 | } |
| 457 | |
| 458 | void ClangMoveTool::removeClassDefinitionInOldFiles() { |
| 459 | for (const auto &MovedDecl : RemovedDecls) { |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 460 | const auto &SM = *MovedDecl.SM; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 461 | auto Range = GetFullRange(&SM, MovedDecl.Decl); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 462 | clang::tooling::Replacement RemoveReplacement( |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 463 | *MovedDecl.SM, clang::CharSourceRange::getCharRange( |
| 464 | Range.getBegin(), Range.getEnd()), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 465 | ""); |
| 466 | std::string FilePath = RemoveReplacement.getFilePath().str(); |
| 467 | addOrMergeReplacement(RemoveReplacement, &FileToReplacements[FilePath]); |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 468 | |
| 469 | llvm::StringRef Code = |
| 470 | SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation())); |
| 471 | format::FormatStyle Style = |
| 472 | format::getStyle("file", FilePath, FallbackStyle); |
| 473 | auto CleanReplacements = format::cleanupAroundReplacements( |
| 474 | Code, FileToReplacements[FilePath], Style); |
| 475 | |
| 476 | if (!CleanReplacements) { |
| 477 | llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n"; |
| 478 | continue; |
| 479 | } |
| 480 | FileToReplacements[FilePath] = *CleanReplacements; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 481 | } |
| 482 | } |
| 483 | |
| 484 | void ClangMoveTool::moveClassDefinitionToNewFiles() { |
| 485 | std::vector<MovedDecl> NewHeaderDecls; |
| 486 | std::vector<MovedDecl> NewCCDecls; |
| 487 | for (const auto &MovedDecl : MovedDecls) { |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 488 | if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory, |
| 489 | Spec.OldHeader)) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 490 | NewHeaderDecls.push_back(MovedDecl); |
| 491 | else |
| 492 | NewCCDecls.push_back(MovedDecl); |
| 493 | } |
| 494 | |
| 495 | if (!Spec.NewHeader.empty()) |
| 496 | FileToReplacements[Spec.NewHeader] = createInsertedReplacements( |
| 497 | HeaderIncludes, NewHeaderDecls, Spec.NewHeader); |
| 498 | if (!Spec.NewCC.empty()) |
| 499 | FileToReplacements[Spec.NewCC] = |
| 500 | createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC); |
| 501 | } |
| 502 | |
| 503 | void ClangMoveTool::onEndOfTranslationUnit() { |
| 504 | if (RemovedDecls.empty()) |
| 505 | return; |
| 506 | removeClassDefinitionInOldFiles(); |
| 507 | moveClassDefinitionToNewFiles(); |
| 508 | } |
| 509 | |
| 510 | } // namespace move |
| 511 | } // namespace clang |