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