1 //===--- USRLocFinder.cpp - Clang refactoring library ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Methods for finding all instances of a USR. Our strategy is very
12 /// simple; we just compare the USR at every relevant AST node with the one
13 /// provided.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "clang/Tooling/Refactoring/Rename/USRLocFinder.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Lex/Lexer.h"
24 #include "clang/Tooling/Core/Lookup.h"
25 #include "clang/Tooling/Refactoring/RecursiveSymbolVisitor.h"
26 #include "clang/Tooling/Refactoring/Rename/SymbolName.h"
27 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Casting.h"
30 #include <cstddef>
31 #include <set>
32 #include <string>
33 #include <vector>
34 
35 using namespace llvm;
36 
37 namespace clang {
38 namespace tooling {
39 
40 namespace {
41 
42 // \brief This visitor recursively searches for all instances of a USR in a
43 // translation unit and stores them for later usage.
44 class USRLocFindingASTVisitor
45     : public RecursiveSymbolVisitor<USRLocFindingASTVisitor> {
46 public:
47   explicit USRLocFindingASTVisitor(const std::vector<std::string> &USRs,
48                                    StringRef PrevName,
49                                    const ASTContext &Context)
50       : RecursiveSymbolVisitor(Context.getSourceManager(),
51                                Context.getLangOpts()),
52         USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) {
53   }
54 
55   bool visitSymbolOccurrence(const NamedDecl *ND,
56                              ArrayRef<SourceRange> NameRanges) {
57     if (USRSet.find(getUSRForDecl(ND)) != USRSet.end()) {
58       assert(NameRanges.size() == 1 &&
59              "Multiple name pieces are not supported yet!");
60       SourceLocation Loc = NameRanges[0].getBegin();
61       const SourceManager &SM = Context.getSourceManager();
62       // TODO: Deal with macro occurrences correctly.
63       if (Loc.isMacroID())
64         Loc = SM.getSpellingLoc(Loc);
65       checkAndAddLocation(Loc);
66     }
67     return true;
68   }
69 
70   // Non-visitors:
71 
72   /// \brief Returns a set of unique symbol occurrences. Duplicate or
73   /// overlapping occurrences are erroneous and should be reported!
74   SymbolOccurrences takeOccurrences() { return std::move(Occurrences); }
75 
76 private:
77   void checkAndAddLocation(SourceLocation Loc) {
78     const SourceLocation BeginLoc = Loc;
79     const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
80         BeginLoc, 0, Context.getSourceManager(), Context.getLangOpts());
81     StringRef TokenName =
82         Lexer::getSourceText(CharSourceRange::getTokenRange(BeginLoc, EndLoc),
83                              Context.getSourceManager(), Context.getLangOpts());
84     size_t Offset = TokenName.find(PrevName.getNamePieces()[0]);
85 
86     // The token of the source location we find actually has the old
87     // name.
88     if (Offset != StringRef::npos)
89       Occurrences.emplace_back(PrevName, SymbolOccurrence::MatchingSymbol,
90                                BeginLoc.getLocWithOffset(Offset));
91   }
92 
93   const std::set<std::string> USRSet;
94   const SymbolName PrevName;
95   SymbolOccurrences Occurrences;
96   const ASTContext &Context;
97 };
98 
99 SourceLocation StartLocationForType(TypeLoc TL) {
100   // For elaborated types (e.g. `struct a::A`) we want the portion after the
101   // `struct` but including the namespace qualifier, `a::`.
102   if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>()) {
103     NestedNameSpecifierLoc NestedNameSpecifier =
104         ElaboratedTypeLoc.getQualifierLoc();
105     if (NestedNameSpecifier.getNestedNameSpecifier())
106       return NestedNameSpecifier.getBeginLoc();
107     TL = TL.getNextTypeLoc();
108   }
109   return TL.getLocStart();
110 }
111 
112 SourceLocation EndLocationForType(TypeLoc TL) {
113   // Dig past any namespace or keyword qualifications.
114   while (TL.getTypeLocClass() == TypeLoc::Elaborated ||
115          TL.getTypeLocClass() == TypeLoc::Qualified)
116     TL = TL.getNextTypeLoc();
117 
118   // The location for template specializations (e.g. Foo<int>) includes the
119   // templated types in its location range.  We want to restrict this to just
120   // before the `<` character.
121   if (TL.getTypeLocClass() == TypeLoc::TemplateSpecialization) {
122     return TL.castAs<TemplateSpecializationTypeLoc>()
123         .getLAngleLoc()
124         .getLocWithOffset(-1);
125   }
126   return TL.getEndLoc();
127 }
128 
129 NestedNameSpecifier *GetNestedNameForType(TypeLoc TL) {
130   // Dig past any keyword qualifications.
131   while (TL.getTypeLocClass() == TypeLoc::Qualified)
132     TL = TL.getNextTypeLoc();
133 
134   // For elaborated types (e.g. `struct a::A`) we want the portion after the
135   // `struct` but including the namespace qualifier, `a::`.
136   if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>())
137     return ElaboratedTypeLoc.getQualifierLoc().getNestedNameSpecifier();
138   return nullptr;
139 }
140 
141 // Find all locations identified by the given USRs for rename.
142 //
143 // This class will traverse the AST and find every AST node whose USR is in the
144 // given USRs' set.
145 class RenameLocFinder : public RecursiveASTVisitor<RenameLocFinder> {
146 public:
147   RenameLocFinder(llvm::ArrayRef<std::string> USRs, ASTContext &Context)
148       : USRSet(USRs.begin(), USRs.end()), Context(Context) {}
149 
150   // A structure records all information of a symbol reference being renamed.
151   // We try to add as few prefix qualifiers as possible.
152   struct RenameInfo {
153     // The begin location of a symbol being renamed.
154     SourceLocation Begin;
155     // The end location of a symbol being renamed.
156     SourceLocation End;
157     // The declaration of a symbol being renamed (can be nullptr).
158     const NamedDecl *FromDecl;
159     // The declaration in which the nested name is contained (can be nullptr).
160     const Decl *Context;
161     // The nested name being replaced (can be nullptr).
162     const NestedNameSpecifier *Specifier;
163     // Determine whether the prefix qualifiers of the NewName should be ignored.
164     // Normally, we set it to true for the symbol declaration and definition to
165     // avoid adding prefix qualifiers.
166     // For example, if it is true and NewName is "a::b::foo", then the symbol
167     // occurrence which the RenameInfo points to will be renamed to "foo".
168     bool IgnorePrefixQualifers;
169   };
170 
171   bool VisitNamedDecl(const NamedDecl *Decl) {
172     // UsingDecl has been handled in other place.
173     if (llvm::isa<UsingDecl>(Decl))
174       return true;
175 
176     // DestructorDecl has been handled in Typeloc.
177     if (llvm::isa<CXXDestructorDecl>(Decl))
178       return true;
179 
180     if (Decl->isImplicit())
181       return true;
182 
183     if (isInUSRSet(Decl)) {
184       RenameInfo Info = {Decl->getLocation(),
185                          Decl->getLocation(),
186                          /*FromDecl=*/nullptr,
187                          /*Context=*/nullptr,
188                          /*Specifier=*/nullptr,
189                          /*IgnorePrefixQualifers=*/true};
190       RenameInfos.push_back(Info);
191     }
192     return true;
193   }
194 
195   bool VisitDeclRefExpr(const DeclRefExpr *Expr) {
196     const NamedDecl *Decl = Expr->getFoundDecl();
197     if (isInUSRSet(Decl)) {
198       RenameInfo Info = {Expr->getSourceRange().getBegin(),
199                          Expr->getSourceRange().getEnd(),
200                          Decl,
201                          getClosestAncestorDecl(*Expr),
202                          Expr->getQualifier(),
203                          /*IgnorePrefixQualifers=*/false};
204       RenameInfos.push_back(Info);
205     }
206 
207     return true;
208   }
209 
210   bool VisitUsingDecl(const UsingDecl *Using) {
211     for (const auto *UsingShadow : Using->shadows()) {
212       if (isInUSRSet(UsingShadow->getTargetDecl())) {
213         UsingDecls.push_back(Using);
214         break;
215       }
216     }
217     return true;
218   }
219 
220   bool VisitNestedNameSpecifierLocations(NestedNameSpecifierLoc NestedLoc) {
221     if (!NestedLoc.getNestedNameSpecifier()->getAsType())
222       return true;
223     if (IsTypeAliasWhichWillBeRenamedElsewhere(NestedLoc.getTypeLoc()))
224       return true;
225 
226     if (const auto *TargetDecl =
227             getSupportedDeclFromTypeLoc(NestedLoc.getTypeLoc())) {
228       if (isInUSRSet(TargetDecl)) {
229         RenameInfo Info = {NestedLoc.getBeginLoc(),
230                            EndLocationForType(NestedLoc.getTypeLoc()),
231                            TargetDecl,
232                            getClosestAncestorDecl(NestedLoc),
233                            NestedLoc.getNestedNameSpecifier()->getPrefix(),
234                            /*IgnorePrefixQualifers=*/false};
235         RenameInfos.push_back(Info);
236       }
237     }
238     return true;
239   }
240 
241   bool VisitTypeLoc(TypeLoc Loc) {
242     if (IsTypeAliasWhichWillBeRenamedElsewhere(Loc))
243       return true;
244 
245     auto Parents = Context.getParents(Loc);
246     TypeLoc ParentTypeLoc;
247     if (!Parents.empty()) {
248       // Handle cases of nested name specificier locations.
249       //
250       // The VisitNestedNameSpecifierLoc interface is not impelmented in
251       // RecursiveASTVisitor, we have to handle it explicitly.
252       if (const auto *NSL = Parents[0].get<NestedNameSpecifierLoc>()) {
253         VisitNestedNameSpecifierLocations(*NSL);
254         return true;
255       }
256 
257       if (const auto *TL = Parents[0].get<TypeLoc>())
258         ParentTypeLoc = *TL;
259     }
260 
261     // Handle the outermost TypeLoc which is directly linked to the interesting
262     // declaration and don't handle nested name specifier locations.
263     if (const auto *TargetDecl = getSupportedDeclFromTypeLoc(Loc)) {
264       if (isInUSRSet(TargetDecl)) {
265         // Only handle the outermost typeLoc.
266         //
267         // For a type like "a::Foo", there will be two typeLocs for it.
268         // One ElaboratedType, the other is RecordType:
269         //
270         //   ElaboratedType 0x33b9390 'a::Foo' sugar
271         //   `-RecordType 0x338fef0 'class a::Foo'
272         //     `-CXXRecord 0x338fe58 'Foo'
273         //
274         // Skip if this is an inner typeLoc.
275         if (!ParentTypeLoc.isNull() &&
276             isInUSRSet(getSupportedDeclFromTypeLoc(ParentTypeLoc)))
277           return true;
278         RenameInfo Info = {StartLocationForType(Loc),
279                            EndLocationForType(Loc),
280                            TargetDecl,
281                            getClosestAncestorDecl(Loc),
282                            GetNestedNameForType(Loc),
283                            /*IgnorePrefixQualifers=*/false};
284         RenameInfos.push_back(Info);
285         return true;
286       }
287     }
288 
289     // Handle specific template class specialiation cases.
290     if (const auto *TemplateSpecType =
291             dyn_cast<TemplateSpecializationType>(Loc.getType())) {
292       TypeLoc TargetLoc = Loc;
293       if (!ParentTypeLoc.isNull()) {
294         if (llvm::isa<ElaboratedType>(ParentTypeLoc.getType()))
295           TargetLoc = ParentTypeLoc;
296       }
297 
298       if (isInUSRSet(TemplateSpecType->getTemplateName().getAsTemplateDecl())) {
299         TypeLoc TargetLoc = Loc;
300         // FIXME: Find a better way to handle this case.
301         // For the qualified template class specification type like
302         // "ns::Foo<int>" in "ns::Foo<int>& f();", we want the parent typeLoc
303         // (ElaboratedType) of the TemplateSpecializationType in order to
304         // catch the prefix qualifiers "ns::".
305         if (!ParentTypeLoc.isNull() &&
306             llvm::isa<ElaboratedType>(ParentTypeLoc.getType()))
307           TargetLoc = ParentTypeLoc;
308         RenameInfo Info = {
309             StartLocationForType(TargetLoc),
310             EndLocationForType(TargetLoc),
311             TemplateSpecType->getTemplateName().getAsTemplateDecl(),
312             getClosestAncestorDecl(
313                 ast_type_traits::DynTypedNode::create(TargetLoc)),
314             GetNestedNameForType(TargetLoc),
315             /*IgnorePrefixQualifers=*/false};
316         RenameInfos.push_back(Info);
317       }
318     }
319     return true;
320   }
321 
322   // Returns a list of RenameInfo.
323   const std::vector<RenameInfo> &getRenameInfos() const { return RenameInfos; }
324 
325   // Returns a list of using declarations which are needed to update.
326   const std::vector<const UsingDecl *> &getUsingDecls() const {
327     return UsingDecls;
328   }
329 
330 private:
331   // FIXME: This method may not be suitable for renaming other types like alias
332   // types. Need to figure out a way to handle it.
333   bool IsTypeAliasWhichWillBeRenamedElsewhere(TypeLoc TL) const {
334     while (!TL.isNull()) {
335       // SubstTemplateTypeParm is the TypeLocation class for a substituted type
336       // inside a template expansion so we ignore these.  For example:
337       //
338       // template<typename T> struct S {
339       //   T t;  // <-- this T becomes a TypeLoc(int) with class
340       //         //     SubstTemplateTypeParm when S<int> is instantiated
341       // }
342       if (TL.getTypeLocClass() == TypeLoc::SubstTemplateTypeParm)
343         return true;
344 
345       // Typedef is the TypeLocation class for a type which is a typedef to the
346       // type we want to replace.  We ignore the use of the typedef as we will
347       // replace the definition of it.  For example:
348       //
349       // typedef int T;
350       // T a;  // <---  This T is a TypeLoc(int) with class Typedef.
351       if (TL.getTypeLocClass() == TypeLoc::Typedef)
352         return true;
353       TL = TL.getNextTypeLoc();
354     }
355     return false;
356   }
357 
358   // Get the supported declaration from a given typeLoc. If the declaration type
359   // is not supported, returns nullptr.
360   //
361   // FIXME: support more types, e.g. enum, type alias.
362   const NamedDecl *getSupportedDeclFromTypeLoc(TypeLoc Loc) {
363     if (const auto *RD = Loc.getType()->getAsCXXRecordDecl())
364       return RD;
365     return nullptr;
366   }
367 
368   // Get the closest ancester which is a declaration of a given AST node.
369   template <typename ASTNodeType>
370   const Decl *getClosestAncestorDecl(const ASTNodeType &Node) {
371     auto Parents = Context.getParents(Node);
372     // FIXME: figure out how to handle it when there are multiple parents.
373     if (Parents.size() != 1)
374       return nullptr;
375     if (ast_type_traits::ASTNodeKind::getFromNodeKind<Decl>().isBaseOf(
376             Parents[0].getNodeKind()))
377       return Parents[0].template get<Decl>();
378     return getClosestAncestorDecl(Parents[0]);
379   }
380 
381   // Get the parent typeLoc of a given typeLoc. If there is no such parent,
382   // return nullptr.
383   const TypeLoc *getParentTypeLoc(TypeLoc Loc) const {
384     auto Parents = Context.getParents(Loc);
385     // FIXME: figure out how to handle it when there are multiple parents.
386     if (Parents.size() != 1)
387       return nullptr;
388     return Parents[0].get<TypeLoc>();
389   }
390 
391   // Check whether the USR of a given Decl is in the USRSet.
392   bool isInUSRSet(const Decl *Decl) const {
393     auto USR = getUSRForDecl(Decl);
394     if (USR.empty())
395       return false;
396     return llvm::is_contained(USRSet, USR);
397   }
398 
399   const std::set<std::string> USRSet;
400   ASTContext &Context;
401   std::vector<RenameInfo> RenameInfos;
402   // Record all interested using declarations which contains the using-shadow
403   // declarations of the symbol declarations being renamed.
404   std::vector<const UsingDecl *> UsingDecls;
405 };
406 
407 } // namespace
408 
409 SymbolOccurrences getOccurrencesOfUSRs(ArrayRef<std::string> USRs,
410                                        StringRef PrevName, Decl *Decl) {
411   USRLocFindingASTVisitor Visitor(USRs, PrevName, Decl->getASTContext());
412   Visitor.TraverseDecl(Decl);
413   return Visitor.takeOccurrences();
414 }
415 
416 std::vector<tooling::AtomicChange>
417 createRenameAtomicChanges(llvm::ArrayRef<std::string> USRs,
418                           llvm::StringRef NewName, Decl *TranslationUnitDecl) {
419   RenameLocFinder Finder(USRs, TranslationUnitDecl->getASTContext());
420   Finder.TraverseDecl(TranslationUnitDecl);
421 
422   const SourceManager &SM =
423       TranslationUnitDecl->getASTContext().getSourceManager();
424 
425   std::vector<tooling::AtomicChange> AtomicChanges;
426   auto Replace = [&](SourceLocation Start, SourceLocation End,
427                      llvm::StringRef Text) {
428     tooling::AtomicChange ReplaceChange = tooling::AtomicChange(SM, Start);
429     llvm::Error Err = ReplaceChange.replace(
430         SM, CharSourceRange::getTokenRange(Start, End), Text);
431     if (Err) {
432       llvm::errs() << "Faile to add replacement to AtomicChange: "
433                    << llvm::toString(std::move(Err)) << "\n";
434       return;
435     }
436     AtomicChanges.push_back(std::move(ReplaceChange));
437   };
438 
439   for (const auto &RenameInfo : Finder.getRenameInfos()) {
440     std::string ReplacedName = NewName.str();
441     if (RenameInfo.IgnorePrefixQualifers) {
442       // Get the name without prefix qualifiers from NewName.
443       size_t LastColonPos = NewName.find_last_of(':');
444       if (LastColonPos != std::string::npos)
445         ReplacedName = NewName.substr(LastColonPos + 1);
446     } else {
447       if (RenameInfo.FromDecl && RenameInfo.Context) {
448         if (!llvm::isa<clang::TranslationUnitDecl>(
449                 RenameInfo.Context->getDeclContext())) {
450           ReplacedName = tooling::replaceNestedName(
451               RenameInfo.Specifier, RenameInfo.Context->getDeclContext(),
452               RenameInfo.FromDecl,
453               NewName.startswith("::") ? NewName.str()
454                                        : ("::" + NewName).str());
455         }
456       }
457       // If the NewName contains leading "::", add it back.
458       if (NewName.startswith("::") && NewName.substr(2) == ReplacedName)
459         ReplacedName = NewName.str();
460     }
461     Replace(RenameInfo.Begin, RenameInfo.End, ReplacedName);
462   }
463 
464   // Hanlde using declarations explicitly as "using a::Foo" don't trigger
465   // typeLoc for "a::Foo".
466   for (const auto *Using : Finder.getUsingDecls())
467     Replace(Using->getLocStart(), Using->getLocEnd(), "using " + NewName.str());
468 
469   return AtomicChanges;
470 }
471 
472 } // end namespace tooling
473 } // end namespace clang
474