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 | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 196 | clang::tooling::Replacement |
| 197 | getReplacementInChangedCode(const clang::tooling::Replacements &Replacements, |
| 198 | const clang::tooling::Replacement &Replacement) { |
| 199 | unsigned Start = Replacements.getShiftedCodePosition(Replacement.getOffset()); |
| 200 | unsigned End = Replacements.getShiftedCodePosition(Replacement.getOffset() + |
| 201 | Replacement.getLength()); |
| 202 | return clang::tooling::Replacement(Replacement.getFilePath(), Start, |
| 203 | End - Start, |
| 204 | Replacement.getReplacementText()); |
| 205 | } |
| 206 | |
| 207 | void addOrMergeReplacement(const clang::tooling::Replacement &Replacement, |
| 208 | clang::tooling::Replacements *Replacements) { |
| 209 | auto Err = Replacements->add(Replacement); |
| 210 | if (Err) { |
| 211 | llvm::consumeError(std::move(Err)); |
| 212 | auto Replace = getReplacementInChangedCode(*Replacements, Replacement); |
| 213 | *Replacements = Replacements->merge(clang::tooling::Replacements(Replace)); |
| 214 | } |
| 215 | } |
| 216 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 217 | bool isInHeaderFile(const clang::SourceManager &SM, const clang::Decl *D, |
| 218 | llvm::StringRef OriginalRunningDirectory, |
| 219 | llvm::StringRef OldHeader) { |
| 220 | if (OldHeader.empty()) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 221 | return false; |
| 222 | auto ExpansionLoc = SM.getExpansionLoc(D->getLocStart()); |
| 223 | if (ExpansionLoc.isInvalid()) |
| 224 | return false; |
| 225 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 226 | if (const auto *FE = SM.getFileEntryForID(SM.getFileID(ExpansionLoc))) { |
| 227 | return MakeAbsolutePath(SM, FE->getName()) == |
| 228 | MakeAbsolutePath(OriginalRunningDirectory, OldHeader); |
| 229 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 230 | |
| 231 | return false; |
| 232 | } |
| 233 | |
| 234 | std::vector<std::string> GetNamespaces(const clang::Decl *D) { |
| 235 | std::vector<std::string> Namespaces; |
| 236 | for (const auto *Context = D->getDeclContext(); Context; |
| 237 | Context = Context->getParent()) { |
| 238 | if (llvm::isa<clang::TranslationUnitDecl>(Context) || |
| 239 | llvm::isa<clang::LinkageSpecDecl>(Context)) |
| 240 | break; |
| 241 | |
| 242 | if (const auto *ND = llvm::dyn_cast<clang::NamespaceDecl>(Context)) |
| 243 | Namespaces.push_back(ND->getName().str()); |
| 244 | } |
| 245 | std::reverse(Namespaces.begin(), Namespaces.end()); |
| 246 | return Namespaces; |
| 247 | } |
| 248 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 249 | clang::tooling::Replacements |
| 250 | createInsertedReplacements(const std::vector<std::string> &Includes, |
| 251 | const std::vector<ClangMoveTool::MovedDecl> &Decls, |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame^] | 252 | llvm::StringRef FileName, |
| 253 | bool IsHeader = false) { |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 254 | clang::tooling::Replacements InsertedReplacements; |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame^] | 255 | std::string GuardName(FileName); |
| 256 | if (IsHeader) { |
| 257 | std::replace(GuardName.begin(), GuardName.end(), '/', '_'); |
| 258 | std::replace(GuardName.begin(), GuardName.end(), '.', '_'); |
| 259 | std::replace(GuardName.begin(), GuardName.end(), '-', '_'); |
| 260 | |
| 261 | GuardName = StringRef(GuardName).upper(); |
| 262 | std::string HeaderGuard = "#ifndef " + GuardName + "\n"; |
| 263 | HeaderGuard += "#define " + GuardName + "\n"; |
| 264 | clang::tooling::Replacement HeaderGuardInclude(FileName, 0, 0, |
| 265 | HeaderGuard); |
| 266 | addOrMergeReplacement(HeaderGuardInclude, &InsertedReplacements); |
| 267 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 268 | |
| 269 | // Add #Includes. |
| 270 | std::string AllIncludesString; |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 271 | // FIXME: Add header guard. |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 272 | for (const auto &Include : Includes) |
| 273 | AllIncludesString += Include; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 274 | |
| 275 | if (!AllIncludesString.empty()) { |
| 276 | clang::tooling::Replacement InsertInclude(FileName, 0, 0, |
| 277 | AllIncludesString + "\n"); |
| 278 | addOrMergeReplacement(InsertInclude, &InsertedReplacements); |
| 279 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 280 | |
| 281 | // Add moved class definition and its related declarations. All declarations |
| 282 | // in same namespace are grouped together. |
| 283 | std::vector<std::string> CurrentNamespaces; |
| 284 | for (const auto &MovedDecl : Decls) { |
| 285 | std::vector<std::string> DeclNamespaces = GetNamespaces(MovedDecl.Decl); |
| 286 | auto CurrentIt = CurrentNamespaces.begin(); |
| 287 | auto DeclIt = DeclNamespaces.begin(); |
| 288 | while (CurrentIt != CurrentNamespaces.end() && |
| 289 | DeclIt != DeclNamespaces.end()) { |
| 290 | if (*CurrentIt != *DeclIt) |
| 291 | break; |
| 292 | ++CurrentIt; |
| 293 | ++DeclIt; |
| 294 | } |
| 295 | std::vector<std::string> NextNamespaces(CurrentNamespaces.begin(), |
| 296 | CurrentIt); |
| 297 | NextNamespaces.insert(NextNamespaces.end(), DeclIt, DeclNamespaces.end()); |
| 298 | auto RemainingSize = CurrentNamespaces.end() - CurrentIt; |
| 299 | for (auto It = CurrentNamespaces.rbegin(); RemainingSize > 0; |
| 300 | --RemainingSize, ++It) { |
| 301 | assert(It < CurrentNamespaces.rend()); |
| 302 | auto code = "} // namespace " + *It + "\n"; |
| 303 | clang::tooling::Replacement InsertedReplacement(FileName, 0, 0, code); |
| 304 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 305 | } |
| 306 | while (DeclIt != DeclNamespaces.end()) { |
| 307 | clang::tooling::Replacement InsertedReplacement( |
| 308 | FileName, 0, 0, "namespace " + *DeclIt + " {\n"); |
| 309 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 310 | ++DeclIt; |
| 311 | } |
| 312 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 313 | clang::tooling::Replacement InsertedReplacement( |
| 314 | FileName, 0, 0, getDeclarationSourceText(MovedDecl.Decl, MovedDecl.SM)); |
| 315 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 316 | |
| 317 | CurrentNamespaces = std::move(NextNamespaces); |
| 318 | } |
| 319 | std::reverse(CurrentNamespaces.begin(), CurrentNamespaces.end()); |
| 320 | for (const auto &NS : CurrentNamespaces) { |
| 321 | clang::tooling::Replacement InsertedReplacement( |
| 322 | FileName, 0, 0, "} // namespace " + NS + "\n"); |
| 323 | addOrMergeReplacement(InsertedReplacement, &InsertedReplacements); |
| 324 | } |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame^] | 325 | |
| 326 | if (IsHeader) { |
| 327 | clang::tooling::Replacement HeaderGuardEnd(FileName, 0, 0, |
| 328 | "#endif // " + GuardName + "\n"); |
| 329 | addOrMergeReplacement(HeaderGuardEnd, &InsertedReplacements); |
| 330 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 331 | return InsertedReplacements; |
| 332 | } |
| 333 | |
| 334 | } // namespace |
| 335 | |
| 336 | std::unique_ptr<clang::ASTConsumer> |
| 337 | ClangMoveAction::CreateASTConsumer(clang::CompilerInstance &Compiler, |
| 338 | StringRef /*InFile*/) { |
| 339 | Compiler.getPreprocessor().addPPCallbacks(llvm::make_unique<FindAllIncludes>( |
| 340 | &Compiler.getSourceManager(), &MoveTool)); |
| 341 | return MatchFinder.newASTConsumer(); |
| 342 | } |
| 343 | |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 344 | ClangMoveTool::ClangMoveTool( |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 345 | const MoveDefinitionSpec &MoveSpec, |
| 346 | std::map<std::string, tooling::Replacements> &FileToReplacements, |
| 347 | llvm::StringRef OriginalRunningDirectory, llvm::StringRef FallbackStyle) |
| 348 | : Spec(MoveSpec), FileToReplacements(FileToReplacements), |
| 349 | OriginalRunningDirectory(OriginalRunningDirectory), |
| 350 | FallbackStyle(FallbackStyle) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 351 | if (!Spec.NewHeader.empty()) |
| 352 | CCIncludes.push_back("#include \"" + Spec.NewHeader + "\"\n"); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 353 | } |
| 354 | |
| 355 | void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) { |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 356 | SmallVector<StringRef, 4> ClassNames; |
| 357 | llvm::StringRef(Spec.Names).split(ClassNames, ','); |
| 358 | Optional<ast_matchers::internal::Matcher<NamedDecl>> InMovedClassNames; |
| 359 | for (StringRef ClassName : ClassNames) { |
| 360 | llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':'); |
| 361 | const auto HasName = hasName(("::" + GlobalClassName).str()); |
| 362 | InMovedClassNames = |
| 363 | InMovedClassNames ? anyOf(*InMovedClassNames, HasName) : HasName; |
| 364 | } |
| 365 | if (!InMovedClassNames) { |
| 366 | llvm::errs() << "No classes being moved.\n"; |
| 367 | return; |
| 368 | } |
| 369 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 370 | auto InOldHeader = isExpansionInFile( |
| 371 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader)); |
| 372 | auto InOldCC = isExpansionInFile( |
| 373 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 374 | auto InOldFiles = anyOf(InOldHeader, InOldCC); |
| 375 | auto InMovedClass = |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 376 | hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames)); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 377 | |
| 378 | // Match moved class declarations. |
| 379 | auto MovedClass = cxxRecordDecl( |
Haojian Wu | 9df3ac1 | 2016-10-13 08:48:42 +0000 | [diff] [blame] | 380 | InOldFiles, *InMovedClassNames, isDefinition(), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 381 | hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()))); |
| 382 | Finder->addMatcher(MovedClass.bind("moved_class"), this); |
| 383 | |
| 384 | // Match moved class methods (static methods included) which are defined |
| 385 | // outside moved class declaration. |
Haojian Wu | e77bcc7 | 2016-10-13 10:31:00 +0000 | [diff] [blame] | 386 | Finder->addMatcher( |
| 387 | cxxMethodDecl(InOldFiles, ofOutermostEnclosingClass(*InMovedClassNames), |
| 388 | isDefinition()) |
| 389 | .bind("class_method"), |
| 390 | this); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 391 | |
| 392 | // Match static member variable definition of the moved class. |
Haojian Wu | 7bd492c | 2016-10-14 10:07:58 +0000 | [diff] [blame] | 393 | Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition(), |
| 394 | isStaticDataMember()) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 395 | .bind("class_static_var_decl"), |
| 396 | this); |
| 397 | |
| 398 | auto inAnonymousNamespace = hasParent(namespaceDecl(isAnonymous())); |
| 399 | // Match functions/variables definitions which are defined in anonymous |
| 400 | // namespace in old cc. |
| 401 | Finder->addMatcher( |
| 402 | namedDecl(anyOf(functionDecl(isDefinition()), varDecl(isDefinition())), |
| 403 | inAnonymousNamespace) |
| 404 | .bind("decls_in_anonymous_ns"), |
| 405 | this); |
| 406 | |
| 407 | // Match static functions/variabale definitions in old cc. |
| 408 | Finder->addMatcher( |
| 409 | namedDecl(anyOf(functionDecl(isDefinition(), unless(InMovedClass), |
Haojian Wu | ef247cb | 2016-09-27 08:01:04 +0000 | [diff] [blame] | 410 | isStaticStorageClass(), InOldCC), |
| 411 | varDecl(isDefinition(), unless(InMovedClass), |
| 412 | isStaticStorageClass(), InOldCC))) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 413 | .bind("static_decls"), |
| 414 | this); |
| 415 | |
| 416 | // Match forward declarations in old header. |
| 417 | Finder->addMatcher( |
| 418 | cxxRecordDecl(unless(anyOf(isImplicit(), isDefinition())), InOldHeader) |
| 419 | .bind("fwd_decl"), |
| 420 | this); |
| 421 | } |
| 422 | |
| 423 | void ClangMoveTool::run(const ast_matchers::MatchFinder::MatchResult &Result) { |
| 424 | if (const auto *CMD = |
| 425 | Result.Nodes.getNodeAs<clang::CXXMethodDecl>("class_method")) { |
| 426 | // Skip inline class methods. isInline() ast matcher doesn't ignore this |
| 427 | // case. |
| 428 | if (!CMD->isInlined()) { |
| 429 | MovedDecls.emplace_back(CMD, &Result.Context->getSourceManager()); |
| 430 | RemovedDecls.push_back(MovedDecls.back()); |
| 431 | } |
| 432 | } else if (const auto *VD = Result.Nodes.getNodeAs<clang::VarDecl>( |
| 433 | "class_static_var_decl")) { |
| 434 | MovedDecls.emplace_back(VD, &Result.Context->getSourceManager()); |
| 435 | RemovedDecls.push_back(MovedDecls.back()); |
| 436 | } else if (const auto *class_decl = |
| 437 | Result.Nodes.getNodeAs<clang::CXXRecordDecl>("moved_class")) { |
| 438 | MovedDecls.emplace_back(class_decl, &Result.Context->getSourceManager()); |
| 439 | RemovedDecls.push_back(MovedDecls.back()); |
| 440 | } else if (const auto *FWD = |
| 441 | Result.Nodes.getNodeAs<clang::CXXRecordDecl>("fwd_decl")) { |
| 442 | // Skip all forwad declarations which appear after moved class declaration. |
| 443 | if (RemovedDecls.empty()) |
| 444 | MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager()); |
| 445 | } else if (const auto *FD = Result.Nodes.getNodeAs<clang::NamedDecl>( |
| 446 | "decls_in_anonymous_ns")) { |
| 447 | MovedDecls.emplace_back(FD, &Result.Context->getSourceManager()); |
| 448 | } else if (const auto *ND = |
| 449 | Result.Nodes.getNodeAs<clang::NamedDecl>("static_decls")) { |
| 450 | MovedDecls.emplace_back(ND, &Result.Context->getSourceManager()); |
| 451 | } |
| 452 | } |
| 453 | |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 454 | void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, |
| 455 | bool IsAngled, |
| 456 | llvm::StringRef SearchPath, |
| 457 | llvm::StringRef FileName, |
| 458 | const SourceManager& SM) { |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 459 | SmallVector<char, 128> HeaderWithSearchPath; |
| 460 | llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader); |
| 461 | std::string AbsoluteOldHeader = |
| 462 | MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader); |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 463 | // FIXME: Add old.h to the new.cc/h when the new target has dependencies on |
| 464 | // old.h/c. For instance, when moved class uses another class defined in |
| 465 | // old.h, the old.h should be added in new.h. |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 466 | if (AbsoluteOldHeader == |
| 467 | MakeAbsolutePath(SM, llvm::StringRef(HeaderWithSearchPath.data(), |
| 468 | HeaderWithSearchPath.size()))) |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 469 | return; |
| 470 | |
| 471 | std::string IncludeLine = |
| 472 | IsAngled ? ("#include <" + IncludeHeader + ">\n").str() |
| 473 | : ("#include \"" + IncludeHeader + "\"\n").str(); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 474 | |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 475 | std::string AbsoluteCurrentFile = MakeAbsolutePath(SM, FileName); |
| 476 | if (AbsoluteOldHeader == AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 477 | HeaderIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 478 | } else if (MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC) == |
Haojian Wu | db72657 | 2016-10-12 15:50:30 +0000 | [diff] [blame] | 479 | AbsoluteCurrentFile) { |
Haojian Wu | daf4cb8 | 2016-09-23 13:28:38 +0000 | [diff] [blame] | 480 | CCIncludes.push_back(IncludeLine); |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 481 | } |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 482 | } |
| 483 | |
| 484 | void ClangMoveTool::removeClassDefinitionInOldFiles() { |
| 485 | for (const auto &MovedDecl : RemovedDecls) { |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 486 | const auto &SM = *MovedDecl.SM; |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 487 | auto Range = GetFullRange(&SM, MovedDecl.Decl); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 488 | clang::tooling::Replacement RemoveReplacement( |
Haojian Wu | 9abbeaa | 2016-10-06 08:59:24 +0000 | [diff] [blame] | 489 | *MovedDecl.SM, clang::CharSourceRange::getCharRange( |
| 490 | Range.getBegin(), Range.getEnd()), |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 491 | ""); |
| 492 | std::string FilePath = RemoveReplacement.getFilePath().str(); |
| 493 | addOrMergeReplacement(RemoveReplacement, &FileToReplacements[FilePath]); |
Haojian Wu | 253d596 | 2016-10-06 08:29:32 +0000 | [diff] [blame] | 494 | |
| 495 | llvm::StringRef Code = |
| 496 | SM.getBufferData(SM.getFileID(MovedDecl.Decl->getLocation())); |
| 497 | format::FormatStyle Style = |
| 498 | format::getStyle("file", FilePath, FallbackStyle); |
| 499 | auto CleanReplacements = format::cleanupAroundReplacements( |
| 500 | Code, FileToReplacements[FilePath], Style); |
| 501 | |
| 502 | if (!CleanReplacements) { |
| 503 | llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n"; |
| 504 | continue; |
| 505 | } |
| 506 | FileToReplacements[FilePath] = *CleanReplacements; |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 507 | } |
| 508 | } |
| 509 | |
| 510 | void ClangMoveTool::moveClassDefinitionToNewFiles() { |
| 511 | std::vector<MovedDecl> NewHeaderDecls; |
| 512 | std::vector<MovedDecl> NewCCDecls; |
| 513 | for (const auto &MovedDecl : MovedDecls) { |
Haojian Wu | d2a6d7b | 2016-10-04 09:05:31 +0000 | [diff] [blame] | 514 | if (isInHeaderFile(*MovedDecl.SM, MovedDecl.Decl, OriginalRunningDirectory, |
| 515 | Spec.OldHeader)) |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 516 | NewHeaderDecls.push_back(MovedDecl); |
| 517 | else |
| 518 | NewCCDecls.push_back(MovedDecl); |
| 519 | } |
| 520 | |
| 521 | if (!Spec.NewHeader.empty()) |
| 522 | FileToReplacements[Spec.NewHeader] = createInsertedReplacements( |
Haojian Wu | 220c755 | 2016-10-14 13:01:36 +0000 | [diff] [blame^] | 523 | HeaderIncludes, NewHeaderDecls, Spec.NewHeader, /*IsHeader=*/true); |
Haojian Wu | 357ef99 | 2016-09-21 13:18:19 +0000 | [diff] [blame] | 524 | if (!Spec.NewCC.empty()) |
| 525 | FileToReplacements[Spec.NewCC] = |
| 526 | createInsertedReplacements(CCIncludes, NewCCDecls, Spec.NewCC); |
| 527 | } |
| 528 | |
| 529 | void ClangMoveTool::onEndOfTranslationUnit() { |
| 530 | if (RemovedDecls.empty()) |
| 531 | return; |
| 532 | removeClassDefinitionInOldFiles(); |
| 533 | moveClassDefinitionToNewFiles(); |
| 534 | } |
| 535 | |
| 536 | } // namespace move |
| 537 | } // namespace clang |