blob: 6a3439cc06127e0cacacb6a5574dc50936abe305 [file] [log] [blame]
Haojian Wu488c5092019-05-31 14:38:16 +00001//===--- 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 McCallc0949122019-05-07 07:11:56 +00009#include "refactor/Rename.h"
Haojian Wu7276a442019-06-25 08:43:17 +000010#include "AST.h"
Haojian Wu7db12302019-11-19 10:10:43 +010011#include "FindTarget.h"
Haojian Wu7276a442019-06-25 08:43:17 +000012#include "Logger.h"
Sam McCall915f9782019-09-04 09:46:06 +000013#include "ParsedAST.h"
Haojian Wu7db12302019-11-19 10:10:43 +010014#include "Selection.h"
Sam McCall19cefc22019-09-03 15:34:47 +000015#include "SourceCode.h"
Haojian Wu7276a442019-06-25 08:43:17 +000016#include "index/SymbolCollector.h"
Haojian Wu7db12302019-11-19 10:10:43 +010017#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Basic/SourceLocation.h"
Haojian Wu8b491732019-08-09 10:55:22 +000020#include "clang/Tooling/Refactoring/Rename/USRFindingAction.h"
Haojian Wu852bafa2019-10-23 14:40:20 +020021#include "llvm/ADT/STLExtras.h"
22#include "llvm/Support/Error.h"
Haojian Wu88053162019-11-19 15:23:36 +010023#include "llvm/Support/FormatVariadic.h"
Sam McCallc0949122019-05-07 07:11:56 +000024
25namespace clang {
26namespace clangd {
27namespace {
28
Haojian Wu7276a442019-06-25 08:43:17 +000029llvm::Optional<std::string> filePath(const SymbolLocation &Loc,
30 llvm::StringRef HintFilePath) {
31 if (!Loc)
32 return None;
Haojian Wuf821ab82019-10-29 10:49:27 +010033 auto Path = URI::resolve(Loc.FileURI, HintFilePath);
34 if (!Path) {
35 elog("Could not resolve URI {0}: {1}", Loc.FileURI, Path.takeError());
Haojian Wu7276a442019-06-25 08:43:17 +000036 return None;
37 }
Haojian Wuf821ab82019-10-29 10:49:27 +010038
39 return *Path;
Haojian Wu7276a442019-06-25 08:43:17 +000040}
41
Haojian Wu7db12302019-11-19 10:10:43 +010042// Returns true if the given location is expanded from any macro body.
43bool 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 Wu7276a442019-06-25 08:43:17 +000053// Query the index to find some other files where the Decl is referenced.
Haojian Wu93a825c2019-06-27 13:24:10 +000054llvm::Optional<std::string> getOtherRefFile(const Decl &D, StringRef MainFile,
Haojian Wu7276a442019-06-25 08:43:17 +000055 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 Wu852bafa2019-10-23 14:40:20 +020061 Req.IDs.insert(*getSymbolID(&D));
Haojian Wu7276a442019-06-25 08:43:17 +000062 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 Wu7db12302019-11-19 10:10:43 +010074llvm::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 Wu7276a442019-06-25 08:43:17 +0000102enum ReasonToReject {
Haojian Wu8b491732019-08-09 10:55:22 +0000103 NoSymbolFound,
Haojian Wu7276a442019-06-25 08:43:17 +0000104 NoIndexProvided,
105 NonIndexable,
Haojian Wu852bafa2019-10-23 14:40:20 +0200106 UsedOutsideFile, // for within-file rename only.
Haojian Wu442a1202019-06-26 08:10:26 +0000107 UnsupportedSymbol,
Haojian Wu7db12302019-11-19 10:10:43 +0100108 AmbiguousSymbol,
Haojian Wu7276a442019-06-25 08:43:17 +0000109};
110
Haojian Wu852bafa2019-10-23 14:40:20 +0200111llvm::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 Wu93a825c2019-06-27 13:24:10 +0000116 if (llvm::isa<NamespaceDecl>(&RenameDecl))
Haojian Wu442a1202019-06-26 08:10:26 +0000117 return ReasonToReject::UnsupportedSymbol;
Haojian Wuaf28bb62019-09-16 10:16:56 +0000118 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(&RenameDecl)) {
119 if (FD->isOverloadedOperator())
120 return ReasonToReject::UnsupportedSymbol;
121 }
Haojian Wu852bafa2019-10-23 14:40:20 +0200122 // function-local symbols is safe to rename.
Haojian Wu93a825c2019-06-27 13:24:10 +0000123 if (RenameDecl.getParentFunctionOrMethod())
Haojian Wu7276a442019-06-25 08:43:17 +0000124 return None;
125
Haojian Wu852bafa2019-10-23 14:40:20 +0200126 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 Wu7276a442019-06-25 08:43:17 +0000163 if (!Index)
164 return ReasonToReject::NoIndexProvided;
165
Haojian Wu852bafa2019-10-23 14:40:20 +0200166 // 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 Wu7276a442019-06-25 08:43:17 +0000181}
182
Haojian Wu9d34f452019-07-01 09:26:48 +0000183llvm::Error makeError(ReasonToReject Reason) {
184 auto Message = [](ReasonToReject Reason) {
185 switch (Reason) {
Haojian Wu852bafa2019-10-23 14:40:20 +0200186 case ReasonToReject::NoSymbolFound:
Haojian Wu8b491732019-08-09 10:55:22 +0000187 return "there is no symbol at the given location";
Haojian Wu852bafa2019-10-23 14:40:20 +0200188 case ReasonToReject::NoIndexProvided:
Haojian Wu08cce032019-11-28 11:39:48 +0100189 return "no index provided";
Haojian Wu852bafa2019-10-23 14:40:20 +0200190 case ReasonToReject::UsedOutsideFile:
Haojian Wu9d34f452019-07-01 09:26:48 +0000191 return "the symbol is used outside main file";
Haojian Wu852bafa2019-10-23 14:40:20 +0200192 case ReasonToReject::NonIndexable:
Haojian Wu9d34f452019-07-01 09:26:48 +0000193 return "symbol may be used in other files (not eligible for indexing)";
Haojian Wu852bafa2019-10-23 14:40:20 +0200194 case ReasonToReject::UnsupportedSymbol:
Haojian Wu9d34f452019-07-01 09:26:48 +0000195 return "symbol is not a supported kind (e.g. namespace, macro)";
Haojian Wu7db12302019-11-19 10:10:43 +0100196 case AmbiguousSymbol:
197 return "there are multiple symbols at the given location";
Haojian Wu9d34f452019-07-01 09:26:48 +0000198 }
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 Wu8b491732019-08-09 10:55:22 +0000206// Return all rename occurrences in the main file.
Haojian Wu7db12302019-11-19 10:10:43 +0100207std::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 Wu8b491732019-08-09 10:55:22 +0000225 for (Decl *TopLevelDecl : AST.getLocalTopLevelDecls()) {
Haojian Wu7db12302019-11-19 10:10:43 +0100226 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 Wu8b491732019-08-09 10:55:22 +0000236 }
Haojian Wu7db12302019-11-19 10:10:43 +0100237
238 return Results;
Haojian Wu8b491732019-08-09 10:55:22 +0000239}
240
Haojian Wu852bafa2019-10-23 14:40:20 +0200241// AST-based rename, it renames all occurrences in the main file.
Sam McCallc0949122019-05-07 07:11:56 +0000242llvm::Expected<tooling::Replacements>
Haojian Wu852bafa2019-10-23 14:40:20 +0200243renameWithinFile(ParsedAST &AST, const NamedDecl &RenameDecl,
244 llvm::StringRef NewName) {
Sam McCallb2a984c02019-09-04 10:15:27 +0000245 const SourceManager &SM = AST.getSourceManager();
Haojian Wu7276a442019-06-25 08:43:17 +0000246
Haojian Wu8b491732019-08-09 10:55:22 +0000247 tooling::Replacements FilteredChanges;
Haojian Wu852bafa2019-10-23 14:40:20 +0200248 for (SourceLocation Loc : findOccurrencesWithinFile(AST, RenameDecl)) {
Haojian Wu7db12302019-11-19 10:10:43 +0100249 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 Wu8b491732019-08-09 10:55:22 +0000265 continue;
Haojian Wu8b491732019-08-09 10:55:22 +0000266 if (auto Err = FilteredChanges.add(tooling::Replacement(
Haojian Wu7db12302019-11-19 10:10:43 +0100267 SM, CharSourceRange::getTokenRange(RenameLoc), NewName)))
Haojian Wu8b491732019-08-09 10:55:22 +0000268 return std::move(Err);
Sam McCallc0949122019-05-07 07:11:56 +0000269 }
270 return FilteredChanges;
271}
272
Haojian Wu852bafa2019-10-23 14:40:20 +0200273Range 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 Wu3c3aca22019-11-28 12:47:32 +0100284llvm::Expected<llvm::StringMap<std::vector<Range>>>
Haojian Wu852bafa2019-10-23 14:40:20 +0200285findOccurrencesOutsideFile(const NamedDecl &RenameDecl,
286 llvm::StringRef MainFile, const SymbolIndex &Index) {
287 RefsRequest RQuest;
288 RQuest.IDs.insert(*getSymbolID(&RenameDecl));
289
Haojian Wu3c3aca22019-11-28 12:47:32 +0100290 // Absolute file path => rename occurrences in that file.
Haojian Wu852bafa2019-10-23 14:40:20 +0200291 llvm::StringMap<std::vector<Range>> AffectedFiles;
Haojian Wu3c3aca22019-11-28 12:47:32 +0100292 // 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 Wu852bafa2019-10-23 14:40:20 +0200297 if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) {
298 if (*RefFilePath != MainFile)
299 AffectedFiles[*RefFilePath].push_back(toRange(R.Location));
300 }
301 });
Haojian Wu3c3aca22019-11-28 12:47:32 +0100302
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 Wu852bafa2019-10-23 14:40:20 +0200315 return AffectedFiles;
316}
317
Haojian Wu852bafa2019-10-23 14:40:20 +0200318// 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.
335llvm::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 Wu3c3aca22019-11-28 12:47:32 +0100341 if (!AffectedFiles)
342 return AffectedFiles.takeError();
Haojian Wu852bafa2019-10-23 14:40:20 +0200343 FileEdits Results;
Haojian Wu3c3aca22019-11-28 12:47:32 +0100344 for (auto &FileAndOccurrences : *AffectedFiles) {
Haojian Wu852bafa2019-10-23 14:40:20 +0200345 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 Wu66ab9322019-11-28 16:48:49 +0100352 auto RenameEdit =
353 buildRenameEdit(FilePath, *AffectedFileCode,
354 std::move(FileAndOccurrences.second), NewName);
Haojian Wu88053162019-11-19 15:23:36 +0100355 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 Wu852bafa2019-10-23 14:40:20 +0200361 if (!RenameEdit->Replacements.empty())
362 Results.insert({FilePath, std::move(*RenameEdit)});
363 }
364 return Results;
365}
366
367} // namespace
368
369llvm::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 Wu66ab9322019-11-28 16:48:49 +0100455llvm::Expected<Edit> buildRenameEdit(llvm::StringRef AbsFilePath,
456 llvm::StringRef InitialCode,
Haojian Wu88053162019-11-19 15:23:36 +0100457 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 Wu66ab9322019-11-28 16:48:49 +0100496 tooling::Replacement(AbsFilePath, R.first, ByteLength, NewName)))
Haojian Wu88053162019-11-19 15:23:36 +0100497 return std::move(Err);
498 }
499 return Edit(InitialCode, std::move(RenameEdit));
500}
501
Sam McCallc0949122019-05-07 07:11:56 +0000502} // namespace clangd
503} // namespace clang