SemaLookup.cpp revision 1cdf4d0686667b7f80c37cdc87679d824819bb5a
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 "Sema.h" 15#include "Lookup.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/CXXInheritance.h" 18#include "clang/AST/Decl.h" 19#include "clang/AST/DeclCXX.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/Parse/DeclSpec.h" 25#include "clang/Basic/Builtins.h" 26#include "clang/Basic/LangOptions.h" 27#include "llvm/ADT/STLExtras.h" 28#include "llvm/ADT/SmallPtrSet.h" 29#include "llvm/Support/ErrorHandling.h" 30#include <list> 31#include <set> 32#include <vector> 33#include <iterator> 34#include <utility> 35#include <algorithm> 36 37using namespace clang; 38 39namespace { 40 class UnqualUsingEntry { 41 const DeclContext *Nominated; 42 const DeclContext *CommonAncestor; 43 44 public: 45 UnqualUsingEntry(const DeclContext *Nominated, 46 const DeclContext *CommonAncestor) 47 : Nominated(Nominated), CommonAncestor(CommonAncestor) { 48 } 49 50 const DeclContext *getCommonAncestor() const { 51 return CommonAncestor; 52 } 53 54 const DeclContext *getNominatedNamespace() const { 55 return Nominated; 56 } 57 58 // Sort by the pointer value of the common ancestor. 59 struct Comparator { 60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { 61 return L.getCommonAncestor() < R.getCommonAncestor(); 62 } 63 64 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { 65 return E.getCommonAncestor() < DC; 66 } 67 68 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { 69 return DC < E.getCommonAncestor(); 70 } 71 }; 72 }; 73 74 /// A collection of using directives, as used by C++ unqualified 75 /// lookup. 76 class UnqualUsingDirectiveSet { 77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy; 78 79 ListTy list; 80 llvm::SmallPtrSet<DeclContext*, 8> visited; 81 82 public: 83 UnqualUsingDirectiveSet() {} 84 85 void visitScopeChain(Scope *S, Scope *InnermostFileScope) { 86 // C++ [namespace.udir]p1: 87 // During unqualified name lookup, the names appear as if they 88 // were declared in the nearest enclosing namespace which contains 89 // both the using-directive and the nominated namespace. 90 DeclContext *InnermostFileDC 91 = static_cast<DeclContext*>(InnermostFileScope->getEntity()); 92 assert(InnermostFileDC && InnermostFileDC->isFileContext()); 93 94 for (; S; S = S->getParent()) { 95 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { 96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC); 97 visit(Ctx, EffectiveDC); 98 } else { 99 Scope::udir_iterator I = S->using_directives_begin(), 100 End = S->using_directives_end(); 101 102 for (; I != End; ++I) 103 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC); 104 } 105 } 106 } 107 108 // Visits a context and collect all of its using directives 109 // recursively. Treats all using directives as if they were 110 // declared in the context. 111 // 112 // A given context is only every visited once, so it is important 113 // that contexts be visited from the inside out in order to get 114 // the effective DCs right. 115 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 116 if (!visited.insert(DC)) 117 return; 118 119 addUsingDirectives(DC, EffectiveDC); 120 } 121 122 // Visits a using directive and collects all of its using 123 // directives recursively. Treats all using directives as if they 124 // were declared in the effective DC. 125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 126 DeclContext *NS = UD->getNominatedNamespace(); 127 if (!visited.insert(NS)) 128 return; 129 130 addUsingDirective(UD, EffectiveDC); 131 addUsingDirectives(NS, EffectiveDC); 132 } 133 134 // Adds all the using directives in a context (and those nominated 135 // by its using directives, transitively) as if they appeared in 136 // the given effective context. 137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 138 llvm::SmallVector<DeclContext*,4> queue; 139 while (true) { 140 DeclContext::udir_iterator I, End; 141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) { 142 UsingDirectiveDecl *UD = *I; 143 DeclContext *NS = UD->getNominatedNamespace(); 144 if (visited.insert(NS)) { 145 addUsingDirective(UD, EffectiveDC); 146 queue.push_back(NS); 147 } 148 } 149 150 if (queue.empty()) 151 return; 152 153 DC = queue.back(); 154 queue.pop_back(); 155 } 156 } 157 158 // Add a using directive as if it had been declared in the given 159 // context. This helps implement C++ [namespace.udir]p3: 160 // The using-directive is transitive: if a scope contains a 161 // using-directive that nominates a second namespace that itself 162 // contains using-directives, the effect is as if the 163 // using-directives from the second namespace also appeared in 164 // the first. 165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 166 // Find the common ancestor between the effective context and 167 // the nominated namespace. 168 DeclContext *Common = UD->getNominatedNamespace(); 169 while (!Common->Encloses(EffectiveDC)) 170 Common = Common->getParent(); 171 Common = Common->getPrimaryContext(); 172 173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 174 } 175 176 void done() { 177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); 178 } 179 180 typedef ListTy::iterator iterator; 181 typedef ListTy::const_iterator const_iterator; 182 183 iterator begin() { return list.begin(); } 184 iterator end() { return list.end(); } 185 const_iterator begin() const { return list.begin(); } 186 const_iterator end() const { return list.end(); } 187 188 std::pair<const_iterator,const_iterator> 189 getNamespacesFor(DeclContext *DC) const { 190 return std::equal_range(begin(), end(), DC->getPrimaryContext(), 191 UnqualUsingEntry::Comparator()); 192 } 193 }; 194} 195 196// Retrieve the set of identifier namespaces that correspond to a 197// specific kind of name lookup. 198static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 199 bool CPlusPlus, 200 bool Redeclaration) { 201 unsigned IDNS = 0; 202 switch (NameKind) { 203 case Sema::LookupOrdinaryName: 204 case Sema::LookupRedeclarationWithLinkage: 205 IDNS = Decl::IDNS_Ordinary; 206 if (CPlusPlus) { 207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 209 } 210 break; 211 212 case Sema::LookupOperatorName: 213 // Operator lookup is its own crazy thing; it is not the same 214 // as (e.g.) looking up an operator name for redeclaration. 215 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 216 IDNS = Decl::IDNS_NonMemberOperator; 217 break; 218 219 case Sema::LookupTagName: 220 if (CPlusPlus) { 221 IDNS = Decl::IDNS_Type; 222 223 // When looking for a redeclaration of a tag name, we add: 224 // 1) TagFriend to find undeclared friend decls 225 // 2) Namespace because they can't "overload" with tag decls. 226 // 3) Tag because it includes class templates, which can't 227 // "overload" with tag decls. 228 if (Redeclaration) 229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 230 } else { 231 IDNS = Decl::IDNS_Tag; 232 } 233 break; 234 235 case Sema::LookupMemberName: 236 IDNS = Decl::IDNS_Member; 237 if (CPlusPlus) 238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 239 break; 240 241 case Sema::LookupNestedNameSpecifierName: 242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 243 break; 244 245 case Sema::LookupNamespaceName: 246 IDNS = Decl::IDNS_Namespace; 247 break; 248 249 case Sema::LookupUsingDeclName: 250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag 251 | Decl::IDNS_Member | Decl::IDNS_Using; 252 break; 253 254 case Sema::LookupObjCProtocolName: 255 IDNS = Decl::IDNS_ObjCProtocol; 256 break; 257 } 258 return IDNS; 259} 260 261void LookupResult::configure() { 262 IDNS = getIDNS(LookupKind, 263 SemaRef.getLangOptions().CPlusPlus, 264 isForRedeclaration()); 265 266 // If we're looking for one of the allocation or deallocation 267 // operators, make sure that the implicitly-declared new and delete 268 // operators can be found. 269 if (!isForRedeclaration()) { 270 switch (Name.getCXXOverloadedOperator()) { 271 case OO_New: 272 case OO_Delete: 273 case OO_Array_New: 274 case OO_Array_Delete: 275 SemaRef.DeclareGlobalNewDelete(); 276 break; 277 278 default: 279 break; 280 } 281 } 282} 283 284// Necessary because CXXBasePaths is not complete in Sema.h 285void LookupResult::deletePaths(CXXBasePaths *Paths) { 286 delete Paths; 287} 288 289/// Resolves the result kind of this lookup. 290void LookupResult::resolveKind() { 291 unsigned N = Decls.size(); 292 293 // Fast case: no possible ambiguity. 294 if (N == 0) { 295 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation); 296 return; 297 } 298 299 // If there's a single decl, we need to examine it to decide what 300 // kind of lookup this is. 301 if (N == 1) { 302 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); 303 if (isa<FunctionTemplateDecl>(D)) 304 ResultKind = FoundOverloaded; 305 else if (isa<UnresolvedUsingValueDecl>(D)) 306 ResultKind = FoundUnresolvedValue; 307 return; 308 } 309 310 // Don't do any extra resolution if we've already resolved as ambiguous. 311 if (ResultKind == Ambiguous) return; 312 313 llvm::SmallPtrSet<NamedDecl*, 16> Unique; 314 315 bool Ambiguous = false; 316 bool HasTag = false, HasFunction = false, HasNonFunction = false; 317 bool HasFunctionTemplate = false, HasUnresolved = false; 318 319 unsigned UniqueTagIndex = 0; 320 321 unsigned I = 0; 322 while (I < N) { 323 NamedDecl *D = Decls[I]->getUnderlyingDecl(); 324 D = cast<NamedDecl>(D->getCanonicalDecl()); 325 326 if (!Unique.insert(D)) { 327 // If it's not unique, pull something off the back (and 328 // continue at this index). 329 Decls[I] = Decls[--N]; 330 } else { 331 // Otherwise, do some decl type analysis and then continue. 332 333 if (isa<UnresolvedUsingValueDecl>(D)) { 334 HasUnresolved = true; 335 } else if (isa<TagDecl>(D)) { 336 if (HasTag) 337 Ambiguous = true; 338 UniqueTagIndex = I; 339 HasTag = true; 340 } else if (isa<FunctionTemplateDecl>(D)) { 341 HasFunction = true; 342 HasFunctionTemplate = true; 343 } else if (isa<FunctionDecl>(D)) { 344 HasFunction = true; 345 } else { 346 if (HasNonFunction) 347 Ambiguous = true; 348 HasNonFunction = true; 349 } 350 I++; 351 } 352 } 353 354 // C++ [basic.scope.hiding]p2: 355 // A class name or enumeration name can be hidden by the name of 356 // an object, function, or enumerator declared in the same 357 // scope. If a class or enumeration name and an object, function, 358 // or enumerator are declared in the same scope (in any order) 359 // with the same name, the class or enumeration name is hidden 360 // wherever the object, function, or enumerator name is visible. 361 // But it's still an error if there are distinct tag types found, 362 // even if they're not visible. (ref?) 363 if (HideTags && HasTag && !Ambiguous && 364 (HasFunction || HasNonFunction || HasUnresolved)) 365 Decls[UniqueTagIndex] = Decls[--N]; 366 367 Decls.set_size(N); 368 369 if (HasNonFunction && (HasFunction || HasUnresolved)) 370 Ambiguous = true; 371 372 if (Ambiguous) 373 setAmbiguous(LookupResult::AmbiguousReference); 374 else if (HasUnresolved) 375 ResultKind = LookupResult::FoundUnresolvedValue; 376 else if (N > 1 || HasFunctionTemplate) 377 ResultKind = LookupResult::FoundOverloaded; 378 else 379 ResultKind = LookupResult::Found; 380} 381 382void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { 383 CXXBasePaths::const_paths_iterator I, E; 384 DeclContext::lookup_iterator DI, DE; 385 for (I = P.begin(), E = P.end(); I != E; ++I) 386 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI) 387 addDecl(*DI); 388} 389 390void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 391 Paths = new CXXBasePaths; 392 Paths->swap(P); 393 addDeclsFromBasePaths(*Paths); 394 resolveKind(); 395 setAmbiguous(AmbiguousBaseSubobjects); 396} 397 398void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 399 Paths = new CXXBasePaths; 400 Paths->swap(P); 401 addDeclsFromBasePaths(*Paths); 402 resolveKind(); 403 setAmbiguous(AmbiguousBaseSubobjectTypes); 404} 405 406void LookupResult::print(llvm::raw_ostream &Out) { 407 Out << Decls.size() << " result(s)"; 408 if (isAmbiguous()) Out << ", ambiguous"; 409 if (Paths) Out << ", base paths present"; 410 411 for (iterator I = begin(), E = end(); I != E; ++I) { 412 Out << "\n"; 413 (*I)->print(Out, 2); 414 } 415} 416 417/// \brief Lookup a builtin function, when name lookup would otherwise 418/// fail. 419static bool LookupBuiltin(Sema &S, LookupResult &R) { 420 Sema::LookupNameKind NameKind = R.getLookupKind(); 421 422 // If we didn't find a use of this identifier, and if the identifier 423 // corresponds to a compiler builtin, create the decl object for the builtin 424 // now, injecting it into translation unit scope, and return it. 425 if (NameKind == Sema::LookupOrdinaryName || 426 NameKind == Sema::LookupRedeclarationWithLinkage) { 427 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); 428 if (II) { 429 // If this is a builtin on this (or all) targets, create the decl. 430 if (unsigned BuiltinID = II->getBuiltinID()) { 431 // In C++, we don't have any predefined library functions like 432 // 'malloc'. Instead, we'll just error. 433 if (S.getLangOptions().CPlusPlus && 434 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 435 return false; 436 437 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 438 S.TUScope, R.isForRedeclaration(), 439 R.getNameLoc()); 440 if (D) 441 R.addDecl(D); 442 return (D != NULL); 443 } 444 } 445 } 446 447 return false; 448} 449 450/// \brief Determine whether we can declare a special member function within 451/// the class at this point. 452static bool CanDeclareSpecialMemberFunction(ASTContext &Context, 453 const CXXRecordDecl *Class) { 454 // We need to have a definition for the class. 455 if (!Class->getDefinition() || Class->isDependentContext()) 456 return false; 457 458 // We can't be in the middle of defining the class. 459 if (const RecordType *RecordTy 460 = Context.getTypeDeclType(Class)->getAs<RecordType>()) 461 return !RecordTy->isBeingDefined(); 462 463 return false; 464} 465 466void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { 467 if (!CanDeclareSpecialMemberFunction(Context, Class)) 468 return; 469 470 // If the copy constructor has not yet been declared, do so now. 471 if (!Class->hasDeclaredCopyConstructor()) 472 DeclareImplicitCopyConstructor(Class); 473 474 // If the copy assignment operator has not yet been declared, do so now. 475 if (!Class->hasDeclaredCopyAssignment()) 476 DeclareImplicitCopyAssignment(Class); 477 478 // If the destructor has not yet been declared, do so now. 479 if (!Class->hasDeclaredDestructor()) 480 DeclareImplicitDestructor(Class); 481} 482 483/// \brief Determine whether this is the name of an implicitly-declared 484/// special member function. 485static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { 486 switch (Name.getNameKind()) { 487 case DeclarationName::CXXConstructorName: 488 case DeclarationName::CXXDestructorName: 489 return true; 490 491 case DeclarationName::CXXOperatorName: 492 return Name.getCXXOverloadedOperator() == OO_Equal; 493 494 default: 495 break; 496 } 497 498 return false; 499} 500 501/// \brief If there are any implicit member functions with the given name 502/// that need to be declared in the given declaration context, do so. 503static void DeclareImplicitMemberFunctionsWithName(Sema &S, 504 DeclarationName Name, 505 const DeclContext *DC) { 506 if (!DC) 507 return; 508 509 switch (Name.getNameKind()) { 510 case DeclarationName::CXXConstructorName: 511 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 512 if (Record->getDefinition() && !Record->hasDeclaredCopyConstructor() && 513 CanDeclareSpecialMemberFunction(S.Context, Record)) 514 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record)); 515 break; 516 517 case DeclarationName::CXXDestructorName: 518 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 519 if (Record->getDefinition() && !Record->hasDeclaredDestructor() && 520 CanDeclareSpecialMemberFunction(S.Context, Record)) 521 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); 522 break; 523 524 case DeclarationName::CXXOperatorName: 525 if (Name.getCXXOverloadedOperator() != OO_Equal) 526 break; 527 528 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 529 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() && 530 CanDeclareSpecialMemberFunction(S.Context, Record)) 531 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record)); 532 break; 533 534 default: 535 break; 536 } 537} 538 539// Adds all qualifying matches for a name within a decl context to the 540// given lookup result. Returns true if any matches were found. 541static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { 542 bool Found = false; 543 544 // Lazily declare C++ special member functions. 545 if (S.getLangOptions().CPlusPlus) 546 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC); 547 548 // Perform lookup into this declaration context. 549 DeclContext::lookup_const_iterator I, E; 550 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) { 551 NamedDecl *D = *I; 552 if (R.isAcceptableDecl(D)) { 553 R.addDecl(D); 554 Found = true; 555 } 556 } 557 558 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R)) 559 return true; 560 561 if (R.getLookupName().getNameKind() 562 != DeclarationName::CXXConversionFunctionName || 563 R.getLookupName().getCXXNameType()->isDependentType() || 564 !isa<CXXRecordDecl>(DC)) 565 return Found; 566 567 // C++ [temp.mem]p6: 568 // A specialization of a conversion function template is not found by 569 // name lookup. Instead, any conversion function templates visible in the 570 // context of the use are considered. [...] 571 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 572 if (!Record->isDefinition()) 573 return Found; 574 575 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions(); 576 for (UnresolvedSetImpl::iterator U = Unresolved->begin(), 577 UEnd = Unresolved->end(); U != UEnd; ++U) { 578 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); 579 if (!ConvTemplate) 580 continue; 581 582 // When we're performing lookup for the purposes of redeclaration, just 583 // add the conversion function template. When we deduce template 584 // arguments for specializations, we'll end up unifying the return 585 // type of the new declaration with the type of the function template. 586 if (R.isForRedeclaration()) { 587 R.addDecl(ConvTemplate); 588 Found = true; 589 continue; 590 } 591 592 // C++ [temp.mem]p6: 593 // [...] For each such operator, if argument deduction succeeds 594 // (14.9.2.3), the resulting specialization is used as if found by 595 // name lookup. 596 // 597 // When referencing a conversion function for any purpose other than 598 // a redeclaration (such that we'll be building an expression with the 599 // result), perform template argument deduction and place the 600 // specialization into the result set. We do this to avoid forcing all 601 // callers to perform special deduction for conversion functions. 602 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc()); 603 FunctionDecl *Specialization = 0; 604 605 const FunctionProtoType *ConvProto 606 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); 607 assert(ConvProto && "Nonsensical conversion function template type"); 608 609 // Compute the type of the function that we would expect the conversion 610 // function to have, if it were to match the name given. 611 // FIXME: Calling convention! 612 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo(); 613 QualType ExpectedType 614 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(), 615 0, 0, ConvProto->isVariadic(), 616 ConvProto->getTypeQuals(), 617 false, false, 0, 0, 618 ConvProtoInfo.withCallingConv(CC_Default)); 619 620 // Perform template argument deduction against the type that we would 621 // expect the function to have. 622 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType, 623 Specialization, Info) 624 == Sema::TDK_Success) { 625 R.addDecl(Specialization); 626 Found = true; 627 } 628 } 629 630 return Found; 631} 632 633// Performs C++ unqualified lookup into the given file context. 634static bool 635CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 636 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) { 637 638 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 639 640 // Perform direct name lookup into the LookupCtx. 641 bool Found = LookupDirect(S, R, NS); 642 643 // Perform direct name lookup into the namespaces nominated by the 644 // using directives whose common ancestor is this namespace. 645 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 646 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS); 647 648 for (; UI != UEnd; ++UI) 649 if (LookupDirect(S, R, UI->getNominatedNamespace())) 650 Found = true; 651 652 R.resolveKind(); 653 654 return Found; 655} 656 657static bool isNamespaceOrTranslationUnitScope(Scope *S) { 658 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 659 return Ctx->isFileContext(); 660 return false; 661} 662 663// Find the next outer declaration context from this scope. This 664// routine actually returns the semantic outer context, which may 665// differ from the lexical context (encoded directly in the Scope 666// stack) when we are parsing a member of a class template. In this 667// case, the second element of the pair will be true, to indicate that 668// name lookup should continue searching in this semantic context when 669// it leaves the current template parameter scope. 670static std::pair<DeclContext *, bool> findOuterContext(Scope *S) { 671 DeclContext *DC = static_cast<DeclContext *>(S->getEntity()); 672 DeclContext *Lexical = 0; 673 for (Scope *OuterS = S->getParent(); OuterS; 674 OuterS = OuterS->getParent()) { 675 if (OuterS->getEntity()) { 676 Lexical = static_cast<DeclContext *>(OuterS->getEntity()); 677 break; 678 } 679 } 680 681 // C++ [temp.local]p8: 682 // In the definition of a member of a class template that appears 683 // outside of the namespace containing the class template 684 // definition, the name of a template-parameter hides the name of 685 // a member of this namespace. 686 // 687 // Example: 688 // 689 // namespace N { 690 // class C { }; 691 // 692 // template<class T> class B { 693 // void f(T); 694 // }; 695 // } 696 // 697 // template<class C> void N::B<C>::f(C) { 698 // C b; // C is the template parameter, not N::C 699 // } 700 // 701 // In this example, the lexical context we return is the 702 // TranslationUnit, while the semantic context is the namespace N. 703 if (!Lexical || !DC || !S->getParent() || 704 !S->getParent()->isTemplateParamScope()) 705 return std::make_pair(Lexical, false); 706 707 // Find the outermost template parameter scope. 708 // For the example, this is the scope for the template parameters of 709 // template<class C>. 710 Scope *OutermostTemplateScope = S->getParent(); 711 while (OutermostTemplateScope->getParent() && 712 OutermostTemplateScope->getParent()->isTemplateParamScope()) 713 OutermostTemplateScope = OutermostTemplateScope->getParent(); 714 715 // Find the namespace context in which the original scope occurs. In 716 // the example, this is namespace N. 717 DeclContext *Semantic = DC; 718 while (!Semantic->isFileContext()) 719 Semantic = Semantic->getParent(); 720 721 // Find the declaration context just outside of the template 722 // parameter scope. This is the context in which the template is 723 // being lexically declaration (a namespace context). In the 724 // example, this is the global scope. 725 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) && 726 Lexical->Encloses(Semantic)) 727 return std::make_pair(Semantic, true); 728 729 return std::make_pair(Lexical, false); 730} 731 732bool Sema::CppLookupName(LookupResult &R, Scope *S) { 733 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup"); 734 735 DeclarationName Name = R.getLookupName(); 736 737 // If this is the name of an implicitly-declared special member function, 738 // go through the scope stack to implicitly declare 739 if (isImplicitlyDeclaredMemberFunctionName(Name)) { 740 for (Scope *PreS = S; PreS; PreS = PreS->getParent()) 741 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity())) 742 DeclareImplicitMemberFunctionsWithName(*this, Name, DC); 743 } 744 745 // Implicitly declare member functions with the name we're looking for, if in 746 // fact we are in a scope where it matters. 747 748 Scope *Initial = S; 749 IdentifierResolver::iterator 750 I = IdResolver.begin(Name), 751 IEnd = IdResolver.end(); 752 753 // First we lookup local scope. 754 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 755 // ...During unqualified name lookup (3.4.1), the names appear as if 756 // they were declared in the nearest enclosing namespace which contains 757 // both the using-directive and the nominated namespace. 758 // [Note: in this context, "contains" means "contains directly or 759 // indirectly". 760 // 761 // For example: 762 // namespace A { int i; } 763 // void foo() { 764 // int i; 765 // { 766 // using namespace A; 767 // ++i; // finds local 'i', A::i appears at global scope 768 // } 769 // } 770 // 771 DeclContext *OutsideOfTemplateParamDC = 0; 772 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 773 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 774 775 // Check whether the IdResolver has anything in this scope. 776 bool Found = false; 777 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) { 778 if (R.isAcceptableDecl(*I)) { 779 Found = true; 780 R.addDecl(*I); 781 } 782 } 783 if (Found) { 784 R.resolveKind(); 785 if (S->isClassScope()) 786 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 787 R.setNamingClass(Record); 788 return true; 789 } 790 791 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 792 S->getParent() && !S->getParent()->isTemplateParamScope()) { 793 // We've just searched the last template parameter scope and 794 // found nothing, so look into the the contexts between the 795 // lexical and semantic declaration contexts returned by 796 // findOuterContext(). This implements the name lookup behavior 797 // of C++ [temp.local]p8. 798 Ctx = OutsideOfTemplateParamDC; 799 OutsideOfTemplateParamDC = 0; 800 } 801 802 if (Ctx) { 803 DeclContext *OuterCtx; 804 bool SearchAfterTemplateScope; 805 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 806 if (SearchAfterTemplateScope) 807 OutsideOfTemplateParamDC = OuterCtx; 808 809 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 810 // We do not directly look into transparent contexts, since 811 // those entities will be found in the nearest enclosing 812 // non-transparent context. 813 if (Ctx->isTransparentContext()) 814 continue; 815 816 // We do not look directly into function or method contexts, 817 // since all of the local variables and parameters of the 818 // function/method are present within the Scope. 819 if (Ctx->isFunctionOrMethod()) { 820 // If we have an Objective-C instance method, look for ivars 821 // in the corresponding interface. 822 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 823 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) 824 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { 825 ObjCInterfaceDecl *ClassDeclared; 826 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( 827 Name.getAsIdentifierInfo(), 828 ClassDeclared)) { 829 if (R.isAcceptableDecl(Ivar)) { 830 R.addDecl(Ivar); 831 R.resolveKind(); 832 return true; 833 } 834 } 835 } 836 } 837 838 continue; 839 } 840 841 // Perform qualified name lookup into this context. 842 // FIXME: In some cases, we know that every name that could be found by 843 // this qualified name lookup will also be on the identifier chain. For 844 // example, inside a class without any base classes, we never need to 845 // perform qualified lookup because all of the members are on top of the 846 // identifier chain. 847 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) 848 return true; 849 } 850 } 851 } 852 853 // Stop if we ran out of scopes. 854 // FIXME: This really, really shouldn't be happening. 855 if (!S) return false; 856 857 // Collect UsingDirectiveDecls in all scopes, and recursively all 858 // nominated namespaces by those using-directives. 859 // 860 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 861 // don't build it for each lookup! 862 863 UnqualUsingDirectiveSet UDirs; 864 UDirs.visitScopeChain(Initial, S); 865 UDirs.done(); 866 867 // Lookup namespace scope, and global scope. 868 // Unqualified name lookup in C++ requires looking into scopes 869 // that aren't strictly lexical, and therefore we walk through the 870 // context as well as walking through the scopes. 871 872 for (; S; S = S->getParent()) { 873 // Check whether the IdResolver has anything in this scope. 874 bool Found = false; 875 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) { 876 if (R.isAcceptableDecl(*I)) { 877 // We found something. Look for anything else in our scope 878 // with this same name and in an acceptable identifier 879 // namespace, so that we can construct an overload set if we 880 // need to. 881 Found = true; 882 R.addDecl(*I); 883 } 884 } 885 886 if (Found && S->isTemplateParamScope()) { 887 R.resolveKind(); 888 return true; 889 } 890 891 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 892 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 893 S->getParent() && !S->getParent()->isTemplateParamScope()) { 894 // We've just searched the last template parameter scope and 895 // found nothing, so look into the the contexts between the 896 // lexical and semantic declaration contexts returned by 897 // findOuterContext(). This implements the name lookup behavior 898 // of C++ [temp.local]p8. 899 Ctx = OutsideOfTemplateParamDC; 900 OutsideOfTemplateParamDC = 0; 901 } 902 903 if (Ctx) { 904 DeclContext *OuterCtx; 905 bool SearchAfterTemplateScope; 906 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 907 if (SearchAfterTemplateScope) 908 OutsideOfTemplateParamDC = OuterCtx; 909 910 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 911 // We do not directly look into transparent contexts, since 912 // those entities will be found in the nearest enclosing 913 // non-transparent context. 914 if (Ctx->isTransparentContext()) 915 continue; 916 917 // If we have a context, and it's not a context stashed in the 918 // template parameter scope for an out-of-line definition, also 919 // look into that context. 920 if (!(Found && S && S->isTemplateParamScope())) { 921 assert(Ctx->isFileContext() && 922 "We should have been looking only at file context here already."); 923 924 // Look into context considering using-directives. 925 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) 926 Found = true; 927 } 928 929 if (Found) { 930 R.resolveKind(); 931 return true; 932 } 933 934 if (R.isForRedeclaration() && !Ctx->isTransparentContext()) 935 return false; 936 } 937 } 938 939 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) 940 return false; 941 } 942 943 return !R.empty(); 944} 945 946/// @brief Perform unqualified name lookup starting from a given 947/// scope. 948/// 949/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 950/// used to find names within the current scope. For example, 'x' in 951/// @code 952/// int x; 953/// int f() { 954/// return x; // unqualified name look finds 'x' in the global scope 955/// } 956/// @endcode 957/// 958/// Different lookup criteria can find different names. For example, a 959/// particular scope can have both a struct and a function of the same 960/// name, and each can be found by certain lookup criteria. For more 961/// information about lookup criteria, see the documentation for the 962/// class LookupCriteria. 963/// 964/// @param S The scope from which unqualified name lookup will 965/// begin. If the lookup criteria permits, name lookup may also search 966/// in the parent scopes. 967/// 968/// @param Name The name of the entity that we are searching for. 969/// 970/// @param Loc If provided, the source location where we're performing 971/// name lookup. At present, this is only used to produce diagnostics when 972/// C library functions (like "malloc") are implicitly declared. 973/// 974/// @returns The result of name lookup, which includes zero or more 975/// declarations and possibly additional information used to diagnose 976/// ambiguities. 977bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { 978 DeclarationName Name = R.getLookupName(); 979 if (!Name) return false; 980 981 LookupNameKind NameKind = R.getLookupKind(); 982 983 if (!getLangOptions().CPlusPlus) { 984 // Unqualified name lookup in C/Objective-C is purely lexical, so 985 // search in the declarations attached to the name. 986 987 if (NameKind == Sema::LookupRedeclarationWithLinkage) { 988 // Find the nearest non-transparent declaration scope. 989 while (!(S->getFlags() & Scope::DeclScope) || 990 (S->getEntity() && 991 static_cast<DeclContext *>(S->getEntity()) 992 ->isTransparentContext())) 993 S = S->getParent(); 994 } 995 996 unsigned IDNS = R.getIdentifierNamespace(); 997 998 // Scan up the scope chain looking for a decl that matches this 999 // identifier that is in the appropriate namespace. This search 1000 // should not take long, as shadowing of names is uncommon, and 1001 // deep shadowing is extremely uncommon. 1002 bool LeftStartingScope = false; 1003 1004 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 1005 IEnd = IdResolver.end(); 1006 I != IEnd; ++I) 1007 if ((*I)->isInIdentifierNamespace(IDNS)) { 1008 if (NameKind == LookupRedeclarationWithLinkage) { 1009 // Determine whether this (or a previous) declaration is 1010 // out-of-scope. 1011 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I))) 1012 LeftStartingScope = true; 1013 1014 // If we found something outside of our starting scope that 1015 // does not have linkage, skip it. 1016 if (LeftStartingScope && !((*I)->hasLinkage())) 1017 continue; 1018 } 1019 1020 R.addDecl(*I); 1021 1022 if ((*I)->getAttr<OverloadableAttr>()) { 1023 // If this declaration has the "overloadable" attribute, we 1024 // might have a set of overloaded functions. 1025 1026 // Figure out what scope the identifier is in. 1027 while (!(S->getFlags() & Scope::DeclScope) || 1028 !S->isDeclScope(DeclPtrTy::make(*I))) 1029 S = S->getParent(); 1030 1031 // Find the last declaration in this scope (with the same 1032 // name, naturally). 1033 IdentifierResolver::iterator LastI = I; 1034 for (++LastI; LastI != IEnd; ++LastI) { 1035 if (!S->isDeclScope(DeclPtrTy::make(*LastI))) 1036 break; 1037 R.addDecl(*LastI); 1038 } 1039 } 1040 1041 R.resolveKind(); 1042 1043 return true; 1044 } 1045 } else { 1046 // Perform C++ unqualified name lookup. 1047 if (CppLookupName(R, S)) 1048 return true; 1049 } 1050 1051 // If we didn't find a use of this identifier, and if the identifier 1052 // corresponds to a compiler builtin, create the decl object for the builtin 1053 // now, injecting it into translation unit scope, and return it. 1054 if (AllowBuiltinCreation) 1055 return LookupBuiltin(*this, R); 1056 1057 return false; 1058} 1059 1060/// @brief Perform qualified name lookup in the namespaces nominated by 1061/// using directives by the given context. 1062/// 1063/// C++98 [namespace.qual]p2: 1064/// Given X::m (where X is a user-declared namespace), or given ::m 1065/// (where X is the global namespace), let S be the set of all 1066/// declarations of m in X and in the transitive closure of all 1067/// namespaces nominated by using-directives in X and its used 1068/// namespaces, except that using-directives are ignored in any 1069/// namespace, including X, directly containing one or more 1070/// declarations of m. No namespace is searched more than once in 1071/// the lookup of a name. If S is the empty set, the program is 1072/// ill-formed. Otherwise, if S has exactly one member, or if the 1073/// context of the reference is a using-declaration 1074/// (namespace.udecl), S is the required set of declarations of 1075/// m. Otherwise if the use of m is not one that allows a unique 1076/// declaration to be chosen from S, the program is ill-formed. 1077/// C++98 [namespace.qual]p5: 1078/// During the lookup of a qualified namespace member name, if the 1079/// lookup finds more than one declaration of the member, and if one 1080/// declaration introduces a class name or enumeration name and the 1081/// other declarations either introduce the same object, the same 1082/// enumerator or a set of functions, the non-type name hides the 1083/// class or enumeration name if and only if the declarations are 1084/// from the same namespace; otherwise (the declarations are from 1085/// different namespaces), the program is ill-formed. 1086static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, 1087 DeclContext *StartDC) { 1088 assert(StartDC->isFileContext() && "start context is not a file context"); 1089 1090 DeclContext::udir_iterator I = StartDC->using_directives_begin(); 1091 DeclContext::udir_iterator E = StartDC->using_directives_end(); 1092 1093 if (I == E) return false; 1094 1095 // We have at least added all these contexts to the queue. 1096 llvm::DenseSet<DeclContext*> Visited; 1097 Visited.insert(StartDC); 1098 1099 // We have not yet looked into these namespaces, much less added 1100 // their "using-children" to the queue. 1101 llvm::SmallVector<NamespaceDecl*, 8> Queue; 1102 1103 // We have already looked into the initial namespace; seed the queue 1104 // with its using-children. 1105 for (; I != E; ++I) { 1106 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace(); 1107 if (Visited.insert(ND).second) 1108 Queue.push_back(ND); 1109 } 1110 1111 // The easiest way to implement the restriction in [namespace.qual]p5 1112 // is to check whether any of the individual results found a tag 1113 // and, if so, to declare an ambiguity if the final result is not 1114 // a tag. 1115 bool FoundTag = false; 1116 bool FoundNonTag = false; 1117 1118 LookupResult LocalR(LookupResult::Temporary, R); 1119 1120 bool Found = false; 1121 while (!Queue.empty()) { 1122 NamespaceDecl *ND = Queue.back(); 1123 Queue.pop_back(); 1124 1125 // We go through some convolutions here to avoid copying results 1126 // between LookupResults. 1127 bool UseLocal = !R.empty(); 1128 LookupResult &DirectR = UseLocal ? LocalR : R; 1129 bool FoundDirect = LookupDirect(S, DirectR, ND); 1130 1131 if (FoundDirect) { 1132 // First do any local hiding. 1133 DirectR.resolveKind(); 1134 1135 // If the local result is a tag, remember that. 1136 if (DirectR.isSingleTagDecl()) 1137 FoundTag = true; 1138 else 1139 FoundNonTag = true; 1140 1141 // Append the local results to the total results if necessary. 1142 if (UseLocal) { 1143 R.addAllDecls(LocalR); 1144 LocalR.clear(); 1145 } 1146 } 1147 1148 // If we find names in this namespace, ignore its using directives. 1149 if (FoundDirect) { 1150 Found = true; 1151 continue; 1152 } 1153 1154 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) { 1155 NamespaceDecl *Nom = (*I)->getNominatedNamespace(); 1156 if (Visited.insert(Nom).second) 1157 Queue.push_back(Nom); 1158 } 1159 } 1160 1161 if (Found) { 1162 if (FoundTag && FoundNonTag) 1163 R.setAmbiguousQualifiedTagHiding(); 1164 else 1165 R.resolveKind(); 1166 } 1167 1168 return Found; 1169} 1170 1171/// \brief Perform qualified name lookup into a given context. 1172/// 1173/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 1174/// names when the context of those names is explicit specified, e.g., 1175/// "std::vector" or "x->member", or as part of unqualified name lookup. 1176/// 1177/// Different lookup criteria can find different names. For example, a 1178/// particular scope can have both a struct and a function of the same 1179/// name, and each can be found by certain lookup criteria. For more 1180/// information about lookup criteria, see the documentation for the 1181/// class LookupCriteria. 1182/// 1183/// \param R captures both the lookup criteria and any lookup results found. 1184/// 1185/// \param LookupCtx The context in which qualified name lookup will 1186/// search. If the lookup criteria permits, name lookup may also search 1187/// in the parent contexts or (for C++ classes) base classes. 1188/// 1189/// \param InUnqualifiedLookup true if this is qualified name lookup that 1190/// occurs as part of unqualified name lookup. 1191/// 1192/// \returns true if lookup succeeded, false if it failed. 1193bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1194 bool InUnqualifiedLookup) { 1195 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 1196 1197 if (!R.getLookupName()) 1198 return false; 1199 1200 // Make sure that the declaration context is complete. 1201 assert((!isa<TagDecl>(LookupCtx) || 1202 LookupCtx->isDependentContext() || 1203 cast<TagDecl>(LookupCtx)->isDefinition() || 1204 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>() 1205 ->isBeingDefined()) && 1206 "Declaration context must already be complete!"); 1207 1208 // Perform qualified name lookup into the LookupCtx. 1209 if (LookupDirect(*this, R, LookupCtx)) { 1210 R.resolveKind(); 1211 if (isa<CXXRecordDecl>(LookupCtx)) 1212 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 1213 return true; 1214 } 1215 1216 // Don't descend into implied contexts for redeclarations. 1217 // C++98 [namespace.qual]p6: 1218 // In a declaration for a namespace member in which the 1219 // declarator-id is a qualified-id, given that the qualified-id 1220 // for the namespace member has the form 1221 // nested-name-specifier unqualified-id 1222 // the unqualified-id shall name a member of the namespace 1223 // designated by the nested-name-specifier. 1224 // See also [class.mfct]p5 and [class.static.data]p2. 1225 if (R.isForRedeclaration()) 1226 return false; 1227 1228 // If this is a namespace, look it up in the implied namespaces. 1229 if (LookupCtx->isFileContext()) 1230 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 1231 1232 // If this isn't a C++ class, we aren't allowed to look into base 1233 // classes, we're done. 1234 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 1235 if (!LookupRec || !LookupRec->getDefinition()) 1236 return false; 1237 1238 // If we're performing qualified name lookup into a dependent class, 1239 // then we are actually looking into a current instantiation. If we have any 1240 // dependent base classes, then we either have to delay lookup until 1241 // template instantiation time (at which point all bases will be available) 1242 // or we have to fail. 1243 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 1244 LookupRec->hasAnyDependentBases()) { 1245 R.setNotFoundInCurrentInstantiation(); 1246 return false; 1247 } 1248 1249 // Perform lookup into our base classes. 1250 CXXBasePaths Paths; 1251 Paths.setOrigin(LookupRec); 1252 1253 // Look for this member in our base classes 1254 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0; 1255 switch (R.getLookupKind()) { 1256 case LookupOrdinaryName: 1257 case LookupMemberName: 1258 case LookupRedeclarationWithLinkage: 1259 BaseCallback = &CXXRecordDecl::FindOrdinaryMember; 1260 break; 1261 1262 case LookupTagName: 1263 BaseCallback = &CXXRecordDecl::FindTagMember; 1264 break; 1265 1266 case LookupUsingDeclName: 1267 // This lookup is for redeclarations only. 1268 1269 case LookupOperatorName: 1270 case LookupNamespaceName: 1271 case LookupObjCProtocolName: 1272 // These lookups will never find a member in a C++ class (or base class). 1273 return false; 1274 1275 case LookupNestedNameSpecifierName: 1276 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; 1277 break; 1278 } 1279 1280 if (!LookupRec->lookupInBases(BaseCallback, 1281 R.getLookupName().getAsOpaquePtr(), Paths)) 1282 return false; 1283 1284 R.setNamingClass(LookupRec); 1285 1286 // C++ [class.member.lookup]p2: 1287 // [...] If the resulting set of declarations are not all from 1288 // sub-objects of the same type, or the set has a nonstatic member 1289 // and includes members from distinct sub-objects, there is an 1290 // ambiguity and the program is ill-formed. Otherwise that set is 1291 // the result of the lookup. 1292 // FIXME: support using declarations! 1293 QualType SubobjectType; 1294 int SubobjectNumber = 0; 1295 AccessSpecifier SubobjectAccess = AS_none; 1296 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 1297 Path != PathEnd; ++Path) { 1298 const CXXBasePathElement &PathElement = Path->back(); 1299 1300 // Pick the best (i.e. most permissive i.e. numerically lowest) access 1301 // across all paths. 1302 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 1303 1304 // Determine whether we're looking at a distinct sub-object or not. 1305 if (SubobjectType.isNull()) { 1306 // This is the first subobject we've looked at. Record its type. 1307 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 1308 SubobjectNumber = PathElement.SubobjectNumber; 1309 } else if (SubobjectType 1310 != Context.getCanonicalType(PathElement.Base->getType())) { 1311 // We found members of the given name in two subobjects of 1312 // different types. This lookup is ambiguous. 1313 R.setAmbiguousBaseSubobjectTypes(Paths); 1314 return true; 1315 } else if (SubobjectNumber != PathElement.SubobjectNumber) { 1316 // We have a different subobject of the same type. 1317 1318 // C++ [class.member.lookup]p5: 1319 // A static member, a nested type or an enumerator defined in 1320 // a base class T can unambiguously be found even if an object 1321 // has more than one base class subobject of type T. 1322 Decl *FirstDecl = *Path->Decls.first; 1323 if (isa<VarDecl>(FirstDecl) || 1324 isa<TypeDecl>(FirstDecl) || 1325 isa<EnumConstantDecl>(FirstDecl)) 1326 continue; 1327 1328 if (isa<CXXMethodDecl>(FirstDecl)) { 1329 // Determine whether all of the methods are static. 1330 bool AllMethodsAreStatic = true; 1331 for (DeclContext::lookup_iterator Func = Path->Decls.first; 1332 Func != Path->Decls.second; ++Func) { 1333 if (!isa<CXXMethodDecl>(*Func)) { 1334 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl"); 1335 break; 1336 } 1337 1338 if (!cast<CXXMethodDecl>(*Func)->isStatic()) { 1339 AllMethodsAreStatic = false; 1340 break; 1341 } 1342 } 1343 1344 if (AllMethodsAreStatic) 1345 continue; 1346 } 1347 1348 // We have found a nonstatic member name in multiple, distinct 1349 // subobjects. Name lookup is ambiguous. 1350 R.setAmbiguousBaseSubobjects(Paths); 1351 return true; 1352 } 1353 } 1354 1355 // Lookup in a base class succeeded; return these results. 1356 1357 DeclContext::lookup_iterator I, E; 1358 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) { 1359 NamedDecl *D = *I; 1360 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 1361 D->getAccess()); 1362 R.addDecl(D, AS); 1363 } 1364 R.resolveKind(); 1365 return true; 1366} 1367 1368/// @brief Performs name lookup for a name that was parsed in the 1369/// source code, and may contain a C++ scope specifier. 1370/// 1371/// This routine is a convenience routine meant to be called from 1372/// contexts that receive a name and an optional C++ scope specifier 1373/// (e.g., "N::M::x"). It will then perform either qualified or 1374/// unqualified name lookup (with LookupQualifiedName or LookupName, 1375/// respectively) on the given name and return those results. 1376/// 1377/// @param S The scope from which unqualified name lookup will 1378/// begin. 1379/// 1380/// @param SS An optional C++ scope-specifier, e.g., "::N::M". 1381/// 1382/// @param Name The name of the entity that name lookup will 1383/// search for. 1384/// 1385/// @param Loc If provided, the source location where we're performing 1386/// name lookup. At present, this is only used to produce diagnostics when 1387/// C library functions (like "malloc") are implicitly declared. 1388/// 1389/// @param EnteringContext Indicates whether we are going to enter the 1390/// context of the scope-specifier SS (if present). 1391/// 1392/// @returns True if any decls were found (but possibly ambiguous) 1393bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1394 bool AllowBuiltinCreation, bool EnteringContext) { 1395 if (SS && SS->isInvalid()) { 1396 // When the scope specifier is invalid, don't even look for 1397 // anything. 1398 return false; 1399 } 1400 1401 if (SS && SS->isSet()) { 1402 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 1403 // We have resolved the scope specifier to a particular declaration 1404 // contex, and will perform name lookup in that context. 1405 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 1406 return false; 1407 1408 R.setContextRange(SS->getRange()); 1409 1410 return LookupQualifiedName(R, DC); 1411 } 1412 1413 // We could not resolve the scope specified to a specific declaration 1414 // context, which means that SS refers to an unknown specialization. 1415 // Name lookup can't find anything in this case. 1416 return false; 1417 } 1418 1419 // Perform unqualified name lookup starting in the given scope. 1420 return LookupName(R, S, AllowBuiltinCreation); 1421} 1422 1423 1424/// @brief Produce a diagnostic describing the ambiguity that resulted 1425/// from name lookup. 1426/// 1427/// @param Result The ambiguous name lookup result. 1428/// 1429/// @param Name The name of the entity that name lookup was 1430/// searching for. 1431/// 1432/// @param NameLoc The location of the name within the source code. 1433/// 1434/// @param LookupRange A source range that provides more 1435/// source-location information concerning the lookup itself. For 1436/// example, this range might highlight a nested-name-specifier that 1437/// precedes the name. 1438/// 1439/// @returns true 1440bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 1441 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1442 1443 DeclarationName Name = Result.getLookupName(); 1444 SourceLocation NameLoc = Result.getNameLoc(); 1445 SourceRange LookupRange = Result.getContextRange(); 1446 1447 switch (Result.getAmbiguityKind()) { 1448 case LookupResult::AmbiguousBaseSubobjects: { 1449 CXXBasePaths *Paths = Result.getBasePaths(); 1450 QualType SubobjectType = Paths->front().back().Base->getType(); 1451 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1452 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1453 << LookupRange; 1454 1455 DeclContext::lookup_iterator Found = Paths->front().Decls.first; 1456 while (isa<CXXMethodDecl>(*Found) && 1457 cast<CXXMethodDecl>(*Found)->isStatic()) 1458 ++Found; 1459 1460 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1461 1462 return true; 1463 } 1464 1465 case LookupResult::AmbiguousBaseSubobjectTypes: { 1466 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1467 << Name << LookupRange; 1468 1469 CXXBasePaths *Paths = Result.getBasePaths(); 1470 std::set<Decl *> DeclsPrinted; 1471 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 1472 PathEnd = Paths->end(); 1473 Path != PathEnd; ++Path) { 1474 Decl *D = *Path->Decls.first; 1475 if (DeclsPrinted.insert(D).second) 1476 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1477 } 1478 1479 return true; 1480 } 1481 1482 case LookupResult::AmbiguousTagHiding: { 1483 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 1484 1485 llvm::SmallPtrSet<NamedDecl*,8> TagDecls; 1486 1487 LookupResult::iterator DI, DE = Result.end(); 1488 for (DI = Result.begin(); DI != DE; ++DI) 1489 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) { 1490 TagDecls.insert(TD); 1491 Diag(TD->getLocation(), diag::note_hidden_tag); 1492 } 1493 1494 for (DI = Result.begin(); DI != DE; ++DI) 1495 if (!isa<TagDecl>(*DI)) 1496 Diag((*DI)->getLocation(), diag::note_hiding_object); 1497 1498 // For recovery purposes, go ahead and implement the hiding. 1499 LookupResult::Filter F = Result.makeFilter(); 1500 while (F.hasNext()) { 1501 if (TagDecls.count(F.next())) 1502 F.erase(); 1503 } 1504 F.done(); 1505 1506 return true; 1507 } 1508 1509 case LookupResult::AmbiguousReference: { 1510 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1511 1512 LookupResult::iterator DI = Result.begin(), DE = Result.end(); 1513 for (; DI != DE; ++DI) 1514 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1515 1516 return true; 1517 } 1518 } 1519 1520 llvm_unreachable("unknown ambiguity kind"); 1521 return true; 1522} 1523 1524namespace { 1525 struct AssociatedLookup { 1526 AssociatedLookup(Sema &S, 1527 Sema::AssociatedNamespaceSet &Namespaces, 1528 Sema::AssociatedClassSet &Classes) 1529 : S(S), Namespaces(Namespaces), Classes(Classes) { 1530 } 1531 1532 Sema &S; 1533 Sema::AssociatedNamespaceSet &Namespaces; 1534 Sema::AssociatedClassSet &Classes; 1535 }; 1536} 1537 1538static void 1539addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 1540 1541static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 1542 DeclContext *Ctx) { 1543 // Add the associated namespace for this class. 1544 1545 // We don't use DeclContext::getEnclosingNamespaceContext() as this may 1546 // be a locally scoped record. 1547 1548 while (Ctx->isRecord() || Ctx->isTransparentContext()) 1549 Ctx = Ctx->getParent(); 1550 1551 if (Ctx->isFileContext()) 1552 Namespaces.insert(Ctx->getPrimaryContext()); 1553} 1554 1555// \brief Add the associated classes and namespaces for argument-dependent 1556// lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 1557static void 1558addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1559 const TemplateArgument &Arg) { 1560 // C++ [basic.lookup.koenig]p2, last bullet: 1561 // -- [...] ; 1562 switch (Arg.getKind()) { 1563 case TemplateArgument::Null: 1564 break; 1565 1566 case TemplateArgument::Type: 1567 // [...] the namespaces and classes associated with the types of the 1568 // template arguments provided for template type parameters (excluding 1569 // template template parameters) 1570 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 1571 break; 1572 1573 case TemplateArgument::Template: { 1574 // [...] the namespaces in which any template template arguments are 1575 // defined; and the classes in which any member templates used as 1576 // template template arguments are defined. 1577 TemplateName Template = Arg.getAsTemplate(); 1578 if (ClassTemplateDecl *ClassTemplate 1579 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 1580 DeclContext *Ctx = ClassTemplate->getDeclContext(); 1581 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1582 Result.Classes.insert(EnclosingClass); 1583 // Add the associated namespace for this class. 1584 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1585 } 1586 break; 1587 } 1588 1589 case TemplateArgument::Declaration: 1590 case TemplateArgument::Integral: 1591 case TemplateArgument::Expression: 1592 // [Note: non-type template arguments do not contribute to the set of 1593 // associated namespaces. ] 1594 break; 1595 1596 case TemplateArgument::Pack: 1597 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), 1598 PEnd = Arg.pack_end(); 1599 P != PEnd; ++P) 1600 addAssociatedClassesAndNamespaces(Result, *P); 1601 break; 1602 } 1603} 1604 1605// \brief Add the associated classes and namespaces for 1606// argument-dependent lookup with an argument of class type 1607// (C++ [basic.lookup.koenig]p2). 1608static void 1609addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1610 CXXRecordDecl *Class) { 1611 1612 // Just silently ignore anything whose name is __va_list_tag. 1613 if (Class->getDeclName() == Result.S.VAListTagName) 1614 return; 1615 1616 // C++ [basic.lookup.koenig]p2: 1617 // [...] 1618 // -- If T is a class type (including unions), its associated 1619 // classes are: the class itself; the class of which it is a 1620 // member, if any; and its direct and indirect base 1621 // classes. Its associated namespaces are the namespaces in 1622 // which its associated classes are defined. 1623 1624 // Add the class of which it is a member, if any. 1625 DeclContext *Ctx = Class->getDeclContext(); 1626 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1627 Result.Classes.insert(EnclosingClass); 1628 // Add the associated namespace for this class. 1629 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1630 1631 // Add the class itself. If we've already seen this class, we don't 1632 // need to visit base classes. 1633 if (!Result.Classes.insert(Class)) 1634 return; 1635 1636 // -- If T is a template-id, its associated namespaces and classes are 1637 // the namespace in which the template is defined; for member 1638 // templates, the member template’s class; the namespaces and classes 1639 // associated with the types of the template arguments provided for 1640 // template type parameters (excluding template template parameters); the 1641 // namespaces in which any template template arguments are defined; and 1642 // the classes in which any member templates used as template template 1643 // arguments are defined. [Note: non-type template arguments do not 1644 // contribute to the set of associated namespaces. ] 1645 if (ClassTemplateSpecializationDecl *Spec 1646 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 1647 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 1648 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1649 Result.Classes.insert(EnclosingClass); 1650 // Add the associated namespace for this class. 1651 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1652 1653 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1654 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 1655 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 1656 } 1657 1658 // Only recurse into base classes for complete types. 1659 if (!Class->hasDefinition()) { 1660 // FIXME: we might need to instantiate templates here 1661 return; 1662 } 1663 1664 // Add direct and indirect base classes along with their associated 1665 // namespaces. 1666 llvm::SmallVector<CXXRecordDecl *, 32> Bases; 1667 Bases.push_back(Class); 1668 while (!Bases.empty()) { 1669 // Pop this class off the stack. 1670 Class = Bases.back(); 1671 Bases.pop_back(); 1672 1673 // Visit the base classes. 1674 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(), 1675 BaseEnd = Class->bases_end(); 1676 Base != BaseEnd; ++Base) { 1677 const RecordType *BaseType = Base->getType()->getAs<RecordType>(); 1678 // In dependent contexts, we do ADL twice, and the first time around, 1679 // the base type might be a dependent TemplateSpecializationType, or a 1680 // TemplateTypeParmType. If that happens, simply ignore it. 1681 // FIXME: If we want to support export, we probably need to add the 1682 // namespace of the template in a TemplateSpecializationType, or even 1683 // the classes and namespaces of known non-dependent arguments. 1684 if (!BaseType) 1685 continue; 1686 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 1687 if (Result.Classes.insert(BaseDecl)) { 1688 // Find the associated namespace for this base class. 1689 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 1690 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 1691 1692 // Make sure we visit the bases of this base class. 1693 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 1694 Bases.push_back(BaseDecl); 1695 } 1696 } 1697 } 1698} 1699 1700// \brief Add the associated classes and namespaces for 1701// argument-dependent lookup with an argument of type T 1702// (C++ [basic.lookup.koenig]p2). 1703static void 1704addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 1705 // C++ [basic.lookup.koenig]p2: 1706 // 1707 // For each argument type T in the function call, there is a set 1708 // of zero or more associated namespaces and a set of zero or more 1709 // associated classes to be considered. The sets of namespaces and 1710 // classes is determined entirely by the types of the function 1711 // arguments (and the namespace of any template template 1712 // argument). Typedef names and using-declarations used to specify 1713 // the types do not contribute to this set. The sets of namespaces 1714 // and classes are determined in the following way: 1715 1716 llvm::SmallVector<const Type *, 16> Queue; 1717 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 1718 1719 while (true) { 1720 switch (T->getTypeClass()) { 1721 1722#define TYPE(Class, Base) 1723#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 1725#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 1726#define ABSTRACT_TYPE(Class, Base) 1727#include "clang/AST/TypeNodes.def" 1728 // T is canonical. We can also ignore dependent types because 1729 // we don't need to do ADL at the definition point, but if we 1730 // wanted to implement template export (or if we find some other 1731 // use for associated classes and namespaces...) this would be 1732 // wrong. 1733 break; 1734 1735 // -- If T is a pointer to U or an array of U, its associated 1736 // namespaces and classes are those associated with U. 1737 case Type::Pointer: 1738 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 1739 continue; 1740 case Type::ConstantArray: 1741 case Type::IncompleteArray: 1742 case Type::VariableArray: 1743 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 1744 continue; 1745 1746 // -- If T is a fundamental type, its associated sets of 1747 // namespaces and classes are both empty. 1748 case Type::Builtin: 1749 break; 1750 1751 // -- If T is a class type (including unions), its associated 1752 // classes are: the class itself; the class of which it is a 1753 // member, if any; and its direct and indirect base 1754 // classes. Its associated namespaces are the namespaces in 1755 // which its associated classes are defined. 1756 case Type::Record: { 1757 CXXRecordDecl *Class 1758 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 1759 addAssociatedClassesAndNamespaces(Result, Class); 1760 break; 1761 } 1762 1763 // -- If T is an enumeration type, its associated namespace is 1764 // the namespace in which it is defined. If it is class 1765 // member, its associated class is the member’s class; else 1766 // it has no associated class. 1767 case Type::Enum: { 1768 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 1769 1770 DeclContext *Ctx = Enum->getDeclContext(); 1771 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1772 Result.Classes.insert(EnclosingClass); 1773 1774 // Add the associated namespace for this class. 1775 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1776 1777 break; 1778 } 1779 1780 // -- If T is a function type, its associated namespaces and 1781 // classes are those associated with the function parameter 1782 // types and those associated with the return type. 1783 case Type::FunctionProto: { 1784 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 1785 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), 1786 ArgEnd = Proto->arg_type_end(); 1787 Arg != ArgEnd; ++Arg) 1788 Queue.push_back(Arg->getTypePtr()); 1789 // fallthrough 1790 } 1791 case Type::FunctionNoProto: { 1792 const FunctionType *FnType = cast<FunctionType>(T); 1793 T = FnType->getResultType().getTypePtr(); 1794 continue; 1795 } 1796 1797 // -- If T is a pointer to a member function of a class X, its 1798 // associated namespaces and classes are those associated 1799 // with the function parameter types and return type, 1800 // together with those associated with X. 1801 // 1802 // -- If T is a pointer to a data member of class X, its 1803 // associated namespaces and classes are those associated 1804 // with the member type together with those associated with 1805 // X. 1806 case Type::MemberPointer: { 1807 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 1808 1809 // Queue up the class type into which this points. 1810 Queue.push_back(MemberPtr->getClass()); 1811 1812 // And directly continue with the pointee type. 1813 T = MemberPtr->getPointeeType().getTypePtr(); 1814 continue; 1815 } 1816 1817 // As an extension, treat this like a normal pointer. 1818 case Type::BlockPointer: 1819 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 1820 continue; 1821 1822 // References aren't covered by the standard, but that's such an 1823 // obvious defect that we cover them anyway. 1824 case Type::LValueReference: 1825 case Type::RValueReference: 1826 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 1827 continue; 1828 1829 // These are fundamental types. 1830 case Type::Vector: 1831 case Type::ExtVector: 1832 case Type::Complex: 1833 break; 1834 1835 // These are ignored by ADL. 1836 case Type::ObjCObject: 1837 case Type::ObjCInterface: 1838 case Type::ObjCObjectPointer: 1839 break; 1840 } 1841 1842 if (Queue.empty()) break; 1843 T = Queue.back(); 1844 Queue.pop_back(); 1845 } 1846} 1847 1848/// \brief Find the associated classes and namespaces for 1849/// argument-dependent lookup for a call with the given set of 1850/// arguments. 1851/// 1852/// This routine computes the sets of associated classes and associated 1853/// namespaces searched by argument-dependent lookup 1854/// (C++ [basic.lookup.argdep]) for a given set of arguments. 1855void 1856Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1857 AssociatedNamespaceSet &AssociatedNamespaces, 1858 AssociatedClassSet &AssociatedClasses) { 1859 AssociatedNamespaces.clear(); 1860 AssociatedClasses.clear(); 1861 1862 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses); 1863 1864 // C++ [basic.lookup.koenig]p2: 1865 // For each argument type T in the function call, there is a set 1866 // of zero or more associated namespaces and a set of zero or more 1867 // associated classes to be considered. The sets of namespaces and 1868 // classes is determined entirely by the types of the function 1869 // arguments (and the namespace of any template template 1870 // argument). 1871 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) { 1872 Expr *Arg = Args[ArgIdx]; 1873 1874 if (Arg->getType() != Context.OverloadTy) { 1875 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 1876 continue; 1877 } 1878 1879 // [...] In addition, if the argument is the name or address of a 1880 // set of overloaded functions and/or function templates, its 1881 // associated classes and namespaces are the union of those 1882 // associated with each of the members of the set: the namespace 1883 // in which the function or function template is defined and the 1884 // classes and namespaces associated with its (non-dependent) 1885 // parameter types and return type. 1886 Arg = Arg->IgnoreParens(); 1887 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) 1888 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) 1889 Arg = unaryOp->getSubExpr(); 1890 1891 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); 1892 if (!ULE) continue; 1893 1894 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end(); 1895 I != E; ++I) { 1896 // Look through any using declarations to find the underlying function. 1897 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 1898 1899 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn); 1900 if (!FDecl) 1901 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl(); 1902 1903 // Add the classes and namespaces associated with the parameter 1904 // types and return type of this function. 1905 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 1906 } 1907 } 1908} 1909 1910/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 1911/// an acceptable non-member overloaded operator for a call whose 1912/// arguments have types T1 (and, if non-empty, T2). This routine 1913/// implements the check in C++ [over.match.oper]p3b2 concerning 1914/// enumeration types. 1915static bool 1916IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 1917 QualType T1, QualType T2, 1918 ASTContext &Context) { 1919 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 1920 return true; 1921 1922 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 1923 return true; 1924 1925 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 1926 if (Proto->getNumArgs() < 1) 1927 return false; 1928 1929 if (T1->isEnumeralType()) { 1930 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 1931 if (Context.hasSameUnqualifiedType(T1, ArgType)) 1932 return true; 1933 } 1934 1935 if (Proto->getNumArgs() < 2) 1936 return false; 1937 1938 if (!T2.isNull() && T2->isEnumeralType()) { 1939 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 1940 if (Context.hasSameUnqualifiedType(T2, ArgType)) 1941 return true; 1942 } 1943 1944 return false; 1945} 1946 1947NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 1948 SourceLocation Loc, 1949 LookupNameKind NameKind, 1950 RedeclarationKind Redecl) { 1951 LookupResult R(*this, Name, Loc, NameKind, Redecl); 1952 LookupName(R, S); 1953 return R.getAsSingle<NamedDecl>(); 1954} 1955 1956/// \brief Find the protocol with the given name, if any. 1957ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 1958 SourceLocation IdLoc) { 1959 Decl *D = LookupSingleName(TUScope, II, IdLoc, 1960 LookupObjCProtocolName); 1961 return cast_or_null<ObjCProtocolDecl>(D); 1962} 1963 1964void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 1965 QualType T1, QualType T2, 1966 UnresolvedSetImpl &Functions) { 1967 // C++ [over.match.oper]p3: 1968 // -- The set of non-member candidates is the result of the 1969 // unqualified lookup of operator@ in the context of the 1970 // expression according to the usual rules for name lookup in 1971 // unqualified function calls (3.4.2) except that all member 1972 // functions are ignored. However, if no operand has a class 1973 // type, only those non-member functions in the lookup set 1974 // that have a first parameter of type T1 or "reference to 1975 // (possibly cv-qualified) T1", when T1 is an enumeration 1976 // type, or (if there is a right operand) a second parameter 1977 // of type T2 or "reference to (possibly cv-qualified) T2", 1978 // when T2 is an enumeration type, are candidate functions. 1979 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 1980 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 1981 LookupName(Operators, S); 1982 1983 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 1984 1985 if (Operators.empty()) 1986 return; 1987 1988 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end(); 1989 Op != OpEnd; ++Op) { 1990 NamedDecl *Found = (*Op)->getUnderlyingDecl(); 1991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) { 1992 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 1993 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD 1994 } else if (FunctionTemplateDecl *FunTmpl 1995 = dyn_cast<FunctionTemplateDecl>(Found)) { 1996 // FIXME: friend operators? 1997 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate, 1998 // later? 1999 if (!FunTmpl->getDeclContext()->isRecord()) 2000 Functions.addDecl(*Op, Op.getAccess()); 2001 } 2002 } 2003} 2004 2005/// \brief Look up the constructors for the given class. 2006DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 2007 // If the copy constructor has not yet been declared, do so now. 2008 if (CanDeclareSpecialMemberFunction(Context, Class) && 2009 !Class->hasDeclaredCopyConstructor()) 2010 DeclareImplicitCopyConstructor(Class); 2011 2012 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 2013 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 2014 return Class->lookup(Name); 2015} 2016 2017/// \brief Look for the destructor of the given class. 2018/// 2019/// During semantic analysis, this routine should be used in lieu of 2020/// CXXRecordDecl::getDestructor(). 2021/// 2022/// \returns The destructor for this class. 2023CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 2024 // If the destructor has not yet been declared, do so now. 2025 if (CanDeclareSpecialMemberFunction(Context, Class) && 2026 !Class->hasDeclaredDestructor()) 2027 DeclareImplicitDestructor(Class); 2028 2029 return Class->getDestructor(); 2030} 2031 2032void ADLResult::insert(NamedDecl *New) { 2033 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 2034 2035 // If we haven't yet seen a decl for this key, or the last decl 2036 // was exactly this one, we're done. 2037 if (Old == 0 || Old == New) { 2038 Old = New; 2039 return; 2040 } 2041 2042 // Otherwise, decide which is a more recent redeclaration. 2043 FunctionDecl *OldFD, *NewFD; 2044 if (isa<FunctionTemplateDecl>(New)) { 2045 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl(); 2046 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl(); 2047 } else { 2048 OldFD = cast<FunctionDecl>(Old); 2049 NewFD = cast<FunctionDecl>(New); 2050 } 2051 2052 FunctionDecl *Cursor = NewFD; 2053 while (true) { 2054 Cursor = Cursor->getPreviousDeclaration(); 2055 2056 // If we got to the end without finding OldFD, OldFD is the newer 2057 // declaration; leave things as they are. 2058 if (!Cursor) return; 2059 2060 // If we do find OldFD, then NewFD is newer. 2061 if (Cursor == OldFD) break; 2062 2063 // Otherwise, keep looking. 2064 } 2065 2066 Old = New; 2067} 2068 2069void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator, 2070 Expr **Args, unsigned NumArgs, 2071 ADLResult &Result) { 2072 // Find all of the associated namespaces and classes based on the 2073 // arguments we have. 2074 AssociatedNamespaceSet AssociatedNamespaces; 2075 AssociatedClassSet AssociatedClasses; 2076 FindAssociatedClassesAndNamespaces(Args, NumArgs, 2077 AssociatedNamespaces, 2078 AssociatedClasses); 2079 2080 QualType T1, T2; 2081 if (Operator) { 2082 T1 = Args[0]->getType(); 2083 if (NumArgs >= 2) 2084 T2 = Args[1]->getType(); 2085 } 2086 2087 // C++ [basic.lookup.argdep]p3: 2088 // Let X be the lookup set produced by unqualified lookup (3.4.1) 2089 // and let Y be the lookup set produced by argument dependent 2090 // lookup (defined as follows). If X contains [...] then Y is 2091 // empty. Otherwise Y is the set of declarations found in the 2092 // namespaces associated with the argument types as described 2093 // below. The set of declarations found by the lookup of the name 2094 // is the union of X and Y. 2095 // 2096 // Here, we compute Y and add its members to the overloaded 2097 // candidate set. 2098 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), 2099 NSEnd = AssociatedNamespaces.end(); 2100 NS != NSEnd; ++NS) { 2101 // When considering an associated namespace, the lookup is the 2102 // same as the lookup performed when the associated namespace is 2103 // used as a qualifier (3.4.3.2) except that: 2104 // 2105 // -- Any using-directives in the associated namespace are 2106 // ignored. 2107 // 2108 // -- Any namespace-scope friend functions declared in 2109 // associated classes are visible within their respective 2110 // namespaces even if they are not visible during an ordinary 2111 // lookup (11.4). 2112 DeclContext::lookup_iterator I, E; 2113 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) { 2114 NamedDecl *D = *I; 2115 // If the only declaration here is an ordinary friend, consider 2116 // it only if it was declared in an associated classes. 2117 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) { 2118 DeclContext *LexDC = D->getLexicalDeclContext(); 2119 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) 2120 continue; 2121 } 2122 2123 if (isa<UsingShadowDecl>(D)) 2124 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2125 2126 if (isa<FunctionDecl>(D)) { 2127 if (Operator && 2128 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D), 2129 T1, T2, Context)) 2130 continue; 2131 } else if (!isa<FunctionTemplateDecl>(D)) 2132 continue; 2133 2134 Result.insert(D); 2135 } 2136 } 2137} 2138 2139//---------------------------------------------------------------------------- 2140// Search for all visible declarations. 2141//---------------------------------------------------------------------------- 2142VisibleDeclConsumer::~VisibleDeclConsumer() { } 2143 2144namespace { 2145 2146class ShadowContextRAII; 2147 2148class VisibleDeclsRecord { 2149public: 2150 /// \brief An entry in the shadow map, which is optimized to store a 2151 /// single declaration (the common case) but can also store a list 2152 /// of declarations. 2153 class ShadowMapEntry { 2154 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector; 2155 2156 /// \brief Contains either the solitary NamedDecl * or a vector 2157 /// of declarations. 2158 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector; 2159 2160 public: 2161 ShadowMapEntry() : DeclOrVector() { } 2162 2163 void Add(NamedDecl *ND); 2164 void Destroy(); 2165 2166 // Iteration. 2167 typedef NamedDecl **iterator; 2168 iterator begin(); 2169 iterator end(); 2170 }; 2171 2172private: 2173 /// \brief A mapping from declaration names to the declarations that have 2174 /// this name within a particular scope. 2175 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 2176 2177 /// \brief A list of shadow maps, which is used to model name hiding. 2178 std::list<ShadowMap> ShadowMaps; 2179 2180 /// \brief The declaration contexts we have already visited. 2181 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 2182 2183 friend class ShadowContextRAII; 2184 2185public: 2186 /// \brief Determine whether we have already visited this context 2187 /// (and, if not, note that we are going to visit that context now). 2188 bool visitedContext(DeclContext *Ctx) { 2189 return !VisitedContexts.insert(Ctx); 2190 } 2191 2192 /// \brief Determine whether the given declaration is hidden in the 2193 /// current scope. 2194 /// 2195 /// \returns the declaration that hides the given declaration, or 2196 /// NULL if no such declaration exists. 2197 NamedDecl *checkHidden(NamedDecl *ND); 2198 2199 /// \brief Add a declaration to the current shadow map. 2200 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); } 2201}; 2202 2203/// \brief RAII object that records when we've entered a shadow context. 2204class ShadowContextRAII { 2205 VisibleDeclsRecord &Visible; 2206 2207 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 2208 2209public: 2210 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 2211 Visible.ShadowMaps.push_back(ShadowMap()); 2212 } 2213 2214 ~ShadowContextRAII() { 2215 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(), 2216 EEnd = Visible.ShadowMaps.back().end(); 2217 E != EEnd; 2218 ++E) 2219 E->second.Destroy(); 2220 2221 Visible.ShadowMaps.pop_back(); 2222 } 2223}; 2224 2225} // end anonymous namespace 2226 2227void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) { 2228 if (DeclOrVector.isNull()) { 2229 // 0 - > 1 elements: just set the single element information. 2230 DeclOrVector = ND; 2231 return; 2232 } 2233 2234 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) { 2235 // 1 -> 2 elements: create the vector of results and push in the 2236 // existing declaration. 2237 DeclVector *Vec = new DeclVector; 2238 Vec->push_back(PrevND); 2239 DeclOrVector = Vec; 2240 } 2241 2242 // Add the new element to the end of the vector. 2243 DeclOrVector.get<DeclVector*>()->push_back(ND); 2244} 2245 2246void VisibleDeclsRecord::ShadowMapEntry::Destroy() { 2247 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) { 2248 delete Vec; 2249 DeclOrVector = ((NamedDecl *)0); 2250 } 2251} 2252 2253VisibleDeclsRecord::ShadowMapEntry::iterator 2254VisibleDeclsRecord::ShadowMapEntry::begin() { 2255 if (DeclOrVector.isNull()) 2256 return 0; 2257 2258 if (DeclOrVector.dyn_cast<NamedDecl *>()) 2259 return &reinterpret_cast<NamedDecl*&>(DeclOrVector); 2260 2261 return DeclOrVector.get<DeclVector *>()->begin(); 2262} 2263 2264VisibleDeclsRecord::ShadowMapEntry::iterator 2265VisibleDeclsRecord::ShadowMapEntry::end() { 2266 if (DeclOrVector.isNull()) 2267 return 0; 2268 2269 if (DeclOrVector.dyn_cast<NamedDecl *>()) 2270 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1; 2271 2272 return DeclOrVector.get<DeclVector *>()->end(); 2273} 2274 2275NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 2276 // Look through using declarations. 2277 ND = ND->getUnderlyingDecl(); 2278 2279 unsigned IDNS = ND->getIdentifierNamespace(); 2280 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 2281 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 2282 SM != SMEnd; ++SM) { 2283 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 2284 if (Pos == SM->end()) 2285 continue; 2286 2287 for (ShadowMapEntry::iterator I = Pos->second.begin(), 2288 IEnd = Pos->second.end(); 2289 I != IEnd; ++I) { 2290 // A tag declaration does not hide a non-tag declaration. 2291 if ((*I)->hasTagIdentifierNamespace() && 2292 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 2293 Decl::IDNS_ObjCProtocol))) 2294 continue; 2295 2296 // Protocols are in distinct namespaces from everything else. 2297 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 2298 || (IDNS & Decl::IDNS_ObjCProtocol)) && 2299 (*I)->getIdentifierNamespace() != IDNS) 2300 continue; 2301 2302 // Functions and function templates in the same scope overload 2303 // rather than hide. FIXME: Look for hiding based on function 2304 // signatures! 2305 if ((*I)->isFunctionOrFunctionTemplate() && 2306 ND->isFunctionOrFunctionTemplate() && 2307 SM == ShadowMaps.rbegin()) 2308 continue; 2309 2310 // We've found a declaration that hides this one. 2311 return *I; 2312 } 2313 } 2314 2315 return 0; 2316} 2317 2318static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, 2319 bool QualifiedNameLookup, 2320 bool InBaseClass, 2321 VisibleDeclConsumer &Consumer, 2322 VisibleDeclsRecord &Visited) { 2323 if (!Ctx) 2324 return; 2325 2326 // Make sure we don't visit the same context twice. 2327 if (Visited.visitedContext(Ctx->getPrimaryContext())) 2328 return; 2329 2330 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 2331 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 2332 2333 // Enumerate all of the results in this context. 2334 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx; 2335 CurCtx = CurCtx->getNextContext()) { 2336 for (DeclContext::decl_iterator D = CurCtx->decls_begin(), 2337 DEnd = CurCtx->decls_end(); 2338 D != DEnd; ++D) { 2339 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 2340 if (Result.isAcceptableDecl(ND)) { 2341 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass); 2342 Visited.add(ND); 2343 } 2344 2345 // Visit transparent contexts inside this context. 2346 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) { 2347 if (InnerCtx->isTransparentContext()) 2348 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass, 2349 Consumer, Visited); 2350 } 2351 } 2352 } 2353 2354 // Traverse using directives for qualified name lookup. 2355 if (QualifiedNameLookup) { 2356 ShadowContextRAII Shadow(Visited); 2357 DeclContext::udir_iterator I, E; 2358 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) { 2359 LookupVisibleDecls((*I)->getNominatedNamespace(), Result, 2360 QualifiedNameLookup, InBaseClass, Consumer, Visited); 2361 } 2362 } 2363 2364 // Traverse the contexts of inherited C++ classes. 2365 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 2366 if (!Record->hasDefinition()) 2367 return; 2368 2369 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(), 2370 BEnd = Record->bases_end(); 2371 B != BEnd; ++B) { 2372 QualType BaseType = B->getType(); 2373 2374 // Don't look into dependent bases, because name lookup can't look 2375 // there anyway. 2376 if (BaseType->isDependentType()) 2377 continue; 2378 2379 const RecordType *Record = BaseType->getAs<RecordType>(); 2380 if (!Record) 2381 continue; 2382 2383 // FIXME: It would be nice to be able to determine whether referencing 2384 // a particular member would be ambiguous. For example, given 2385 // 2386 // struct A { int member; }; 2387 // struct B { int member; }; 2388 // struct C : A, B { }; 2389 // 2390 // void f(C *c) { c->### } 2391 // 2392 // accessing 'member' would result in an ambiguity. However, we 2393 // could be smart enough to qualify the member with the base 2394 // class, e.g., 2395 // 2396 // c->B::member 2397 // 2398 // or 2399 // 2400 // c->A::member 2401 2402 // Find results in this base class (and its bases). 2403 ShadowContextRAII Shadow(Visited); 2404 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, 2405 true, Consumer, Visited); 2406 } 2407 } 2408 2409 // Traverse the contexts of Objective-C classes. 2410 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 2411 // Traverse categories. 2412 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); 2413 Category; Category = Category->getNextClassCategory()) { 2414 ShadowContextRAII Shadow(Visited); 2415 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false, 2416 Consumer, Visited); 2417 } 2418 2419 // Traverse protocols. 2420 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(), 2421 E = IFace->protocol_end(); I != E; ++I) { 2422 ShadowContextRAII Shadow(Visited); 2423 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 2424 Visited); 2425 } 2426 2427 // Traverse the superclass. 2428 if (IFace->getSuperClass()) { 2429 ShadowContextRAII Shadow(Visited); 2430 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, 2431 true, Consumer, Visited); 2432 } 2433 2434 // If there is an implementation, traverse it. We do this to find 2435 // synthesized ivars. 2436 if (IFace->getImplementation()) { 2437 ShadowContextRAII Shadow(Visited); 2438 LookupVisibleDecls(IFace->getImplementation(), Result, 2439 QualifiedNameLookup, true, Consumer, Visited); 2440 } 2441 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 2442 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(), 2443 E = Protocol->protocol_end(); I != E; ++I) { 2444 ShadowContextRAII Shadow(Visited); 2445 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 2446 Visited); 2447 } 2448 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 2449 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(), 2450 E = Category->protocol_end(); I != E; ++I) { 2451 ShadowContextRAII Shadow(Visited); 2452 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 2453 Visited); 2454 } 2455 2456 // If there is an implementation, traverse it. 2457 if (Category->getImplementation()) { 2458 ShadowContextRAII Shadow(Visited); 2459 LookupVisibleDecls(Category->getImplementation(), Result, 2460 QualifiedNameLookup, true, Consumer, Visited); 2461 } 2462 } 2463} 2464 2465static void LookupVisibleDecls(Scope *S, LookupResult &Result, 2466 UnqualUsingDirectiveSet &UDirs, 2467 VisibleDeclConsumer &Consumer, 2468 VisibleDeclsRecord &Visited) { 2469 if (!S) 2470 return; 2471 2472 if (!S->getEntity() || !S->getParent() || 2473 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) { 2474 // Walk through the declarations in this Scope. 2475 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 2476 D != DEnd; ++D) { 2477 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get()))) 2478 if (Result.isAcceptableDecl(ND)) { 2479 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false); 2480 Visited.add(ND); 2481 } 2482 } 2483 } 2484 2485 // FIXME: C++ [temp.local]p8 2486 DeclContext *Entity = 0; 2487 if (S->getEntity()) { 2488 // Look into this scope's declaration context, along with any of its 2489 // parent lookup contexts (e.g., enclosing classes), up to the point 2490 // where we hit the context stored in the next outer scope. 2491 Entity = (DeclContext *)S->getEntity(); 2492 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME 2493 2494 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 2495 Ctx = Ctx->getLookupParent()) { 2496 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 2497 if (Method->isInstanceMethod()) { 2498 // For instance methods, look for ivars in the method's interface. 2499 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 2500 Result.getNameLoc(), Sema::LookupMemberName); 2501 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) 2502 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 2503 /*InBaseClass=*/false, Consumer, Visited); 2504 } 2505 2506 // We've already performed all of the name lookup that we need 2507 // to for Objective-C methods; the next context will be the 2508 // outer scope. 2509 break; 2510 } 2511 2512 if (Ctx->isFunctionOrMethod()) 2513 continue; 2514 2515 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 2516 /*InBaseClass=*/false, Consumer, Visited); 2517 } 2518 } else if (!S->getParent()) { 2519 // Look into the translation unit scope. We walk through the translation 2520 // unit's declaration context, because the Scope itself won't have all of 2521 // the declarations if we loaded a precompiled header. 2522 // FIXME: We would like the translation unit's Scope object to point to the 2523 // translation unit, so we don't need this special "if" branch. However, 2524 // doing so would force the normal C++ name-lookup code to look into the 2525 // translation unit decl when the IdentifierInfo chains would suffice. 2526 // Once we fix that problem (which is part of a more general "don't look 2527 // in DeclContexts unless we have to" optimization), we can eliminate this. 2528 Entity = Result.getSema().Context.getTranslationUnitDecl(); 2529 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 2530 /*InBaseClass=*/false, Consumer, Visited); 2531 } 2532 2533 if (Entity) { 2534 // Lookup visible declarations in any namespaces found by using 2535 // directives. 2536 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 2537 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity); 2538 for (; UI != UEnd; ++UI) 2539 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()), 2540 Result, /*QualifiedNameLookup=*/false, 2541 /*InBaseClass=*/false, Consumer, Visited); 2542 } 2543 2544 // Lookup names in the parent scope. 2545 ShadowContextRAII Shadow(Visited); 2546 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited); 2547} 2548 2549void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2550 VisibleDeclConsumer &Consumer) { 2551 // Determine the set of using directives available during 2552 // unqualified name lookup. 2553 Scope *Initial = S; 2554 UnqualUsingDirectiveSet UDirs; 2555 if (getLangOptions().CPlusPlus) { 2556 // Find the first namespace or translation-unit scope. 2557 while (S && !isNamespaceOrTranslationUnitScope(S)) 2558 S = S->getParent(); 2559 2560 UDirs.visitScopeChain(Initial, S); 2561 } 2562 UDirs.done(); 2563 2564 // Look for visible declarations. 2565 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 2566 VisibleDeclsRecord Visited; 2567 ShadowContextRAII Shadow(Visited); 2568 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited); 2569} 2570 2571void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2572 VisibleDeclConsumer &Consumer) { 2573 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 2574 VisibleDeclsRecord Visited; 2575 ShadowContextRAII Shadow(Visited); 2576 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 2577 /*InBaseClass=*/false, Consumer, Visited); 2578} 2579 2580//---------------------------------------------------------------------------- 2581// Typo correction 2582//---------------------------------------------------------------------------- 2583 2584namespace { 2585class TypoCorrectionConsumer : public VisibleDeclConsumer { 2586 /// \brief The name written that is a typo in the source. 2587 llvm::StringRef Typo; 2588 2589 /// \brief The results found that have the smallest edit distance 2590 /// found (so far) with the typo name. 2591 llvm::SmallVector<NamedDecl *, 4> BestResults; 2592 2593 /// \brief The keywords that have the smallest edit distance. 2594 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords; 2595 2596 /// \brief The best edit distance found so far. 2597 unsigned BestEditDistance; 2598 2599public: 2600 explicit TypoCorrectionConsumer(IdentifierInfo *Typo) 2601 : Typo(Typo->getName()) { } 2602 2603 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass); 2604 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword); 2605 2606 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator; 2607 iterator begin() const { return BestResults.begin(); } 2608 iterator end() const { return BestResults.end(); } 2609 void clear_decls() { BestResults.clear(); } 2610 2611 bool empty() const { return BestResults.empty() && BestKeywords.empty(); } 2612 2613 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator 2614 keyword_iterator; 2615 keyword_iterator keyword_begin() const { return BestKeywords.begin(); } 2616 keyword_iterator keyword_end() const { return BestKeywords.end(); } 2617 bool keyword_empty() const { return BestKeywords.empty(); } 2618 unsigned keyword_size() const { return BestKeywords.size(); } 2619 2620 unsigned getBestEditDistance() const { return BestEditDistance; } 2621}; 2622 2623} 2624 2625void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 2626 bool InBaseClass) { 2627 // Don't consider hidden names for typo correction. 2628 if (Hiding) 2629 return; 2630 2631 // Only consider entities with identifiers for names, ignoring 2632 // special names (constructors, overloaded operators, selectors, 2633 // etc.). 2634 IdentifierInfo *Name = ND->getIdentifier(); 2635 if (!Name) 2636 return; 2637 2638 // Compute the edit distance between the typo and the name of this 2639 // entity. If this edit distance is not worse than the best edit 2640 // distance we've seen so far, add it to the list of results. 2641 unsigned ED = Typo.edit_distance(Name->getName()); 2642 if (!BestResults.empty() || !BestKeywords.empty()) { 2643 if (ED < BestEditDistance) { 2644 // This result is better than any we've seen before; clear out 2645 // the previous results. 2646 BestResults.clear(); 2647 BestKeywords.clear(); 2648 BestEditDistance = ED; 2649 } else if (ED > BestEditDistance) { 2650 // This result is worse than the best results we've seen so far; 2651 // ignore it. 2652 return; 2653 } 2654 } else 2655 BestEditDistance = ED; 2656 2657 BestResults.push_back(ND); 2658} 2659 2660void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context, 2661 llvm::StringRef Keyword) { 2662 // Compute the edit distance between the typo and this keyword. 2663 // If this edit distance is not worse than the best edit 2664 // distance we've seen so far, add it to the list of results. 2665 unsigned ED = Typo.edit_distance(Keyword); 2666 if (!BestResults.empty() || !BestKeywords.empty()) { 2667 if (ED < BestEditDistance) { 2668 BestResults.clear(); 2669 BestKeywords.clear(); 2670 BestEditDistance = ED; 2671 } else if (ED > BestEditDistance) { 2672 // This result is worse than the best results we've seen so far; 2673 // ignore it. 2674 return; 2675 } 2676 } else 2677 BestEditDistance = ED; 2678 2679 BestKeywords.push_back(&Context.Idents.get(Keyword)); 2680} 2681 2682/// \brief Try to "correct" a typo in the source code by finding 2683/// visible declarations whose names are similar to the name that was 2684/// present in the source code. 2685/// 2686/// \param Res the \c LookupResult structure that contains the name 2687/// that was present in the source code along with the name-lookup 2688/// criteria used to search for the name. On success, this structure 2689/// will contain the results of name lookup. 2690/// 2691/// \param S the scope in which name lookup occurs. 2692/// 2693/// \param SS the nested-name-specifier that precedes the name we're 2694/// looking for, if present. 2695/// 2696/// \param MemberContext if non-NULL, the context in which to look for 2697/// a member access expression. 2698/// 2699/// \param EnteringContext whether we're entering the context described by 2700/// the nested-name-specifier SS. 2701/// 2702/// \param CTC The context in which typo correction occurs, which impacts the 2703/// set of keywords permitted. 2704/// 2705/// \param OPT when non-NULL, the search for visible declarations will 2706/// also walk the protocols in the qualified interfaces of \p OPT. 2707/// 2708/// \returns the corrected name if the typo was corrected, otherwise returns an 2709/// empty \c DeclarationName. When a typo was corrected, the result structure 2710/// may contain the results of name lookup for the correct name or it may be 2711/// empty. 2712DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS, 2713 DeclContext *MemberContext, 2714 bool EnteringContext, 2715 CorrectTypoContext CTC, 2716 const ObjCObjectPointerType *OPT) { 2717 if (Diags.hasFatalErrorOccurred()) 2718 return DeclarationName(); 2719 2720 // Provide a stop gap for files that are just seriously broken. Trying 2721 // to correct all typos can turn into a HUGE performance penalty, causing 2722 // some files to take minutes to get rejected by the parser. 2723 // FIXME: Is this the right solution? 2724 if (TyposCorrected == 20) 2725 return DeclarationName(); 2726 ++TyposCorrected; 2727 2728 // We only attempt to correct typos for identifiers. 2729 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo(); 2730 if (!Typo) 2731 return DeclarationName(); 2732 2733 // If the scope specifier itself was invalid, don't try to correct 2734 // typos. 2735 if (SS && SS->isInvalid()) 2736 return DeclarationName(); 2737 2738 // Never try to correct typos during template deduction or 2739 // instantiation. 2740 if (!ActiveTemplateInstantiations.empty()) 2741 return DeclarationName(); 2742 2743 TypoCorrectionConsumer Consumer(Typo); 2744 2745 // Perform name lookup to find visible, similarly-named entities. 2746 if (MemberContext) { 2747 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer); 2748 2749 // Look in qualified interfaces. 2750 if (OPT) { 2751 for (ObjCObjectPointerType::qual_iterator 2752 I = OPT->qual_begin(), E = OPT->qual_end(); 2753 I != E; ++I) 2754 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer); 2755 } 2756 } else if (SS && SS->isSet()) { 2757 DeclContext *DC = computeDeclContext(*SS, EnteringContext); 2758 if (!DC) 2759 return DeclarationName(); 2760 2761 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer); 2762 } else { 2763 LookupVisibleDecls(S, Res.getLookupKind(), Consumer); 2764 } 2765 2766 // Add context-dependent keywords. 2767 bool WantTypeSpecifiers = false; 2768 bool WantExpressionKeywords = false; 2769 bool WantCXXNamedCasts = false; 2770 bool WantRemainingKeywords = false; 2771 switch (CTC) { 2772 case CTC_Unknown: 2773 WantTypeSpecifiers = true; 2774 WantExpressionKeywords = true; 2775 WantCXXNamedCasts = true; 2776 WantRemainingKeywords = true; 2777 2778 if (ObjCMethodDecl *Method = getCurMethodDecl()) 2779 if (Method->getClassInterface() && 2780 Method->getClassInterface()->getSuperClass()) 2781 Consumer.addKeywordResult(Context, "super"); 2782 2783 break; 2784 2785 case CTC_NoKeywords: 2786 break; 2787 2788 case CTC_Type: 2789 WantTypeSpecifiers = true; 2790 break; 2791 2792 case CTC_ObjCMessageReceiver: 2793 Consumer.addKeywordResult(Context, "super"); 2794 // Fall through to handle message receivers like expressions. 2795 2796 case CTC_Expression: 2797 if (getLangOptions().CPlusPlus) 2798 WantTypeSpecifiers = true; 2799 WantExpressionKeywords = true; 2800 // Fall through to get C++ named casts. 2801 2802 case CTC_CXXCasts: 2803 WantCXXNamedCasts = true; 2804 break; 2805 2806 case CTC_MemberLookup: 2807 if (getLangOptions().CPlusPlus) 2808 Consumer.addKeywordResult(Context, "template"); 2809 break; 2810 } 2811 2812 if (WantTypeSpecifiers) { 2813 // Add type-specifier keywords to the set of results. 2814 const char *CTypeSpecs[] = { 2815 "char", "const", "double", "enum", "float", "int", "long", "short", 2816 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool", 2817 "_Complex", "_Imaginary", 2818 // storage-specifiers as well 2819 "extern", "inline", "static", "typedef" 2820 }; 2821 2822 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]); 2823 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 2824 Consumer.addKeywordResult(Context, CTypeSpecs[I]); 2825 2826 if (getLangOptions().C99) 2827 Consumer.addKeywordResult(Context, "restrict"); 2828 if (getLangOptions().Bool || getLangOptions().CPlusPlus) 2829 Consumer.addKeywordResult(Context, "bool"); 2830 2831 if (getLangOptions().CPlusPlus) { 2832 Consumer.addKeywordResult(Context, "class"); 2833 Consumer.addKeywordResult(Context, "typename"); 2834 Consumer.addKeywordResult(Context, "wchar_t"); 2835 2836 if (getLangOptions().CPlusPlus0x) { 2837 Consumer.addKeywordResult(Context, "char16_t"); 2838 Consumer.addKeywordResult(Context, "char32_t"); 2839 Consumer.addKeywordResult(Context, "constexpr"); 2840 Consumer.addKeywordResult(Context, "decltype"); 2841 Consumer.addKeywordResult(Context, "thread_local"); 2842 } 2843 } 2844 2845 if (getLangOptions().GNUMode) 2846 Consumer.addKeywordResult(Context, "typeof"); 2847 } 2848 2849 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) { 2850 Consumer.addKeywordResult(Context, "const_cast"); 2851 Consumer.addKeywordResult(Context, "dynamic_cast"); 2852 Consumer.addKeywordResult(Context, "reinterpret_cast"); 2853 Consumer.addKeywordResult(Context, "static_cast"); 2854 } 2855 2856 if (WantExpressionKeywords) { 2857 Consumer.addKeywordResult(Context, "sizeof"); 2858 if (getLangOptions().Bool || getLangOptions().CPlusPlus) { 2859 Consumer.addKeywordResult(Context, "false"); 2860 Consumer.addKeywordResult(Context, "true"); 2861 } 2862 2863 if (getLangOptions().CPlusPlus) { 2864 const char *CXXExprs[] = { 2865 "delete", "new", "operator", "throw", "typeid" 2866 }; 2867 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]); 2868 for (unsigned I = 0; I != NumCXXExprs; ++I) 2869 Consumer.addKeywordResult(Context, CXXExprs[I]); 2870 2871 if (isa<CXXMethodDecl>(CurContext) && 2872 cast<CXXMethodDecl>(CurContext)->isInstance()) 2873 Consumer.addKeywordResult(Context, "this"); 2874 2875 if (getLangOptions().CPlusPlus0x) { 2876 Consumer.addKeywordResult(Context, "alignof"); 2877 Consumer.addKeywordResult(Context, "nullptr"); 2878 } 2879 } 2880 } 2881 2882 if (WantRemainingKeywords) { 2883 if (getCurFunctionOrMethodDecl() || getCurBlock()) { 2884 // Statements. 2885 const char *CStmts[] = { 2886 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 2887 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]); 2888 for (unsigned I = 0; I != NumCStmts; ++I) 2889 Consumer.addKeywordResult(Context, CStmts[I]); 2890 2891 if (getLangOptions().CPlusPlus) { 2892 Consumer.addKeywordResult(Context, "catch"); 2893 Consumer.addKeywordResult(Context, "try"); 2894 } 2895 2896 if (S && S->getBreakParent()) 2897 Consumer.addKeywordResult(Context, "break"); 2898 2899 if (S && S->getContinueParent()) 2900 Consumer.addKeywordResult(Context, "continue"); 2901 2902 if (!getSwitchStack().empty()) { 2903 Consumer.addKeywordResult(Context, "case"); 2904 Consumer.addKeywordResult(Context, "default"); 2905 } 2906 } else { 2907 if (getLangOptions().CPlusPlus) { 2908 Consumer.addKeywordResult(Context, "namespace"); 2909 Consumer.addKeywordResult(Context, "template"); 2910 } 2911 2912 if (S && S->isClassScope()) { 2913 Consumer.addKeywordResult(Context, "explicit"); 2914 Consumer.addKeywordResult(Context, "friend"); 2915 Consumer.addKeywordResult(Context, "mutable"); 2916 Consumer.addKeywordResult(Context, "private"); 2917 Consumer.addKeywordResult(Context, "protected"); 2918 Consumer.addKeywordResult(Context, "public"); 2919 Consumer.addKeywordResult(Context, "virtual"); 2920 } 2921 } 2922 2923 if (getLangOptions().CPlusPlus) { 2924 Consumer.addKeywordResult(Context, "using"); 2925 2926 if (getLangOptions().CPlusPlus0x) 2927 Consumer.addKeywordResult(Context, "static_assert"); 2928 } 2929 } 2930 2931 // If we haven't found anything, we're done. 2932 if (Consumer.empty()) 2933 return DeclarationName(); 2934 2935 // Only allow a single, closest name in the result set (it's okay to 2936 // have overloads of that name, though). 2937 DeclarationName BestName; 2938 NamedDecl *BestIvarOrPropertyDecl = 0; 2939 bool FoundIvarOrPropertyDecl = false; 2940 2941 // Check all of the declaration results to find the best name so far. 2942 for (TypoCorrectionConsumer::iterator I = Consumer.begin(), 2943 IEnd = Consumer.end(); 2944 I != IEnd; ++I) { 2945 if (!BestName) 2946 BestName = (*I)->getDeclName(); 2947 else if (BestName != (*I)->getDeclName()) 2948 return DeclarationName(); 2949 2950 // \brief Keep track of either an Objective-C ivar or a property, but not 2951 // both. 2952 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) { 2953 if (FoundIvarOrPropertyDecl) 2954 BestIvarOrPropertyDecl = 0; 2955 else { 2956 BestIvarOrPropertyDecl = *I; 2957 FoundIvarOrPropertyDecl = true; 2958 } 2959 } 2960 } 2961 2962 // Now check all of the keyword results to find the best name. 2963 switch (Consumer.keyword_size()) { 2964 case 0: 2965 // No keywords matched. 2966 break; 2967 2968 case 1: 2969 // If we already have a name 2970 if (!BestName) { 2971 // We did not have anything previously, 2972 BestName = *Consumer.keyword_begin(); 2973 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) { 2974 // We have a declaration with the same name as a context-sensitive 2975 // keyword. The keyword takes precedence. 2976 BestIvarOrPropertyDecl = 0; 2977 FoundIvarOrPropertyDecl = false; 2978 Consumer.clear_decls(); 2979 } else if (CTC == CTC_ObjCMessageReceiver && 2980 (*Consumer.keyword_begin())->isStr("super")) { 2981 // In an Objective-C message send, give the "super" keyword a slight 2982 // edge over entities not in function or method scope. 2983 for (TypoCorrectionConsumer::iterator I = Consumer.begin(), 2984 IEnd = Consumer.end(); 2985 I != IEnd; ++I) { 2986 if ((*I)->getDeclName() == BestName) { 2987 if ((*I)->getDeclContext()->isFunctionOrMethod()) 2988 return DeclarationName(); 2989 } 2990 } 2991 2992 // Everything found was outside a function or method; the 'super' 2993 // keyword takes precedence. 2994 BestIvarOrPropertyDecl = 0; 2995 FoundIvarOrPropertyDecl = false; 2996 Consumer.clear_decls(); 2997 BestName = *Consumer.keyword_begin(); 2998 } else { 2999 // Name collision; we will not correct typos. 3000 return DeclarationName(); 3001 } 3002 break; 3003 3004 default: 3005 // Name collision; we will not correct typos. 3006 return DeclarationName(); 3007 } 3008 3009 // BestName is the closest viable name to what the user 3010 // typed. However, to make sure that we don't pick something that's 3011 // way off, make sure that the user typed at least 3 characters for 3012 // each correction. 3013 unsigned ED = Consumer.getBestEditDistance(); 3014 if (ED == 0 || !BestName.getAsIdentifierInfo() || 3015 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3) 3016 return DeclarationName(); 3017 3018 // Perform name lookup again with the name we chose, and declare 3019 // success if we found something that was not ambiguous. 3020 Res.clear(); 3021 Res.setLookupName(BestName); 3022 3023 // If we found an ivar or property, add that result; no further 3024 // lookup is required. 3025 if (BestIvarOrPropertyDecl) 3026 Res.addDecl(BestIvarOrPropertyDecl); 3027 // If we're looking into the context of a member, perform qualified 3028 // name lookup on the best name. 3029 else if (!Consumer.keyword_empty()) { 3030 // The best match was a keyword. Return it. 3031 return BestName; 3032 } else if (MemberContext) 3033 LookupQualifiedName(Res, MemberContext); 3034 // Perform lookup as if we had just parsed the best name. 3035 else 3036 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 3037 EnteringContext); 3038 3039 if (Res.isAmbiguous()) { 3040 Res.suppressDiagnostics(); 3041 return DeclarationName(); 3042 } 3043 3044 if (Res.getResultKind() != LookupResult::NotFound) 3045 return BestName; 3046 3047 return DeclarationName(); 3048} 3049