USRFindingAction.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. //===--- USRFindingAction.cpp - Clang refactoring library -----------------===//
  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. /// \file
  10. /// Provides an action to find USR for the symbol at <offset>, as well as
  11. /// all additional USRs.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Tooling/Refactoring/Rename/USRFindingAction.h"
  15. #include "clang/AST/AST.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/RecursiveASTVisitor.h"
  20. #include "clang/Basic/FileManager.h"
  21. #include "clang/Frontend/CompilerInstance.h"
  22. #include "clang/Frontend/FrontendAction.h"
  23. #include "clang/Lex/Lexer.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. #include "clang/Tooling/CommonOptionsParser.h"
  26. #include "clang/Tooling/Refactoring.h"
  27. #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
  28. #include "clang/Tooling/Tooling.h"
  29. #include <algorithm>
  30. #include <set>
  31. #include <string>
  32. #include <vector>
  33. using namespace llvm;
  34. namespace clang {
  35. namespace tooling {
  36. const NamedDecl *getCanonicalSymbolDeclaration(const NamedDecl *FoundDecl) {
  37. if (!FoundDecl)
  38. return nullptr;
  39. // If FoundDecl is a constructor or destructor, we want to instead take
  40. // the Decl of the corresponding class.
  41. if (const auto *CtorDecl = dyn_cast<CXXConstructorDecl>(FoundDecl))
  42. FoundDecl = CtorDecl->getParent();
  43. else if (const auto *DtorDecl = dyn_cast<CXXDestructorDecl>(FoundDecl))
  44. FoundDecl = DtorDecl->getParent();
  45. // FIXME: (Alex L): Canonicalize implicit template instantions, just like
  46. // the indexer does it.
  47. // Note: please update the declaration's doc comment every time the
  48. // canonicalization rules are changed.
  49. return FoundDecl;
  50. }
  51. namespace {
  52. // NamedDeclFindingConsumer should delegate finding USRs of given Decl to
  53. // AdditionalUSRFinder. AdditionalUSRFinder adds USRs of ctor and dtor if given
  54. // Decl refers to class and adds USRs of all overridden methods if Decl refers
  55. // to virtual method.
  56. class AdditionalUSRFinder : public RecursiveASTVisitor<AdditionalUSRFinder> {
  57. public:
  58. AdditionalUSRFinder(const Decl *FoundDecl, ASTContext &Context)
  59. : FoundDecl(FoundDecl), Context(Context) {}
  60. std::vector<std::string> Find() {
  61. // Fill OverriddenMethods and PartialSpecs storages.
  62. TraverseAST(Context);
  63. if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(FoundDecl)) {
  64. addUSRsOfOverridenFunctions(MethodDecl);
  65. for (const auto &OverriddenMethod : OverriddenMethods) {
  66. if (checkIfOverriddenFunctionAscends(OverriddenMethod))
  67. USRSet.insert(getUSRForDecl(OverriddenMethod));
  68. }
  69. addUSRsOfInstantiatedMethods(MethodDecl);
  70. } else if (const auto *RecordDecl = dyn_cast<CXXRecordDecl>(FoundDecl)) {
  71. handleCXXRecordDecl(RecordDecl);
  72. } else if (const auto *TemplateDecl =
  73. dyn_cast<ClassTemplateDecl>(FoundDecl)) {
  74. handleClassTemplateDecl(TemplateDecl);
  75. } else if (const auto *FD = dyn_cast<FunctionDecl>(FoundDecl)) {
  76. USRSet.insert(getUSRForDecl(FD));
  77. if (const auto *FTD = FD->getPrimaryTemplate())
  78. handleFunctionTemplateDecl(FTD);
  79. } else if (const auto *FD = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
  80. handleFunctionTemplateDecl(FD);
  81. } else if (const auto *VTD = dyn_cast<VarTemplateDecl>(FoundDecl)) {
  82. handleVarTemplateDecl(VTD);
  83. } else if (const auto *VD =
  84. dyn_cast<VarTemplateSpecializationDecl>(FoundDecl)) {
  85. // FIXME: figure out why FoundDecl can be a VarTemplateSpecializationDecl.
  86. handleVarTemplateDecl(VD->getSpecializedTemplate());
  87. } else if (const auto *VD = dyn_cast<VarDecl>(FoundDecl)) {
  88. USRSet.insert(getUSRForDecl(VD));
  89. if (const auto *VTD = VD->getDescribedVarTemplate())
  90. handleVarTemplateDecl(VTD);
  91. } else {
  92. USRSet.insert(getUSRForDecl(FoundDecl));
  93. }
  94. return std::vector<std::string>(USRSet.begin(), USRSet.end());
  95. }
  96. bool shouldVisitTemplateInstantiations() const { return true; }
  97. bool VisitCXXMethodDecl(const CXXMethodDecl *MethodDecl) {
  98. if (MethodDecl->isVirtual())
  99. OverriddenMethods.push_back(MethodDecl);
  100. if (MethodDecl->getInstantiatedFromMemberFunction())
  101. InstantiatedMethods.push_back(MethodDecl);
  102. return true;
  103. }
  104. private:
  105. void handleCXXRecordDecl(const CXXRecordDecl *RecordDecl) {
  106. if (!RecordDecl->getDefinition()) {
  107. USRSet.insert(getUSRForDecl(RecordDecl));
  108. return;
  109. }
  110. RecordDecl = RecordDecl->getDefinition();
  111. if (const auto *ClassTemplateSpecDecl =
  112. dyn_cast<ClassTemplateSpecializationDecl>(RecordDecl))
  113. handleClassTemplateDecl(ClassTemplateSpecDecl->getSpecializedTemplate());
  114. addUSRsOfCtorDtors(RecordDecl);
  115. }
  116. void handleClassTemplateDecl(const ClassTemplateDecl *TemplateDecl) {
  117. for (const auto *Specialization : TemplateDecl->specializations())
  118. addUSRsOfCtorDtors(Specialization);
  119. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  120. TemplateDecl->getPartialSpecializations(PartialSpecs);
  121. for (const auto *Spec : PartialSpecs)
  122. addUSRsOfCtorDtors(Spec);
  123. addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
  124. }
  125. void handleFunctionTemplateDecl(const FunctionTemplateDecl *FTD) {
  126. USRSet.insert(getUSRForDecl(FTD));
  127. USRSet.insert(getUSRForDecl(FTD->getTemplatedDecl()));
  128. for (const auto *S : FTD->specializations())
  129. USRSet.insert(getUSRForDecl(S));
  130. }
  131. void handleVarTemplateDecl(const VarTemplateDecl *VTD) {
  132. USRSet.insert(getUSRForDecl(VTD));
  133. USRSet.insert(getUSRForDecl(VTD->getTemplatedDecl()));
  134. for (const auto *Spec : VTD->specializations())
  135. USRSet.insert(getUSRForDecl(Spec));
  136. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  137. VTD->getPartialSpecializations(PartialSpecs);
  138. for (const auto *Spec : PartialSpecs)
  139. USRSet.insert(getUSRForDecl(Spec));
  140. }
  141. void addUSRsOfCtorDtors(const CXXRecordDecl *RD) {
  142. const auto* RecordDecl = RD->getDefinition();
  143. // Skip if the CXXRecordDecl doesn't have definition.
  144. if (!RecordDecl) {
  145. USRSet.insert(getUSRForDecl(RD));
  146. return;
  147. }
  148. for (const auto *CtorDecl : RecordDecl->ctors())
  149. USRSet.insert(getUSRForDecl(CtorDecl));
  150. // Add template constructor decls, they are not in ctors() unfortunately.
  151. if (RecordDecl->hasUserDeclaredConstructor())
  152. for (const auto *D : RecordDecl->decls())
  153. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  154. if (const auto *Ctor =
  155. dyn_cast<CXXConstructorDecl>(FTD->getTemplatedDecl()))
  156. USRSet.insert(getUSRForDecl(Ctor));
  157. USRSet.insert(getUSRForDecl(RecordDecl->getDestructor()));
  158. USRSet.insert(getUSRForDecl(RecordDecl));
  159. }
  160. void addUSRsOfOverridenFunctions(const CXXMethodDecl *MethodDecl) {
  161. USRSet.insert(getUSRForDecl(MethodDecl));
  162. // Recursively visit each OverridenMethod.
  163. for (const auto &OverriddenMethod : MethodDecl->overridden_methods())
  164. addUSRsOfOverridenFunctions(OverriddenMethod);
  165. }
  166. void addUSRsOfInstantiatedMethods(const CXXMethodDecl *MethodDecl) {
  167. // For renaming a class template method, all references of the instantiated
  168. // member methods should be renamed too, so add USRs of the instantiated
  169. // methods to the USR set.
  170. USRSet.insert(getUSRForDecl(MethodDecl));
  171. if (const auto *FT = MethodDecl->getInstantiatedFromMemberFunction())
  172. USRSet.insert(getUSRForDecl(FT));
  173. for (const auto *Method : InstantiatedMethods) {
  174. if (USRSet.find(getUSRForDecl(
  175. Method->getInstantiatedFromMemberFunction())) != USRSet.end())
  176. USRSet.insert(getUSRForDecl(Method));
  177. }
  178. }
  179. bool checkIfOverriddenFunctionAscends(const CXXMethodDecl *MethodDecl) {
  180. for (const auto &OverriddenMethod : MethodDecl->overridden_methods()) {
  181. if (USRSet.find(getUSRForDecl(OverriddenMethod)) != USRSet.end())
  182. return true;
  183. return checkIfOverriddenFunctionAscends(OverriddenMethod);
  184. }
  185. return false;
  186. }
  187. const Decl *FoundDecl;
  188. ASTContext &Context;
  189. std::set<std::string> USRSet;
  190. std::vector<const CXXMethodDecl *> OverriddenMethods;
  191. std::vector<const CXXMethodDecl *> InstantiatedMethods;
  192. };
  193. } // namespace
  194. std::vector<std::string> getUSRsForDeclaration(const NamedDecl *ND,
  195. ASTContext &Context) {
  196. AdditionalUSRFinder Finder(ND, Context);
  197. return Finder.Find();
  198. }
  199. class NamedDeclFindingConsumer : public ASTConsumer {
  200. public:
  201. NamedDeclFindingConsumer(ArrayRef<unsigned> SymbolOffsets,
  202. ArrayRef<std::string> QualifiedNames,
  203. std::vector<std::string> &SpellingNames,
  204. std::vector<std::vector<std::string>> &USRList,
  205. bool Force, bool &ErrorOccurred)
  206. : SymbolOffsets(SymbolOffsets), QualifiedNames(QualifiedNames),
  207. SpellingNames(SpellingNames), USRList(USRList), Force(Force),
  208. ErrorOccurred(ErrorOccurred) {}
  209. private:
  210. bool FindSymbol(ASTContext &Context, const SourceManager &SourceMgr,
  211. unsigned SymbolOffset, const std::string &QualifiedName) {
  212. DiagnosticsEngine &Engine = Context.getDiagnostics();
  213. const FileID MainFileID = SourceMgr.getMainFileID();
  214. if (SymbolOffset >= SourceMgr.getFileIDSize(MainFileID)) {
  215. ErrorOccurred = true;
  216. unsigned InvalidOffset = Engine.getCustomDiagID(
  217. DiagnosticsEngine::Error,
  218. "SourceLocation in file %0 at offset %1 is invalid");
  219. Engine.Report(SourceLocation(), InvalidOffset)
  220. << SourceMgr.getFileEntryForID(MainFileID)->getName() << SymbolOffset;
  221. return false;
  222. }
  223. const SourceLocation Point = SourceMgr.getLocForStartOfFile(MainFileID)
  224. .getLocWithOffset(SymbolOffset);
  225. const NamedDecl *FoundDecl = QualifiedName.empty()
  226. ? getNamedDeclAt(Context, Point)
  227. : getNamedDeclFor(Context, QualifiedName);
  228. if (FoundDecl == nullptr) {
  229. if (QualifiedName.empty()) {
  230. FullSourceLoc FullLoc(Point, SourceMgr);
  231. unsigned CouldNotFindSymbolAt = Engine.getCustomDiagID(
  232. DiagnosticsEngine::Error,
  233. "clang-rename could not find symbol (offset %0)");
  234. Engine.Report(Point, CouldNotFindSymbolAt) << SymbolOffset;
  235. ErrorOccurred = true;
  236. return false;
  237. }
  238. if (Force) {
  239. SpellingNames.push_back(std::string());
  240. USRList.push_back(std::vector<std::string>());
  241. return true;
  242. }
  243. unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID(
  244. DiagnosticsEngine::Error, "clang-rename could not find symbol %0");
  245. Engine.Report(CouldNotFindSymbolNamed) << QualifiedName;
  246. ErrorOccurred = true;
  247. return false;
  248. }
  249. FoundDecl = getCanonicalSymbolDeclaration(FoundDecl);
  250. SpellingNames.push_back(FoundDecl->getNameAsString());
  251. AdditionalUSRFinder Finder(FoundDecl, Context);
  252. USRList.push_back(Finder.Find());
  253. return true;
  254. }
  255. void HandleTranslationUnit(ASTContext &Context) override {
  256. const SourceManager &SourceMgr = Context.getSourceManager();
  257. for (unsigned Offset : SymbolOffsets) {
  258. if (!FindSymbol(Context, SourceMgr, Offset, ""))
  259. return;
  260. }
  261. for (const std::string &QualifiedName : QualifiedNames) {
  262. if (!FindSymbol(Context, SourceMgr, 0, QualifiedName))
  263. return;
  264. }
  265. }
  266. ArrayRef<unsigned> SymbolOffsets;
  267. ArrayRef<std::string> QualifiedNames;
  268. std::vector<std::string> &SpellingNames;
  269. std::vector<std::vector<std::string>> &USRList;
  270. bool Force;
  271. bool &ErrorOccurred;
  272. };
  273. std::unique_ptr<ASTConsumer> USRFindingAction::newASTConsumer() {
  274. return std::make_unique<NamedDeclFindingConsumer>(
  275. SymbolOffsets, QualifiedNames, SpellingNames, USRList, Force,
  276. ErrorOccurred);
  277. }
  278. } // end namespace tooling
  279. } // end namespace clang