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 // Returns true if the given Loc is valid for edit. We don't edit the 43 // SourceLocations that are valid or in temporary buffer. 44 bool IsValidEditLoc(const clang::SourceManager& SM, clang::SourceLocation Loc) { 45 if (Loc.isInvalid()) 46 return false; 47 const clang::FullSourceLoc FullLoc(Loc, SM); 48 std::pair<clang::FileID, unsigned> FileIdAndOffset = 49 FullLoc.getSpellingLoc().getDecomposedLoc(); 50 return SM.getFileEntryForID(FileIdAndOffset.first) != nullptr; 51 } 52 53 // \brief This visitor recursively searches for all instances of a USR in a 54 // translation unit and stores them for later usage. 55 class USRLocFindingASTVisitor 56 : public RecursiveSymbolVisitor<USRLocFindingASTVisitor> { 57 public: 58 explicit USRLocFindingASTVisitor(const std::vector<std::string> &USRs, 59 StringRef PrevName, 60 const ASTContext &Context) 61 : RecursiveSymbolVisitor(Context.getSourceManager(), 62 Context.getLangOpts()), 63 USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) { 64 } 65 66 bool visitSymbolOccurrence(const NamedDecl *ND, 67 ArrayRef<SourceRange> NameRanges) { 68 if (USRSet.find(getUSRForDecl(ND)) != USRSet.end()) { 69 assert(NameRanges.size() == 1 && 70 "Multiple name pieces are not supported yet!"); 71 SourceLocation Loc = NameRanges[0].getBegin(); 72 const SourceManager &SM = Context.getSourceManager(); 73 // TODO: Deal with macro occurrences correctly. 74 if (Loc.isMacroID()) 75 Loc = SM.getSpellingLoc(Loc); 76 checkAndAddLocation(Loc); 77 } 78 return true; 79 } 80 81 // Non-visitors: 82 83 /// \brief Returns a set of unique symbol occurrences. Duplicate or 84 /// overlapping occurrences are erroneous and should be reported! 85 SymbolOccurrences takeOccurrences() { return std::move(Occurrences); } 86 87 private: 88 void checkAndAddLocation(SourceLocation Loc) { 89 const SourceLocation BeginLoc = Loc; 90 const SourceLocation EndLoc = Lexer::getLocForEndOfToken( 91 BeginLoc, 0, Context.getSourceManager(), Context.getLangOpts()); 92 StringRef TokenName = 93 Lexer::getSourceText(CharSourceRange::getTokenRange(BeginLoc, EndLoc), 94 Context.getSourceManager(), Context.getLangOpts()); 95 size_t Offset = TokenName.find(PrevName.getNamePieces()[0]); 96 97 // The token of the source location we find actually has the old 98 // name. 99 if (Offset != StringRef::npos) 100 Occurrences.emplace_back(PrevName, SymbolOccurrence::MatchingSymbol, 101 BeginLoc.getLocWithOffset(Offset)); 102 } 103 104 const std::set<std::string> USRSet; 105 const SymbolName PrevName; 106 SymbolOccurrences Occurrences; 107 const ASTContext &Context; 108 }; 109 110 SourceLocation StartLocationForType(TypeLoc TL) { 111 // For elaborated types (e.g. `struct a::A`) we want the portion after the 112 // `struct` but including the namespace qualifier, `a::`. 113 if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>()) { 114 NestedNameSpecifierLoc NestedNameSpecifier = 115 ElaboratedTypeLoc.getQualifierLoc(); 116 if (NestedNameSpecifier.getNestedNameSpecifier()) 117 return NestedNameSpecifier.getBeginLoc(); 118 TL = TL.getNextTypeLoc(); 119 } 120 return TL.getLocStart(); 121 } 122 123 SourceLocation EndLocationForType(TypeLoc TL) { 124 // Dig past any namespace or keyword qualifications. 125 while (TL.getTypeLocClass() == TypeLoc::Elaborated || 126 TL.getTypeLocClass() == TypeLoc::Qualified) 127 TL = TL.getNextTypeLoc(); 128 129 // The location for template specializations (e.g. Foo<int>) includes the 130 // templated types in its location range. We want to restrict this to just 131 // before the `<` character. 132 if (TL.getTypeLocClass() == TypeLoc::TemplateSpecialization) { 133 return TL.castAs<TemplateSpecializationTypeLoc>() 134 .getLAngleLoc() 135 .getLocWithOffset(-1); 136 } 137 return TL.getEndLoc(); 138 } 139 140 NestedNameSpecifier *GetNestedNameForType(TypeLoc TL) { 141 // Dig past any keyword qualifications. 142 while (TL.getTypeLocClass() == TypeLoc::Qualified) 143 TL = TL.getNextTypeLoc(); 144 145 // For elaborated types (e.g. `struct a::A`) we want the portion after the 146 // `struct` but including the namespace qualifier, `a::`. 147 if (auto ElaboratedTypeLoc = TL.getAs<clang::ElaboratedTypeLoc>()) 148 return ElaboratedTypeLoc.getQualifierLoc().getNestedNameSpecifier(); 149 return nullptr; 150 } 151 152 // Find all locations identified by the given USRs for rename. 153 // 154 // This class will traverse the AST and find every AST node whose USR is in the 155 // given USRs' set. 156 class RenameLocFinder : public RecursiveASTVisitor<RenameLocFinder> { 157 public: 158 RenameLocFinder(llvm::ArrayRef<std::string> USRs, ASTContext &Context) 159 : USRSet(USRs.begin(), USRs.end()), Context(Context) {} 160 161 // A structure records all information of a symbol reference being renamed. 162 // We try to add as few prefix qualifiers as possible. 163 struct RenameInfo { 164 // The begin location of a symbol being renamed. 165 SourceLocation Begin; 166 // The end location of a symbol being renamed. 167 SourceLocation End; 168 // The declaration of a symbol being renamed (can be nullptr). 169 const NamedDecl *FromDecl; 170 // The declaration in which the nested name is contained (can be nullptr). 171 const Decl *Context; 172 // The nested name being replaced (can be nullptr). 173 const NestedNameSpecifier *Specifier; 174 // Determine whether the prefix qualifiers of the NewName should be ignored. 175 // Normally, we set it to true for the symbol declaration and definition to 176 // avoid adding prefix qualifiers. 177 // For example, if it is true and NewName is "a::b::foo", then the symbol 178 // occurrence which the RenameInfo points to will be renamed to "foo". 179 bool IgnorePrefixQualifers; 180 }; 181 182 bool VisitNamedDecl(const NamedDecl *Decl) { 183 // UsingDecl has been handled in other place. 184 if (llvm::isa<UsingDecl>(Decl)) 185 return true; 186 187 // DestructorDecl has been handled in Typeloc. 188 if (llvm::isa<CXXDestructorDecl>(Decl)) 189 return true; 190 191 if (Decl->isImplicit()) 192 return true; 193 194 if (isInUSRSet(Decl)) { 195 // For the case of renaming an alias template, we actually rename the 196 // underlying alias declaration of the template. 197 if (const auto* TAT = dyn_cast<TypeAliasTemplateDecl>(Decl)) 198 Decl = TAT->getTemplatedDecl(); 199 200 auto StartLoc = Decl->getLocation(); 201 auto EndLoc = StartLoc; 202 if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) { 203 RenameInfo Info = {StartLoc, 204 EndLoc, 205 /*FromDecl=*/nullptr, 206 /*Context=*/nullptr, 207 /*Specifier=*/nullptr, 208 /*IgnorePrefixQualifers=*/true}; 209 RenameInfos.push_back(Info); 210 } 211 } 212 return true; 213 } 214 215 bool VisitDeclRefExpr(const DeclRefExpr *Expr) { 216 const NamedDecl *Decl = Expr->getFoundDecl(); 217 // Get the underlying declaration of the shadow declaration introduced by a 218 // using declaration. 219 if (auto *UsingShadow = llvm::dyn_cast<UsingShadowDecl>(Decl)) { 220 Decl = UsingShadow->getTargetDecl(); 221 } 222 223 auto StartLoc = Expr->getLocStart(); 224 // For template function call expressions like `foo<int>()`, we want to 225 // restrict the end of location to just before the `<` character. 226 SourceLocation EndLoc = Expr->hasExplicitTemplateArgs() 227 ? Expr->getLAngleLoc().getLocWithOffset(-1) 228 : Expr->getLocEnd(); 229 230 // In case of renaming an enum declaration, we have to explicitly handle 231 // unscoped enum constants referenced in expressions (e.g. 232 // "auto r = ns1::ns2::Green" where Green is an enum constant of an unscoped 233 // enum decl "ns1::ns2::Color") as these enum constants cannot be caught by 234 // TypeLoc. 235 if (const auto *T = llvm::dyn_cast<EnumConstantDecl>(Decl)) { 236 // FIXME: Handle the enum constant without prefix qualifiers (`a = Green`) 237 // when renaming an unscoped enum declaration with a new namespace. 238 if (!Expr->hasQualifier()) 239 return true; 240 241 if (const auto *ED = 242 llvm::dyn_cast_or_null<EnumDecl>(getClosestAncestorDecl(*T))) { 243 if (ED->isScoped()) 244 return true; 245 Decl = ED; 246 } 247 // The current fix would qualify "ns1::ns2::Green" as 248 // "ns1::ns2::Color::Green". 249 // 250 // Get the EndLoc of the replacement by moving 1 character backward ( 251 // to exclude the last '::'). 252 // 253 // ns1::ns2::Green; 254 // ^ ^^ 255 // BeginLoc |EndLoc of the qualifier 256 // new EndLoc 257 EndLoc = Expr->getQualifierLoc().getEndLoc().getLocWithOffset(-1); 258 assert(EndLoc.isValid() && 259 "The enum constant should have prefix qualifers."); 260 } 261 if (isInUSRSet(Decl) && 262 IsValidEditLoc(Context.getSourceManager(), StartLoc)) { 263 RenameInfo Info = {StartLoc, 264 EndLoc, 265 Decl, 266 getClosestAncestorDecl(*Expr), 267 Expr->getQualifier(), 268 /*IgnorePrefixQualifers=*/false}; 269 RenameInfos.push_back(Info); 270 } 271 272 return true; 273 } 274 275 bool VisitUsingDecl(const UsingDecl *Using) { 276 for (const auto *UsingShadow : Using->shadows()) { 277 if (isInUSRSet(UsingShadow->getTargetDecl())) { 278 UsingDecls.push_back(Using); 279 break; 280 } 281 } 282 return true; 283 } 284 285 bool VisitNestedNameSpecifierLocations(NestedNameSpecifierLoc NestedLoc) { 286 if (!NestedLoc.getNestedNameSpecifier()->getAsType()) 287 return true; 288 289 if (const auto *TargetDecl = 290 getSupportedDeclFromTypeLoc(NestedLoc.getTypeLoc())) { 291 if (isInUSRSet(TargetDecl)) { 292 RenameInfo Info = {NestedLoc.getBeginLoc(), 293 EndLocationForType(NestedLoc.getTypeLoc()), 294 TargetDecl, 295 getClosestAncestorDecl(NestedLoc), 296 NestedLoc.getNestedNameSpecifier()->getPrefix(), 297 /*IgnorePrefixQualifers=*/false}; 298 RenameInfos.push_back(Info); 299 } 300 } 301 return true; 302 } 303 304 bool VisitTypeLoc(TypeLoc Loc) { 305 auto Parents = Context.getParents(Loc); 306 TypeLoc ParentTypeLoc; 307 if (!Parents.empty()) { 308 // Handle cases of nested name specificier locations. 309 // 310 // The VisitNestedNameSpecifierLoc interface is not impelmented in 311 // RecursiveASTVisitor, we have to handle it explicitly. 312 if (const auto *NSL = Parents[0].get<NestedNameSpecifierLoc>()) { 313 VisitNestedNameSpecifierLocations(*NSL); 314 return true; 315 } 316 317 if (const auto *TL = Parents[0].get<TypeLoc>()) 318 ParentTypeLoc = *TL; 319 } 320 321 // Handle the outermost TypeLoc which is directly linked to the interesting 322 // declaration and don't handle nested name specifier locations. 323 if (const auto *TargetDecl = getSupportedDeclFromTypeLoc(Loc)) { 324 if (isInUSRSet(TargetDecl)) { 325 // Only handle the outermost typeLoc. 326 // 327 // For a type like "a::Foo", there will be two typeLocs for it. 328 // One ElaboratedType, the other is RecordType: 329 // 330 // ElaboratedType 0x33b9390 'a::Foo' sugar 331 // `-RecordType 0x338fef0 'class a::Foo' 332 // `-CXXRecord 0x338fe58 'Foo' 333 // 334 // Skip if this is an inner typeLoc. 335 if (!ParentTypeLoc.isNull() && 336 isInUSRSet(getSupportedDeclFromTypeLoc(ParentTypeLoc))) 337 return true; 338 339 auto StartLoc = StartLocationForType(Loc); 340 auto EndLoc = EndLocationForType(Loc); 341 if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) { 342 RenameInfo Info = {StartLoc, 343 EndLoc, 344 TargetDecl, 345 getClosestAncestorDecl(Loc), 346 GetNestedNameForType(Loc), 347 /*IgnorePrefixQualifers=*/false}; 348 RenameInfos.push_back(Info); 349 } 350 return true; 351 } 352 } 353 354 // Handle specific template class specialiation cases. 355 if (const auto *TemplateSpecType = 356 dyn_cast<TemplateSpecializationType>(Loc.getType())) { 357 TypeLoc TargetLoc = Loc; 358 if (!ParentTypeLoc.isNull()) { 359 if (llvm::isa<ElaboratedType>(ParentTypeLoc.getType())) 360 TargetLoc = ParentTypeLoc; 361 } 362 363 if (isInUSRSet(TemplateSpecType->getTemplateName().getAsTemplateDecl())) { 364 TypeLoc TargetLoc = Loc; 365 // FIXME: Find a better way to handle this case. 366 // For the qualified template class specification type like 367 // "ns::Foo<int>" in "ns::Foo<int>& f();", we want the parent typeLoc 368 // (ElaboratedType) of the TemplateSpecializationType in order to 369 // catch the prefix qualifiers "ns::". 370 if (!ParentTypeLoc.isNull() && 371 llvm::isa<ElaboratedType>(ParentTypeLoc.getType())) 372 TargetLoc = ParentTypeLoc; 373 374 auto StartLoc = StartLocationForType(TargetLoc); 375 auto EndLoc = EndLocationForType(TargetLoc); 376 if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) { 377 RenameInfo Info = { 378 StartLoc, 379 EndLoc, 380 TemplateSpecType->getTemplateName().getAsTemplateDecl(), 381 getClosestAncestorDecl( 382 ast_type_traits::DynTypedNode::create(TargetLoc)), 383 GetNestedNameForType(TargetLoc), 384 /*IgnorePrefixQualifers=*/false}; 385 RenameInfos.push_back(Info); 386 } 387 } 388 } 389 return true; 390 } 391 392 // Returns a list of RenameInfo. 393 const std::vector<RenameInfo> &getRenameInfos() const { return RenameInfos; } 394 395 // Returns a list of using declarations which are needed to update. 396 const std::vector<const UsingDecl *> &getUsingDecls() const { 397 return UsingDecls; 398 } 399 400 private: 401 // Get the supported declaration from a given typeLoc. If the declaration type 402 // is not supported, returns nullptr. 403 const NamedDecl *getSupportedDeclFromTypeLoc(TypeLoc Loc) { 404 if (const auto* TT = Loc.getType()->getAs<clang::TypedefType>()) 405 return TT->getDecl(); 406 if (const auto *RD = Loc.getType()->getAsCXXRecordDecl()) 407 return RD; 408 if (const auto *ED = 409 llvm::dyn_cast_or_null<EnumDecl>(Loc.getType()->getAsTagDecl())) 410 return ED; 411 return nullptr; 412 } 413 414 // Get the closest ancester which is a declaration of a given AST node. 415 template <typename ASTNodeType> 416 const Decl *getClosestAncestorDecl(const ASTNodeType &Node) { 417 auto Parents = Context.getParents(Node); 418 // FIXME: figure out how to handle it when there are multiple parents. 419 if (Parents.size() != 1) 420 return nullptr; 421 if (ast_type_traits::ASTNodeKind::getFromNodeKind<Decl>().isBaseOf( 422 Parents[0].getNodeKind())) 423 return Parents[0].template get<Decl>(); 424 return getClosestAncestorDecl(Parents[0]); 425 } 426 427 // Get the parent typeLoc of a given typeLoc. If there is no such parent, 428 // return nullptr. 429 const TypeLoc *getParentTypeLoc(TypeLoc Loc) const { 430 auto Parents = Context.getParents(Loc); 431 // FIXME: figure out how to handle it when there are multiple parents. 432 if (Parents.size() != 1) 433 return nullptr; 434 return Parents[0].get<TypeLoc>(); 435 } 436 437 // Check whether the USR of a given Decl is in the USRSet. 438 bool isInUSRSet(const Decl *Decl) const { 439 auto USR = getUSRForDecl(Decl); 440 if (USR.empty()) 441 return false; 442 return llvm::is_contained(USRSet, USR); 443 } 444 445 const std::set<std::string> USRSet; 446 ASTContext &Context; 447 std::vector<RenameInfo> RenameInfos; 448 // Record all interested using declarations which contains the using-shadow 449 // declarations of the symbol declarations being renamed. 450 std::vector<const UsingDecl *> UsingDecls; 451 }; 452 453 } // namespace 454 455 SymbolOccurrences getOccurrencesOfUSRs(ArrayRef<std::string> USRs, 456 StringRef PrevName, Decl *Decl) { 457 USRLocFindingASTVisitor Visitor(USRs, PrevName, Decl->getASTContext()); 458 Visitor.TraverseDecl(Decl); 459 return Visitor.takeOccurrences(); 460 } 461 462 std::vector<tooling::AtomicChange> 463 createRenameAtomicChanges(llvm::ArrayRef<std::string> USRs, 464 llvm::StringRef NewName, Decl *TranslationUnitDecl) { 465 RenameLocFinder Finder(USRs, TranslationUnitDecl->getASTContext()); 466 Finder.TraverseDecl(TranslationUnitDecl); 467 468 const SourceManager &SM = 469 TranslationUnitDecl->getASTContext().getSourceManager(); 470 471 std::vector<tooling::AtomicChange> AtomicChanges; 472 auto Replace = [&](SourceLocation Start, SourceLocation End, 473 llvm::StringRef Text) { 474 tooling::AtomicChange ReplaceChange = tooling::AtomicChange(SM, Start); 475 llvm::Error Err = ReplaceChange.replace( 476 SM, CharSourceRange::getTokenRange(Start, End), Text); 477 if (Err) { 478 llvm::errs() << "Faile to add replacement to AtomicChange: " 479 << llvm::toString(std::move(Err)) << "\n"; 480 return; 481 } 482 AtomicChanges.push_back(std::move(ReplaceChange)); 483 }; 484 485 for (const auto &RenameInfo : Finder.getRenameInfos()) { 486 std::string ReplacedName = NewName.str(); 487 if (RenameInfo.IgnorePrefixQualifers) { 488 // Get the name without prefix qualifiers from NewName. 489 size_t LastColonPos = NewName.find_last_of(':'); 490 if (LastColonPos != std::string::npos) 491 ReplacedName = NewName.substr(LastColonPos + 1); 492 } else { 493 if (RenameInfo.FromDecl && RenameInfo.Context) { 494 if (!llvm::isa<clang::TranslationUnitDecl>( 495 RenameInfo.Context->getDeclContext())) { 496 ReplacedName = tooling::replaceNestedName( 497 RenameInfo.Specifier, RenameInfo.Context->getDeclContext(), 498 RenameInfo.FromDecl, 499 NewName.startswith("::") ? NewName.str() 500 : ("::" + NewName).str()); 501 } else { 502 // This fixes the case where type `T` is a parameter inside a function 503 // type (e.g. `std::function<void(T)>`) and the DeclContext of `T` 504 // becomes the translation unit. As a workaround, we simply use 505 // fully-qualified name here for all references whose `DeclContext` is 506 // the translation unit and ignore the possible existence of 507 // using-decls (in the global scope) that can shorten the replaced 508 // name. 509 llvm::StringRef ActualName = Lexer::getSourceText( 510 CharSourceRange::getTokenRange( 511 SourceRange(RenameInfo.Begin, RenameInfo.End)), 512 SM, TranslationUnitDecl->getASTContext().getLangOpts()); 513 // Add the leading "::" back if the name written in the code contains 514 // it. 515 if (ActualName.startswith("::") && !NewName.startswith("::")) { 516 ReplacedName = "::" + NewName.str(); 517 } 518 } 519 } 520 // If the NewName contains leading "::", add it back. 521 if (NewName.startswith("::") && NewName.substr(2) == ReplacedName) 522 ReplacedName = NewName.str(); 523 } 524 Replace(RenameInfo.Begin, RenameInfo.End, ReplacedName); 525 } 526 527 // Hanlde using declarations explicitly as "using a::Foo" don't trigger 528 // typeLoc for "a::Foo". 529 for (const auto *Using : Finder.getUsingDecls()) 530 Replace(Using->getLocStart(), Using->getLocEnd(), "using " + NewName.str()); 531 532 return AtomicChanges; 533 } 534 535 } // end namespace tooling 536 } // end namespace clang 537