| Haojian Wu | 488c509 | 2019-05-31 14:38:16 +0000 | [diff] [blame] | 1 | //===--- Rename.cpp - Symbol-rename refactorings -----------------*- C++-*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| Sam McCall | c094912 | 2019-05-07 07:11:56 +0000 | [diff] [blame] | 9 | #include "refactor/Rename.h" |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 10 | #include "AST.h" |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 11 | #include "FindTarget.h" |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 12 | #include "Logger.h" |
| Sam McCall | 915f978 | 2019-09-04 09:46:06 +0000 | [diff] [blame] | 13 | #include "ParsedAST.h" |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 14 | #include "Selection.h" |
| Sam McCall | 19cefc2 | 2019-09-03 15:34:47 +0000 | [diff] [blame] | 15 | #include "SourceCode.h" |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 16 | #include "index/SymbolCollector.h" |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 17 | #include "clang/AST/DeclCXX.h" |
| 18 | #include "clang/AST/DeclTemplate.h" |
| 19 | #include "clang/Basic/SourceLocation.h" |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 20 | #include "clang/Tooling/Refactoring/Rename/USRFindingAction.h" |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 21 | #include "llvm/ADT/STLExtras.h" |
| 22 | #include "llvm/Support/Error.h" |
| Haojian Wu | 8805316 | 2019-11-19 15:23:36 +0100 | [diff] [blame] | 23 | #include "llvm/Support/FormatVariadic.h" |
| Sam McCall | c094912 | 2019-05-07 07:11:56 +0000 | [diff] [blame] | 24 | |
| 25 | namespace clang { |
| 26 | namespace clangd { |
| 27 | namespace { |
| 28 | |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 29 | llvm::Optional<std::string> filePath(const SymbolLocation &Loc, |
| 30 | llvm::StringRef HintFilePath) { |
| 31 | if (!Loc) |
| 32 | return None; |
| Haojian Wu | f821ab8 | 2019-10-29 10:49:27 +0100 | [diff] [blame] | 33 | auto Path = URI::resolve(Loc.FileURI, HintFilePath); |
| 34 | if (!Path) { |
| 35 | elog("Could not resolve URI {0}: {1}", Loc.FileURI, Path.takeError()); |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 36 | return None; |
| 37 | } |
| Haojian Wu | f821ab8 | 2019-10-29 10:49:27 +0100 | [diff] [blame] | 38 | |
| 39 | return *Path; |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 40 | } |
| 41 | |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 42 | // Returns true if the given location is expanded from any macro body. |
| 43 | bool isInMacroBody(const SourceManager &SM, SourceLocation Loc) { |
| 44 | while (Loc.isMacroID()) { |
| 45 | if (SM.isMacroBodyExpansion(Loc)) |
| 46 | return true; |
| 47 | Loc = SM.getImmediateMacroCallerLoc(Loc); |
| 48 | } |
| 49 | |
| 50 | return false; |
| 51 | } |
| 52 | |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 53 | // Query the index to find some other files where the Decl is referenced. |
| Haojian Wu | 93a825c | 2019-06-27 13:24:10 +0000 | [diff] [blame] | 54 | llvm::Optional<std::string> getOtherRefFile(const Decl &D, StringRef MainFile, |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 55 | const SymbolIndex &Index) { |
| 56 | RefsRequest Req; |
| 57 | // We limit the number of results, this is a correctness/performance |
| 58 | // tradeoff. We expect the number of symbol references in the current file |
| 59 | // is smaller than the limit. |
| 60 | Req.Limit = 100; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 61 | Req.IDs.insert(*getSymbolID(&D)); |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 62 | llvm::Optional<std::string> OtherFile; |
| 63 | Index.refs(Req, [&](const Ref &R) { |
| 64 | if (OtherFile) |
| 65 | return; |
| 66 | if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) { |
| 67 | if (*RefFilePath != MainFile) |
| 68 | OtherFile = *RefFilePath; |
| 69 | } |
| 70 | }); |
| 71 | return OtherFile; |
| 72 | } |
| 73 | |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 74 | llvm::DenseSet<const Decl *> locateDeclAt(ParsedAST &AST, |
| 75 | SourceLocation TokenStartLoc) { |
| 76 | unsigned Offset = |
| 77 | AST.getSourceManager().getDecomposedSpellingLoc(TokenStartLoc).second; |
| 78 | |
| 79 | SelectionTree Selection(AST.getASTContext(), AST.getTokens(), Offset); |
| 80 | const SelectionTree::Node *SelectedNode = Selection.commonAncestor(); |
| 81 | if (!SelectedNode) |
| 82 | return {}; |
| 83 | |
| 84 | // If the location points to a Decl, we check it is actually on the name |
| 85 | // range of the Decl. This would avoid allowing rename on unrelated tokens. |
| 86 | // ^class Foo {} // SelectionTree returns CXXRecordDecl, |
| 87 | // // we don't attempt to trigger rename on this position. |
| 88 | // FIXME: make this work on destructors, e.g. "~F^oo()". |
| 89 | if (const auto *D = SelectedNode->ASTNode.get<Decl>()) { |
| 90 | if (D->getLocation() != TokenStartLoc) |
| 91 | return {}; |
| 92 | } |
| 93 | |
| 94 | llvm::DenseSet<const Decl *> Result; |
| 95 | for (const auto *D : |
| 96 | targetDecl(SelectedNode->ASTNode, |
| 97 | DeclRelation::Alias | DeclRelation::TemplatePattern)) |
| 98 | Result.insert(D); |
| 99 | return Result; |
| 100 | } |
| 101 | |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 102 | enum ReasonToReject { |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 103 | NoSymbolFound, |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 104 | NoIndexProvided, |
| 105 | NonIndexable, |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 106 | UsedOutsideFile, // for within-file rename only. |
| Haojian Wu | 442a120 | 2019-06-26 08:10:26 +0000 | [diff] [blame] | 107 | UnsupportedSymbol, |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 108 | AmbiguousSymbol, |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 109 | }; |
| 110 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 111 | llvm::Optional<ReasonToReject> renameable(const Decl &RenameDecl, |
| 112 | StringRef MainFilePath, |
| 113 | const SymbolIndex *Index, |
| 114 | bool CrossFile) { |
| 115 | // Filter out symbols that are unsupported in both rename modes. |
| Haojian Wu | 93a825c | 2019-06-27 13:24:10 +0000 | [diff] [blame] | 116 | if (llvm::isa<NamespaceDecl>(&RenameDecl)) |
| Haojian Wu | 442a120 | 2019-06-26 08:10:26 +0000 | [diff] [blame] | 117 | return ReasonToReject::UnsupportedSymbol; |
| Haojian Wu | af28bb6 | 2019-09-16 10:16:56 +0000 | [diff] [blame] | 118 | if (const auto *FD = llvm::dyn_cast<FunctionDecl>(&RenameDecl)) { |
| 119 | if (FD->isOverloadedOperator()) |
| 120 | return ReasonToReject::UnsupportedSymbol; |
| 121 | } |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 122 | // function-local symbols is safe to rename. |
| Haojian Wu | 93a825c | 2019-06-27 13:24:10 +0000 | [diff] [blame] | 123 | if (RenameDecl.getParentFunctionOrMethod()) |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 124 | return None; |
| 125 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 126 | bool IsIndexable = |
| 127 | isa<NamedDecl>(RenameDecl) && |
| 128 | SymbolCollector::shouldCollectSymbol( |
| 129 | cast<NamedDecl>(RenameDecl), RenameDecl.getASTContext(), |
| 130 | SymbolCollector::Options(), CrossFile); |
| 131 | if (!IsIndexable) // If the symbol is not indexable, we disallow rename. |
| 132 | return ReasonToReject::NonIndexable; |
| 133 | |
| 134 | if (!CrossFile) { |
| 135 | auto &ASTCtx = RenameDecl.getASTContext(); |
| 136 | const auto &SM = ASTCtx.getSourceManager(); |
| 137 | bool MainFileIsHeader = isHeaderFile(MainFilePath, ASTCtx.getLangOpts()); |
| 138 | bool DeclaredInMainFile = isInsideMainFile(RenameDecl.getBeginLoc(), SM); |
| 139 | |
| 140 | if (!DeclaredInMainFile) |
| 141 | // We are sure the symbol is used externally, bail out early. |
| 142 | return ReasonToReject::UsedOutsideFile; |
| 143 | |
| 144 | // If the symbol is declared in the main file (which is not a header), we |
| 145 | // rename it. |
| 146 | if (!MainFileIsHeader) |
| 147 | return None; |
| 148 | |
| 149 | if (!Index) |
| 150 | return ReasonToReject::NoIndexProvided; |
| 151 | |
| 152 | auto OtherFile = getOtherRefFile(RenameDecl, MainFilePath, *Index); |
| 153 | // If the symbol is indexable and has no refs from other files in the index, |
| 154 | // we rename it. |
| 155 | if (!OtherFile) |
| 156 | return None; |
| 157 | // If the symbol is indexable and has refs from other files in the index, |
| 158 | // we disallow rename. |
| 159 | return ReasonToReject::UsedOutsideFile; |
| 160 | } |
| 161 | |
| 162 | assert(CrossFile); |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 163 | if (!Index) |
| 164 | return ReasonToReject::NoIndexProvided; |
| 165 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 166 | // Blacklist symbols that are not supported yet in cross-file mode due to the |
| 167 | // limitations of our index. |
| 168 | // FIXME: renaming templates requries to rename all related specializations, |
| 169 | // our index doesn't have this information. |
| 170 | if (RenameDecl.getDescribedTemplate()) |
| 171 | return ReasonToReject::UnsupportedSymbol; |
| 172 | |
| 173 | // FIXME: renaming virtual methods requires to rename all overridens in |
| 174 | // subclasses, our index doesn't have this information. |
| 175 | // Note: within-file rename does support this through the AST. |
| 176 | if (const auto *S = llvm::dyn_cast<CXXMethodDecl>(&RenameDecl)) { |
| 177 | if (S->isVirtual()) |
| 178 | return ReasonToReject::UnsupportedSymbol; |
| 179 | } |
| 180 | return None; |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 181 | } |
| 182 | |
| Haojian Wu | 9d34f45 | 2019-07-01 09:26:48 +0000 | [diff] [blame] | 183 | llvm::Error makeError(ReasonToReject Reason) { |
| 184 | auto Message = [](ReasonToReject Reason) { |
| 185 | switch (Reason) { |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 186 | case ReasonToReject::NoSymbolFound: |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 187 | return "there is no symbol at the given location"; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 188 | case ReasonToReject::NoIndexProvided: |
| Haojian Wu | 08cce03 | 2019-11-28 11:39:48 +0100 | [diff] [blame] | 189 | return "no index provided"; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 190 | case ReasonToReject::UsedOutsideFile: |
| Haojian Wu | 9d34f45 | 2019-07-01 09:26:48 +0000 | [diff] [blame] | 191 | return "the symbol is used outside main file"; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 192 | case ReasonToReject::NonIndexable: |
| Haojian Wu | 9d34f45 | 2019-07-01 09:26:48 +0000 | [diff] [blame] | 193 | return "symbol may be used in other files (not eligible for indexing)"; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 194 | case ReasonToReject::UnsupportedSymbol: |
| Haojian Wu | 9d34f45 | 2019-07-01 09:26:48 +0000 | [diff] [blame] | 195 | return "symbol is not a supported kind (e.g. namespace, macro)"; |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 196 | case AmbiguousSymbol: |
| 197 | return "there are multiple symbols at the given location"; |
| Haojian Wu | 9d34f45 | 2019-07-01 09:26:48 +0000 | [diff] [blame] | 198 | } |
| 199 | llvm_unreachable("unhandled reason kind"); |
| 200 | }; |
| 201 | return llvm::make_error<llvm::StringError>( |
| 202 | llvm::formatv("Cannot rename symbol: {0}", Message(Reason)), |
| 203 | llvm::inconvertibleErrorCode()); |
| 204 | } |
| 205 | |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 206 | // Return all rename occurrences in the main file. |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 207 | std::vector<SourceLocation> findOccurrencesWithinFile(ParsedAST &AST, |
| 208 | const NamedDecl &ND) { |
| 209 | // In theory, locateDeclAt should return the primary template. However, if the |
| 210 | // cursor is under the underlying CXXRecordDecl of the ClassTemplateDecl, ND |
| 211 | // will be the CXXRecordDecl, for this case, we need to get the primary |
| 212 | // template maunally. |
| 213 | const auto &RenameDecl = |
| 214 | ND.getDescribedTemplate() ? *ND.getDescribedTemplate() : ND; |
| 215 | // getUSRsForDeclaration will find other related symbols, e.g. virtual and its |
| 216 | // overriddens, primary template and all explicit specializations. |
| 217 | // FIXME: get rid of the remaining tooling APIs. |
| 218 | std::vector<std::string> RenameUSRs = tooling::getUSRsForDeclaration( |
| 219 | tooling::getCanonicalSymbolDeclaration(&RenameDecl), AST.getASTContext()); |
| 220 | llvm::DenseSet<SymbolID> TargetIDs; |
| 221 | for (auto &USR : RenameUSRs) |
| 222 | TargetIDs.insert(SymbolID(USR)); |
| 223 | |
| 224 | std::vector<SourceLocation> Results; |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 225 | for (Decl *TopLevelDecl : AST.getLocalTopLevelDecls()) { |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 226 | findExplicitReferences(TopLevelDecl, [&](ReferenceLoc Ref) { |
| 227 | if (Ref.Targets.empty()) |
| 228 | return; |
| 229 | for (const auto *Target : Ref.Targets) { |
| 230 | auto ID = getSymbolID(Target); |
| 231 | if (!ID || TargetIDs.find(*ID) == TargetIDs.end()) |
| 232 | return; |
| 233 | } |
| 234 | Results.push_back(Ref.NameLoc); |
| 235 | }); |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 236 | } |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 237 | |
| 238 | return Results; |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 239 | } |
| 240 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 241 | // AST-based rename, it renames all occurrences in the main file. |
| Sam McCall | c094912 | 2019-05-07 07:11:56 +0000 | [diff] [blame] | 242 | llvm::Expected<tooling::Replacements> |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 243 | renameWithinFile(ParsedAST &AST, const NamedDecl &RenameDecl, |
| 244 | llvm::StringRef NewName) { |
| Sam McCall | b2a984c0 | 2019-09-04 10:15:27 +0000 | [diff] [blame] | 245 | const SourceManager &SM = AST.getSourceManager(); |
| Haojian Wu | 7276a44 | 2019-06-25 08:43:17 +0000 | [diff] [blame] | 246 | |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 247 | tooling::Replacements FilteredChanges; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 248 | for (SourceLocation Loc : findOccurrencesWithinFile(AST, RenameDecl)) { |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 249 | SourceLocation RenameLoc = Loc; |
| 250 | // We don't rename in any macro bodies, but we allow rename the symbol |
| 251 | // spelled in a top-level macro argument in the main file. |
| 252 | if (RenameLoc.isMacroID()) { |
| 253 | if (isInMacroBody(SM, RenameLoc)) |
| 254 | continue; |
| 255 | RenameLoc = SM.getSpellingLoc(Loc); |
| 256 | } |
| 257 | // Filter out locations not from main file. |
| 258 | // We traverse only main file decls, but locations could come from an |
| 259 | // non-preamble #include file e.g. |
| 260 | // void test() { |
| 261 | // int f^oo; |
| 262 | // #include "use_foo.inc" |
| 263 | // } |
| 264 | if (!isInsideMainFile(RenameLoc, SM)) |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 265 | continue; |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 266 | if (auto Err = FilteredChanges.add(tooling::Replacement( |
| Haojian Wu | 7db1230 | 2019-11-19 10:10:43 +0100 | [diff] [blame] | 267 | SM, CharSourceRange::getTokenRange(RenameLoc), NewName))) |
| Haojian Wu | 8b49173 | 2019-08-09 10:55:22 +0000 | [diff] [blame] | 268 | return std::move(Err); |
| Sam McCall | c094912 | 2019-05-07 07:11:56 +0000 | [diff] [blame] | 269 | } |
| 270 | return FilteredChanges; |
| 271 | } |
| 272 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 273 | Range toRange(const SymbolLocation &L) { |
| 274 | Range R; |
| 275 | R.start.line = L.Start.line(); |
| 276 | R.start.character = L.Start.column(); |
| 277 | R.end.line = L.End.line(); |
| 278 | R.end.character = L.End.column(); |
| 279 | return R; |
| 280 | }; |
| 281 | |
| 282 | // Return all rename occurrences (per the index) outside of the main file, |
| 283 | // grouped by the absolute file path. |
| Haojian Wu | 3c3aca2 | 2019-11-28 12:47:32 +0100 | [diff] [blame] | 284 | llvm::Expected<llvm::StringMap<std::vector<Range>>> |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 285 | findOccurrencesOutsideFile(const NamedDecl &RenameDecl, |
| 286 | llvm::StringRef MainFile, const SymbolIndex &Index) { |
| 287 | RefsRequest RQuest; |
| 288 | RQuest.IDs.insert(*getSymbolID(&RenameDecl)); |
| 289 | |
| Haojian Wu | 3c3aca2 | 2019-11-28 12:47:32 +0100 | [diff] [blame] | 290 | // Absolute file path => rename occurrences in that file. |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 291 | llvm::StringMap<std::vector<Range>> AffectedFiles; |
| Haojian Wu | 3c3aca2 | 2019-11-28 12:47:32 +0100 | [diff] [blame] | 292 | // FIXME: make the limit customizable. |
| 293 | static constexpr size_t MaxLimitFiles = 50; |
| 294 | bool HasMore = Index.refs(RQuest, [&](const Ref &R) { |
| 295 | if (AffectedFiles.size() > MaxLimitFiles) |
| 296 | return; |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 297 | if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) { |
| 298 | if (*RefFilePath != MainFile) |
| 299 | AffectedFiles[*RefFilePath].push_back(toRange(R.Location)); |
| 300 | } |
| 301 | }); |
| Haojian Wu | 3c3aca2 | 2019-11-28 12:47:32 +0100 | [diff] [blame] | 302 | |
| 303 | if (AffectedFiles.size() > MaxLimitFiles) |
| 304 | return llvm::make_error<llvm::StringError>( |
| 305 | llvm::formatv("The number of affected files exceeds the max limit {0}", |
| 306 | MaxLimitFiles), |
| 307 | llvm::inconvertibleErrorCode()); |
| 308 | if (HasMore) { |
| 309 | return llvm::make_error<llvm::StringError>( |
| 310 | llvm::formatv("The symbol {0} has too many occurrences", |
| 311 | RenameDecl.getQualifiedNameAsString()), |
| 312 | llvm::inconvertibleErrorCode()); |
| 313 | } |
| 314 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 315 | return AffectedFiles; |
| 316 | } |
| 317 | |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 318 | // Index-based rename, it renames all occurrences outside of the main file. |
| 319 | // |
| 320 | // The cross-file rename is purely based on the index, as we don't want to |
| 321 | // build all ASTs for affected files, which may cause a performance hit. |
| 322 | // We choose to trade off some correctness for performance and scalability. |
| 323 | // |
| 324 | // Clangd builds a dynamic index for all opened files on top of the static |
| 325 | // index of the whole codebase. Dynamic index is up-to-date (respects dirty |
| 326 | // buffers) as long as clangd finishes processing opened files, while static |
| 327 | // index (background index) is relatively stale. We choose the dirty buffers |
| 328 | // as the file content we rename on, and fallback to file content on disk if |
| 329 | // there is no dirty buffer. |
| 330 | // |
| 331 | // FIXME: add range patching heuristics to detect staleness of the index, and |
| 332 | // report to users. |
| 333 | // FIXME: our index may return implicit references, which are non-eligitble |
| 334 | // for rename, we should filter out these references. |
| 335 | llvm::Expected<FileEdits> renameOutsideFile( |
| 336 | const NamedDecl &RenameDecl, llvm::StringRef MainFilePath, |
| 337 | llvm::StringRef NewName, const SymbolIndex &Index, |
| 338 | llvm::function_ref<llvm::Expected<std::string>(PathRef)> GetFileContent) { |
| 339 | auto AffectedFiles = |
| 340 | findOccurrencesOutsideFile(RenameDecl, MainFilePath, Index); |
| Haojian Wu | 3c3aca2 | 2019-11-28 12:47:32 +0100 | [diff] [blame] | 341 | if (!AffectedFiles) |
| 342 | return AffectedFiles.takeError(); |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 343 | FileEdits Results; |
| Haojian Wu | 3c3aca2 | 2019-11-28 12:47:32 +0100 | [diff] [blame] | 344 | for (auto &FileAndOccurrences : *AffectedFiles) { |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 345 | llvm::StringRef FilePath = FileAndOccurrences.first(); |
| 346 | |
| 347 | auto AffectedFileCode = GetFileContent(FilePath); |
| 348 | if (!AffectedFileCode) { |
| 349 | elog("Fail to read file content: {0}", AffectedFileCode.takeError()); |
| 350 | continue; |
| 351 | } |
| Haojian Wu | 66ab932 | 2019-11-28 16:48:49 +0100 | [diff] [blame^] | 352 | auto RenameEdit = |
| 353 | buildRenameEdit(FilePath, *AffectedFileCode, |
| 354 | std::move(FileAndOccurrences.second), NewName); |
| Haojian Wu | 8805316 | 2019-11-19 15:23:36 +0100 | [diff] [blame] | 355 | if (!RenameEdit) { |
| 356 | return llvm::make_error<llvm::StringError>( |
| 357 | llvm::formatv("fail to build rename edit for file {0}: {1}", FilePath, |
| 358 | llvm::toString(RenameEdit.takeError())), |
| 359 | llvm::inconvertibleErrorCode()); |
| 360 | } |
| Haojian Wu | 852bafa | 2019-10-23 14:40:20 +0200 | [diff] [blame] | 361 | if (!RenameEdit->Replacements.empty()) |
| 362 | Results.insert({FilePath, std::move(*RenameEdit)}); |
| 363 | } |
| 364 | return Results; |
| 365 | } |
| 366 | |
| 367 | } // namespace |
| 368 | |
| 369 | llvm::Expected<FileEdits> rename(const RenameInputs &RInputs) { |
| 370 | ParsedAST &AST = RInputs.AST; |
| 371 | const SourceManager &SM = AST.getSourceManager(); |
| 372 | llvm::StringRef MainFileCode = SM.getBufferData(SM.getMainFileID()); |
| 373 | auto GetFileContent = [&RInputs, |
| 374 | &SM](PathRef AbsPath) -> llvm::Expected<std::string> { |
| 375 | llvm::Optional<std::string> DirtyBuffer; |
| 376 | if (RInputs.GetDirtyBuffer && |
| 377 | (DirtyBuffer = RInputs.GetDirtyBuffer(AbsPath))) |
| 378 | return std::move(*DirtyBuffer); |
| 379 | |
| 380 | auto Content = |
| 381 | SM.getFileManager().getVirtualFileSystem().getBufferForFile(AbsPath); |
| 382 | if (!Content) |
| 383 | return llvm::createStringError( |
| 384 | llvm::inconvertibleErrorCode(), |
| 385 | llvm::formatv("Fail to open file {0}: {1}", AbsPath, |
| 386 | Content.getError().message())); |
| 387 | if (!*Content) |
| 388 | return llvm::createStringError( |
| 389 | llvm::inconvertibleErrorCode(), |
| 390 | llvm::formatv("Got no buffer for file {0}", AbsPath)); |
| 391 | |
| 392 | return (*Content)->getBuffer().str(); |
| 393 | }; |
| 394 | SourceLocation SourceLocationBeg = |
| 395 | SM.getMacroArgExpandedLocation(getBeginningOfIdentifier( |
| 396 | RInputs.Pos, SM, AST.getASTContext().getLangOpts())); |
| 397 | // FIXME: renaming macros is not supported yet, the macro-handling code should |
| 398 | // be moved to rename tooling library. |
| 399 | if (locateMacroAt(SourceLocationBeg, AST.getPreprocessor())) |
| 400 | return makeError(ReasonToReject::UnsupportedSymbol); |
| 401 | |
| 402 | auto DeclsUnderCursor = locateDeclAt(AST, SourceLocationBeg); |
| 403 | if (DeclsUnderCursor.empty()) |
| 404 | return makeError(ReasonToReject::NoSymbolFound); |
| 405 | if (DeclsUnderCursor.size() > 1) |
| 406 | return makeError(ReasonToReject::AmbiguousSymbol); |
| 407 | |
| 408 | const auto *RenameDecl = llvm::dyn_cast<NamedDecl>(*DeclsUnderCursor.begin()); |
| 409 | if (!RenameDecl) |
| 410 | return makeError(ReasonToReject::UnsupportedSymbol); |
| 411 | |
| 412 | auto Reject = |
| 413 | renameable(*RenameDecl->getCanonicalDecl(), RInputs.MainFilePath, |
| 414 | RInputs.Index, RInputs.AllowCrossFile); |
| 415 | if (Reject) |
| 416 | return makeError(*Reject); |
| 417 | |
| 418 | // We have two implemenations of the rename: |
| 419 | // - AST-based rename: used for renaming local symbols, e.g. variables |
| 420 | // defined in a function body; |
| 421 | // - index-based rename: used for renaming non-local symbols, and not |
| 422 | // feasible for local symbols (as by design our index don't index these |
| 423 | // symbols by design; |
| 424 | // To make cross-file rename work for local symbol, we use a hybrid solution: |
| 425 | // - run AST-based rename on the main file; |
| 426 | // - run index-based rename on other affected files; |
| 427 | auto MainFileRenameEdit = renameWithinFile(AST, *RenameDecl, RInputs.NewName); |
| 428 | if (!MainFileRenameEdit) |
| 429 | return MainFileRenameEdit.takeError(); |
| 430 | |
| 431 | if (!RInputs.AllowCrossFile) { |
| 432 | // within-file rename, just return the main file results. |
| 433 | return FileEdits( |
| 434 | {std::make_pair(RInputs.MainFilePath, |
| 435 | Edit{MainFileCode, std::move(*MainFileRenameEdit)})}); |
| 436 | } |
| 437 | |
| 438 | FileEdits Results; |
| 439 | // renameable safely guards us that at this point we are renaming a local |
| 440 | // symbol if we don't have index, |
| 441 | if (RInputs.Index) { |
| 442 | auto OtherFilesEdits = |
| 443 | renameOutsideFile(*RenameDecl, RInputs.MainFilePath, RInputs.NewName, |
| 444 | *RInputs.Index, GetFileContent); |
| 445 | if (!OtherFilesEdits) |
| 446 | return OtherFilesEdits.takeError(); |
| 447 | Results = std::move(*OtherFilesEdits); |
| 448 | } |
| 449 | // Attach the rename edits for the main file. |
| 450 | Results.try_emplace(RInputs.MainFilePath, MainFileCode, |
| 451 | std::move(*MainFileRenameEdit)); |
| 452 | return Results; |
| 453 | } |
| 454 | |
| Haojian Wu | 66ab932 | 2019-11-28 16:48:49 +0100 | [diff] [blame^] | 455 | llvm::Expected<Edit> buildRenameEdit(llvm::StringRef AbsFilePath, |
| 456 | llvm::StringRef InitialCode, |
| Haojian Wu | 8805316 | 2019-11-19 15:23:36 +0100 | [diff] [blame] | 457 | std::vector<Range> Occurrences, |
| 458 | llvm::StringRef NewName) { |
| 459 | llvm::sort(Occurrences); |
| 460 | // These two always correspond to the same position. |
| 461 | Position LastPos{0, 0}; |
| 462 | size_t LastOffset = 0; |
| 463 | |
| 464 | auto Offset = [&](const Position &P) -> llvm::Expected<size_t> { |
| 465 | assert(LastPos <= P && "malformed input"); |
| 466 | Position Shifted = { |
| 467 | P.line - LastPos.line, |
| 468 | P.line > LastPos.line ? P.character : P.character - LastPos.character}; |
| 469 | auto ShiftedOffset = |
| 470 | positionToOffset(InitialCode.substr(LastOffset), Shifted); |
| 471 | if (!ShiftedOffset) |
| 472 | return llvm::make_error<llvm::StringError>( |
| 473 | llvm::formatv("fail to convert the position {0} to offset ({1})", P, |
| 474 | llvm::toString(ShiftedOffset.takeError())), |
| 475 | llvm::inconvertibleErrorCode()); |
| 476 | LastPos = P; |
| 477 | LastOffset += *ShiftedOffset; |
| 478 | return LastOffset; |
| 479 | }; |
| 480 | |
| 481 | std::vector<std::pair</*start*/ size_t, /*end*/ size_t>> OccurrencesOffsets; |
| 482 | for (const auto &R : Occurrences) { |
| 483 | auto StartOffset = Offset(R.start); |
| 484 | if (!StartOffset) |
| 485 | return StartOffset.takeError(); |
| 486 | auto EndOffset = Offset(R.end); |
| 487 | if (!EndOffset) |
| 488 | return EndOffset.takeError(); |
| 489 | OccurrencesOffsets.push_back({*StartOffset, *EndOffset}); |
| 490 | } |
| 491 | |
| 492 | tooling::Replacements RenameEdit; |
| 493 | for (const auto &R : OccurrencesOffsets) { |
| 494 | auto ByteLength = R.second - R.first; |
| 495 | if (auto Err = RenameEdit.add( |
| Haojian Wu | 66ab932 | 2019-11-28 16:48:49 +0100 | [diff] [blame^] | 496 | tooling::Replacement(AbsFilePath, R.first, ByteLength, NewName))) |
| Haojian Wu | 8805316 | 2019-11-19 15:23:36 +0100 | [diff] [blame] | 497 | return std::move(Err); |
| 498 | } |
| 499 | return Edit(InitialCode, std::move(RenameEdit)); |
| 500 | } |
| 501 | |
| Sam McCall | c094912 | 2019-05-07 07:11:56 +0000 | [diff] [blame] | 502 | } // namespace clangd |
| 503 | } // namespace clang |