clang-tools  10.0.0svn
Rename.cpp
Go to the documentation of this file.
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 
9 #include "refactor/Rename.h"
10 #include "AST.h"
11 #include "Logger.h"
12 #include "ParsedAST.h"
13 #include "SourceCode.h"
14 #include "index/SymbolCollector.h"
15 #include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
16 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
17 #include "clang/Tooling/Refactoring/Rename/USRFindingAction.h"
18 #include "clang/Tooling/Refactoring/Rename/USRLocFinder.h"
19 
20 namespace clang {
21 namespace clangd {
22 namespace {
23 
24 llvm::Optional<std::string> filePath(const SymbolLocation &Loc,
25  llvm::StringRef HintFilePath) {
26  if (!Loc)
27  return None;
28  auto Uri = URI::parse(Loc.FileURI);
29  if (!Uri) {
30  elog("Could not parse URI {0}: {1}", Loc.FileURI, Uri.takeError());
31  return None;
32  }
33  auto U = URIForFile::fromURI(*Uri, HintFilePath);
34  if (!U) {
35  elog("Could not resolve URI {0}: {1}", Loc.FileURI, U.takeError());
36  return None;
37  }
38  return U->file().str();
39 }
40 
41 // Query the index to find some other files where the Decl is referenced.
42 llvm::Optional<std::string> getOtherRefFile(const Decl &D, StringRef MainFile,
43  const SymbolIndex &Index) {
44  RefsRequest Req;
45  // We limit the number of results, this is a correctness/performance
46  // tradeoff. We expect the number of symbol references in the current file
47  // is smaller than the limit.
48  Req.Limit = 100;
49  if (auto ID = getSymbolID(&D))
50  Req.IDs.insert(*ID);
51  llvm::Optional<std::string> OtherFile;
52  Index.refs(Req, [&](const Ref &R) {
53  if (OtherFile)
54  return;
55  if (auto RefFilePath = filePath(R.Location, /*HintFilePath=*/MainFile)) {
56  if (*RefFilePath != MainFile)
57  OtherFile = *RefFilePath;
58  }
59  });
60  return OtherFile;
61 }
62 
64  NoSymbolFound,
65  NoIndexProvided,
66  NonIndexable,
67  UsedOutsideFile,
68  UnsupportedSymbol,
69 };
70 
71 // Check the symbol Decl is renameable (per the index) within the file.
72 llvm::Optional<ReasonToReject> renamableWithinFile(const Decl &RenameDecl,
73  StringRef MainFile,
74  const SymbolIndex *Index) {
75  if (llvm::isa<NamespaceDecl>(&RenameDecl))
76  return ReasonToReject::UnsupportedSymbol;
77  auto &ASTCtx = RenameDecl.getASTContext();
78  const auto &SM = ASTCtx.getSourceManager();
79  bool MainFileIsHeader = ASTCtx.getLangOpts().IsHeaderFile;
80  bool DeclaredInMainFile = isInsideMainFile(RenameDecl.getBeginLoc(), SM);
81 
82  // If the symbol is declared in the main file (which is not a header), we
83  // rename it.
84  if (DeclaredInMainFile && !MainFileIsHeader)
85  return None;
86 
87  // Below are cases where the symbol is declared in the header.
88  // If the symbol is function-local, we rename it.
89  if (RenameDecl.getParentFunctionOrMethod())
90  return None;
91 
92  if (!Index)
93  return ReasonToReject::NoIndexProvided;
94 
95  bool IsIndexable = isa<NamedDecl>(RenameDecl) &&
97  cast<NamedDecl>(RenameDecl), ASTCtx, {}, false);
98  // If the symbol is not indexable, we disallow rename.
99  if (!IsIndexable)
100  return ReasonToReject::NonIndexable;
101  auto OtherFile = getOtherRefFile(RenameDecl, MainFile, *Index);
102  // If the symbol is indexable and has no refs from other files in the index,
103  // we rename it.
104  if (!OtherFile)
105  return None;
106  // If the symbol is indexable and has refs from other files in the index,
107  // we disallow rename.
108  return ReasonToReject::UsedOutsideFile;
109 }
110 
112  auto Message = [](ReasonToReject Reason) {
113  switch (Reason) {
114  case NoSymbolFound:
115  return "there is no symbol at the given location";
116  case NoIndexProvided:
117  return "symbol may be used in other files (no index available)";
118  case UsedOutsideFile:
119  return "the symbol is used outside main file";
120  case NonIndexable:
121  return "symbol may be used in other files (not eligible for indexing)";
122  case UnsupportedSymbol:
123  return "symbol is not a supported kind (e.g. namespace, macro)";
124  }
125  llvm_unreachable("unhandled reason kind");
126  };
127  return llvm::make_error<llvm::StringError>(
128  llvm::formatv("Cannot rename symbol: {0}", Message(Reason)),
129  llvm::inconvertibleErrorCode());
130 }
131 
132 // Return all rename occurrences in the main file.
133 tooling::SymbolOccurrences
134 findOccurrencesWithinFile(ParsedAST &AST, const NamedDecl *RenameDecl) {
135  const NamedDecl *CanonicalRenameDecl =
136  tooling::getCanonicalSymbolDeclaration(RenameDecl);
137  assert(CanonicalRenameDecl && "RenameDecl must be not null");
138  std::vector<std::string> RenameUSRs =
139  tooling::getUSRsForDeclaration(CanonicalRenameDecl, AST.getASTContext());
140  std::string OldName = CanonicalRenameDecl->getNameAsString();
141  tooling::SymbolOccurrences Result;
142  for (Decl *TopLevelDecl : AST.getLocalTopLevelDecls()) {
143  tooling::SymbolOccurrences RenameInDecl =
144  tooling::getOccurrencesOfUSRs(RenameUSRs, OldName, TopLevelDecl);
145  Result.insert(Result.end(), std::make_move_iterator(RenameInDecl.begin()),
146  std::make_move_iterator(RenameInDecl.end()));
147  }
148  return Result;
149 }
150 
151 } // namespace
152 
153 llvm::Expected<tooling::Replacements>
154 renameWithinFile(ParsedAST &AST, llvm::StringRef File, Position Pos,
155  llvm::StringRef NewName, const SymbolIndex *Index) {
156  const SourceManager &SM = AST.getSourceManager();
157  SourceLocation SourceLocationBeg = SM.getMacroArgExpandedLocation(
158  getBeginningOfIdentifier(Pos, SM, AST.getASTContext().getLangOpts()));
159  // FIXME: renaming macros is not supported yet, the macro-handling code should
160  // be moved to rename tooling library.
161  if (locateMacroAt(SourceLocationBeg, AST.getPreprocessor()))
162  return makeError(UnsupportedSymbol);
163 
164  const auto *RenameDecl =
165  tooling::getNamedDeclAt(AST.getASTContext(), SourceLocationBeg);
166  if (!RenameDecl)
167  return makeError(NoSymbolFound);
168 
169  if (auto Reject =
170  renamableWithinFile(*RenameDecl->getCanonicalDecl(), File, Index))
171  return makeError(*Reject);
172 
173  // Rename sometimes returns duplicate edits (which is a bug). A side-effect of
174  // adding them to a single Replacements object is these are deduplicated.
175  tooling::Replacements FilteredChanges;
176  for (const tooling::SymbolOccurrence &Rename :
177  findOccurrencesWithinFile(AST, RenameDecl)) {
178  // Currently, we only support normal rename (one range) for C/C++.
179  // FIXME: support multiple-range rename for objective-c methods.
180  if (Rename.getNameRanges().size() > 1)
181  continue;
182  // We shouldn't have conflicting replacements. If there are conflicts, it
183  // means that we have bugs either in clangd or in Rename library, therefore
184  // we refuse to perform the rename.
185  if (auto Err = FilteredChanges.add(tooling::Replacement(
186  AST.getASTContext().getSourceManager(),
187  CharSourceRange::getCharRange(Rename.getNameRanges()[0]), NewName)))
188  return std::move(Err);
189  }
190  return FilteredChanges;
191 }
192 
193 } // namespace clangd
194 } // namespace clang
SourceLocation Loc
&#39;#&#39; location in the include directive
llvm::Optional< SymbolID > getSymbolID(const Decl *D)
Gets the symbol ID for a declaration, if possible.
Definition: AST.cpp:191
static llvm::Error makeError(const char *Msg)
Definition: RIFF.cpp:16
Preprocessor & getPreprocessor()
Definition: ParsedAST.cpp:449
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:85
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
Definition: SourceCode.cpp:468
SourceLocation getBeginningOfIdentifier(const Position &Pos, const SourceManager &SM, const LangOptions &LangOpts)
Get the beginning SourceLocation at a specified Pos in the main file.
Definition: SourceCode.cpp:240
constexpr llvm::StringLiteral Message
ArrayRef< Decl * > getLocalTopLevelDecls()
This function returns top-level decls present in the main file of the AST.
Definition: ParsedAST.cpp:459
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:56
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:443
std::string MainFile
llvm::Expected< tooling::Replacements > renameWithinFile(ParsedAST &AST, llvm::StringRef File, Position Pos, llvm::StringRef NewName, const SymbolIndex *Index)
Renames all occurrences of the symbol at Pos to NewName.
Definition: Rename.cpp:154
static llvm::Expected< URIForFile > fromURI(const URI &U, llvm::StringRef HintPath)
Definition: Protocol.cpp:45
const Decl * D
Definition: XRefs.cpp:847
Stores and provides access to parsed AST.
Definition: ParsedAST.h:45
SourceManager & getSourceManager()
Definition: ParsedAST.h:72
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static llvm::Expected< URI > parse(llvm::StringRef Uri)
Parse a URI string "<scheme>:[//<authority>/]<path>".
Definition: URI.cpp:164
llvm::Optional< DefinedMacro > locateMacroAt(SourceLocation Loc, Preprocessor &PP)
Definition: SourceCode.cpp:893
const SymbolIndex * Index
Definition: Dexp.cpp:84