USRFindingAction.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. llvm::for_each(VTD->specializations(), [&](const auto *Spec) {
  135. USRSet.insert(getUSRForDecl(Spec));
  136. });
  137. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  138. VTD->getPartialSpecializations(PartialSpecs);
  139. llvm::for_each(PartialSpecs, [&](const auto *Spec) {
  140. USRSet.insert(getUSRForDecl(Spec));
  141. });
  142. }
  143. void addUSRsOfCtorDtors(const CXXRecordDecl *RD) {
  144. const auto* RecordDecl = RD->getDefinition();
  145. // Skip if the CXXRecordDecl doesn't have definition.
  146. if (!RecordDecl) {
  147. USRSet.insert(getUSRForDecl(RD));
  148. return;
  149. }
  150. for (const auto *CtorDecl : RecordDecl->ctors())
  151. USRSet.insert(getUSRForDecl(CtorDecl));
  152. // Add template constructor decls, they are not in ctors() unfortunately.
  153. if (RecordDecl->hasUserDeclaredConstructor())
  154. for (const auto *D : RecordDecl->decls())
  155. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  156. if (const auto *Ctor =
  157. dyn_cast<CXXConstructorDecl>(FTD->getTemplatedDecl()))
  158. USRSet.insert(getUSRForDecl(Ctor));
  159. USRSet.insert(getUSRForDecl(RecordDecl->getDestructor()));
  160. USRSet.insert(getUSRForDecl(RecordDecl));
  161. }
  162. void addUSRsOfOverridenFunctions(const CXXMethodDecl *MethodDecl) {
  163. USRSet.insert(getUSRForDecl(MethodDecl));
  164. // Recursively visit each OverridenMethod.
  165. for (const auto &OverriddenMethod : MethodDecl->overridden_methods())
  166. addUSRsOfOverridenFunctions(OverriddenMethod);
  167. }
  168. void addUSRsOfInstantiatedMethods(const CXXMethodDecl *MethodDecl) {
  169. // For renaming a class template method, all references of the instantiated
  170. // member methods should be renamed too, so add USRs of the instantiated
  171. // methods to the USR set.
  172. USRSet.insert(getUSRForDecl(MethodDecl));
  173. if (const auto *FT = MethodDecl->getInstantiatedFromMemberFunction())
  174. USRSet.insert(getUSRForDecl(FT));
  175. for (const auto *Method : InstantiatedMethods) {
  176. if (USRSet.find(getUSRForDecl(
  177. Method->getInstantiatedFromMemberFunction())) != USRSet.end())
  178. USRSet.insert(getUSRForDecl(Method));
  179. }
  180. }
  181. bool checkIfOverriddenFunctionAscends(const CXXMethodDecl *MethodDecl) {
  182. for (const auto &OverriddenMethod : MethodDecl->overridden_methods()) {
  183. if (USRSet.find(getUSRForDecl(OverriddenMethod)) != USRSet.end())
  184. return true;
  185. return checkIfOverriddenFunctionAscends(OverriddenMethod);
  186. }
  187. return false;
  188. }
  189. const Decl *FoundDecl;
  190. ASTContext &Context;
  191. std::set<std::string> USRSet;
  192. std::vector<const CXXMethodDecl *> OverriddenMethods;
  193. std::vector<const CXXMethodDecl *> InstantiatedMethods;
  194. };
  195. } // namespace
  196. std::vector<std::string> getUSRsForDeclaration(const NamedDecl *ND,
  197. ASTContext &Context) {
  198. AdditionalUSRFinder Finder(ND, Context);
  199. return Finder.Find();
  200. }
  201. class NamedDeclFindingConsumer : public ASTConsumer {
  202. public:
  203. NamedDeclFindingConsumer(ArrayRef<unsigned> SymbolOffsets,
  204. ArrayRef<std::string> QualifiedNames,
  205. std::vector<std::string> &SpellingNames,
  206. std::vector<std::vector<std::string>> &USRList,
  207. bool Force, bool &ErrorOccurred)
  208. : SymbolOffsets(SymbolOffsets), QualifiedNames(QualifiedNames),
  209. SpellingNames(SpellingNames), USRList(USRList), Force(Force),
  210. ErrorOccurred(ErrorOccurred) {}
  211. private:
  212. bool FindSymbol(ASTContext &Context, const SourceManager &SourceMgr,
  213. unsigned SymbolOffset, const std::string &QualifiedName) {
  214. DiagnosticsEngine &Engine = Context.getDiagnostics();
  215. const FileID MainFileID = SourceMgr.getMainFileID();
  216. if (SymbolOffset >= SourceMgr.getFileIDSize(MainFileID)) {
  217. ErrorOccurred = true;
  218. unsigned InvalidOffset = Engine.getCustomDiagID(
  219. DiagnosticsEngine::Error,
  220. "SourceLocation in file %0 at offset %1 is invalid");
  221. Engine.Report(SourceLocation(), InvalidOffset)
  222. << SourceMgr.getFileEntryForID(MainFileID)->getName() << SymbolOffset;
  223. return false;
  224. }
  225. const SourceLocation Point = SourceMgr.getLocForStartOfFile(MainFileID)
  226. .getLocWithOffset(SymbolOffset);
  227. const NamedDecl *FoundDecl = QualifiedName.empty()
  228. ? getNamedDeclAt(Context, Point)
  229. : getNamedDeclFor(Context, QualifiedName);
  230. if (FoundDecl == nullptr) {
  231. if (QualifiedName.empty()) {
  232. FullSourceLoc FullLoc(Point, SourceMgr);
  233. unsigned CouldNotFindSymbolAt = Engine.getCustomDiagID(
  234. DiagnosticsEngine::Error,
  235. "clang-rename could not find symbol (offset %0)");
  236. Engine.Report(Point, CouldNotFindSymbolAt) << SymbolOffset;
  237. ErrorOccurred = true;
  238. return false;
  239. }
  240. if (Force) {
  241. SpellingNames.push_back(std::string());
  242. USRList.push_back(std::vector<std::string>());
  243. return true;
  244. }
  245. unsigned CouldNotFindSymbolNamed = Engine.getCustomDiagID(
  246. DiagnosticsEngine::Error, "clang-rename could not find symbol %0");
  247. Engine.Report(CouldNotFindSymbolNamed) << QualifiedName;
  248. ErrorOccurred = true;
  249. return false;
  250. }
  251. FoundDecl = getCanonicalSymbolDeclaration(FoundDecl);
  252. SpellingNames.push_back(FoundDecl->getNameAsString());
  253. AdditionalUSRFinder Finder(FoundDecl, Context);
  254. USRList.push_back(Finder.Find());
  255. return true;
  256. }
  257. void HandleTranslationUnit(ASTContext &Context) override {
  258. const SourceManager &SourceMgr = Context.getSourceManager();
  259. for (unsigned Offset : SymbolOffsets) {
  260. if (!FindSymbol(Context, SourceMgr, Offset, ""))
  261. return;
  262. }
  263. for (const std::string &QualifiedName : QualifiedNames) {
  264. if (!FindSymbol(Context, SourceMgr, 0, QualifiedName))
  265. return;
  266. }
  267. }
  268. ArrayRef<unsigned> SymbolOffsets;
  269. ArrayRef<std::string> QualifiedNames;
  270. std::vector<std::string> &SpellingNames;
  271. std::vector<std::vector<std::string>> &USRList;
  272. bool Force;
  273. bool &ErrorOccurred;
  274. };
  275. std::unique_ptr<ASTConsumer> USRFindingAction::newASTConsumer() {
  276. return std::make_unique<NamedDeclFindingConsumer>(
  277. SymbolOffsets, QualifiedNames, SpellingNames, USRList, Force,
  278. ErrorOccurred);
  279. }
  280. } // end namespace tooling
  281. } // end namespace clang