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