1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===// 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 // This file implements name lookup for C, C++, Objective-C, and 11 // Objective-C++. 12 // 13 //===----------------------------------------------------------------------===// 14 #include "clang/Sema/Lookup.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclLookups.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/Lex/ModuleLoader.h" 27 #include "clang/Sema/DeclSpec.h" 28 #include "clang/Sema/ExternalSemaSource.h" 29 #include "clang/Sema/Overload.h" 30 #include "clang/Sema/Scope.h" 31 #include "clang/Sema/ScopeInfo.h" 32 #include "clang/Sema/Sema.h" 33 #include "clang/Sema/SemaInternal.h" 34 #include "clang/Sema/TemplateDeduction.h" 35 #include "clang/Sema/TypoCorrection.h" 36 #include "llvm/ADT/STLExtras.h" 37 #include "llvm/ADT/SetVector.h" 38 #include "llvm/ADT/SmallPtrSet.h" 39 #include "llvm/ADT/StringMap.h" 40 #include "llvm/ADT/TinyPtrVector.h" 41 #include "llvm/ADT/edit_distance.h" 42 #include "llvm/Support/ErrorHandling.h" 43 #include <algorithm> 44 #include <iterator> 45 #include <limits> 46 #include <list> 47 #include <map> 48 #include <set> 49 #include <utility> 50 #include <vector> 51 52 using namespace clang; 53 using namespace sema; 54 55 namespace { 56 class UnqualUsingEntry { 57 const DeclContext *Nominated; 58 const DeclContext *CommonAncestor; 59 60 public: 61 UnqualUsingEntry(const DeclContext *Nominated, 62 const DeclContext *CommonAncestor) 63 : Nominated(Nominated), CommonAncestor(CommonAncestor) { 64 } 65 66 const DeclContext *getCommonAncestor() const { 67 return CommonAncestor; 68 } 69 70 const DeclContext *getNominatedNamespace() const { 71 return Nominated; 72 } 73 74 // Sort by the pointer value of the common ancestor. 75 struct Comparator { 76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { 77 return L.getCommonAncestor() < R.getCommonAncestor(); 78 } 79 80 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { 81 return E.getCommonAncestor() < DC; 82 } 83 84 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { 85 return DC < E.getCommonAncestor(); 86 } 87 }; 88 }; 89 90 /// A collection of using directives, as used by C++ unqualified 91 /// lookup. 92 class UnqualUsingDirectiveSet { 93 typedef SmallVector<UnqualUsingEntry, 8> ListTy; 94 95 ListTy list; 96 llvm::SmallPtrSet<DeclContext*, 8> visited; 97 98 public: 99 UnqualUsingDirectiveSet() {} 100 101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) { 102 // C++ [namespace.udir]p1: 103 // During unqualified name lookup, the names appear as if they 104 // were declared in the nearest enclosing namespace which contains 105 // both the using-directive and the nominated namespace. 106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity(); 107 assert(InnermostFileDC && InnermostFileDC->isFileContext()); 108 109 for (; S; S = S->getParent()) { 110 // C++ [namespace.udir]p1: 111 // A using-directive shall not appear in class scope, but may 112 // appear in namespace scope or in block scope. 113 DeclContext *Ctx = S->getEntity(); 114 if (Ctx && Ctx->isFileContext()) { 115 visit(Ctx, Ctx); 116 } else if (!Ctx || Ctx->isFunctionOrMethod()) { 117 for (auto *I : S->using_directives()) 118 visit(I, InnermostFileDC); 119 } 120 } 121 } 122 123 // Visits a context and collect all of its using directives 124 // recursively. Treats all using directives as if they were 125 // declared in the context. 126 // 127 // A given context is only every visited once, so it is important 128 // that contexts be visited from the inside out in order to get 129 // the effective DCs right. 130 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 131 if (!visited.insert(DC)) 132 return; 133 134 addUsingDirectives(DC, EffectiveDC); 135 } 136 137 // Visits a using directive and collects all of its using 138 // directives recursively. Treats all using directives as if they 139 // were declared in the effective DC. 140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 141 DeclContext *NS = UD->getNominatedNamespace(); 142 if (!visited.insert(NS)) 143 return; 144 145 addUsingDirective(UD, EffectiveDC); 146 addUsingDirectives(NS, EffectiveDC); 147 } 148 149 // Adds all the using directives in a context (and those nominated 150 // by its using directives, transitively) as if they appeared in 151 // the given effective context. 152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 153 SmallVector<DeclContext*,4> queue; 154 while (true) { 155 for (auto UD : DC->using_directives()) { 156 DeclContext *NS = UD->getNominatedNamespace(); 157 if (visited.insert(NS)) { 158 addUsingDirective(UD, EffectiveDC); 159 queue.push_back(NS); 160 } 161 } 162 163 if (queue.empty()) 164 return; 165 166 DC = queue.pop_back_val(); 167 } 168 } 169 170 // Add a using directive as if it had been declared in the given 171 // context. This helps implement C++ [namespace.udir]p3: 172 // The using-directive is transitive: if a scope contains a 173 // using-directive that nominates a second namespace that itself 174 // contains using-directives, the effect is as if the 175 // using-directives from the second namespace also appeared in 176 // the first. 177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 178 // Find the common ancestor between the effective context and 179 // the nominated namespace. 180 DeclContext *Common = UD->getNominatedNamespace(); 181 while (!Common->Encloses(EffectiveDC)) 182 Common = Common->getParent(); 183 Common = Common->getPrimaryContext(); 184 185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 186 } 187 188 void done() { 189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); 190 } 191 192 typedef ListTy::const_iterator const_iterator; 193 194 const_iterator begin() const { return list.begin(); } 195 const_iterator end() const { return list.end(); } 196 197 std::pair<const_iterator,const_iterator> 198 getNamespacesFor(DeclContext *DC) const { 199 return std::equal_range(begin(), end(), DC->getPrimaryContext(), 200 UnqualUsingEntry::Comparator()); 201 } 202 }; 203 } 204 205 // Retrieve the set of identifier namespaces that correspond to a 206 // specific kind of name lookup. 207 static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 208 bool CPlusPlus, 209 bool Redeclaration) { 210 unsigned IDNS = 0; 211 switch (NameKind) { 212 case Sema::LookupObjCImplicitSelfParam: 213 case Sema::LookupOrdinaryName: 214 case Sema::LookupRedeclarationWithLinkage: 215 case Sema::LookupLocalFriendName: 216 IDNS = Decl::IDNS_Ordinary; 217 if (CPlusPlus) { 218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 219 if (Redeclaration) 220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 221 } 222 if (Redeclaration) 223 IDNS |= Decl::IDNS_LocalExtern; 224 break; 225 226 case Sema::LookupOperatorName: 227 // Operator lookup is its own crazy thing; it is not the same 228 // as (e.g.) looking up an operator name for redeclaration. 229 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 230 IDNS = Decl::IDNS_NonMemberOperator; 231 break; 232 233 case Sema::LookupTagName: 234 if (CPlusPlus) { 235 IDNS = Decl::IDNS_Type; 236 237 // When looking for a redeclaration of a tag name, we add: 238 // 1) TagFriend to find undeclared friend decls 239 // 2) Namespace because they can't "overload" with tag decls. 240 // 3) Tag because it includes class templates, which can't 241 // "overload" with tag decls. 242 if (Redeclaration) 243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 244 } else { 245 IDNS = Decl::IDNS_Tag; 246 } 247 break; 248 249 case Sema::LookupLabel: 250 IDNS = Decl::IDNS_Label; 251 break; 252 253 case Sema::LookupMemberName: 254 IDNS = Decl::IDNS_Member; 255 if (CPlusPlus) 256 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 257 break; 258 259 case Sema::LookupNestedNameSpecifierName: 260 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 261 break; 262 263 case Sema::LookupNamespaceName: 264 IDNS = Decl::IDNS_Namespace; 265 break; 266 267 case Sema::LookupUsingDeclName: 268 assert(Redeclaration && "should only be used for redecl lookup"); 269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | 270 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend | 271 Decl::IDNS_LocalExtern; 272 break; 273 274 case Sema::LookupObjCProtocolName: 275 IDNS = Decl::IDNS_ObjCProtocol; 276 break; 277 278 case Sema::LookupAnyName: 279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member 280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol 281 | Decl::IDNS_Type; 282 break; 283 } 284 return IDNS; 285 } 286 287 void LookupResult::configure() { 288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus, 289 isForRedeclaration()); 290 291 // If we're looking for one of the allocation or deallocation 292 // operators, make sure that the implicitly-declared new and delete 293 // operators can be found. 294 switch (NameInfo.getName().getCXXOverloadedOperator()) { 295 case OO_New: 296 case OO_Delete: 297 case OO_Array_New: 298 case OO_Array_Delete: 299 SemaRef.DeclareGlobalNewDelete(); 300 break; 301 302 default: 303 break; 304 } 305 306 // Compiler builtins are always visible, regardless of where they end 307 // up being declared. 308 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { 309 if (unsigned BuiltinID = Id->getBuiltinID()) { 310 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 311 AllowHidden = true; 312 } 313 } 314 } 315 316 bool LookupResult::sanity() const { 317 // This function is never called by NDEBUG builds. 318 assert(ResultKind != NotFound || Decls.size() == 0); 319 assert(ResultKind != Found || Decls.size() == 1); 320 assert(ResultKind != FoundOverloaded || Decls.size() > 1 || 321 (Decls.size() == 1 && 322 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))); 323 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved()); 324 assert(ResultKind != Ambiguous || Decls.size() > 1 || 325 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || 326 Ambiguity == AmbiguousBaseSubobjectTypes))); 327 assert((Paths != nullptr) == (ResultKind == Ambiguous && 328 (Ambiguity == AmbiguousBaseSubobjectTypes || 329 Ambiguity == AmbiguousBaseSubobjects))); 330 return true; 331 } 332 333 // Necessary because CXXBasePaths is not complete in Sema.h 334 void LookupResult::deletePaths(CXXBasePaths *Paths) { 335 delete Paths; 336 } 337 338 /// Get a representative context for a declaration such that two declarations 339 /// will have the same context if they were found within the same scope. 340 static DeclContext *getContextForScopeMatching(Decl *D) { 341 // For function-local declarations, use that function as the context. This 342 // doesn't account for scopes within the function; the caller must deal with 343 // those. 344 DeclContext *DC = D->getLexicalDeclContext(); 345 if (DC->isFunctionOrMethod()) 346 return DC; 347 348 // Otherwise, look at the semantic context of the declaration. The 349 // declaration must have been found there. 350 return D->getDeclContext()->getRedeclContext(); 351 } 352 353 /// Resolves the result kind of this lookup. 354 void LookupResult::resolveKind() { 355 unsigned N = Decls.size(); 356 357 // Fast case: no possible ambiguity. 358 if (N == 0) { 359 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation); 360 return; 361 } 362 363 // If there's a single decl, we need to examine it to decide what 364 // kind of lookup this is. 365 if (N == 1) { 366 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); 367 if (isa<FunctionTemplateDecl>(D)) 368 ResultKind = FoundOverloaded; 369 else if (isa<UnresolvedUsingValueDecl>(D)) 370 ResultKind = FoundUnresolvedValue; 371 return; 372 } 373 374 // Don't do any extra resolution if we've already resolved as ambiguous. 375 if (ResultKind == Ambiguous) return; 376 377 llvm::SmallPtrSet<NamedDecl*, 16> Unique; 378 llvm::SmallPtrSet<QualType, 16> UniqueTypes; 379 380 bool Ambiguous = false; 381 bool HasTag = false, HasFunction = false, HasNonFunction = false; 382 bool HasFunctionTemplate = false, HasUnresolved = false; 383 384 unsigned UniqueTagIndex = 0; 385 386 unsigned I = 0; 387 while (I < N) { 388 NamedDecl *D = Decls[I]->getUnderlyingDecl(); 389 D = cast<NamedDecl>(D->getCanonicalDecl()); 390 391 // Ignore an invalid declaration unless it's the only one left. 392 if (D->isInvalidDecl() && I < N-1) { 393 Decls[I] = Decls[--N]; 394 continue; 395 } 396 397 // Redeclarations of types via typedef can occur both within a scope 398 // and, through using declarations and directives, across scopes. There is 399 // no ambiguity if they all refer to the same type, so unique based on the 400 // canonical type. 401 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) { 402 if (!TD->getDeclContext()->isRecord()) { 403 QualType T = SemaRef.Context.getTypeDeclType(TD); 404 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) { 405 // The type is not unique; pull something off the back and continue 406 // at this index. 407 Decls[I] = Decls[--N]; 408 continue; 409 } 410 } 411 } 412 413 if (!Unique.insert(D)) { 414 // If it's not unique, pull something off the back (and 415 // continue at this index). 416 Decls[I] = Decls[--N]; 417 continue; 418 } 419 420 // Otherwise, do some decl type analysis and then continue. 421 422 if (isa<UnresolvedUsingValueDecl>(D)) { 423 HasUnresolved = true; 424 } else if (isa<TagDecl>(D)) { 425 if (HasTag) 426 Ambiguous = true; 427 UniqueTagIndex = I; 428 HasTag = true; 429 } else if (isa<FunctionTemplateDecl>(D)) { 430 HasFunction = true; 431 HasFunctionTemplate = true; 432 } else if (isa<FunctionDecl>(D)) { 433 HasFunction = true; 434 } else { 435 if (HasNonFunction) 436 Ambiguous = true; 437 HasNonFunction = true; 438 } 439 I++; 440 } 441 442 // C++ [basic.scope.hiding]p2: 443 // A class name or enumeration name can be hidden by the name of 444 // an object, function, or enumerator declared in the same 445 // scope. If a class or enumeration name and an object, function, 446 // or enumerator are declared in the same scope (in any order) 447 // with the same name, the class or enumeration name is hidden 448 // wherever the object, function, or enumerator name is visible. 449 // But it's still an error if there are distinct tag types found, 450 // even if they're not visible. (ref?) 451 if (HideTags && HasTag && !Ambiguous && 452 (HasFunction || HasNonFunction || HasUnresolved)) { 453 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals( 454 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1]))) 455 Decls[UniqueTagIndex] = Decls[--N]; 456 else 457 Ambiguous = true; 458 } 459 460 Decls.set_size(N); 461 462 if (HasNonFunction && (HasFunction || HasUnresolved)) 463 Ambiguous = true; 464 465 if (Ambiguous) 466 setAmbiguous(LookupResult::AmbiguousReference); 467 else if (HasUnresolved) 468 ResultKind = LookupResult::FoundUnresolvedValue; 469 else if (N > 1 || HasFunctionTemplate) 470 ResultKind = LookupResult::FoundOverloaded; 471 else 472 ResultKind = LookupResult::Found; 473 } 474 475 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { 476 CXXBasePaths::const_paths_iterator I, E; 477 for (I = P.begin(), E = P.end(); I != E; ++I) 478 for (DeclContext::lookup_iterator DI = I->Decls.begin(), 479 DE = I->Decls.end(); DI != DE; ++DI) 480 addDecl(*DI); 481 } 482 483 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 484 Paths = new CXXBasePaths; 485 Paths->swap(P); 486 addDeclsFromBasePaths(*Paths); 487 resolveKind(); 488 setAmbiguous(AmbiguousBaseSubobjects); 489 } 490 491 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 492 Paths = new CXXBasePaths; 493 Paths->swap(P); 494 addDeclsFromBasePaths(*Paths); 495 resolveKind(); 496 setAmbiguous(AmbiguousBaseSubobjectTypes); 497 } 498 499 void LookupResult::print(raw_ostream &Out) { 500 Out << Decls.size() << " result(s)"; 501 if (isAmbiguous()) Out << ", ambiguous"; 502 if (Paths) Out << ", base paths present"; 503 504 for (iterator I = begin(), E = end(); I != E; ++I) { 505 Out << "\n"; 506 (*I)->print(Out, 2); 507 } 508 } 509 510 /// \brief Lookup a builtin function, when name lookup would otherwise 511 /// fail. 512 static bool LookupBuiltin(Sema &S, LookupResult &R) { 513 Sema::LookupNameKind NameKind = R.getLookupKind(); 514 515 // If we didn't find a use of this identifier, and if the identifier 516 // corresponds to a compiler builtin, create the decl object for the builtin 517 // now, injecting it into translation unit scope, and return it. 518 if (NameKind == Sema::LookupOrdinaryName || 519 NameKind == Sema::LookupRedeclarationWithLinkage) { 520 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); 521 if (II) { 522 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode && 523 II == S.getFloat128Identifier()) { 524 // libstdc++4.7's type_traits expects type __float128 to exist, so 525 // insert a dummy type to make that header build in gnu++11 mode. 526 R.addDecl(S.getASTContext().getFloat128StubType()); 527 return true; 528 } 529 530 // If this is a builtin on this (or all) targets, create the decl. 531 if (unsigned BuiltinID = II->getBuiltinID()) { 532 // In C++, we don't have any predefined library functions like 533 // 'malloc'. Instead, we'll just error. 534 if (S.getLangOpts().CPlusPlus && 535 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 536 return false; 537 538 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, 539 BuiltinID, S.TUScope, 540 R.isForRedeclaration(), 541 R.getNameLoc())) { 542 R.addDecl(D); 543 return true; 544 } 545 } 546 } 547 } 548 549 return false; 550 } 551 552 /// \brief Determine whether we can declare a special member function within 553 /// the class at this point. 554 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) { 555 // We need to have a definition for the class. 556 if (!Class->getDefinition() || Class->isDependentContext()) 557 return false; 558 559 // We can't be in the middle of defining the class. 560 return !Class->isBeingDefined(); 561 } 562 563 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { 564 if (!CanDeclareSpecialMemberFunction(Class)) 565 return; 566 567 // If the default constructor has not yet been declared, do so now. 568 if (Class->needsImplicitDefaultConstructor()) 569 DeclareImplicitDefaultConstructor(Class); 570 571 // If the copy constructor has not yet been declared, do so now. 572 if (Class->needsImplicitCopyConstructor()) 573 DeclareImplicitCopyConstructor(Class); 574 575 // If the copy assignment operator has not yet been declared, do so now. 576 if (Class->needsImplicitCopyAssignment()) 577 DeclareImplicitCopyAssignment(Class); 578 579 if (getLangOpts().CPlusPlus11) { 580 // If the move constructor has not yet been declared, do so now. 581 if (Class->needsImplicitMoveConstructor()) 582 DeclareImplicitMoveConstructor(Class); // might not actually do it 583 584 // If the move assignment operator has not yet been declared, do so now. 585 if (Class->needsImplicitMoveAssignment()) 586 DeclareImplicitMoveAssignment(Class); // might not actually do it 587 } 588 589 // If the destructor has not yet been declared, do so now. 590 if (Class->needsImplicitDestructor()) 591 DeclareImplicitDestructor(Class); 592 } 593 594 /// \brief Determine whether this is the name of an implicitly-declared 595 /// special member function. 596 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { 597 switch (Name.getNameKind()) { 598 case DeclarationName::CXXConstructorName: 599 case DeclarationName::CXXDestructorName: 600 return true; 601 602 case DeclarationName::CXXOperatorName: 603 return Name.getCXXOverloadedOperator() == OO_Equal; 604 605 default: 606 break; 607 } 608 609 return false; 610 } 611 612 /// \brief If there are any implicit member functions with the given name 613 /// that need to be declared in the given declaration context, do so. 614 static void DeclareImplicitMemberFunctionsWithName(Sema &S, 615 DeclarationName Name, 616 const DeclContext *DC) { 617 if (!DC) 618 return; 619 620 switch (Name.getNameKind()) { 621 case DeclarationName::CXXConstructorName: 622 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 623 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 624 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 625 if (Record->needsImplicitDefaultConstructor()) 626 S.DeclareImplicitDefaultConstructor(Class); 627 if (Record->needsImplicitCopyConstructor()) 628 S.DeclareImplicitCopyConstructor(Class); 629 if (S.getLangOpts().CPlusPlus11 && 630 Record->needsImplicitMoveConstructor()) 631 S.DeclareImplicitMoveConstructor(Class); 632 } 633 break; 634 635 case DeclarationName::CXXDestructorName: 636 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 637 if (Record->getDefinition() && Record->needsImplicitDestructor() && 638 CanDeclareSpecialMemberFunction(Record)) 639 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); 640 break; 641 642 case DeclarationName::CXXOperatorName: 643 if (Name.getCXXOverloadedOperator() != OO_Equal) 644 break; 645 646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) { 647 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 648 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 649 if (Record->needsImplicitCopyAssignment()) 650 S.DeclareImplicitCopyAssignment(Class); 651 if (S.getLangOpts().CPlusPlus11 && 652 Record->needsImplicitMoveAssignment()) 653 S.DeclareImplicitMoveAssignment(Class); 654 } 655 } 656 break; 657 658 default: 659 break; 660 } 661 } 662 663 // Adds all qualifying matches for a name within a decl context to the 664 // given lookup result. Returns true if any matches were found. 665 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { 666 bool Found = false; 667 668 // Lazily declare C++ special member functions. 669 if (S.getLangOpts().CPlusPlus) 670 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC); 671 672 // Perform lookup into this declaration context. 673 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName()); 674 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E; 675 ++I) { 676 NamedDecl *D = *I; 677 if ((D = R.getAcceptableDecl(D))) { 678 R.addDecl(D); 679 Found = true; 680 } 681 } 682 683 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R)) 684 return true; 685 686 if (R.getLookupName().getNameKind() 687 != DeclarationName::CXXConversionFunctionName || 688 R.getLookupName().getCXXNameType()->isDependentType() || 689 !isa<CXXRecordDecl>(DC)) 690 return Found; 691 692 // C++ [temp.mem]p6: 693 // A specialization of a conversion function template is not found by 694 // name lookup. Instead, any conversion function templates visible in the 695 // context of the use are considered. [...] 696 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 697 if (!Record->isCompleteDefinition()) 698 return Found; 699 700 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(), 701 UEnd = Record->conversion_end(); U != UEnd; ++U) { 702 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); 703 if (!ConvTemplate) 704 continue; 705 706 // When we're performing lookup for the purposes of redeclaration, just 707 // add the conversion function template. When we deduce template 708 // arguments for specializations, we'll end up unifying the return 709 // type of the new declaration with the type of the function template. 710 if (R.isForRedeclaration()) { 711 R.addDecl(ConvTemplate); 712 Found = true; 713 continue; 714 } 715 716 // C++ [temp.mem]p6: 717 // [...] For each such operator, if argument deduction succeeds 718 // (14.9.2.3), the resulting specialization is used as if found by 719 // name lookup. 720 // 721 // When referencing a conversion function for any purpose other than 722 // a redeclaration (such that we'll be building an expression with the 723 // result), perform template argument deduction and place the 724 // specialization into the result set. We do this to avoid forcing all 725 // callers to perform special deduction for conversion functions. 726 TemplateDeductionInfo Info(R.getNameLoc()); 727 FunctionDecl *Specialization = nullptr; 728 729 const FunctionProtoType *ConvProto 730 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); 731 assert(ConvProto && "Nonsensical conversion function template type"); 732 733 // Compute the type of the function that we would expect the conversion 734 // function to have, if it were to match the name given. 735 // FIXME: Calling convention! 736 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo(); 737 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C); 738 EPI.ExceptionSpecType = EST_None; 739 EPI.NumExceptions = 0; 740 QualType ExpectedType 741 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(), 742 None, EPI); 743 744 // Perform template argument deduction against the type that we would 745 // expect the function to have. 746 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType, 747 Specialization, Info) 748 == Sema::TDK_Success) { 749 R.addDecl(Specialization); 750 Found = true; 751 } 752 } 753 754 return Found; 755 } 756 757 // Performs C++ unqualified lookup into the given file context. 758 static bool 759 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 760 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) { 761 762 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 763 764 // Perform direct name lookup into the LookupCtx. 765 bool Found = LookupDirect(S, R, NS); 766 767 // Perform direct name lookup into the namespaces nominated by the 768 // using directives whose common ancestor is this namespace. 769 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 770 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS); 771 772 for (; UI != UEnd; ++UI) 773 if (LookupDirect(S, R, UI->getNominatedNamespace())) 774 Found = true; 775 776 R.resolveKind(); 777 778 return Found; 779 } 780 781 static bool isNamespaceOrTranslationUnitScope(Scope *S) { 782 if (DeclContext *Ctx = S->getEntity()) 783 return Ctx->isFileContext(); 784 return false; 785 } 786 787 // Find the next outer declaration context from this scope. This 788 // routine actually returns the semantic outer context, which may 789 // differ from the lexical context (encoded directly in the Scope 790 // stack) when we are parsing a member of a class template. In this 791 // case, the second element of the pair will be true, to indicate that 792 // name lookup should continue searching in this semantic context when 793 // it leaves the current template parameter scope. 794 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) { 795 DeclContext *DC = S->getEntity(); 796 DeclContext *Lexical = nullptr; 797 for (Scope *OuterS = S->getParent(); OuterS; 798 OuterS = OuterS->getParent()) { 799 if (OuterS->getEntity()) { 800 Lexical = OuterS->getEntity(); 801 break; 802 } 803 } 804 805 // C++ [temp.local]p8: 806 // In the definition of a member of a class template that appears 807 // outside of the namespace containing the class template 808 // definition, the name of a template-parameter hides the name of 809 // a member of this namespace. 810 // 811 // Example: 812 // 813 // namespace N { 814 // class C { }; 815 // 816 // template<class T> class B { 817 // void f(T); 818 // }; 819 // } 820 // 821 // template<class C> void N::B<C>::f(C) { 822 // C b; // C is the template parameter, not N::C 823 // } 824 // 825 // In this example, the lexical context we return is the 826 // TranslationUnit, while the semantic context is the namespace N. 827 if (!Lexical || !DC || !S->getParent() || 828 !S->getParent()->isTemplateParamScope()) 829 return std::make_pair(Lexical, false); 830 831 // Find the outermost template parameter scope. 832 // For the example, this is the scope for the template parameters of 833 // template<class C>. 834 Scope *OutermostTemplateScope = S->getParent(); 835 while (OutermostTemplateScope->getParent() && 836 OutermostTemplateScope->getParent()->isTemplateParamScope()) 837 OutermostTemplateScope = OutermostTemplateScope->getParent(); 838 839 // Find the namespace context in which the original scope occurs. In 840 // the example, this is namespace N. 841 DeclContext *Semantic = DC; 842 while (!Semantic->isFileContext()) 843 Semantic = Semantic->getParent(); 844 845 // Find the declaration context just outside of the template 846 // parameter scope. This is the context in which the template is 847 // being lexically declaration (a namespace context). In the 848 // example, this is the global scope. 849 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) && 850 Lexical->Encloses(Semantic)) 851 return std::make_pair(Semantic, true); 852 853 return std::make_pair(Lexical, false); 854 } 855 856 namespace { 857 /// An RAII object to specify that we want to find block scope extern 858 /// declarations. 859 struct FindLocalExternScope { 860 FindLocalExternScope(LookupResult &R) 861 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() & 862 Decl::IDNS_LocalExtern) { 863 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary); 864 } 865 void restore() { 866 R.setFindLocalExtern(OldFindLocalExtern); 867 } 868 ~FindLocalExternScope() { 869 restore(); 870 } 871 LookupResult &R; 872 bool OldFindLocalExtern; 873 }; 874 } 875 876 bool Sema::CppLookupName(LookupResult &R, Scope *S) { 877 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup"); 878 879 DeclarationName Name = R.getLookupName(); 880 Sema::LookupNameKind NameKind = R.getLookupKind(); 881 882 // If this is the name of an implicitly-declared special member function, 883 // go through the scope stack to implicitly declare 884 if (isImplicitlyDeclaredMemberFunctionName(Name)) { 885 for (Scope *PreS = S; PreS; PreS = PreS->getParent()) 886 if (DeclContext *DC = PreS->getEntity()) 887 DeclareImplicitMemberFunctionsWithName(*this, Name, DC); 888 } 889 890 // Implicitly declare member functions with the name we're looking for, if in 891 // fact we are in a scope where it matters. 892 893 Scope *Initial = S; 894 IdentifierResolver::iterator 895 I = IdResolver.begin(Name), 896 IEnd = IdResolver.end(); 897 898 // First we lookup local scope. 899 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 900 // ...During unqualified name lookup (3.4.1), the names appear as if 901 // they were declared in the nearest enclosing namespace which contains 902 // both the using-directive and the nominated namespace. 903 // [Note: in this context, "contains" means "contains directly or 904 // indirectly". 905 // 906 // For example: 907 // namespace A { int i; } 908 // void foo() { 909 // int i; 910 // { 911 // using namespace A; 912 // ++i; // finds local 'i', A::i appears at global scope 913 // } 914 // } 915 // 916 UnqualUsingDirectiveSet UDirs; 917 bool VisitedUsingDirectives = false; 918 bool LeftStartingScope = false; 919 DeclContext *OutsideOfTemplateParamDC = nullptr; 920 921 // When performing a scope lookup, we want to find local extern decls. 922 FindLocalExternScope FindLocals(R); 923 924 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 925 DeclContext *Ctx = S->getEntity(); 926 927 // Check whether the IdResolver has anything in this scope. 928 bool Found = false; 929 for (; I != IEnd && S->isDeclScope(*I); ++I) { 930 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 931 if (NameKind == LookupRedeclarationWithLinkage) { 932 // Determine whether this (or a previous) declaration is 933 // out-of-scope. 934 if (!LeftStartingScope && !Initial->isDeclScope(*I)) 935 LeftStartingScope = true; 936 937 // If we found something outside of our starting scope that 938 // does not have linkage, skip it. If it's a template parameter, 939 // we still find it, so we can diagnose the invalid redeclaration. 940 if (LeftStartingScope && !((*I)->hasLinkage()) && 941 !(*I)->isTemplateParameter()) { 942 R.setShadowed(); 943 continue; 944 } 945 } 946 947 Found = true; 948 R.addDecl(ND); 949 } 950 } 951 if (Found) { 952 R.resolveKind(); 953 if (S->isClassScope()) 954 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 955 R.setNamingClass(Record); 956 return true; 957 } 958 959 if (NameKind == LookupLocalFriendName && !S->isClassScope()) { 960 // C++11 [class.friend]p11: 961 // If a friend declaration appears in a local class and the name 962 // specified is an unqualified name, a prior declaration is 963 // looked up without considering scopes that are outside the 964 // innermost enclosing non-class scope. 965 return false; 966 } 967 968 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 969 S->getParent() && !S->getParent()->isTemplateParamScope()) { 970 // We've just searched the last template parameter scope and 971 // found nothing, so look into the contexts between the 972 // lexical and semantic declaration contexts returned by 973 // findOuterContext(). This implements the name lookup behavior 974 // of C++ [temp.local]p8. 975 Ctx = OutsideOfTemplateParamDC; 976 OutsideOfTemplateParamDC = nullptr; 977 } 978 979 if (Ctx) { 980 DeclContext *OuterCtx; 981 bool SearchAfterTemplateScope; 982 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 983 if (SearchAfterTemplateScope) 984 OutsideOfTemplateParamDC = OuterCtx; 985 986 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 987 // We do not directly look into transparent contexts, since 988 // those entities will be found in the nearest enclosing 989 // non-transparent context. 990 if (Ctx->isTransparentContext()) 991 continue; 992 993 // We do not look directly into function or method contexts, 994 // since all of the local variables and parameters of the 995 // function/method are present within the Scope. 996 if (Ctx->isFunctionOrMethod()) { 997 // If we have an Objective-C instance method, look for ivars 998 // in the corresponding interface. 999 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 1000 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) 1001 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { 1002 ObjCInterfaceDecl *ClassDeclared; 1003 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( 1004 Name.getAsIdentifierInfo(), 1005 ClassDeclared)) { 1006 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) { 1007 R.addDecl(ND); 1008 R.resolveKind(); 1009 return true; 1010 } 1011 } 1012 } 1013 } 1014 1015 continue; 1016 } 1017 1018 // If this is a file context, we need to perform unqualified name 1019 // lookup considering using directives. 1020 if (Ctx->isFileContext()) { 1021 // If we haven't handled using directives yet, do so now. 1022 if (!VisitedUsingDirectives) { 1023 // Add using directives from this context up to the top level. 1024 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) { 1025 if (UCtx->isTransparentContext()) 1026 continue; 1027 1028 UDirs.visit(UCtx, UCtx); 1029 } 1030 1031 // Find the innermost file scope, so we can add using directives 1032 // from local scopes. 1033 Scope *InnermostFileScope = S; 1034 while (InnermostFileScope && 1035 !isNamespaceOrTranslationUnitScope(InnermostFileScope)) 1036 InnermostFileScope = InnermostFileScope->getParent(); 1037 UDirs.visitScopeChain(Initial, InnermostFileScope); 1038 1039 UDirs.done(); 1040 1041 VisitedUsingDirectives = true; 1042 } 1043 1044 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) { 1045 R.resolveKind(); 1046 return true; 1047 } 1048 1049 continue; 1050 } 1051 1052 // Perform qualified name lookup into this context. 1053 // FIXME: In some cases, we know that every name that could be found by 1054 // this qualified name lookup will also be on the identifier chain. For 1055 // example, inside a class without any base classes, we never need to 1056 // perform qualified lookup because all of the members are on top of the 1057 // identifier chain. 1058 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) 1059 return true; 1060 } 1061 } 1062 } 1063 1064 // Stop if we ran out of scopes. 1065 // FIXME: This really, really shouldn't be happening. 1066 if (!S) return false; 1067 1068 // If we are looking for members, no need to look into global/namespace scope. 1069 if (NameKind == LookupMemberName) 1070 return false; 1071 1072 // Collect UsingDirectiveDecls in all scopes, and recursively all 1073 // nominated namespaces by those using-directives. 1074 // 1075 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 1076 // don't build it for each lookup! 1077 if (!VisitedUsingDirectives) { 1078 UDirs.visitScopeChain(Initial, S); 1079 UDirs.done(); 1080 } 1081 1082 // If we're not performing redeclaration lookup, do not look for local 1083 // extern declarations outside of a function scope. 1084 if (!R.isForRedeclaration()) 1085 FindLocals.restore(); 1086 1087 // Lookup namespace scope, and global scope. 1088 // Unqualified name lookup in C++ requires looking into scopes 1089 // that aren't strictly lexical, and therefore we walk through the 1090 // context as well as walking through the scopes. 1091 for (; S; S = S->getParent()) { 1092 // Check whether the IdResolver has anything in this scope. 1093 bool Found = false; 1094 for (; I != IEnd && S->isDeclScope(*I); ++I) { 1095 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 1096 // We found something. Look for anything else in our scope 1097 // with this same name and in an acceptable identifier 1098 // namespace, so that we can construct an overload set if we 1099 // need to. 1100 Found = true; 1101 R.addDecl(ND); 1102 } 1103 } 1104 1105 if (Found && S->isTemplateParamScope()) { 1106 R.resolveKind(); 1107 return true; 1108 } 1109 1110 DeclContext *Ctx = S->getEntity(); 1111 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 1112 S->getParent() && !S->getParent()->isTemplateParamScope()) { 1113 // We've just searched the last template parameter scope and 1114 // found nothing, so look into the contexts between the 1115 // lexical and semantic declaration contexts returned by 1116 // findOuterContext(). This implements the name lookup behavior 1117 // of C++ [temp.local]p8. 1118 Ctx = OutsideOfTemplateParamDC; 1119 OutsideOfTemplateParamDC = nullptr; 1120 } 1121 1122 if (Ctx) { 1123 DeclContext *OuterCtx; 1124 bool SearchAfterTemplateScope; 1125 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 1126 if (SearchAfterTemplateScope) 1127 OutsideOfTemplateParamDC = OuterCtx; 1128 1129 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 1130 // We do not directly look into transparent contexts, since 1131 // those entities will be found in the nearest enclosing 1132 // non-transparent context. 1133 if (Ctx->isTransparentContext()) 1134 continue; 1135 1136 // If we have a context, and it's not a context stashed in the 1137 // template parameter scope for an out-of-line definition, also 1138 // look into that context. 1139 if (!(Found && S && S->isTemplateParamScope())) { 1140 assert(Ctx->isFileContext() && 1141 "We should have been looking only at file context here already."); 1142 1143 // Look into context considering using-directives. 1144 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) 1145 Found = true; 1146 } 1147 1148 if (Found) { 1149 R.resolveKind(); 1150 return true; 1151 } 1152 1153 if (R.isForRedeclaration() && !Ctx->isTransparentContext()) 1154 return false; 1155 } 1156 } 1157 1158 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) 1159 return false; 1160 } 1161 1162 return !R.empty(); 1163 } 1164 1165 /// \brief Find the declaration that a class temploid member specialization was 1166 /// instantiated from, or the member itself if it is an explicit specialization. 1167 static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) { 1168 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom(); 1169 } 1170 1171 /// \brief Find the module in which the given declaration was defined. 1172 static Module *getDefiningModule(Decl *Entity) { 1173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) { 1174 // If this function was instantiated from a template, the defining module is 1175 // the module containing the pattern. 1176 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 1177 Entity = Pattern; 1178 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) { 1179 // If it's a class template specialization, find the template or partial 1180 // specialization from which it was instantiated. 1181 if (ClassTemplateSpecializationDecl *SpecRD = 1182 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 1183 llvm::PointerUnion<ClassTemplateDecl*, 1184 ClassTemplatePartialSpecializationDecl*> From = 1185 SpecRD->getInstantiatedFrom(); 1186 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>()) 1187 Entity = FromTemplate->getTemplatedDecl(); 1188 else if (From) 1189 Entity = From.get<ClassTemplatePartialSpecializationDecl*>(); 1190 // Otherwise, it's an explicit specialization. 1191 } else if (MemberSpecializationInfo *MSInfo = 1192 RD->getMemberSpecializationInfo()) 1193 Entity = getInstantiatedFrom(RD, MSInfo); 1194 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) { 1195 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo()) 1196 Entity = getInstantiatedFrom(ED, MSInfo); 1197 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) { 1198 // FIXME: Map from variable template specializations back to the template. 1199 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) 1200 Entity = getInstantiatedFrom(VD, MSInfo); 1201 } 1202 1203 // Walk up to the containing context. That might also have been instantiated 1204 // from a template. 1205 DeclContext *Context = Entity->getDeclContext(); 1206 if (Context->isFileContext()) 1207 return Entity->getOwningModule(); 1208 return getDefiningModule(cast<Decl>(Context)); 1209 } 1210 1211 llvm::DenseSet<Module*> &Sema::getLookupModules() { 1212 unsigned N = ActiveTemplateInstantiations.size(); 1213 for (unsigned I = ActiveTemplateInstantiationLookupModules.size(); 1214 I != N; ++I) { 1215 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity); 1216 if (M && !LookupModulesCache.insert(M).second) 1217 M = nullptr; 1218 ActiveTemplateInstantiationLookupModules.push_back(M); 1219 } 1220 return LookupModulesCache; 1221 } 1222 1223 /// \brief Determine whether a declaration is visible to name lookup. 1224 /// 1225 /// This routine determines whether the declaration D is visible in the current 1226 /// lookup context, taking into account the current template instantiation 1227 /// stack. During template instantiation, a declaration is visible if it is 1228 /// visible from a module containing any entity on the template instantiation 1229 /// path (by instantiating a template, you allow it to see the declarations that 1230 /// your module can see, including those later on in your module). 1231 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) { 1232 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() && 1233 "should not call this: not in slow case"); 1234 Module *DeclModule = D->getOwningModule(); 1235 assert(DeclModule && "hidden decl not from a module"); 1236 1237 // Find the extra places where we need to look. 1238 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules(); 1239 if (LookupModules.empty()) 1240 return false; 1241 1242 // If our lookup set contains the decl's module, it's visible. 1243 if (LookupModules.count(DeclModule)) 1244 return true; 1245 1246 // If the declaration isn't exported, it's not visible in any other module. 1247 if (D->isModulePrivate()) 1248 return false; 1249 1250 // Check whether DeclModule is transitively exported to an import of 1251 // the lookup set. 1252 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(), 1253 E = LookupModules.end(); 1254 I != E; ++I) 1255 if ((*I)->isModuleVisible(DeclModule)) 1256 return true; 1257 return false; 1258 } 1259 1260 /// \brief Retrieve the visible declaration corresponding to D, if any. 1261 /// 1262 /// This routine determines whether the declaration D is visible in the current 1263 /// module, with the current imports. If not, it checks whether any 1264 /// redeclaration of D is visible, and if so, returns that declaration. 1265 /// 1266 /// \returns D, or a visible previous declaration of D, whichever is more recent 1267 /// and visible. If no declaration of D is visible, returns null. 1268 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 1269 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 1270 1271 for (auto RD : D->redecls()) { 1272 if (auto ND = dyn_cast<NamedDecl>(RD)) { 1273 if (LookupResult::isVisible(SemaRef, ND)) 1274 return ND; 1275 } 1276 } 1277 1278 return nullptr; 1279 } 1280 1281 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const { 1282 return findAcceptableDecl(SemaRef, D); 1283 } 1284 1285 /// @brief Perform unqualified name lookup starting from a given 1286 /// scope. 1287 /// 1288 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 1289 /// used to find names within the current scope. For example, 'x' in 1290 /// @code 1291 /// int x; 1292 /// int f() { 1293 /// return x; // unqualified name look finds 'x' in the global scope 1294 /// } 1295 /// @endcode 1296 /// 1297 /// Different lookup criteria can find different names. For example, a 1298 /// particular scope can have both a struct and a function of the same 1299 /// name, and each can be found by certain lookup criteria. For more 1300 /// information about lookup criteria, see the documentation for the 1301 /// class LookupCriteria. 1302 /// 1303 /// @param S The scope from which unqualified name lookup will 1304 /// begin. If the lookup criteria permits, name lookup may also search 1305 /// in the parent scopes. 1306 /// 1307 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to 1308 /// look up and the lookup kind), and is updated with the results of lookup 1309 /// including zero or more declarations and possibly additional information 1310 /// used to diagnose ambiguities. 1311 /// 1312 /// @returns \c true if lookup succeeded and false otherwise. 1313 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { 1314 DeclarationName Name = R.getLookupName(); 1315 if (!Name) return false; 1316 1317 LookupNameKind NameKind = R.getLookupKind(); 1318 1319 if (!getLangOpts().CPlusPlus) { 1320 // Unqualified name lookup in C/Objective-C is purely lexical, so 1321 // search in the declarations attached to the name. 1322 if (NameKind == Sema::LookupRedeclarationWithLinkage) { 1323 // Find the nearest non-transparent declaration scope. 1324 while (!(S->getFlags() & Scope::DeclScope) || 1325 (S->getEntity() && S->getEntity()->isTransparentContext())) 1326 S = S->getParent(); 1327 } 1328 1329 // When performing a scope lookup, we want to find local extern decls. 1330 FindLocalExternScope FindLocals(R); 1331 1332 // Scan up the scope chain looking for a decl that matches this 1333 // identifier that is in the appropriate namespace. This search 1334 // should not take long, as shadowing of names is uncommon, and 1335 // deep shadowing is extremely uncommon. 1336 bool LeftStartingScope = false; 1337 1338 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 1339 IEnd = IdResolver.end(); 1340 I != IEnd; ++I) 1341 if (NamedDecl *D = R.getAcceptableDecl(*I)) { 1342 if (NameKind == LookupRedeclarationWithLinkage) { 1343 // Determine whether this (or a previous) declaration is 1344 // out-of-scope. 1345 if (!LeftStartingScope && !S->isDeclScope(*I)) 1346 LeftStartingScope = true; 1347 1348 // If we found something outside of our starting scope that 1349 // does not have linkage, skip it. 1350 if (LeftStartingScope && !((*I)->hasLinkage())) { 1351 R.setShadowed(); 1352 continue; 1353 } 1354 } 1355 else if (NameKind == LookupObjCImplicitSelfParam && 1356 !isa<ImplicitParamDecl>(*I)) 1357 continue; 1358 1359 R.addDecl(D); 1360 1361 // Check whether there are any other declarations with the same name 1362 // and in the same scope. 1363 if (I != IEnd) { 1364 // Find the scope in which this declaration was declared (if it 1365 // actually exists in a Scope). 1366 while (S && !S->isDeclScope(D)) 1367 S = S->getParent(); 1368 1369 // If the scope containing the declaration is the translation unit, 1370 // then we'll need to perform our checks based on the matching 1371 // DeclContexts rather than matching scopes. 1372 if (S && isNamespaceOrTranslationUnitScope(S)) 1373 S = nullptr; 1374 1375 // Compute the DeclContext, if we need it. 1376 DeclContext *DC = nullptr; 1377 if (!S) 1378 DC = (*I)->getDeclContext()->getRedeclContext(); 1379 1380 IdentifierResolver::iterator LastI = I; 1381 for (++LastI; LastI != IEnd; ++LastI) { 1382 if (S) { 1383 // Match based on scope. 1384 if (!S->isDeclScope(*LastI)) 1385 break; 1386 } else { 1387 // Match based on DeclContext. 1388 DeclContext *LastDC 1389 = (*LastI)->getDeclContext()->getRedeclContext(); 1390 if (!LastDC->Equals(DC)) 1391 break; 1392 } 1393 1394 // If the declaration is in the right namespace and visible, add it. 1395 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI)) 1396 R.addDecl(LastD); 1397 } 1398 1399 R.resolveKind(); 1400 } 1401 1402 return true; 1403 } 1404 } else { 1405 // Perform C++ unqualified name lookup. 1406 if (CppLookupName(R, S)) 1407 return true; 1408 } 1409 1410 // If we didn't find a use of this identifier, and if the identifier 1411 // corresponds to a compiler builtin, create the decl object for the builtin 1412 // now, injecting it into translation unit scope, and return it. 1413 if (AllowBuiltinCreation && LookupBuiltin(*this, R)) 1414 return true; 1415 1416 // If we didn't find a use of this identifier, the ExternalSource 1417 // may be able to handle the situation. 1418 // Note: some lookup failures are expected! 1419 // See e.g. R.isForRedeclaration(). 1420 return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); 1421 } 1422 1423 /// @brief Perform qualified name lookup in the namespaces nominated by 1424 /// using directives by the given context. 1425 /// 1426 /// C++98 [namespace.qual]p2: 1427 /// Given X::m (where X is a user-declared namespace), or given \::m 1428 /// (where X is the global namespace), let S be the set of all 1429 /// declarations of m in X and in the transitive closure of all 1430 /// namespaces nominated by using-directives in X and its used 1431 /// namespaces, except that using-directives are ignored in any 1432 /// namespace, including X, directly containing one or more 1433 /// declarations of m. No namespace is searched more than once in 1434 /// the lookup of a name. If S is the empty set, the program is 1435 /// ill-formed. Otherwise, if S has exactly one member, or if the 1436 /// context of the reference is a using-declaration 1437 /// (namespace.udecl), S is the required set of declarations of 1438 /// m. Otherwise if the use of m is not one that allows a unique 1439 /// declaration to be chosen from S, the program is ill-formed. 1440 /// 1441 /// C++98 [namespace.qual]p5: 1442 /// During the lookup of a qualified namespace member name, if the 1443 /// lookup finds more than one declaration of the member, and if one 1444 /// declaration introduces a class name or enumeration name and the 1445 /// other declarations either introduce the same object, the same 1446 /// enumerator or a set of functions, the non-type name hides the 1447 /// class or enumeration name if and only if the declarations are 1448 /// from the same namespace; otherwise (the declarations are from 1449 /// different namespaces), the program is ill-formed. 1450 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, 1451 DeclContext *StartDC) { 1452 assert(StartDC->isFileContext() && "start context is not a file context"); 1453 1454 DeclContext::udir_range UsingDirectives = StartDC->using_directives(); 1455 if (UsingDirectives.begin() == UsingDirectives.end()) return false; 1456 1457 // We have at least added all these contexts to the queue. 1458 llvm::SmallPtrSet<DeclContext*, 8> Visited; 1459 Visited.insert(StartDC); 1460 1461 // We have not yet looked into these namespaces, much less added 1462 // their "using-children" to the queue. 1463 SmallVector<NamespaceDecl*, 8> Queue; 1464 1465 // We have already looked into the initial namespace; seed the queue 1466 // with its using-children. 1467 for (auto *I : UsingDirectives) { 1468 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace(); 1469 if (Visited.insert(ND)) 1470 Queue.push_back(ND); 1471 } 1472 1473 // The easiest way to implement the restriction in [namespace.qual]p5 1474 // is to check whether any of the individual results found a tag 1475 // and, if so, to declare an ambiguity if the final result is not 1476 // a tag. 1477 bool FoundTag = false; 1478 bool FoundNonTag = false; 1479 1480 LookupResult LocalR(LookupResult::Temporary, R); 1481 1482 bool Found = false; 1483 while (!Queue.empty()) { 1484 NamespaceDecl *ND = Queue.pop_back_val(); 1485 1486 // We go through some convolutions here to avoid copying results 1487 // between LookupResults. 1488 bool UseLocal = !R.empty(); 1489 LookupResult &DirectR = UseLocal ? LocalR : R; 1490 bool FoundDirect = LookupDirect(S, DirectR, ND); 1491 1492 if (FoundDirect) { 1493 // First do any local hiding. 1494 DirectR.resolveKind(); 1495 1496 // If the local result is a tag, remember that. 1497 if (DirectR.isSingleTagDecl()) 1498 FoundTag = true; 1499 else 1500 FoundNonTag = true; 1501 1502 // Append the local results to the total results if necessary. 1503 if (UseLocal) { 1504 R.addAllDecls(LocalR); 1505 LocalR.clear(); 1506 } 1507 } 1508 1509 // If we find names in this namespace, ignore its using directives. 1510 if (FoundDirect) { 1511 Found = true; 1512 continue; 1513 } 1514 1515 for (auto I : ND->using_directives()) { 1516 NamespaceDecl *Nom = I->getNominatedNamespace(); 1517 if (Visited.insert(Nom)) 1518 Queue.push_back(Nom); 1519 } 1520 } 1521 1522 if (Found) { 1523 if (FoundTag && FoundNonTag) 1524 R.setAmbiguousQualifiedTagHiding(); 1525 else 1526 R.resolveKind(); 1527 } 1528 1529 return Found; 1530 } 1531 1532 /// \brief Callback that looks for any member of a class with the given name. 1533 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, 1534 CXXBasePath &Path, 1535 void *Name) { 1536 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 1537 1538 DeclarationName N = DeclarationName::getFromOpaquePtr(Name); 1539 Path.Decls = BaseRecord->lookup(N); 1540 return !Path.Decls.empty(); 1541 } 1542 1543 /// \brief Determine whether the given set of member declarations contains only 1544 /// static members, nested types, and enumerators. 1545 template<typename InputIterator> 1546 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) { 1547 Decl *D = (*First)->getUnderlyingDecl(); 1548 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D)) 1549 return true; 1550 1551 if (isa<CXXMethodDecl>(D)) { 1552 // Determine whether all of the methods are static. 1553 bool AllMethodsAreStatic = true; 1554 for(; First != Last; ++First) { 1555 D = (*First)->getUnderlyingDecl(); 1556 1557 if (!isa<CXXMethodDecl>(D)) { 1558 assert(isa<TagDecl>(D) && "Non-function must be a tag decl"); 1559 break; 1560 } 1561 1562 if (!cast<CXXMethodDecl>(D)->isStatic()) { 1563 AllMethodsAreStatic = false; 1564 break; 1565 } 1566 } 1567 1568 if (AllMethodsAreStatic) 1569 return true; 1570 } 1571 1572 return false; 1573 } 1574 1575 /// \brief Perform qualified name lookup into a given context. 1576 /// 1577 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 1578 /// names when the context of those names is explicit specified, e.g., 1579 /// "std::vector" or "x->member", or as part of unqualified name lookup. 1580 /// 1581 /// Different lookup criteria can find different names. For example, a 1582 /// particular scope can have both a struct and a function of the same 1583 /// name, and each can be found by certain lookup criteria. For more 1584 /// information about lookup criteria, see the documentation for the 1585 /// class LookupCriteria. 1586 /// 1587 /// \param R captures both the lookup criteria and any lookup results found. 1588 /// 1589 /// \param LookupCtx The context in which qualified name lookup will 1590 /// search. If the lookup criteria permits, name lookup may also search 1591 /// in the parent contexts or (for C++ classes) base classes. 1592 /// 1593 /// \param InUnqualifiedLookup true if this is qualified name lookup that 1594 /// occurs as part of unqualified name lookup. 1595 /// 1596 /// \returns true if lookup succeeded, false if it failed. 1597 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1598 bool InUnqualifiedLookup) { 1599 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 1600 1601 if (!R.getLookupName()) 1602 return false; 1603 1604 // Make sure that the declaration context is complete. 1605 assert((!isa<TagDecl>(LookupCtx) || 1606 LookupCtx->isDependentContext() || 1607 cast<TagDecl>(LookupCtx)->isCompleteDefinition() || 1608 cast<TagDecl>(LookupCtx)->isBeingDefined()) && 1609 "Declaration context must already be complete!"); 1610 1611 // Perform qualified name lookup into the LookupCtx. 1612 if (LookupDirect(*this, R, LookupCtx)) { 1613 R.resolveKind(); 1614 if (isa<CXXRecordDecl>(LookupCtx)) 1615 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 1616 return true; 1617 } 1618 1619 // Don't descend into implied contexts for redeclarations. 1620 // C++98 [namespace.qual]p6: 1621 // In a declaration for a namespace member in which the 1622 // declarator-id is a qualified-id, given that the qualified-id 1623 // for the namespace member has the form 1624 // nested-name-specifier unqualified-id 1625 // the unqualified-id shall name a member of the namespace 1626 // designated by the nested-name-specifier. 1627 // See also [class.mfct]p5 and [class.static.data]p2. 1628 if (R.isForRedeclaration()) 1629 return false; 1630 1631 // If this is a namespace, look it up in the implied namespaces. 1632 if (LookupCtx->isFileContext()) 1633 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 1634 1635 // If this isn't a C++ class, we aren't allowed to look into base 1636 // classes, we're done. 1637 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 1638 if (!LookupRec || !LookupRec->getDefinition()) 1639 return false; 1640 1641 // If we're performing qualified name lookup into a dependent class, 1642 // then we are actually looking into a current instantiation. If we have any 1643 // dependent base classes, then we either have to delay lookup until 1644 // template instantiation time (at which point all bases will be available) 1645 // or we have to fail. 1646 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 1647 LookupRec->hasAnyDependentBases()) { 1648 R.setNotFoundInCurrentInstantiation(); 1649 return false; 1650 } 1651 1652 // Perform lookup into our base classes. 1653 CXXBasePaths Paths; 1654 Paths.setOrigin(LookupRec); 1655 1656 // Look for this member in our base classes 1657 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr; 1658 switch (R.getLookupKind()) { 1659 case LookupObjCImplicitSelfParam: 1660 case LookupOrdinaryName: 1661 case LookupMemberName: 1662 case LookupRedeclarationWithLinkage: 1663 case LookupLocalFriendName: 1664 BaseCallback = &CXXRecordDecl::FindOrdinaryMember; 1665 break; 1666 1667 case LookupTagName: 1668 BaseCallback = &CXXRecordDecl::FindTagMember; 1669 break; 1670 1671 case LookupAnyName: 1672 BaseCallback = &LookupAnyMember; 1673 break; 1674 1675 case LookupUsingDeclName: 1676 // This lookup is for redeclarations only. 1677 1678 case LookupOperatorName: 1679 case LookupNamespaceName: 1680 case LookupObjCProtocolName: 1681 case LookupLabel: 1682 // These lookups will never find a member in a C++ class (or base class). 1683 return false; 1684 1685 case LookupNestedNameSpecifierName: 1686 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; 1687 break; 1688 } 1689 1690 if (!LookupRec->lookupInBases(BaseCallback, 1691 R.getLookupName().getAsOpaquePtr(), Paths)) 1692 return false; 1693 1694 R.setNamingClass(LookupRec); 1695 1696 // C++ [class.member.lookup]p2: 1697 // [...] If the resulting set of declarations are not all from 1698 // sub-objects of the same type, or the set has a nonstatic member 1699 // and includes members from distinct sub-objects, there is an 1700 // ambiguity and the program is ill-formed. Otherwise that set is 1701 // the result of the lookup. 1702 QualType SubobjectType; 1703 int SubobjectNumber = 0; 1704 AccessSpecifier SubobjectAccess = AS_none; 1705 1706 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 1707 Path != PathEnd; ++Path) { 1708 const CXXBasePathElement &PathElement = Path->back(); 1709 1710 // Pick the best (i.e. most permissive i.e. numerically lowest) access 1711 // across all paths. 1712 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 1713 1714 // Determine whether we're looking at a distinct sub-object or not. 1715 if (SubobjectType.isNull()) { 1716 // This is the first subobject we've looked at. Record its type. 1717 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 1718 SubobjectNumber = PathElement.SubobjectNumber; 1719 continue; 1720 } 1721 1722 if (SubobjectType 1723 != Context.getCanonicalType(PathElement.Base->getType())) { 1724 // We found members of the given name in two subobjects of 1725 // different types. If the declaration sets aren't the same, this 1726 // lookup is ambiguous. 1727 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) { 1728 CXXBasePaths::paths_iterator FirstPath = Paths.begin(); 1729 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin(); 1730 DeclContext::lookup_iterator CurrentD = Path->Decls.begin(); 1731 1732 while (FirstD != FirstPath->Decls.end() && 1733 CurrentD != Path->Decls.end()) { 1734 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() != 1735 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl()) 1736 break; 1737 1738 ++FirstD; 1739 ++CurrentD; 1740 } 1741 1742 if (FirstD == FirstPath->Decls.end() && 1743 CurrentD == Path->Decls.end()) 1744 continue; 1745 } 1746 1747 R.setAmbiguousBaseSubobjectTypes(Paths); 1748 return true; 1749 } 1750 1751 if (SubobjectNumber != PathElement.SubobjectNumber) { 1752 // We have a different subobject of the same type. 1753 1754 // C++ [class.member.lookup]p5: 1755 // A static member, a nested type or an enumerator defined in 1756 // a base class T can unambiguously be found even if an object 1757 // has more than one base class subobject of type T. 1758 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) 1759 continue; 1760 1761 // We have found a nonstatic member name in multiple, distinct 1762 // subobjects. Name lookup is ambiguous. 1763 R.setAmbiguousBaseSubobjects(Paths); 1764 return true; 1765 } 1766 } 1767 1768 // Lookup in a base class succeeded; return these results. 1769 1770 DeclContext::lookup_result DR = Paths.front().Decls; 1771 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) { 1772 NamedDecl *D = *I; 1773 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 1774 D->getAccess()); 1775 R.addDecl(D, AS); 1776 } 1777 R.resolveKind(); 1778 return true; 1779 } 1780 1781 /// @brief Performs name lookup for a name that was parsed in the 1782 /// source code, and may contain a C++ scope specifier. 1783 /// 1784 /// This routine is a convenience routine meant to be called from 1785 /// contexts that receive a name and an optional C++ scope specifier 1786 /// (e.g., "N::M::x"). It will then perform either qualified or 1787 /// unqualified name lookup (with LookupQualifiedName or LookupName, 1788 /// respectively) on the given name and return those results. 1789 /// 1790 /// @param S The scope from which unqualified name lookup will 1791 /// begin. 1792 /// 1793 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 1794 /// 1795 /// @param EnteringContext Indicates whether we are going to enter the 1796 /// context of the scope-specifier SS (if present). 1797 /// 1798 /// @returns True if any decls were found (but possibly ambiguous) 1799 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1800 bool AllowBuiltinCreation, bool EnteringContext) { 1801 if (SS && SS->isInvalid()) { 1802 // When the scope specifier is invalid, don't even look for 1803 // anything. 1804 return false; 1805 } 1806 1807 if (SS && SS->isSet()) { 1808 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 1809 // We have resolved the scope specifier to a particular declaration 1810 // contex, and will perform name lookup in that context. 1811 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 1812 return false; 1813 1814 R.setContextRange(SS->getRange()); 1815 return LookupQualifiedName(R, DC); 1816 } 1817 1818 // We could not resolve the scope specified to a specific declaration 1819 // context, which means that SS refers to an unknown specialization. 1820 // Name lookup can't find anything in this case. 1821 R.setNotFoundInCurrentInstantiation(); 1822 R.setContextRange(SS->getRange()); 1823 return false; 1824 } 1825 1826 // Perform unqualified name lookup starting in the given scope. 1827 return LookupName(R, S, AllowBuiltinCreation); 1828 } 1829 1830 1831 /// \brief Produce a diagnostic describing the ambiguity that resulted 1832 /// from name lookup. 1833 /// 1834 /// \param Result The result of the ambiguous lookup to be diagnosed. 1835 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 1836 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1837 1838 DeclarationName Name = Result.getLookupName(); 1839 SourceLocation NameLoc = Result.getNameLoc(); 1840 SourceRange LookupRange = Result.getContextRange(); 1841 1842 switch (Result.getAmbiguityKind()) { 1843 case LookupResult::AmbiguousBaseSubobjects: { 1844 CXXBasePaths *Paths = Result.getBasePaths(); 1845 QualType SubobjectType = Paths->front().back().Base->getType(); 1846 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1847 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1848 << LookupRange; 1849 1850 DeclContext::lookup_iterator Found = Paths->front().Decls.begin(); 1851 while (isa<CXXMethodDecl>(*Found) && 1852 cast<CXXMethodDecl>(*Found)->isStatic()) 1853 ++Found; 1854 1855 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1856 break; 1857 } 1858 1859 case LookupResult::AmbiguousBaseSubobjectTypes: { 1860 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1861 << Name << LookupRange; 1862 1863 CXXBasePaths *Paths = Result.getBasePaths(); 1864 std::set<Decl *> DeclsPrinted; 1865 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 1866 PathEnd = Paths->end(); 1867 Path != PathEnd; ++Path) { 1868 Decl *D = Path->Decls.front(); 1869 if (DeclsPrinted.insert(D).second) 1870 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1871 } 1872 break; 1873 } 1874 1875 case LookupResult::AmbiguousTagHiding: { 1876 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 1877 1878 llvm::SmallPtrSet<NamedDecl*,8> TagDecls; 1879 1880 LookupResult::iterator DI, DE = Result.end(); 1881 for (DI = Result.begin(); DI != DE; ++DI) 1882 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) { 1883 TagDecls.insert(TD); 1884 Diag(TD->getLocation(), diag::note_hidden_tag); 1885 } 1886 1887 for (DI = Result.begin(); DI != DE; ++DI) 1888 if (!isa<TagDecl>(*DI)) 1889 Diag((*DI)->getLocation(), diag::note_hiding_object); 1890 1891 // For recovery purposes, go ahead and implement the hiding. 1892 LookupResult::Filter F = Result.makeFilter(); 1893 while (F.hasNext()) { 1894 if (TagDecls.count(F.next())) 1895 F.erase(); 1896 } 1897 F.done(); 1898 break; 1899 } 1900 1901 case LookupResult::AmbiguousReference: { 1902 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1903 1904 LookupResult::iterator DI = Result.begin(), DE = Result.end(); 1905 for (; DI != DE; ++DI) 1906 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1907 break; 1908 } 1909 } 1910 } 1911 1912 namespace { 1913 struct AssociatedLookup { 1914 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, 1915 Sema::AssociatedNamespaceSet &Namespaces, 1916 Sema::AssociatedClassSet &Classes) 1917 : S(S), Namespaces(Namespaces), Classes(Classes), 1918 InstantiationLoc(InstantiationLoc) { 1919 } 1920 1921 Sema &S; 1922 Sema::AssociatedNamespaceSet &Namespaces; 1923 Sema::AssociatedClassSet &Classes; 1924 SourceLocation InstantiationLoc; 1925 }; 1926 } 1927 1928 static void 1929 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 1930 1931 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 1932 DeclContext *Ctx) { 1933 // Add the associated namespace for this class. 1934 1935 // We don't use DeclContext::getEnclosingNamespaceContext() as this may 1936 // be a locally scoped record. 1937 1938 // We skip out of inline namespaces. The innermost non-inline namespace 1939 // contains all names of all its nested inline namespaces anyway, so we can 1940 // replace the entire inline namespace tree with its root. 1941 while (Ctx->isRecord() || Ctx->isTransparentContext() || 1942 Ctx->isInlineNamespace()) 1943 Ctx = Ctx->getParent(); 1944 1945 if (Ctx->isFileContext()) 1946 Namespaces.insert(Ctx->getPrimaryContext()); 1947 } 1948 1949 // \brief Add the associated classes and namespaces for argument-dependent 1950 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 1951 static void 1952 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1953 const TemplateArgument &Arg) { 1954 // C++ [basic.lookup.koenig]p2, last bullet: 1955 // -- [...] ; 1956 switch (Arg.getKind()) { 1957 case TemplateArgument::Null: 1958 break; 1959 1960 case TemplateArgument::Type: 1961 // [...] the namespaces and classes associated with the types of the 1962 // template arguments provided for template type parameters (excluding 1963 // template template parameters) 1964 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 1965 break; 1966 1967 case TemplateArgument::Template: 1968 case TemplateArgument::TemplateExpansion: { 1969 // [...] the namespaces in which any template template arguments are 1970 // defined; and the classes in which any member templates used as 1971 // template template arguments are defined. 1972 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 1973 if (ClassTemplateDecl *ClassTemplate 1974 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 1975 DeclContext *Ctx = ClassTemplate->getDeclContext(); 1976 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1977 Result.Classes.insert(EnclosingClass); 1978 // Add the associated namespace for this class. 1979 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1980 } 1981 break; 1982 } 1983 1984 case TemplateArgument::Declaration: 1985 case TemplateArgument::Integral: 1986 case TemplateArgument::Expression: 1987 case TemplateArgument::NullPtr: 1988 // [Note: non-type template arguments do not contribute to the set of 1989 // associated namespaces. ] 1990 break; 1991 1992 case TemplateArgument::Pack: 1993 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), 1994 PEnd = Arg.pack_end(); 1995 P != PEnd; ++P) 1996 addAssociatedClassesAndNamespaces(Result, *P); 1997 break; 1998 } 1999 } 2000 2001 // \brief Add the associated classes and namespaces for 2002 // argument-dependent lookup with an argument of class type 2003 // (C++ [basic.lookup.koenig]p2). 2004 static void 2005 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2006 CXXRecordDecl *Class) { 2007 2008 // Just silently ignore anything whose name is __va_list_tag. 2009 if (Class->getDeclName() == Result.S.VAListTagName) 2010 return; 2011 2012 // C++ [basic.lookup.koenig]p2: 2013 // [...] 2014 // -- If T is a class type (including unions), its associated 2015 // classes are: the class itself; the class of which it is a 2016 // member, if any; and its direct and indirect base 2017 // classes. Its associated namespaces are the namespaces in 2018 // which its associated classes are defined. 2019 2020 // Add the class of which it is a member, if any. 2021 DeclContext *Ctx = Class->getDeclContext(); 2022 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2023 Result.Classes.insert(EnclosingClass); 2024 // Add the associated namespace for this class. 2025 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2026 2027 // Add the class itself. If we've already seen this class, we don't 2028 // need to visit base classes. 2029 // 2030 // FIXME: That's not correct, we may have added this class only because it 2031 // was the enclosing class of another class, and in that case we won't have 2032 // added its base classes yet. 2033 if (!Result.Classes.insert(Class)) 2034 return; 2035 2036 // -- If T is a template-id, its associated namespaces and classes are 2037 // the namespace in which the template is defined; for member 2038 // templates, the member template's class; the namespaces and classes 2039 // associated with the types of the template arguments provided for 2040 // template type parameters (excluding template template parameters); the 2041 // namespaces in which any template template arguments are defined; and 2042 // the classes in which any member templates used as template template 2043 // arguments are defined. [Note: non-type template arguments do not 2044 // contribute to the set of associated namespaces. ] 2045 if (ClassTemplateSpecializationDecl *Spec 2046 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 2047 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 2048 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2049 Result.Classes.insert(EnclosingClass); 2050 // Add the associated namespace for this class. 2051 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2052 2053 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 2054 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 2055 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 2056 } 2057 2058 // Only recurse into base classes for complete types. 2059 if (!Class->hasDefinition()) 2060 return; 2061 2062 // Add direct and indirect base classes along with their associated 2063 // namespaces. 2064 SmallVector<CXXRecordDecl *, 32> Bases; 2065 Bases.push_back(Class); 2066 while (!Bases.empty()) { 2067 // Pop this class off the stack. 2068 Class = Bases.pop_back_val(); 2069 2070 // Visit the base classes. 2071 for (const auto &Base : Class->bases()) { 2072 const RecordType *BaseType = Base.getType()->getAs<RecordType>(); 2073 // In dependent contexts, we do ADL twice, and the first time around, 2074 // the base type might be a dependent TemplateSpecializationType, or a 2075 // TemplateTypeParmType. If that happens, simply ignore it. 2076 // FIXME: If we want to support export, we probably need to add the 2077 // namespace of the template in a TemplateSpecializationType, or even 2078 // the classes and namespaces of known non-dependent arguments. 2079 if (!BaseType) 2080 continue; 2081 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 2082 if (Result.Classes.insert(BaseDecl)) { 2083 // Find the associated namespace for this base class. 2084 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 2085 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 2086 2087 // Make sure we visit the bases of this base class. 2088 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 2089 Bases.push_back(BaseDecl); 2090 } 2091 } 2092 } 2093 } 2094 2095 // \brief Add the associated classes and namespaces for 2096 // argument-dependent lookup with an argument of type T 2097 // (C++ [basic.lookup.koenig]p2). 2098 static void 2099 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 2100 // C++ [basic.lookup.koenig]p2: 2101 // 2102 // For each argument type T in the function call, there is a set 2103 // of zero or more associated namespaces and a set of zero or more 2104 // associated classes to be considered. The sets of namespaces and 2105 // classes is determined entirely by the types of the function 2106 // arguments (and the namespace of any template template 2107 // argument). Typedef names and using-declarations used to specify 2108 // the types do not contribute to this set. The sets of namespaces 2109 // and classes are determined in the following way: 2110 2111 SmallVector<const Type *, 16> Queue; 2112 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 2113 2114 while (true) { 2115 switch (T->getTypeClass()) { 2116 2117 #define TYPE(Class, Base) 2118 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2119 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2120 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2121 #define ABSTRACT_TYPE(Class, Base) 2122 #include "clang/AST/TypeNodes.def" 2123 // T is canonical. We can also ignore dependent types because 2124 // we don't need to do ADL at the definition point, but if we 2125 // wanted to implement template export (or if we find some other 2126 // use for associated classes and namespaces...) this would be 2127 // wrong. 2128 break; 2129 2130 // -- If T is a pointer to U or an array of U, its associated 2131 // namespaces and classes are those associated with U. 2132 case Type::Pointer: 2133 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 2134 continue; 2135 case Type::ConstantArray: 2136 case Type::IncompleteArray: 2137 case Type::VariableArray: 2138 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 2139 continue; 2140 2141 // -- If T is a fundamental type, its associated sets of 2142 // namespaces and classes are both empty. 2143 case Type::Builtin: 2144 break; 2145 2146 // -- If T is a class type (including unions), its associated 2147 // classes are: the class itself; the class of which it is a 2148 // member, if any; and its direct and indirect base 2149 // classes. Its associated namespaces are the namespaces in 2150 // which its associated classes are defined. 2151 case Type::Record: { 2152 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0), 2153 /*no diagnostic*/ 0); 2154 CXXRecordDecl *Class 2155 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 2156 addAssociatedClassesAndNamespaces(Result, Class); 2157 break; 2158 } 2159 2160 // -- If T is an enumeration type, its associated namespace is 2161 // the namespace in which it is defined. If it is class 2162 // member, its associated class is the member's class; else 2163 // it has no associated class. 2164 case Type::Enum: { 2165 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 2166 2167 DeclContext *Ctx = Enum->getDeclContext(); 2168 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2169 Result.Classes.insert(EnclosingClass); 2170 2171 // Add the associated namespace for this class. 2172 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2173 2174 break; 2175 } 2176 2177 // -- If T is a function type, its associated namespaces and 2178 // classes are those associated with the function parameter 2179 // types and those associated with the return type. 2180 case Type::FunctionProto: { 2181 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2182 for (const auto &Arg : Proto->param_types()) 2183 Queue.push_back(Arg.getTypePtr()); 2184 // fallthrough 2185 } 2186 case Type::FunctionNoProto: { 2187 const FunctionType *FnType = cast<FunctionType>(T); 2188 T = FnType->getReturnType().getTypePtr(); 2189 continue; 2190 } 2191 2192 // -- If T is a pointer to a member function of a class X, its 2193 // associated namespaces and classes are those associated 2194 // with the function parameter types and return type, 2195 // together with those associated with X. 2196 // 2197 // -- If T is a pointer to a data member of class X, its 2198 // associated namespaces and classes are those associated 2199 // with the member type together with those associated with 2200 // X. 2201 case Type::MemberPointer: { 2202 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 2203 2204 // Queue up the class type into which this points. 2205 Queue.push_back(MemberPtr->getClass()); 2206 2207 // And directly continue with the pointee type. 2208 T = MemberPtr->getPointeeType().getTypePtr(); 2209 continue; 2210 } 2211 2212 // As an extension, treat this like a normal pointer. 2213 case Type::BlockPointer: 2214 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 2215 continue; 2216 2217 // References aren't covered by the standard, but that's such an 2218 // obvious defect that we cover them anyway. 2219 case Type::LValueReference: 2220 case Type::RValueReference: 2221 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 2222 continue; 2223 2224 // These are fundamental types. 2225 case Type::Vector: 2226 case Type::ExtVector: 2227 case Type::Complex: 2228 break; 2229 2230 // Non-deduced auto types only get here for error cases. 2231 case Type::Auto: 2232 break; 2233 2234 // If T is an Objective-C object or interface type, or a pointer to an 2235 // object or interface type, the associated namespace is the global 2236 // namespace. 2237 case Type::ObjCObject: 2238 case Type::ObjCInterface: 2239 case Type::ObjCObjectPointer: 2240 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); 2241 break; 2242 2243 // Atomic types are just wrappers; use the associations of the 2244 // contained type. 2245 case Type::Atomic: 2246 T = cast<AtomicType>(T)->getValueType().getTypePtr(); 2247 continue; 2248 } 2249 2250 if (Queue.empty()) 2251 break; 2252 T = Queue.pop_back_val(); 2253 } 2254 } 2255 2256 /// \brief Find the associated classes and namespaces for 2257 /// argument-dependent lookup for a call with the given set of 2258 /// arguments. 2259 /// 2260 /// This routine computes the sets of associated classes and associated 2261 /// namespaces searched by argument-dependent lookup 2262 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 2263 void Sema::FindAssociatedClassesAndNamespaces( 2264 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 2265 AssociatedNamespaceSet &AssociatedNamespaces, 2266 AssociatedClassSet &AssociatedClasses) { 2267 AssociatedNamespaces.clear(); 2268 AssociatedClasses.clear(); 2269 2270 AssociatedLookup Result(*this, InstantiationLoc, 2271 AssociatedNamespaces, AssociatedClasses); 2272 2273 // C++ [basic.lookup.koenig]p2: 2274 // For each argument type T in the function call, there is a set 2275 // of zero or more associated namespaces and a set of zero or more 2276 // associated classes to be considered. The sets of namespaces and 2277 // classes is determined entirely by the types of the function 2278 // arguments (and the namespace of any template template 2279 // argument). 2280 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 2281 Expr *Arg = Args[ArgIdx]; 2282 2283 if (Arg->getType() != Context.OverloadTy) { 2284 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 2285 continue; 2286 } 2287 2288 // [...] In addition, if the argument is the name or address of a 2289 // set of overloaded functions and/or function templates, its 2290 // associated classes and namespaces are the union of those 2291 // associated with each of the members of the set: the namespace 2292 // in which the function or function template is defined and the 2293 // classes and namespaces associated with its (non-dependent) 2294 // parameter types and return type. 2295 Arg = Arg->IgnoreParens(); 2296 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) 2297 if (unaryOp->getOpcode() == UO_AddrOf) 2298 Arg = unaryOp->getSubExpr(); 2299 2300 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); 2301 if (!ULE) continue; 2302 2303 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end(); 2304 I != E; ++I) { 2305 // Look through any using declarations to find the underlying function. 2306 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction(); 2307 2308 // Add the classes and namespaces associated with the parameter 2309 // types and return type of this function. 2310 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 2311 } 2312 } 2313 } 2314 2315 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 2316 SourceLocation Loc, 2317 LookupNameKind NameKind, 2318 RedeclarationKind Redecl) { 2319 LookupResult R(*this, Name, Loc, NameKind, Redecl); 2320 LookupName(R, S); 2321 return R.getAsSingle<NamedDecl>(); 2322 } 2323 2324 /// \brief Find the protocol with the given name, if any. 2325 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 2326 SourceLocation IdLoc, 2327 RedeclarationKind Redecl) { 2328 Decl *D = LookupSingleName(TUScope, II, IdLoc, 2329 LookupObjCProtocolName, Redecl); 2330 return cast_or_null<ObjCProtocolDecl>(D); 2331 } 2332 2333 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2334 QualType T1, QualType T2, 2335 UnresolvedSetImpl &Functions) { 2336 // C++ [over.match.oper]p3: 2337 // -- The set of non-member candidates is the result of the 2338 // unqualified lookup of operator@ in the context of the 2339 // expression according to the usual rules for name lookup in 2340 // unqualified function calls (3.4.2) except that all member 2341 // functions are ignored. 2342 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2343 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 2344 LookupName(Operators, S); 2345 2346 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 2347 Functions.append(Operators.begin(), Operators.end()); 2348 } 2349 2350 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD, 2351 CXXSpecialMember SM, 2352 bool ConstArg, 2353 bool VolatileArg, 2354 bool RValueThis, 2355 bool ConstThis, 2356 bool VolatileThis) { 2357 assert(CanDeclareSpecialMemberFunction(RD) && 2358 "doing special member lookup into record that isn't fully complete"); 2359 RD = RD->getDefinition(); 2360 if (RValueThis || ConstThis || VolatileThis) 2361 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && 2362 "constructors and destructors always have unqualified lvalue this"); 2363 if (ConstArg || VolatileArg) 2364 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && 2365 "parameter-less special members can't have qualified arguments"); 2366 2367 llvm::FoldingSetNodeID ID; 2368 ID.AddPointer(RD); 2369 ID.AddInteger(SM); 2370 ID.AddInteger(ConstArg); 2371 ID.AddInteger(VolatileArg); 2372 ID.AddInteger(RValueThis); 2373 ID.AddInteger(ConstThis); 2374 ID.AddInteger(VolatileThis); 2375 2376 void *InsertPoint; 2377 SpecialMemberOverloadResult *Result = 2378 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); 2379 2380 // This was already cached 2381 if (Result) 2382 return Result; 2383 2384 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>(); 2385 Result = new (Result) SpecialMemberOverloadResult(ID); 2386 SpecialMemberCache.InsertNode(Result, InsertPoint); 2387 2388 if (SM == CXXDestructor) { 2389 if (RD->needsImplicitDestructor()) 2390 DeclareImplicitDestructor(RD); 2391 CXXDestructorDecl *DD = RD->getDestructor(); 2392 assert(DD && "record without a destructor"); 2393 Result->setMethod(DD); 2394 Result->setKind(DD->isDeleted() ? 2395 SpecialMemberOverloadResult::NoMemberOrDeleted : 2396 SpecialMemberOverloadResult::Success); 2397 return Result; 2398 } 2399 2400 // Prepare for overload resolution. Here we construct a synthetic argument 2401 // if necessary and make sure that implicit functions are declared. 2402 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); 2403 DeclarationName Name; 2404 Expr *Arg = nullptr; 2405 unsigned NumArgs; 2406 2407 QualType ArgType = CanTy; 2408 ExprValueKind VK = VK_LValue; 2409 2410 if (SM == CXXDefaultConstructor) { 2411 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 2412 NumArgs = 0; 2413 if (RD->needsImplicitDefaultConstructor()) 2414 DeclareImplicitDefaultConstructor(RD); 2415 } else { 2416 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { 2417 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 2418 if (RD->needsImplicitCopyConstructor()) 2419 DeclareImplicitCopyConstructor(RD); 2420 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) 2421 DeclareImplicitMoveConstructor(RD); 2422 } else { 2423 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2424 if (RD->needsImplicitCopyAssignment()) 2425 DeclareImplicitCopyAssignment(RD); 2426 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) 2427 DeclareImplicitMoveAssignment(RD); 2428 } 2429 2430 if (ConstArg) 2431 ArgType.addConst(); 2432 if (VolatileArg) 2433 ArgType.addVolatile(); 2434 2435 // This isn't /really/ specified by the standard, but it's implied 2436 // we should be working from an RValue in the case of move to ensure 2437 // that we prefer to bind to rvalue references, and an LValue in the 2438 // case of copy to ensure we don't bind to rvalue references. 2439 // Possibly an XValue is actually correct in the case of move, but 2440 // there is no semantic difference for class types in this restricted 2441 // case. 2442 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) 2443 VK = VK_LValue; 2444 else 2445 VK = VK_RValue; 2446 } 2447 2448 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK); 2449 2450 if (SM != CXXDefaultConstructor) { 2451 NumArgs = 1; 2452 Arg = &FakeArg; 2453 } 2454 2455 // Create the object argument 2456 QualType ThisTy = CanTy; 2457 if (ConstThis) 2458 ThisTy.addConst(); 2459 if (VolatileThis) 2460 ThisTy.addVolatile(); 2461 Expr::Classification Classification = 2462 OpaqueValueExpr(SourceLocation(), ThisTy, 2463 RValueThis ? VK_RValue : VK_LValue).Classify(Context); 2464 2465 // Now we perform lookup on the name we computed earlier and do overload 2466 // resolution. Lookup is only performed directly into the class since there 2467 // will always be a (possibly implicit) declaration to shadow any others. 2468 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal); 2469 DeclContext::lookup_result R = RD->lookup(Name); 2470 assert(!R.empty() && 2471 "lookup for a constructor or assignment operator was empty"); 2472 2473 // Copy the candidates as our processing of them may load new declarations 2474 // from an external source and invalidate lookup_result. 2475 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); 2476 2477 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(), 2478 E = Candidates.end(); 2479 I != E; ++I) { 2480 NamedDecl *Cand = *I; 2481 2482 if (Cand->isInvalidDecl()) 2483 continue; 2484 2485 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) { 2486 // FIXME: [namespace.udecl]p15 says that we should only consider a 2487 // using declaration here if it does not match a declaration in the 2488 // derived class. We do not implement this correctly in other cases 2489 // either. 2490 Cand = U->getTargetDecl(); 2491 2492 if (Cand->isInvalidDecl()) 2493 continue; 2494 } 2495 2496 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) { 2497 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 2498 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy, 2499 Classification, llvm::makeArrayRef(&Arg, NumArgs), 2500 OCS, true); 2501 else 2502 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), 2503 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 2504 } else if (FunctionTemplateDecl *Tmpl = 2505 dyn_cast<FunctionTemplateDecl>(Cand)) { 2506 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 2507 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 2508 RD, nullptr, ThisTy, Classification, 2509 llvm::makeArrayRef(&Arg, NumArgs), 2510 OCS, true); 2511 else 2512 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 2513 nullptr, llvm::makeArrayRef(&Arg, NumArgs), 2514 OCS, true); 2515 } else { 2516 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl"); 2517 } 2518 } 2519 2520 OverloadCandidateSet::iterator Best; 2521 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) { 2522 case OR_Success: 2523 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 2524 Result->setKind(SpecialMemberOverloadResult::Success); 2525 break; 2526 2527 case OR_Deleted: 2528 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 2529 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 2530 break; 2531 2532 case OR_Ambiguous: 2533 Result->setMethod(nullptr); 2534 Result->setKind(SpecialMemberOverloadResult::Ambiguous); 2535 break; 2536 2537 case OR_No_Viable_Function: 2538 Result->setMethod(nullptr); 2539 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 2540 break; 2541 } 2542 2543 return Result; 2544 } 2545 2546 /// \brief Look up the default constructor for the given class. 2547 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { 2548 SpecialMemberOverloadResult *Result = 2549 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, 2550 false, false); 2551 2552 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2553 } 2554 2555 /// \brief Look up the copying constructor for the given class. 2556 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, 2557 unsigned Quals) { 2558 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2559 "non-const, non-volatile qualifiers for copy ctor arg"); 2560 SpecialMemberOverloadResult *Result = 2561 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, 2562 Quals & Qualifiers::Volatile, false, false, false); 2563 2564 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2565 } 2566 2567 /// \brief Look up the moving constructor for the given class. 2568 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, 2569 unsigned Quals) { 2570 SpecialMemberOverloadResult *Result = 2571 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, 2572 Quals & Qualifiers::Volatile, false, false, false); 2573 2574 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2575 } 2576 2577 /// \brief Look up the constructors for the given class. 2578 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 2579 // If the implicit constructors have not yet been declared, do so now. 2580 if (CanDeclareSpecialMemberFunction(Class)) { 2581 if (Class->needsImplicitDefaultConstructor()) 2582 DeclareImplicitDefaultConstructor(Class); 2583 if (Class->needsImplicitCopyConstructor()) 2584 DeclareImplicitCopyConstructor(Class); 2585 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) 2586 DeclareImplicitMoveConstructor(Class); 2587 } 2588 2589 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 2590 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 2591 return Class->lookup(Name); 2592 } 2593 2594 /// \brief Look up the copying assignment operator for the given class. 2595 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, 2596 unsigned Quals, bool RValueThis, 2597 unsigned ThisQuals) { 2598 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2599 "non-const, non-volatile qualifiers for copy assignment arg"); 2600 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2601 "non-const, non-volatile qualifiers for copy assignment this"); 2602 SpecialMemberOverloadResult *Result = 2603 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, 2604 Quals & Qualifiers::Volatile, RValueThis, 2605 ThisQuals & Qualifiers::Const, 2606 ThisQuals & Qualifiers::Volatile); 2607 2608 return Result->getMethod(); 2609 } 2610 2611 /// \brief Look up the moving assignment operator for the given class. 2612 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, 2613 unsigned Quals, 2614 bool RValueThis, 2615 unsigned ThisQuals) { 2616 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2617 "non-const, non-volatile qualifiers for copy assignment this"); 2618 SpecialMemberOverloadResult *Result = 2619 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, 2620 Quals & Qualifiers::Volatile, RValueThis, 2621 ThisQuals & Qualifiers::Const, 2622 ThisQuals & Qualifiers::Volatile); 2623 2624 return Result->getMethod(); 2625 } 2626 2627 /// \brief Look for the destructor of the given class. 2628 /// 2629 /// During semantic analysis, this routine should be used in lieu of 2630 /// CXXRecordDecl::getDestructor(). 2631 /// 2632 /// \returns The destructor for this class. 2633 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 2634 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor, 2635 false, false, false, 2636 false, false)->getMethod()); 2637 } 2638 2639 /// LookupLiteralOperator - Determine which literal operator should be used for 2640 /// a user-defined literal, per C++11 [lex.ext]. 2641 /// 2642 /// Normal overload resolution is not used to select which literal operator to 2643 /// call for a user-defined literal. Look up the provided literal operator name, 2644 /// and filter the results to the appropriate set for the given argument types. 2645 Sema::LiteralOperatorLookupResult 2646 Sema::LookupLiteralOperator(Scope *S, LookupResult &R, 2647 ArrayRef<QualType> ArgTys, 2648 bool AllowRaw, bool AllowTemplate, 2649 bool AllowStringTemplate) { 2650 LookupName(R, S); 2651 assert(R.getResultKind() != LookupResult::Ambiguous && 2652 "literal operator lookup can't be ambiguous"); 2653 2654 // Filter the lookup results appropriately. 2655 LookupResult::Filter F = R.makeFilter(); 2656 2657 bool FoundRaw = false; 2658 bool FoundTemplate = false; 2659 bool FoundStringTemplate = false; 2660 bool FoundExactMatch = false; 2661 2662 while (F.hasNext()) { 2663 Decl *D = F.next(); 2664 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 2665 D = USD->getTargetDecl(); 2666 2667 // If the declaration we found is invalid, skip it. 2668 if (D->isInvalidDecl()) { 2669 F.erase(); 2670 continue; 2671 } 2672 2673 bool IsRaw = false; 2674 bool IsTemplate = false; 2675 bool IsStringTemplate = false; 2676 bool IsExactMatch = false; 2677 2678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2679 if (FD->getNumParams() == 1 && 2680 FD->getParamDecl(0)->getType()->getAs<PointerType>()) 2681 IsRaw = true; 2682 else if (FD->getNumParams() == ArgTys.size()) { 2683 IsExactMatch = true; 2684 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { 2685 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); 2686 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { 2687 IsExactMatch = false; 2688 break; 2689 } 2690 } 2691 } 2692 } 2693 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) { 2694 TemplateParameterList *Params = FD->getTemplateParameters(); 2695 if (Params->size() == 1) 2696 IsTemplate = true; 2697 else 2698 IsStringTemplate = true; 2699 } 2700 2701 if (IsExactMatch) { 2702 FoundExactMatch = true; 2703 AllowRaw = false; 2704 AllowTemplate = false; 2705 AllowStringTemplate = false; 2706 if (FoundRaw || FoundTemplate || FoundStringTemplate) { 2707 // Go through again and remove the raw and template decls we've 2708 // already found. 2709 F.restart(); 2710 FoundRaw = FoundTemplate = FoundStringTemplate = false; 2711 } 2712 } else if (AllowRaw && IsRaw) { 2713 FoundRaw = true; 2714 } else if (AllowTemplate && IsTemplate) { 2715 FoundTemplate = true; 2716 } else if (AllowStringTemplate && IsStringTemplate) { 2717 FoundStringTemplate = true; 2718 } else { 2719 F.erase(); 2720 } 2721 } 2722 2723 F.done(); 2724 2725 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching 2726 // parameter type, that is used in preference to a raw literal operator 2727 // or literal operator template. 2728 if (FoundExactMatch) 2729 return LOLR_Cooked; 2730 2731 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal 2732 // operator template, but not both. 2733 if (FoundRaw && FoundTemplate) { 2734 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 2735 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 2736 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction()); 2737 return LOLR_Error; 2738 } 2739 2740 if (FoundRaw) 2741 return LOLR_Raw; 2742 2743 if (FoundTemplate) 2744 return LOLR_Template; 2745 2746 if (FoundStringTemplate) 2747 return LOLR_StringTemplate; 2748 2749 // Didn't find anything we could use. 2750 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) 2751 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] 2752 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw 2753 << (AllowTemplate || AllowStringTemplate); 2754 return LOLR_Error; 2755 } 2756 2757 void ADLResult::insert(NamedDecl *New) { 2758 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 2759 2760 // If we haven't yet seen a decl for this key, or the last decl 2761 // was exactly this one, we're done. 2762 if (Old == nullptr || Old == New) { 2763 Old = New; 2764 return; 2765 } 2766 2767 // Otherwise, decide which is a more recent redeclaration. 2768 FunctionDecl *OldFD = Old->getAsFunction(); 2769 FunctionDecl *NewFD = New->getAsFunction(); 2770 2771 FunctionDecl *Cursor = NewFD; 2772 while (true) { 2773 Cursor = Cursor->getPreviousDecl(); 2774 2775 // If we got to the end without finding OldFD, OldFD is the newer 2776 // declaration; leave things as they are. 2777 if (!Cursor) return; 2778 2779 // If we do find OldFD, then NewFD is newer. 2780 if (Cursor == OldFD) break; 2781 2782 // Otherwise, keep looking. 2783 } 2784 2785 Old = New; 2786 } 2787 2788 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 2789 ArrayRef<Expr *> Args, ADLResult &Result) { 2790 // Find all of the associated namespaces and classes based on the 2791 // arguments we have. 2792 AssociatedNamespaceSet AssociatedNamespaces; 2793 AssociatedClassSet AssociatedClasses; 2794 FindAssociatedClassesAndNamespaces(Loc, Args, 2795 AssociatedNamespaces, 2796 AssociatedClasses); 2797 2798 // C++ [basic.lookup.argdep]p3: 2799 // Let X be the lookup set produced by unqualified lookup (3.4.1) 2800 // and let Y be the lookup set produced by argument dependent 2801 // lookup (defined as follows). If X contains [...] then Y is 2802 // empty. Otherwise Y is the set of declarations found in the 2803 // namespaces associated with the argument types as described 2804 // below. The set of declarations found by the lookup of the name 2805 // is the union of X and Y. 2806 // 2807 // Here, we compute Y and add its members to the overloaded 2808 // candidate set. 2809 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), 2810 NSEnd = AssociatedNamespaces.end(); 2811 NS != NSEnd; ++NS) { 2812 // When considering an associated namespace, the lookup is the 2813 // same as the lookup performed when the associated namespace is 2814 // used as a qualifier (3.4.3.2) except that: 2815 // 2816 // -- Any using-directives in the associated namespace are 2817 // ignored. 2818 // 2819 // -- Any namespace-scope friend functions declared in 2820 // associated classes are visible within their respective 2821 // namespaces even if they are not visible during an ordinary 2822 // lookup (11.4). 2823 DeclContext::lookup_result R = (*NS)->lookup(Name); 2824 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 2825 ++I) { 2826 NamedDecl *D = *I; 2827 // If the only declaration here is an ordinary friend, consider 2828 // it only if it was declared in an associated classes. 2829 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) { 2830 // If it's neither ordinarily visible nor a friend, we can't find it. 2831 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0) 2832 continue; 2833 2834 bool DeclaredInAssociatedClass = false; 2835 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) { 2836 DeclContext *LexDC = DI->getLexicalDeclContext(); 2837 if (isa<CXXRecordDecl>(LexDC) && 2838 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) { 2839 DeclaredInAssociatedClass = true; 2840 break; 2841 } 2842 } 2843 if (!DeclaredInAssociatedClass) 2844 continue; 2845 } 2846 2847 if (isa<UsingShadowDecl>(D)) 2848 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2849 2850 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) 2851 continue; 2852 2853 Result.insert(D); 2854 } 2855 } 2856 } 2857 2858 //---------------------------------------------------------------------------- 2859 // Search for all visible declarations. 2860 //---------------------------------------------------------------------------- 2861 VisibleDeclConsumer::~VisibleDeclConsumer() { } 2862 2863 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } 2864 2865 namespace { 2866 2867 class ShadowContextRAII; 2868 2869 class VisibleDeclsRecord { 2870 public: 2871 /// \brief An entry in the shadow map, which is optimized to store a 2872 /// single declaration (the common case) but can also store a list 2873 /// of declarations. 2874 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; 2875 2876 private: 2877 /// \brief A mapping from declaration names to the declarations that have 2878 /// this name within a particular scope. 2879 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 2880 2881 /// \brief A list of shadow maps, which is used to model name hiding. 2882 std::list<ShadowMap> ShadowMaps; 2883 2884 /// \brief The declaration contexts we have already visited. 2885 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 2886 2887 friend class ShadowContextRAII; 2888 2889 public: 2890 /// \brief Determine whether we have already visited this context 2891 /// (and, if not, note that we are going to visit that context now). 2892 bool visitedContext(DeclContext *Ctx) { 2893 return !VisitedContexts.insert(Ctx); 2894 } 2895 2896 bool alreadyVisitedContext(DeclContext *Ctx) { 2897 return VisitedContexts.count(Ctx); 2898 } 2899 2900 /// \brief Determine whether the given declaration is hidden in the 2901 /// current scope. 2902 /// 2903 /// \returns the declaration that hides the given declaration, or 2904 /// NULL if no such declaration exists. 2905 NamedDecl *checkHidden(NamedDecl *ND); 2906 2907 /// \brief Add a declaration to the current shadow map. 2908 void add(NamedDecl *ND) { 2909 ShadowMaps.back()[ND->getDeclName()].push_back(ND); 2910 } 2911 }; 2912 2913 /// \brief RAII object that records when we've entered a shadow context. 2914 class ShadowContextRAII { 2915 VisibleDeclsRecord &Visible; 2916 2917 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 2918 2919 public: 2920 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 2921 Visible.ShadowMaps.push_back(ShadowMap()); 2922 } 2923 2924 ~ShadowContextRAII() { 2925 Visible.ShadowMaps.pop_back(); 2926 } 2927 }; 2928 2929 } // end anonymous namespace 2930 2931 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 2932 // Look through using declarations. 2933 ND = ND->getUnderlyingDecl(); 2934 2935 unsigned IDNS = ND->getIdentifierNamespace(); 2936 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 2937 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 2938 SM != SMEnd; ++SM) { 2939 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 2940 if (Pos == SM->end()) 2941 continue; 2942 2943 for (ShadowMapEntry::iterator I = Pos->second.begin(), 2944 IEnd = Pos->second.end(); 2945 I != IEnd; ++I) { 2946 // A tag declaration does not hide a non-tag declaration. 2947 if ((*I)->hasTagIdentifierNamespace() && 2948 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 2949 Decl::IDNS_ObjCProtocol))) 2950 continue; 2951 2952 // Protocols are in distinct namespaces from everything else. 2953 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 2954 || (IDNS & Decl::IDNS_ObjCProtocol)) && 2955 (*I)->getIdentifierNamespace() != IDNS) 2956 continue; 2957 2958 // Functions and function templates in the same scope overload 2959 // rather than hide. FIXME: Look for hiding based on function 2960 // signatures! 2961 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 2962 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 2963 SM == ShadowMaps.rbegin()) 2964 continue; 2965 2966 // We've found a declaration that hides this one. 2967 return *I; 2968 } 2969 } 2970 2971 return nullptr; 2972 } 2973 2974 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, 2975 bool QualifiedNameLookup, 2976 bool InBaseClass, 2977 VisibleDeclConsumer &Consumer, 2978 VisibleDeclsRecord &Visited) { 2979 if (!Ctx) 2980 return; 2981 2982 // Make sure we don't visit the same context twice. 2983 if (Visited.visitedContext(Ctx->getPrimaryContext())) 2984 return; 2985 2986 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 2987 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 2988 2989 // Enumerate all of the results in this context. 2990 for (const auto &R : Ctx->lookups()) { 2991 for (auto *I : R) { 2992 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) { 2993 if ((ND = Result.getAcceptableDecl(ND))) { 2994 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 2995 Visited.add(ND); 2996 } 2997 } 2998 } 2999 } 3000 3001 // Traverse using directives for qualified name lookup. 3002 if (QualifiedNameLookup) { 3003 ShadowContextRAII Shadow(Visited); 3004 for (auto I : Ctx->using_directives()) { 3005 LookupVisibleDecls(I->getNominatedNamespace(), Result, 3006 QualifiedNameLookup, InBaseClass, Consumer, Visited); 3007 } 3008 } 3009 3010 // Traverse the contexts of inherited C++ classes. 3011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 3012 if (!Record->hasDefinition()) 3013 return; 3014 3015 for (const auto &B : Record->bases()) { 3016 QualType BaseType = B.getType(); 3017 3018 // Don't look into dependent bases, because name lookup can't look 3019 // there anyway. 3020 if (BaseType->isDependentType()) 3021 continue; 3022 3023 const RecordType *Record = BaseType->getAs<RecordType>(); 3024 if (!Record) 3025 continue; 3026 3027 // FIXME: It would be nice to be able to determine whether referencing 3028 // a particular member would be ambiguous. For example, given 3029 // 3030 // struct A { int member; }; 3031 // struct B { int member; }; 3032 // struct C : A, B { }; 3033 // 3034 // void f(C *c) { c->### } 3035 // 3036 // accessing 'member' would result in an ambiguity. However, we 3037 // could be smart enough to qualify the member with the base 3038 // class, e.g., 3039 // 3040 // c->B::member 3041 // 3042 // or 3043 // 3044 // c->A::member 3045 3046 // Find results in this base class (and its bases). 3047 ShadowContextRAII Shadow(Visited); 3048 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, 3049 true, Consumer, Visited); 3050 } 3051 } 3052 3053 // Traverse the contexts of Objective-C classes. 3054 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 3055 // Traverse categories. 3056 for (auto *Cat : IFace->visible_categories()) { 3057 ShadowContextRAII Shadow(Visited); 3058 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, 3059 Consumer, Visited); 3060 } 3061 3062 // Traverse protocols. 3063 for (auto *I : IFace->all_referenced_protocols()) { 3064 ShadowContextRAII Shadow(Visited); 3065 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 3066 Visited); 3067 } 3068 3069 // Traverse the superclass. 3070 if (IFace->getSuperClass()) { 3071 ShadowContextRAII Shadow(Visited); 3072 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, 3073 true, Consumer, Visited); 3074 } 3075 3076 // If there is an implementation, traverse it. We do this to find 3077 // synthesized ivars. 3078 if (IFace->getImplementation()) { 3079 ShadowContextRAII Shadow(Visited); 3080 LookupVisibleDecls(IFace->getImplementation(), Result, 3081 QualifiedNameLookup, InBaseClass, Consumer, Visited); 3082 } 3083 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 3084 for (auto *I : Protocol->protocols()) { 3085 ShadowContextRAII Shadow(Visited); 3086 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 3087 Visited); 3088 } 3089 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 3090 for (auto *I : Category->protocols()) { 3091 ShadowContextRAII Shadow(Visited); 3092 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 3093 Visited); 3094 } 3095 3096 // If there is an implementation, traverse it. 3097 if (Category->getImplementation()) { 3098 ShadowContextRAII Shadow(Visited); 3099 LookupVisibleDecls(Category->getImplementation(), Result, 3100 QualifiedNameLookup, true, Consumer, Visited); 3101 } 3102 } 3103 } 3104 3105 static void LookupVisibleDecls(Scope *S, LookupResult &Result, 3106 UnqualUsingDirectiveSet &UDirs, 3107 VisibleDeclConsumer &Consumer, 3108 VisibleDeclsRecord &Visited) { 3109 if (!S) 3110 return; 3111 3112 if (!S->getEntity() || 3113 (!S->getParent() && 3114 !Visited.alreadyVisitedContext(S->getEntity())) || 3115 (S->getEntity())->isFunctionOrMethod()) { 3116 FindLocalExternScope FindLocals(Result); 3117 // Walk through the declarations in this Scope. 3118 for (auto *D : S->decls()) { 3119 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3120 if ((ND = Result.getAcceptableDecl(ND))) { 3121 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false); 3122 Visited.add(ND); 3123 } 3124 } 3125 } 3126 3127 // FIXME: C++ [temp.local]p8 3128 DeclContext *Entity = nullptr; 3129 if (S->getEntity()) { 3130 // Look into this scope's declaration context, along with any of its 3131 // parent lookup contexts (e.g., enclosing classes), up to the point 3132 // where we hit the context stored in the next outer scope. 3133 Entity = S->getEntity(); 3134 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME 3135 3136 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 3137 Ctx = Ctx->getLookupParent()) { 3138 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 3139 if (Method->isInstanceMethod()) { 3140 // For instance methods, look for ivars in the method's interface. 3141 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 3142 Result.getNameLoc(), Sema::LookupMemberName); 3143 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { 3144 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 3145 /*InBaseClass=*/false, Consumer, Visited); 3146 } 3147 } 3148 3149 // We've already performed all of the name lookup that we need 3150 // to for Objective-C methods; the next context will be the 3151 // outer scope. 3152 break; 3153 } 3154 3155 if (Ctx->isFunctionOrMethod()) 3156 continue; 3157 3158 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 3159 /*InBaseClass=*/false, Consumer, Visited); 3160 } 3161 } else if (!S->getParent()) { 3162 // Look into the translation unit scope. We walk through the translation 3163 // unit's declaration context, because the Scope itself won't have all of 3164 // the declarations if we loaded a precompiled header. 3165 // FIXME: We would like the translation unit's Scope object to point to the 3166 // translation unit, so we don't need this special "if" branch. However, 3167 // doing so would force the normal C++ name-lookup code to look into the 3168 // translation unit decl when the IdentifierInfo chains would suffice. 3169 // Once we fix that problem (which is part of a more general "don't look 3170 // in DeclContexts unless we have to" optimization), we can eliminate this. 3171 Entity = Result.getSema().Context.getTranslationUnitDecl(); 3172 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 3173 /*InBaseClass=*/false, Consumer, Visited); 3174 } 3175 3176 if (Entity) { 3177 // Lookup visible declarations in any namespaces found by using 3178 // directives. 3179 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 3180 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity); 3181 for (; UI != UEnd; ++UI) 3182 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()), 3183 Result, /*QualifiedNameLookup=*/false, 3184 /*InBaseClass=*/false, Consumer, Visited); 3185 } 3186 3187 // Lookup names in the parent scope. 3188 ShadowContextRAII Shadow(Visited); 3189 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited); 3190 } 3191 3192 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 3193 VisibleDeclConsumer &Consumer, 3194 bool IncludeGlobalScope) { 3195 // Determine the set of using directives available during 3196 // unqualified name lookup. 3197 Scope *Initial = S; 3198 UnqualUsingDirectiveSet UDirs; 3199 if (getLangOpts().CPlusPlus) { 3200 // Find the first namespace or translation-unit scope. 3201 while (S && !isNamespaceOrTranslationUnitScope(S)) 3202 S = S->getParent(); 3203 3204 UDirs.visitScopeChain(Initial, S); 3205 } 3206 UDirs.done(); 3207 3208 // Look for visible declarations. 3209 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 3210 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3211 VisibleDeclsRecord Visited; 3212 if (!IncludeGlobalScope) 3213 Visited.visitedContext(Context.getTranslationUnitDecl()); 3214 ShadowContextRAII Shadow(Visited); 3215 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited); 3216 } 3217 3218 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 3219 VisibleDeclConsumer &Consumer, 3220 bool IncludeGlobalScope) { 3221 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 3222 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3223 VisibleDeclsRecord Visited; 3224 if (!IncludeGlobalScope) 3225 Visited.visitedContext(Context.getTranslationUnitDecl()); 3226 ShadowContextRAII Shadow(Visited); 3227 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 3228 /*InBaseClass=*/false, Consumer, Visited); 3229 } 3230 3231 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 3232 /// If GnuLabelLoc is a valid source location, then this is a definition 3233 /// of an __label__ label name, otherwise it is a normal label definition 3234 /// or use. 3235 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, 3236 SourceLocation GnuLabelLoc) { 3237 // Do a lookup to see if we have a label with this name already. 3238 NamedDecl *Res = nullptr; 3239 3240 if (GnuLabelLoc.isValid()) { 3241 // Local label definitions always shadow existing labels. 3242 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); 3243 Scope *S = CurScope; 3244 PushOnScopeChains(Res, S, true); 3245 return cast<LabelDecl>(Res); 3246 } 3247 3248 // Not a GNU local label. 3249 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); 3250 // If we found a label, check to see if it is in the same context as us. 3251 // When in a Block, we don't want to reuse a label in an enclosing function. 3252 if (Res && Res->getDeclContext() != CurContext) 3253 Res = nullptr; 3254 if (!Res) { 3255 // If not forward referenced or defined already, create the backing decl. 3256 Res = LabelDecl::Create(Context, CurContext, Loc, II); 3257 Scope *S = CurScope->getFnParent(); 3258 assert(S && "Not in a function?"); 3259 PushOnScopeChains(Res, S, true); 3260 } 3261 return cast<LabelDecl>(Res); 3262 } 3263 3264 //===----------------------------------------------------------------------===// 3265 // Typo correction 3266 //===----------------------------------------------------------------------===// 3267 3268 static bool isCandidateViable(CorrectionCandidateCallback &CCC, 3269 TypoCorrection &Candidate) { 3270 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); 3271 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; 3272 } 3273 3274 static void LookupPotentialTypoResult(Sema &SemaRef, 3275 LookupResult &Res, 3276 IdentifierInfo *Name, 3277 Scope *S, CXXScopeSpec *SS, 3278 DeclContext *MemberContext, 3279 bool EnteringContext, 3280 bool isObjCIvarLookup, 3281 bool FindHidden); 3282 3283 // Fill the supplied vector with the IdentifierInfo pointers for each piece of 3284 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", 3285 // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). 3286 static void getNestedNameSpecifierIdentifiers( 3287 NestedNameSpecifier *NNS, 3288 SmallVectorImpl<const IdentifierInfo*> &Identifiers) { 3289 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) 3290 getNestedNameSpecifierIdentifiers(Prefix, Identifiers); 3291 else 3292 Identifiers.clear(); 3293 3294 const IdentifierInfo *II = nullptr; 3295 3296 switch (NNS->getKind()) { 3297 case NestedNameSpecifier::Identifier: 3298 II = NNS->getAsIdentifier(); 3299 break; 3300 3301 case NestedNameSpecifier::Namespace: 3302 if (NNS->getAsNamespace()->isAnonymousNamespace()) 3303 return; 3304 II = NNS->getAsNamespace()->getIdentifier(); 3305 break; 3306 3307 case NestedNameSpecifier::NamespaceAlias: 3308 II = NNS->getAsNamespaceAlias()->getIdentifier(); 3309 break; 3310 3311 case NestedNameSpecifier::TypeSpecWithTemplate: 3312 case NestedNameSpecifier::TypeSpec: 3313 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); 3314 break; 3315 3316 case NestedNameSpecifier::Global: 3317 return; 3318 } 3319 3320 if (II) 3321 Identifiers.push_back(II); 3322 } 3323 3324 namespace { 3325 3326 static const unsigned MaxTypoDistanceResultSets = 5; 3327 3328 class TypoCorrectionConsumer : public VisibleDeclConsumer { 3329 typedef SmallVector<TypoCorrection, 1> TypoResultList; 3330 typedef llvm::StringMap<TypoResultList> TypoResultsMap; 3331 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap; 3332 3333 public: 3334 explicit TypoCorrectionConsumer(Sema &SemaRef, 3335 const DeclarationNameInfo &TypoName, 3336 Sema::LookupNameKind LookupKind, 3337 Scope *S, CXXScopeSpec *SS, 3338 CorrectionCandidateCallback &CCC, 3339 DeclContext *MemberContext, 3340 bool EnteringContext) 3341 : Typo(TypoName.getName().getAsIdentifierInfo()), SemaRef(SemaRef), S(S), 3342 SS(SS), CorrectionValidator(CCC), MemberContext(MemberContext), 3343 Result(SemaRef, TypoName, LookupKind), 3344 Namespaces(SemaRef.Context, SemaRef.CurContext, SS), 3345 EnteringContext(EnteringContext), SearchNamespaces(false) { 3346 Result.suppressDiagnostics(); 3347 } 3348 3349 bool includeHiddenDecls() const override { return true; } 3350 3351 // Methods for adding potential corrections to the consumer. 3352 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 3353 bool InBaseClass) override; 3354 void FoundName(StringRef Name); 3355 void addKeywordResult(StringRef Keyword); 3356 void addCorrection(TypoCorrection Correction); 3357 3358 bool empty() const { return CorrectionResults.empty(); } 3359 3360 /// \brief Return the list of TypoCorrections for the given identifier from 3361 /// the set of corrections that have the closest edit distance, if any. 3362 TypoResultList &operator[](StringRef Name) { 3363 return CorrectionResults.begin()->second[Name]; 3364 } 3365 3366 /// \brief Return the edit distance of the corrections that have the 3367 /// closest/best edit distance from the original typop. 3368 unsigned getBestEditDistance(bool Normalized) { 3369 if (CorrectionResults.empty()) 3370 return (std::numeric_limits<unsigned>::max)(); 3371 3372 unsigned BestED = CorrectionResults.begin()->first; 3373 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED; 3374 } 3375 3376 /// \brief Set-up method to add to the consumer the set of namespaces to use 3377 /// in performing corrections to nested name specifiers. This method also 3378 /// implicitly adds all of the known classes in the current AST context to the 3379 /// to the consumer for correcting nested name specifiers. 3380 void 3381 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces); 3382 3383 /// \brief Return the next typo correction that passes all internal filters 3384 /// and is deemed valid by the consumer's CorrectionCandidateCallback, 3385 /// starting with the corrections that have the closest edit distance. An 3386 /// empty TypoCorrection is returned once no more viable corrections remain 3387 /// in the consumer. 3388 TypoCorrection getNextCorrection(); 3389 3390 private: 3391 class NamespaceSpecifierSet { 3392 struct SpecifierInfo { 3393 DeclContext* DeclCtx; 3394 NestedNameSpecifier* NameSpecifier; 3395 unsigned EditDistance; 3396 }; 3397 3398 typedef SmallVector<DeclContext*, 4> DeclContextList; 3399 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList; 3400 3401 ASTContext &Context; 3402 DeclContextList CurContextChain; 3403 std::string CurNameSpecifier; 3404 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers; 3405 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers; 3406 bool isSorted; 3407 3408 SpecifierInfoList Specifiers; 3409 llvm::SmallSetVector<unsigned, 4> Distances; 3410 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap; 3411 3412 /// \brief Helper for building the list of DeclContexts between the current 3413 /// context and the top of the translation unit 3414 static DeclContextList buildContextChain(DeclContext *Start); 3415 3416 void sortNamespaces(); 3417 3418 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain, 3419 NestedNameSpecifier *&NNS); 3420 3421 public: 3422 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext, 3423 CXXScopeSpec *CurScopeSpec); 3424 3425 /// \brief Add the DeclContext (a namespace or record) to the set, computing 3426 /// the corresponding NestedNameSpecifier and its distance in the process. 3427 void addNameSpecifier(DeclContext *Ctx); 3428 3429 typedef SpecifierInfoList::iterator iterator; 3430 iterator begin() { 3431 if (!isSorted) sortNamespaces(); 3432 return Specifiers.begin(); 3433 } 3434 iterator end() { return Specifiers.end(); } 3435 }; 3436 3437 void addName(StringRef Name, NamedDecl *ND, 3438 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false); 3439 3440 /// \brief Find any visible decls for the given typo correction candidate. 3441 /// If none are found, it to the set of candidates for which qualified lookups 3442 /// will be performed to find possible nested name specifier changes. 3443 bool resolveCorrection(TypoCorrection &Candidate); 3444 3445 /// \brief Perform qualified lookups on the queued set of typo correction 3446 /// candidates and add the nested name specifier changes to each candidate if 3447 /// a lookup succeeds (at which point the candidate will be returned to the 3448 /// main pool of potential corrections). 3449 void performQualifiedLookups(); 3450 3451 /// \brief The name written that is a typo in the source. 3452 IdentifierInfo *Typo; 3453 3454 /// \brief The results found that have the smallest edit distance 3455 /// found (so far) with the typo name. 3456 /// 3457 /// The pointer value being set to the current DeclContext indicates 3458 /// whether there is a keyword with this name. 3459 TypoEditDistanceMap CorrectionResults; 3460 3461 Sema &SemaRef; 3462 Scope *S; 3463 CXXScopeSpec *SS; 3464 CorrectionCandidateCallback &CorrectionValidator; 3465 DeclContext *MemberContext; 3466 LookupResult Result; 3467 NamespaceSpecifierSet Namespaces; 3468 SmallVector<TypoCorrection, 2> QualifiedResults; 3469 bool EnteringContext; 3470 bool SearchNamespaces; 3471 }; 3472 3473 } 3474 3475 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 3476 DeclContext *Ctx, bool InBaseClass) { 3477 // Don't consider hidden names for typo correction. 3478 if (Hiding) 3479 return; 3480 3481 // Only consider entities with identifiers for names, ignoring 3482 // special names (constructors, overloaded operators, selectors, 3483 // etc.). 3484 IdentifierInfo *Name = ND->getIdentifier(); 3485 if (!Name) 3486 return; 3487 3488 // Only consider visible declarations and declarations from modules with 3489 // names that exactly match. 3490 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo && 3491 !findAcceptableDecl(SemaRef, ND)) 3492 return; 3493 3494 FoundName(Name->getName()); 3495 } 3496 3497 void TypoCorrectionConsumer::FoundName(StringRef Name) { 3498 // Compute the edit distance between the typo and the name of this 3499 // entity, and add the identifier to the list of results. 3500 addName(Name, nullptr); 3501 } 3502 3503 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { 3504 // Compute the edit distance between the typo and this keyword, 3505 // and add the keyword to the list of results. 3506 addName(Keyword, nullptr, nullptr, true); 3507 } 3508 3509 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, 3510 NestedNameSpecifier *NNS, bool isKeyword) { 3511 // Use a simple length-based heuristic to determine the minimum possible 3512 // edit distance. If the minimum isn't good enough, bail out early. 3513 StringRef TypoStr = Typo->getName(); 3514 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size()); 3515 if (MinED && TypoStr.size() / MinED < 3) 3516 return; 3517 3518 // Compute an upper bound on the allowable edit distance, so that the 3519 // edit-distance algorithm can short-circuit. 3520 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1; 3521 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound); 3522 if (ED >= UpperBound) return; 3523 3524 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); 3525 if (isKeyword) TC.makeKeyword(); 3526 addCorrection(TC); 3527 } 3528 3529 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { 3530 StringRef TypoStr = Typo->getName(); 3531 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); 3532 3533 // For very short typos, ignore potential corrections that have a different 3534 // base identifier from the typo or which have a normalized edit distance 3535 // longer than the typo itself. 3536 if (TypoStr.size() < 3 && 3537 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size())) 3538 return; 3539 3540 // If the correction is resolved but is not viable, ignore it. 3541 if (Correction.isResolved() && 3542 !isCandidateViable(CorrectionValidator, Correction)) 3543 return; 3544 3545 TypoResultList &CList = 3546 CorrectionResults[Correction.getEditDistance(false)][Name]; 3547 3548 if (!CList.empty() && !CList.back().isResolved()) 3549 CList.pop_back(); 3550 if (NamedDecl *NewND = Correction.getCorrectionDecl()) { 3551 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts()); 3552 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end(); 3553 RI != RIEnd; ++RI) { 3554 // If the Correction refers to a decl already in the result list, 3555 // replace the existing result if the string representation of Correction 3556 // comes before the current result alphabetically, then stop as there is 3557 // nothing more to be done to add Correction to the candidate set. 3558 if (RI->getCorrectionDecl() == NewND) { 3559 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts())) 3560 *RI = Correction; 3561 return; 3562 } 3563 } 3564 } 3565 if (CList.empty() || Correction.isResolved()) 3566 CList.push_back(Correction); 3567 3568 while (CorrectionResults.size() > MaxTypoDistanceResultSets) 3569 CorrectionResults.erase(std::prev(CorrectionResults.end())); 3570 } 3571 3572 void TypoCorrectionConsumer::addNamespaces( 3573 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) { 3574 SearchNamespaces = true; 3575 3576 for (auto KNPair : KnownNamespaces) 3577 Namespaces.addNameSpecifier(KNPair.first); 3578 3579 bool SSIsTemplate = false; 3580 if (NestedNameSpecifier *NNS = 3581 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) { 3582 if (const Type *T = NNS->getAsType()) 3583 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; 3584 } 3585 for (const auto *TI : SemaRef.getASTContext().types()) { 3586 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { 3587 CD = CD->getCanonicalDecl(); 3588 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && 3589 !CD->isUnion() && CD->getIdentifier() && 3590 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) && 3591 (CD->isBeingDefined() || CD->isCompleteDefinition())) 3592 Namespaces.addNameSpecifier(CD); 3593 } 3594 } 3595 } 3596 3597 TypoCorrection TypoCorrectionConsumer::getNextCorrection() { 3598 while (!CorrectionResults.empty()) { 3599 auto DI = CorrectionResults.begin(); 3600 if (DI->second.empty()) { 3601 CorrectionResults.erase(DI); 3602 continue; 3603 } 3604 3605 auto RI = DI->second.begin(); 3606 if (RI->second.empty()) { 3607 DI->second.erase(RI); 3608 performQualifiedLookups(); 3609 continue; 3610 } 3611 3612 TypoCorrection TC = RI->second.pop_back_val(); 3613 if (TC.isResolved() || resolveCorrection(TC)) 3614 return TC; 3615 } 3616 return TypoCorrection(); 3617 } 3618 3619 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) { 3620 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); 3621 DeclContext *TempMemberContext = MemberContext; 3622 CXXScopeSpec *TempSS = SS; 3623 retry_lookup: 3624 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext, 3625 EnteringContext, 3626 CorrectionValidator.IsObjCIvarLookup, 3627 Name == Typo && !Candidate.WillReplaceSpecifier()); 3628 switch (Result.getResultKind()) { 3629 case LookupResult::NotFound: 3630 case LookupResult::NotFoundInCurrentInstantiation: 3631 case LookupResult::FoundUnresolvedValue: 3632 if (TempSS) { 3633 // Immediately retry the lookup without the given CXXScopeSpec 3634 TempSS = nullptr; 3635 Candidate.WillReplaceSpecifier(true); 3636 goto retry_lookup; 3637 } 3638 if (TempMemberContext) { 3639 if (SS && !TempSS) 3640 TempSS = SS; 3641 TempMemberContext = nullptr; 3642 goto retry_lookup; 3643 } 3644 if (SearchNamespaces) 3645 QualifiedResults.push_back(Candidate); 3646 break; 3647 3648 case LookupResult::Ambiguous: 3649 // We don't deal with ambiguities. 3650 break; 3651 3652 case LookupResult::Found: 3653 case LookupResult::FoundOverloaded: 3654 // Store all of the Decls for overloaded symbols 3655 for (auto *TRD : Result) 3656 Candidate.addCorrectionDecl(TRD); 3657 if (!isCandidateViable(CorrectionValidator, Candidate)) { 3658 if (SearchNamespaces) 3659 QualifiedResults.push_back(Candidate); 3660 break; 3661 } 3662 return true; 3663 } 3664 return false; 3665 } 3666 3667 void TypoCorrectionConsumer::performQualifiedLookups() { 3668 unsigned TypoLen = Typo->getName().size(); 3669 for (auto QR : QualifiedResults) { 3670 for (auto NSI : Namespaces) { 3671 DeclContext *Ctx = NSI.DeclCtx; 3672 const Type *NSType = NSI.NameSpecifier->getAsType(); 3673 3674 // If the current NestedNameSpecifier refers to a class and the 3675 // current correction candidate is the name of that class, then skip 3676 // it as it is unlikely a qualified version of the class' constructor 3677 // is an appropriate correction. 3678 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) { 3679 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) 3680 continue; 3681 } 3682 3683 TypoCorrection TC(QR); 3684 TC.ClearCorrectionDecls(); 3685 TC.setCorrectionSpecifier(NSI.NameSpecifier); 3686 TC.setQualifierDistance(NSI.EditDistance); 3687 TC.setCallbackDistance(0); // Reset the callback distance 3688 3689 // If the current correction candidate and namespace combination are 3690 // too far away from the original typo based on the normalized edit 3691 // distance, then skip performing a qualified name lookup. 3692 unsigned TmpED = TC.getEditDistance(true); 3693 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED && 3694 TypoLen / TmpED < 3) 3695 continue; 3696 3697 Result.clear(); 3698 Result.setLookupName(QR.getCorrectionAsIdentifierInfo()); 3699 if (!SemaRef.LookupQualifiedName(Result, Ctx)) 3700 continue; 3701 3702 // Any corrections added below will be validated in subsequent 3703 // iterations of the main while() loop over the Consumer's contents. 3704 switch (Result.getResultKind()) { 3705 case LookupResult::Found: 3706 case LookupResult::FoundOverloaded: { 3707 if (SS && SS->isValid()) { 3708 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts()); 3709 std::string OldQualified; 3710 llvm::raw_string_ostream OldOStream(OldQualified); 3711 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy()); 3712 OldOStream << Typo->getName(); 3713 // If correction candidate would be an identical written qualified 3714 // identifer, then the existing CXXScopeSpec probably included a 3715 // typedef that didn't get accounted for properly. 3716 if (OldOStream.str() == NewQualified) 3717 break; 3718 } 3719 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end(); 3720 TRD != TRDEnd; ++TRD) { 3721 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(), 3722 NSType ? NSType->getAsCXXRecordDecl() 3723 : nullptr, 3724 TRD.getPair()) == Sema::AR_accessible) 3725 TC.addCorrectionDecl(*TRD); 3726 } 3727 if (TC.isResolved()) 3728 addCorrection(TC); 3729 break; 3730 } 3731 case LookupResult::NotFound: 3732 case LookupResult::NotFoundInCurrentInstantiation: 3733 case LookupResult::Ambiguous: 3734 case LookupResult::FoundUnresolvedValue: 3735 break; 3736 } 3737 } 3738 } 3739 QualifiedResults.clear(); 3740 } 3741 3742 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet( 3743 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec) 3744 : Context(Context), CurContextChain(buildContextChain(CurContext)), 3745 isSorted(false) { 3746 if (NestedNameSpecifier *NNS = 3747 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) { 3748 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); 3749 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 3750 3751 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers); 3752 } 3753 // Build the list of identifiers that would be used for an absolute 3754 // (from the global context) NestedNameSpecifier referring to the current 3755 // context. 3756 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3757 CEnd = CurContextChain.rend(); 3758 C != CEnd; ++C) { 3759 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) 3760 CurContextIdentifiers.push_back(ND->getIdentifier()); 3761 } 3762 3763 // Add the global context as a NestedNameSpecifier 3764 Distances.insert(1); 3765 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()), 3766 NestedNameSpecifier::GlobalSpecifier(Context), 1}; 3767 DistanceMap[1].push_back(SI); 3768 } 3769 3770 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain( 3771 DeclContext *Start) -> DeclContextList { 3772 assert(Start && "Building a context chain from a null context"); 3773 DeclContextList Chain; 3774 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr; 3775 DC = DC->getLookupParent()) { 3776 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); 3777 if (!DC->isInlineNamespace() && !DC->isTransparentContext() && 3778 !(ND && ND->isAnonymousNamespace())) 3779 Chain.push_back(DC->getPrimaryContext()); 3780 } 3781 return Chain; 3782 } 3783 3784 void TypoCorrectionConsumer::NamespaceSpecifierSet::sortNamespaces() { 3785 SmallVector<unsigned, 4> sortedDistances; 3786 sortedDistances.append(Distances.begin(), Distances.end()); 3787 3788 if (sortedDistances.size() > 1) 3789 std::sort(sortedDistances.begin(), sortedDistances.end()); 3790 3791 Specifiers.clear(); 3792 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(), 3793 DIEnd = sortedDistances.end(); 3794 DI != DIEnd; ++DI) { 3795 SpecifierInfoList &SpecList = DistanceMap[*DI]; 3796 Specifiers.append(SpecList.begin(), SpecList.end()); 3797 } 3798 3799 isSorted = true; 3800 } 3801 3802 unsigned 3803 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier( 3804 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) { 3805 unsigned NumSpecifiers = 0; 3806 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(), 3807 CEnd = DeclChain.rend(); 3808 C != CEnd; ++C) { 3809 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) { 3810 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 3811 ++NumSpecifiers; 3812 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) { 3813 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), 3814 RD->getTypeForDecl()); 3815 ++NumSpecifiers; 3816 } 3817 } 3818 return NumSpecifiers; 3819 } 3820 3821 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier( 3822 DeclContext *Ctx) { 3823 NestedNameSpecifier *NNS = nullptr; 3824 unsigned NumSpecifiers = 0; 3825 DeclContextList NamespaceDeclChain(buildContextChain(Ctx)); 3826 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 3827 3828 // Eliminate common elements from the two DeclContext chains. 3829 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3830 CEnd = CurContextChain.rend(); 3831 C != CEnd && !NamespaceDeclChain.empty() && 3832 NamespaceDeclChain.back() == *C; ++C) { 3833 NamespaceDeclChain.pop_back(); 3834 } 3835 3836 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 3837 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS); 3838 3839 // Add an explicit leading '::' specifier if needed. 3840 if (NamespaceDeclChain.empty()) { 3841 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 3842 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3843 NumSpecifiers = 3844 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 3845 } else if (NamedDecl *ND = 3846 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) { 3847 IdentifierInfo *Name = ND->getIdentifier(); 3848 bool SameNameSpecifier = false; 3849 if (std::find(CurNameSpecifierIdentifiers.begin(), 3850 CurNameSpecifierIdentifiers.end(), 3851 Name) != CurNameSpecifierIdentifiers.end()) { 3852 std::string NewNameSpecifier; 3853 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); 3854 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; 3855 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 3856 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 3857 SpecifierOStream.flush(); 3858 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; 3859 } 3860 if (SameNameSpecifier || 3861 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(), 3862 Name) != CurContextIdentifiers.end()) { 3863 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 3864 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3865 NumSpecifiers = 3866 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 3867 } 3868 } 3869 3870 // If the built NestedNameSpecifier would be replacing an existing 3871 // NestedNameSpecifier, use the number of component identifiers that 3872 // would need to be changed as the edit distance instead of the number 3873 // of components in the built NestedNameSpecifier. 3874 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 3875 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 3876 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 3877 NumSpecifiers = llvm::ComputeEditDistance( 3878 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers), 3879 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers)); 3880 } 3881 3882 isSorted = false; 3883 Distances.insert(NumSpecifiers); 3884 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers}; 3885 DistanceMap[NumSpecifiers].push_back(SI); 3886 } 3887 3888 /// \brief Perform name lookup for a possible result for typo correction. 3889 static void LookupPotentialTypoResult(Sema &SemaRef, 3890 LookupResult &Res, 3891 IdentifierInfo *Name, 3892 Scope *S, CXXScopeSpec *SS, 3893 DeclContext *MemberContext, 3894 bool EnteringContext, 3895 bool isObjCIvarLookup, 3896 bool FindHidden) { 3897 Res.suppressDiagnostics(); 3898 Res.clear(); 3899 Res.setLookupName(Name); 3900 Res.setAllowHidden(FindHidden); 3901 if (MemberContext) { 3902 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { 3903 if (isObjCIvarLookup) { 3904 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { 3905 Res.addDecl(Ivar); 3906 Res.resolveKind(); 3907 return; 3908 } 3909 } 3910 3911 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) { 3912 Res.addDecl(Prop); 3913 Res.resolveKind(); 3914 return; 3915 } 3916 } 3917 3918 SemaRef.LookupQualifiedName(Res, MemberContext); 3919 return; 3920 } 3921 3922 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 3923 EnteringContext); 3924 3925 // Fake ivar lookup; this should really be part of 3926 // LookupParsedName. 3927 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 3928 if (Method->isInstanceMethod() && Method->getClassInterface() && 3929 (Res.empty() || 3930 (Res.isSingleResult() && 3931 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { 3932 if (ObjCIvarDecl *IV 3933 = Method->getClassInterface()->lookupInstanceVariable(Name)) { 3934 Res.addDecl(IV); 3935 Res.resolveKind(); 3936 } 3937 } 3938 } 3939 } 3940 3941 /// \brief Add keywords to the consumer as possible typo corrections. 3942 static void AddKeywordsToConsumer(Sema &SemaRef, 3943 TypoCorrectionConsumer &Consumer, 3944 Scope *S, CorrectionCandidateCallback &CCC, 3945 bool AfterNestedNameSpecifier) { 3946 if (AfterNestedNameSpecifier) { 3947 // For 'X::', we know exactly which keywords can appear next. 3948 Consumer.addKeywordResult("template"); 3949 if (CCC.WantExpressionKeywords) 3950 Consumer.addKeywordResult("operator"); 3951 return; 3952 } 3953 3954 if (CCC.WantObjCSuper) 3955 Consumer.addKeywordResult("super"); 3956 3957 if (CCC.WantTypeSpecifiers) { 3958 // Add type-specifier keywords to the set of results. 3959 static const char *const CTypeSpecs[] = { 3960 "char", "const", "double", "enum", "float", "int", "long", "short", 3961 "signed", "struct", "union", "unsigned", "void", "volatile", 3962 "_Complex", "_Imaginary", 3963 // storage-specifiers as well 3964 "extern", "inline", "static", "typedef" 3965 }; 3966 3967 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); 3968 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 3969 Consumer.addKeywordResult(CTypeSpecs[I]); 3970 3971 if (SemaRef.getLangOpts().C99) 3972 Consumer.addKeywordResult("restrict"); 3973 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) 3974 Consumer.addKeywordResult("bool"); 3975 else if (SemaRef.getLangOpts().C99) 3976 Consumer.addKeywordResult("_Bool"); 3977 3978 if (SemaRef.getLangOpts().CPlusPlus) { 3979 Consumer.addKeywordResult("class"); 3980 Consumer.addKeywordResult("typename"); 3981 Consumer.addKeywordResult("wchar_t"); 3982 3983 if (SemaRef.getLangOpts().CPlusPlus11) { 3984 Consumer.addKeywordResult("char16_t"); 3985 Consumer.addKeywordResult("char32_t"); 3986 Consumer.addKeywordResult("constexpr"); 3987 Consumer.addKeywordResult("decltype"); 3988 Consumer.addKeywordResult("thread_local"); 3989 } 3990 } 3991 3992 if (SemaRef.getLangOpts().GNUMode) 3993 Consumer.addKeywordResult("typeof"); 3994 } 3995 3996 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { 3997 Consumer.addKeywordResult("const_cast"); 3998 Consumer.addKeywordResult("dynamic_cast"); 3999 Consumer.addKeywordResult("reinterpret_cast"); 4000 Consumer.addKeywordResult("static_cast"); 4001 } 4002 4003 if (CCC.WantExpressionKeywords) { 4004 Consumer.addKeywordResult("sizeof"); 4005 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { 4006 Consumer.addKeywordResult("false"); 4007 Consumer.addKeywordResult("true"); 4008 } 4009 4010 if (SemaRef.getLangOpts().CPlusPlus) { 4011 static const char *const CXXExprs[] = { 4012 "delete", "new", "operator", "throw", "typeid" 4013 }; 4014 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); 4015 for (unsigned I = 0; I != NumCXXExprs; ++I) 4016 Consumer.addKeywordResult(CXXExprs[I]); 4017 4018 if (isa<CXXMethodDecl>(SemaRef.CurContext) && 4019 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) 4020 Consumer.addKeywordResult("this"); 4021 4022 if (SemaRef.getLangOpts().CPlusPlus11) { 4023 Consumer.addKeywordResult("alignof"); 4024 Consumer.addKeywordResult("nullptr"); 4025 } 4026 } 4027 4028 if (SemaRef.getLangOpts().C11) { 4029 // FIXME: We should not suggest _Alignof if the alignof macro 4030 // is present. 4031 Consumer.addKeywordResult("_Alignof"); 4032 } 4033 } 4034 4035 if (CCC.WantRemainingKeywords) { 4036 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { 4037 // Statements. 4038 static const char *const CStmts[] = { 4039 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 4040 const unsigned NumCStmts = llvm::array_lengthof(CStmts); 4041 for (unsigned I = 0; I != NumCStmts; ++I) 4042 Consumer.addKeywordResult(CStmts[I]); 4043 4044 if (SemaRef.getLangOpts().CPlusPlus) { 4045 Consumer.addKeywordResult("catch"); 4046 Consumer.addKeywordResult("try"); 4047 } 4048 4049 if (S && S->getBreakParent()) 4050 Consumer.addKeywordResult("break"); 4051 4052 if (S && S->getContinueParent()) 4053 Consumer.addKeywordResult("continue"); 4054 4055 if (!SemaRef.getCurFunction()->SwitchStack.empty()) { 4056 Consumer.addKeywordResult("case"); 4057 Consumer.addKeywordResult("default"); 4058 } 4059 } else { 4060 if (SemaRef.getLangOpts().CPlusPlus) { 4061 Consumer.addKeywordResult("namespace"); 4062 Consumer.addKeywordResult("template"); 4063 } 4064 4065 if (S && S->isClassScope()) { 4066 Consumer.addKeywordResult("explicit"); 4067 Consumer.addKeywordResult("friend"); 4068 Consumer.addKeywordResult("mutable"); 4069 Consumer.addKeywordResult("private"); 4070 Consumer.addKeywordResult("protected"); 4071 Consumer.addKeywordResult("public"); 4072 Consumer.addKeywordResult("virtual"); 4073 } 4074 } 4075 4076 if (SemaRef.getLangOpts().CPlusPlus) { 4077 Consumer.addKeywordResult("using"); 4078 4079 if (SemaRef.getLangOpts().CPlusPlus11) 4080 Consumer.addKeywordResult("static_assert"); 4081 } 4082 } 4083 } 4084 4085 /// \brief Check whether the declarations found for a typo correction are 4086 /// visible, and if none of them are, convert the correction to an 'import 4087 /// a module' correction. 4088 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) { 4089 if (TC.begin() == TC.end()) 4090 return; 4091 4092 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); 4093 4094 for (/**/; DI != DE; ++DI) 4095 if (!LookupResult::isVisible(SemaRef, *DI)) 4096 break; 4097 // Nothing to do if all decls are visible. 4098 if (DI == DE) 4099 return; 4100 4101 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); 4102 bool AnyVisibleDecls = !NewDecls.empty(); 4103 4104 for (/**/; DI != DE; ++DI) { 4105 NamedDecl *VisibleDecl = *DI; 4106 if (!LookupResult::isVisible(SemaRef, *DI)) 4107 VisibleDecl = findAcceptableDecl(SemaRef, *DI); 4108 4109 if (VisibleDecl) { 4110 if (!AnyVisibleDecls) { 4111 // Found a visible decl, discard all hidden ones. 4112 AnyVisibleDecls = true; 4113 NewDecls.clear(); 4114 } 4115 NewDecls.push_back(VisibleDecl); 4116 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) 4117 NewDecls.push_back(*DI); 4118 } 4119 4120 if (NewDecls.empty()) 4121 TC = TypoCorrection(); 4122 else { 4123 TC.setCorrectionDecls(NewDecls); 4124 TC.setRequiresImport(!AnyVisibleDecls); 4125 } 4126 } 4127 4128 /// \brief Try to "correct" a typo in the source code by finding 4129 /// visible declarations whose names are similar to the name that was 4130 /// present in the source code. 4131 /// 4132 /// \param TypoName the \c DeclarationNameInfo structure that contains 4133 /// the name that was present in the source code along with its location. 4134 /// 4135 /// \param LookupKind the name-lookup criteria used to search for the name. 4136 /// 4137 /// \param S the scope in which name lookup occurs. 4138 /// 4139 /// \param SS the nested-name-specifier that precedes the name we're 4140 /// looking for, if present. 4141 /// 4142 /// \param CCC A CorrectionCandidateCallback object that provides further 4143 /// validation of typo correction candidates. It also provides flags for 4144 /// determining the set of keywords permitted. 4145 /// 4146 /// \param MemberContext if non-NULL, the context in which to look for 4147 /// a member access expression. 4148 /// 4149 /// \param EnteringContext whether we're entering the context described by 4150 /// the nested-name-specifier SS. 4151 /// 4152 /// \param OPT when non-NULL, the search for visible declarations will 4153 /// also walk the protocols in the qualified interfaces of \p OPT. 4154 /// 4155 /// \returns a \c TypoCorrection containing the corrected name if the typo 4156 /// along with information such as the \c NamedDecl where the corrected name 4157 /// was declared, and any additional \c NestedNameSpecifier needed to access 4158 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 4159 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, 4160 Sema::LookupNameKind LookupKind, 4161 Scope *S, CXXScopeSpec *SS, 4162 CorrectionCandidateCallback &CCC, 4163 CorrectTypoKind Mode, 4164 DeclContext *MemberContext, 4165 bool EnteringContext, 4166 const ObjCObjectPointerType *OPT, 4167 bool RecordFailure) { 4168 // Always let the ExternalSource have the first chance at correction, even 4169 // if we would otherwise have given up. 4170 if (ExternalSource) { 4171 if (TypoCorrection Correction = ExternalSource->CorrectTypo( 4172 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT)) 4173 return Correction; 4174 } 4175 4176 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || 4177 DisableTypoCorrection) 4178 return TypoCorrection(); 4179 4180 // In Microsoft mode, don't perform typo correction in a template member 4181 // function dependent context because it interferes with the "lookup into 4182 // dependent bases of class templates" feature. 4183 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 4184 isa<CXXMethodDecl>(CurContext)) 4185 return TypoCorrection(); 4186 4187 // We only attempt to correct typos for identifiers. 4188 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 4189 if (!Typo) 4190 return TypoCorrection(); 4191 4192 // If the scope specifier itself was invalid, don't try to correct 4193 // typos. 4194 if (SS && SS->isInvalid()) 4195 return TypoCorrection(); 4196 4197 // Never try to correct typos during template deduction or 4198 // instantiation. 4199 if (!ActiveTemplateInstantiations.empty()) 4200 return TypoCorrection(); 4201 4202 // Don't try to correct 'super'. 4203 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) 4204 return TypoCorrection(); 4205 4206 // Abort if typo correction already failed for this specific typo. 4207 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo); 4208 if (locs != TypoCorrectionFailures.end() && 4209 locs->second.count(TypoName.getLoc())) 4210 return TypoCorrection(); 4211 4212 // Don't try to correct the identifier "vector" when in AltiVec mode. 4213 // TODO: Figure out why typo correction misbehaves in this case, fix it, and 4214 // remove this workaround. 4215 if (getLangOpts().AltiVec && Typo->isStr("vector")) 4216 return TypoCorrection(); 4217 4218 // If we're handling a missing symbol error, using modules, and the 4219 // special search all modules option is used, look for a missing import. 4220 if ((Mode == CTK_ErrorRecovery) && getLangOpts().Modules && 4221 getLangOpts().ModulesSearchAll) { 4222 // The following has the side effect of loading the missing module. 4223 getModuleLoader().lookupMissingImports(Typo->getName(), 4224 TypoName.getLocStart()); 4225 } 4226 4227 TypoCorrectionConsumer Consumer(*this, TypoName, LookupKind, S, SS, CCC, 4228 MemberContext, EnteringContext); 4229 4230 // If a callback object considers an empty typo correction candidate to be 4231 // viable, assume it does not do any actual validation of the candidates. 4232 TypoCorrection EmptyCorrection; 4233 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection); 4234 4235 // Perform name lookup to find visible, similarly-named entities. 4236 bool IsUnqualifiedLookup = false; 4237 DeclContext *QualifiedDC = MemberContext; 4238 if (MemberContext) { 4239 LookupVisibleDecls(MemberContext, LookupKind, Consumer); 4240 4241 // Look in qualified interfaces. 4242 if (OPT) { 4243 for (auto *I : OPT->quals()) 4244 LookupVisibleDecls(I, LookupKind, Consumer); 4245 } 4246 } else if (SS && SS->isSet()) { 4247 QualifiedDC = computeDeclContext(*SS, EnteringContext); 4248 if (!QualifiedDC) 4249 return TypoCorrection(); 4250 4251 // Provide a stop gap for files that are just seriously broken. Trying 4252 // to correct all typos can turn into a HUGE performance penalty, causing 4253 // some files to take minutes to get rejected by the parser. 4254 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 4255 return TypoCorrection(); 4256 ++TyposCorrected; 4257 4258 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer); 4259 } else { 4260 IsUnqualifiedLookup = true; 4261 UnqualifiedTyposCorrectedMap::iterator Cached 4262 = UnqualifiedTyposCorrected.find(Typo); 4263 if (Cached != UnqualifiedTyposCorrected.end()) { 4264 // Add the cached value, unless it's a keyword or fails validation. In the 4265 // keyword case, we'll end up adding the keyword below. 4266 if (Cached->second) { 4267 if (!Cached->second.isKeyword() && 4268 isCandidateViable(CCC, Cached->second)) { 4269 // Do not use correction that is unaccessible in the given scope. 4270 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl(); 4271 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(), 4272 CorrectionDecl->getLocation()); 4273 LookupResult R(*this, NameInfo, LookupOrdinaryName); 4274 if (LookupName(R, S)) 4275 Consumer.addCorrection(Cached->second); 4276 } 4277 } else { 4278 // Only honor no-correction cache hits when a callback that will validate 4279 // correction candidates is not being used. 4280 if (!ValidatingCallback) 4281 return TypoCorrection(); 4282 } 4283 } 4284 if (Cached == UnqualifiedTyposCorrected.end()) { 4285 // Provide a stop gap for files that are just seriously broken. Trying 4286 // to correct all typos can turn into a HUGE performance penalty, causing 4287 // some files to take minutes to get rejected by the parser. 4288 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 4289 return TypoCorrection(); 4290 } 4291 } 4292 4293 // Determine whether we are going to search in the various namespaces for 4294 // corrections. 4295 bool SearchNamespaces 4296 = getLangOpts().CPlusPlus && 4297 (IsUnqualifiedLookup || (SS && SS->isSet())); 4298 // In a few cases we *only* want to search for corrections based on just 4299 // adding or changing the nested name specifier. 4300 unsigned TypoLen = Typo->getName().size(); 4301 bool AllowOnlyNNSChanges = TypoLen < 3; 4302 4303 if (IsUnqualifiedLookup || SearchNamespaces) { 4304 // For unqualified lookup, look through all of the names that we have 4305 // seen in this translation unit. 4306 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4307 for (IdentifierTable::iterator I = Context.Idents.begin(), 4308 IEnd = Context.Idents.end(); 4309 I != IEnd; ++I) 4310 Consumer.FoundName(I->getKey()); 4311 4312 // Walk through identifiers in external identifier sources. 4313 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4314 if (IdentifierInfoLookup *External 4315 = Context.Idents.getExternalIdentifierLookup()) { 4316 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 4317 do { 4318 StringRef Name = Iter->Next(); 4319 if (Name.empty()) 4320 break; 4321 4322 Consumer.FoundName(Name); 4323 } while (true); 4324 } 4325 } 4326 4327 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty()); 4328 4329 // If we haven't found anything, we're done. 4330 if (Consumer.empty()) 4331 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4332 IsUnqualifiedLookup); 4333 4334 // Make sure the best edit distance (prior to adding any namespace qualifiers) 4335 // is not more that about a third of the length of the typo's identifier. 4336 unsigned ED = Consumer.getBestEditDistance(true); 4337 if (ED > 0 && TypoLen / ED < 3) 4338 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4339 IsUnqualifiedLookup); 4340 4341 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going 4342 // to search those namespaces. 4343 if (SearchNamespaces) { 4344 // Load any externally-known namespaces. 4345 if (ExternalSource && !LoadedExternalKnownNamespaces) { 4346 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; 4347 LoadedExternalKnownNamespaces = true; 4348 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); 4349 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I) 4350 KnownNamespaces[ExternalKnownNamespaces[I]] = true; 4351 } 4352 4353 Consumer.addNamespaces(KnownNamespaces); 4354 } 4355 4356 TypoCorrection BestTC = Consumer.getNextCorrection(); 4357 TypoCorrection SecondBestTC = Consumer.getNextCorrection(); 4358 if (!BestTC) 4359 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4360 4361 ED = BestTC.getEditDistance(); 4362 4363 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) { 4364 // If this was an unqualified lookup and we believe the callback 4365 // object wouldn't have filtered out possible corrections, note 4366 // that no correction was found. 4367 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4368 IsUnqualifiedLookup && !ValidatingCallback); 4369 } 4370 4371 // If only a single name remains, return that result. 4372 if (!SecondBestTC || 4373 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) { 4374 const TypoCorrection &Result = BestTC; 4375 4376 // Don't correct to a keyword that's the same as the typo; the keyword 4377 // wasn't actually in scope. 4378 if (ED == 0 && Result.isKeyword()) 4379 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4380 4381 // Record the correction for unqualified lookup. 4382 if (IsUnqualifiedLookup) 4383 UnqualifiedTyposCorrected[Typo] = Result; 4384 4385 TypoCorrection TC = Result; 4386 TC.setCorrectionRange(SS, TypoName); 4387 checkCorrectionVisibility(*this, TC); 4388 return TC; 4389 } 4390 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; 4391 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for 4392 // some instances of CTC_Unknown, while WantRemainingKeywords is true 4393 // for CTC_Unknown but not for CTC_ObjCMessageReceiver. 4394 else if (SecondBestTC && CCC.WantObjCSuper && !CCC.WantRemainingKeywords) { 4395 // Prefer 'super' when we're completing in a message-receiver 4396 // context. 4397 4398 if (BestTC.getCorrection().getAsString() != "super") { 4399 if (SecondBestTC.getCorrection().getAsString() == "super") 4400 BestTC = SecondBestTC; 4401 else if (Consumer["super"].front().isKeyword()) 4402 BestTC = Consumer["super"].front(); 4403 } 4404 // Don't correct to a keyword that's the same as the typo; the keyword 4405 // wasn't actually in scope. 4406 if (BestTC.getEditDistance() == 0 || 4407 BestTC.getCorrection().getAsString() != "super") 4408 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4409 4410 // Record the correction for unqualified lookup. 4411 if (IsUnqualifiedLookup) 4412 UnqualifiedTyposCorrected[Typo] = BestTC; 4413 4414 BestTC.setCorrectionRange(SS, TypoName); 4415 return BestTC; 4416 } 4417 4418 // Record the failure's location if needed and return an empty correction. If 4419 // this was an unqualified lookup and we believe the callback object did not 4420 // filter out possible corrections, also cache the failure for the typo. 4421 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4422 IsUnqualifiedLookup && !ValidatingCallback); 4423 } 4424 4425 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { 4426 if (!CDecl) return; 4427 4428 if (isKeyword()) 4429 CorrectionDecls.clear(); 4430 4431 CorrectionDecls.push_back(CDecl->getUnderlyingDecl()); 4432 4433 if (!CorrectionName) 4434 CorrectionName = CDecl->getDeclName(); 4435 } 4436 4437 std::string TypoCorrection::getAsString(const LangOptions &LO) const { 4438 if (CorrectionNameSpec) { 4439 std::string tmpBuffer; 4440 llvm::raw_string_ostream PrefixOStream(tmpBuffer); 4441 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); 4442 PrefixOStream << CorrectionName; 4443 return PrefixOStream.str(); 4444 } 4445 4446 return CorrectionName.getAsString(); 4447 } 4448 4449 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) { 4450 if (!candidate.isResolved()) 4451 return true; 4452 4453 if (candidate.isKeyword()) 4454 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || 4455 WantRemainingKeywords || WantObjCSuper; 4456 4457 bool HasNonType = false; 4458 bool HasStaticMethod = false; 4459 bool HasNonStaticMethod = false; 4460 for (Decl *D : candidate) { 4461 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 4462 D = FTD->getTemplatedDecl(); 4463 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 4464 if (Method->isStatic()) 4465 HasStaticMethod = true; 4466 else 4467 HasNonStaticMethod = true; 4468 } 4469 if (!isa<TypeDecl>(D)) 4470 HasNonType = true; 4471 } 4472 4473 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod && 4474 !candidate.getCorrectionSpecifier()) 4475 return false; 4476 4477 return WantTypeSpecifiers || HasNonType; 4478 } 4479 4480 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, 4481 bool HasExplicitTemplateArgs, 4482 MemberExpr *ME) 4483 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), 4484 CurContext(SemaRef.CurContext), MemberFn(ME) { 4485 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 4486 WantRemainingKeywords = false; 4487 } 4488 4489 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { 4490 if (!candidate.getCorrectionDecl()) 4491 return candidate.isKeyword(); 4492 4493 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 4494 DIEnd = candidate.end(); 4495 DI != DIEnd; ++DI) { 4496 FunctionDecl *FD = nullptr; 4497 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 4498 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 4499 FD = FTD->getTemplatedDecl(); 4500 if (!HasExplicitTemplateArgs && !FD) { 4501 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 4502 // If the Decl is neither a function nor a template function, 4503 // determine if it is a pointer or reference to a function. If so, 4504 // check against the number of arguments expected for the pointee. 4505 QualType ValType = cast<ValueDecl>(ND)->getType(); 4506 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 4507 ValType = ValType->getPointeeType(); 4508 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 4509 if (FPT->getNumParams() == NumArgs) 4510 return true; 4511 } 4512 } 4513 4514 // Skip the current candidate if it is not a FunctionDecl or does not accept 4515 // the current number of arguments. 4516 if (!FD || !(FD->getNumParams() >= NumArgs && 4517 FD->getMinRequiredArguments() <= NumArgs)) 4518 continue; 4519 4520 // If the current candidate is a non-static C++ method, skip the candidate 4521 // unless the method being corrected--or the current DeclContext, if the 4522 // function being corrected is not a method--is a method in the same class 4523 // or a descendent class of the candidate's parent class. 4524 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 4525 if (MemberFn || !MD->isStatic()) { 4526 CXXMethodDecl *CurMD = 4527 MemberFn 4528 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl()) 4529 : dyn_cast_or_null<CXXMethodDecl>(CurContext); 4530 CXXRecordDecl *CurRD = 4531 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr; 4532 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); 4533 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD))) 4534 continue; 4535 } 4536 } 4537 return true; 4538 } 4539 return false; 4540 } 4541 4542 void Sema::diagnoseTypo(const TypoCorrection &Correction, 4543 const PartialDiagnostic &TypoDiag, 4544 bool ErrorRecovery) { 4545 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), 4546 ErrorRecovery); 4547 } 4548 4549 /// Find which declaration we should import to provide the definition of 4550 /// the given declaration. 4551 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) { 4552 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4553 return VD->getDefinition(); 4554 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4555 return FD->isDefined(FD) ? FD : nullptr; 4556 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 4557 return TD->getDefinition(); 4558 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) 4559 return ID->getDefinition(); 4560 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) 4561 return PD->getDefinition(); 4562 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 4563 return getDefinitionToImport(TD->getTemplatedDecl()); 4564 return nullptr; 4565 } 4566 4567 /// \brief Diagnose a successfully-corrected typo. Separated from the correction 4568 /// itself to allow external validation of the result, etc. 4569 /// 4570 /// \param Correction The result of performing typo correction. 4571 /// \param TypoDiag The diagnostic to produce. This will have the corrected 4572 /// string added to it (and usually also a fixit). 4573 /// \param PrevNote A note to use when indicating the location of the entity to 4574 /// which we are correcting. Will have the correction string added to it. 4575 /// \param ErrorRecovery If \c true (the default), the caller is going to 4576 /// recover from the typo as if the corrected string had been typed. 4577 /// In this case, \c PDiag must be an error, and we will attach a fixit 4578 /// to it. 4579 void Sema::diagnoseTypo(const TypoCorrection &Correction, 4580 const PartialDiagnostic &TypoDiag, 4581 const PartialDiagnostic &PrevNote, 4582 bool ErrorRecovery) { 4583 std::string CorrectedStr = Correction.getAsString(getLangOpts()); 4584 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); 4585 FixItHint FixTypo = FixItHint::CreateReplacement( 4586 Correction.getCorrectionRange(), CorrectedStr); 4587 4588 // Maybe we're just missing a module import. 4589 if (Correction.requiresImport()) { 4590 NamedDecl *Decl = Correction.getCorrectionDecl(); 4591 assert(Decl && "import required but no declaration to import"); 4592 4593 // Suggest importing a module providing the definition of this entity, if 4594 // possible. 4595 const NamedDecl *Def = getDefinitionToImport(Decl); 4596 if (!Def) 4597 Def = Decl; 4598 Module *Owner = Def->getOwningModule(); 4599 assert(Owner && "definition of hidden declaration is not in a module"); 4600 4601 Diag(Correction.getCorrectionRange().getBegin(), 4602 diag::err_module_private_declaration) 4603 << Def << Owner->getFullModuleName(); 4604 Diag(Def->getLocation(), diag::note_previous_declaration); 4605 4606 // Recover by implicitly importing this module. 4607 if (ErrorRecovery) 4608 createImplicitModuleImportForErrorRecovery( 4609 Correction.getCorrectionRange().getBegin(), Owner); 4610 return; 4611 } 4612 4613 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) 4614 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); 4615 4616 NamedDecl *ChosenDecl = 4617 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl(); 4618 if (PrevNote.getDiagID() && ChosenDecl) 4619 Diag(ChosenDecl->getLocation(), PrevNote) 4620 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); 4621 } 4622