SemaLookup.cpp revision 411889e15e0335f6951d2410c5bd67839c4fff66
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 "SemaInherit.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/Decl.h" 18#include "clang/AST/DeclCXX.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/Expr.h" 21#include "clang/Parse/DeclSpec.h" 22#include "clang/Basic/LangOptions.h" 23#include "llvm/ADT/STLExtras.h" 24#include "llvm/ADT/SmallPtrSet.h" 25#include <set> 26#include <vector> 27#include <iterator> 28#include <utility> 29#include <algorithm> 30 31using namespace clang; 32 33typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy; 34typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet; 35typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy; 36 37/// UsingDirAncestorCompare - Implements strict weak ordering of 38/// UsingDirectives. It orders them by address of its common ancestor. 39struct UsingDirAncestorCompare { 40 41 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext. 42 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const { 43 return U->getCommonAncestor() < Ctx; 44 } 45 46 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext. 47 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const { 48 return Ctx < U->getCommonAncestor(); 49 } 50 51 /// @brief Compares UsingDirectiveDecl common ancestors. 52 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const { 53 return U1->getCommonAncestor() < U2->getCommonAncestor(); 54 } 55}; 56 57/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs 58/// (ordered by common ancestors), found in namespace NS, 59/// including all found (recursively) in their nominated namespaces. 60void AddNamespaceUsingDirectives(DeclContext *NS, 61 UsingDirectivesTy &UDirs, 62 NamespaceSet &Visited) { 63 DeclContext::udir_iterator I, End; 64 65 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) { 66 UDirs.push_back(*I); 67 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); 68 NamespaceDecl *Nominated = (*I)->getNominatedNamespace(); 69 if (Visited.insert(Nominated).second) 70 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ Visited); 71 } 72} 73 74/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S, 75/// including all found in the namespaces they nominate. 76static void AddScopeUsingDirectives(Scope *S, UsingDirectivesTy &UDirs) { 77 NamespaceSet VisitedNS; 78 79 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { 80 81 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx)) 82 VisitedNS.insert(NS); 83 84 AddNamespaceUsingDirectives(Ctx, UDirs, /*ref*/ VisitedNS); 85 86 } else { 87 Scope::udir_iterator 88 I = S->using_directives_begin(), 89 End = S->using_directives_end(); 90 91 for (; I != End; ++I) { 92 UsingDirectiveDecl * UD = static_cast<UsingDirectiveDecl*>(*I); 93 UDirs.push_back(UD); 94 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); 95 96 NamespaceDecl *Nominated = UD->getNominatedNamespace(); 97 if (!VisitedNS.count(Nominated)) { 98 VisitedNS.insert(Nominated); 99 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ VisitedNS); 100 } 101 } 102 } 103} 104 105/// MaybeConstructOverloadSet - Name lookup has determined that the 106/// elements in [I, IEnd) have the name that we are looking for, and 107/// *I is a match for the namespace. This routine returns an 108/// appropriate Decl for name lookup, which may either be *I or an 109/// OverloadedFunctionDecl that represents the overloaded functions in 110/// [I, IEnd). 111/// 112/// The existance of this routine is temporary; users of LookupResult 113/// should be able to handle multiple results, to deal with cases of 114/// ambiguity and overloaded functions without needing to create a 115/// Decl node. 116template<typename DeclIterator> 117static NamedDecl * 118MaybeConstructOverloadSet(ASTContext &Context, 119 DeclIterator I, DeclIterator IEnd) { 120 assert(I != IEnd && "Iterator range cannot be empty"); 121 assert(!isa<OverloadedFunctionDecl>(*I) && 122 "Cannot have an overloaded function"); 123 124 if (isa<FunctionDecl>(*I)) { 125 // If we found a function, there might be more functions. If 126 // so, collect them into an overload set. 127 DeclIterator Last = I; 128 OverloadedFunctionDecl *Ovl = 0; 129 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) { 130 if (!Ovl) { 131 // FIXME: We leak this overload set. Eventually, we want to 132 // stop building the declarations for these overload sets, so 133 // there will be nothing to leak. 134 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(), 135 (*I)->getDeclName()); 136 Ovl->addOverload(cast<FunctionDecl>(*I)); 137 } 138 Ovl->addOverload(cast<FunctionDecl>(*Last)); 139 } 140 141 // If we had more than one function, we built an overload 142 // set. Return it. 143 if (Ovl) 144 return Ovl; 145 } 146 147 return *I; 148} 149 150/// Merges together multiple LookupResults dealing with duplicated Decl's. 151static Sema::LookupResult 152MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) { 153 typedef Sema::LookupResult LResult; 154 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy; 155 156 // Remove duplicated Decl pointing at same Decl, by storing them in 157 // associative collection. This might be case for code like: 158 // 159 // namespace A { int i; } 160 // namespace B { using namespace A; } 161 // namespace C { using namespace A; } 162 // 163 // void foo() { 164 // using namespace B; 165 // using namespace C; 166 // ++i; // finds A::i, from both namespace B and C at global scope 167 // } 168 // 169 // C++ [namespace.qual].p3: 170 // The same declaration found more than once is not an ambiguity 171 // (because it is still a unique declaration). 172 DeclsSetTy FoundDecls; 173 174 // Counter of tag names, and functions for resolving ambiguity 175 // and name hiding. 176 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0; 177 178 LookupResultsTy::iterator I = Results.begin(), End = Results.end(); 179 180 // No name lookup results, return early. 181 if (I == End) return LResult::CreateLookupResult(Context, 0); 182 183 // Keep track of the tag declaration we found. We only use this if 184 // we find a single tag declaration. 185 TagDecl *TagFound = 0; 186 187 for (; I != End; ++I) { 188 switch (I->getKind()) { 189 case LResult::NotFound: 190 assert(false && 191 "Should be always successful name lookup result here."); 192 break; 193 194 case LResult::AmbiguousReference: 195 case LResult::AmbiguousBaseSubobjectTypes: 196 case LResult::AmbiguousBaseSubobjects: 197 assert(false && "Shouldn't get ambiguous lookup here."); 198 break; 199 200 case LResult::Found: { 201 NamedDecl *ND = I->getAsDecl(); 202 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) { 203 TagFound = Context.getCanonicalDecl(TD); 204 TagNames += FoundDecls.insert(TagFound)? 1 : 0; 205 } else if (isa<FunctionDecl>(ND)) 206 Functions += FoundDecls.insert(ND)? 1 : 0; 207 else 208 FoundDecls.insert(ND); 209 break; 210 } 211 212 case LResult::FoundOverloaded: 213 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI) 214 Functions += FoundDecls.insert(*FI)? 1 : 0; 215 break; 216 } 217 } 218 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions; 219 bool Ambiguous = false, NameHidesTags = false; 220 221 if (FoundDecls.size() == 1) { 222 // 1) Exactly one result. 223 } else if (TagNames > 1) { 224 // 2) Multiple tag names (even though they may be hidden by an 225 // object name). 226 Ambiguous = true; 227 } else if (FoundDecls.size() - TagNames == 1) { 228 // 3) Ordinary name hides (optional) tag. 229 NameHidesTags = TagFound; 230 } else if (Functions) { 231 // C++ [basic.lookup].p1: 232 // ... Name lookup may associate more than one declaration with 233 // a name if it finds the name to be a function name; the declarations 234 // are said to form a set of overloaded functions (13.1). 235 // Overload resolution (13.3) takes place after name lookup has succeeded. 236 // 237 if (!OrdinaryNonFunc) { 238 // 4) Functions hide tag names. 239 NameHidesTags = TagFound; 240 } else { 241 // 5) Functions + ordinary names. 242 Ambiguous = true; 243 } 244 } else { 245 // 6) Multiple non-tag names 246 Ambiguous = true; 247 } 248 249 if (Ambiguous) 250 return LResult::CreateLookupResult(Context, 251 FoundDecls.begin(), FoundDecls.size()); 252 if (NameHidesTags) { 253 // There's only one tag, TagFound. Remove it. 254 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?"); 255 FoundDecls.erase(TagFound); 256 } 257 258 // Return successful name lookup result. 259 return LResult::CreateLookupResult(Context, 260 MaybeConstructOverloadSet(Context, 261 FoundDecls.begin(), 262 FoundDecls.end())); 263} 264 265// Retrieve the set of identifier namespaces that correspond to a 266// specific kind of name lookup. 267inline unsigned 268getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind, 269 bool CPlusPlus) { 270 unsigned IDNS = 0; 271 switch (NameKind) { 272 case Sema::LookupOrdinaryName: 273 case Sema::LookupOperatorName: 274 IDNS = Decl::IDNS_Ordinary; 275 if (CPlusPlus) 276 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member; 277 break; 278 279 case Sema::LookupTagName: 280 IDNS = Decl::IDNS_Tag; 281 break; 282 283 case Sema::LookupMemberName: 284 IDNS = Decl::IDNS_Member; 285 if (CPlusPlus) 286 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 287 break; 288 289 case Sema::LookupNestedNameSpecifierName: 290 case Sema::LookupNamespaceName: 291 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member; 292 break; 293 } 294 return IDNS; 295} 296 297Sema::LookupResult 298Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) { 299 LookupResult Result; 300 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))? 301 OverloadedDeclSingleDecl : SingleDecl; 302 Result.First = reinterpret_cast<uintptr_t>(D); 303 Result.Last = 0; 304 Result.Context = &Context; 305 return Result; 306} 307 308/// @brief Moves the name-lookup results from Other to this LookupResult. 309Sema::LookupResult 310Sema::LookupResult::CreateLookupResult(ASTContext &Context, 311 IdentifierResolver::iterator F, 312 IdentifierResolver::iterator L) { 313 LookupResult Result; 314 Result.Context = &Context; 315 316 if (F != L && isa<FunctionDecl>(*F)) { 317 IdentifierResolver::iterator Next = F; 318 ++Next; 319 if (Next != L && isa<FunctionDecl>(*Next)) { 320 Result.StoredKind = OverloadedDeclFromIdResolver; 321 Result.First = F.getAsOpaqueValue(); 322 Result.Last = L.getAsOpaqueValue(); 323 return Result; 324 } 325 } 326 327 Result.StoredKind = SingleDecl; 328 Result.First = reinterpret_cast<uintptr_t>(*F); 329 Result.Last = 0; 330 return Result; 331} 332 333Sema::LookupResult 334Sema::LookupResult::CreateLookupResult(ASTContext &Context, 335 DeclContext::lookup_iterator F, 336 DeclContext::lookup_iterator L) { 337 LookupResult Result; 338 Result.Context = &Context; 339 340 if (F != L && isa<FunctionDecl>(*F)) { 341 DeclContext::lookup_iterator Next = F; 342 ++Next; 343 if (Next != L && isa<FunctionDecl>(*Next)) { 344 Result.StoredKind = OverloadedDeclFromDeclContext; 345 Result.First = reinterpret_cast<uintptr_t>(F); 346 Result.Last = reinterpret_cast<uintptr_t>(L); 347 return Result; 348 } 349 } 350 351 Result.StoredKind = SingleDecl; 352 Result.First = reinterpret_cast<uintptr_t>(*F); 353 Result.Last = 0; 354 return Result; 355} 356 357/// @brief Determine the result of name lookup. 358Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const { 359 switch (StoredKind) { 360 case SingleDecl: 361 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound; 362 363 case OverloadedDeclSingleDecl: 364 case OverloadedDeclFromIdResolver: 365 case OverloadedDeclFromDeclContext: 366 return FoundOverloaded; 367 368 case AmbiguousLookupStoresBasePaths: 369 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects; 370 371 case AmbiguousLookupStoresDecls: 372 return AmbiguousReference; 373 } 374 375 // We can't ever get here. 376 return NotFound; 377} 378 379/// @brief Converts the result of name lookup into a single (possible 380/// NULL) pointer to a declaration. 381/// 382/// The resulting declaration will either be the declaration we found 383/// (if only a single declaration was found), an 384/// OverloadedFunctionDecl (if an overloaded function was found), or 385/// NULL (if no declaration was found). This conversion must not be 386/// used anywhere where name lookup could result in an ambiguity. 387/// 388/// The OverloadedFunctionDecl conversion is meant as a stop-gap 389/// solution, since it causes the OverloadedFunctionDecl to be 390/// leaked. FIXME: Eventually, there will be a better way to iterate 391/// over the set of overloaded functions returned by name lookup. 392NamedDecl *Sema::LookupResult::getAsDecl() const { 393 switch (StoredKind) { 394 case SingleDecl: 395 return reinterpret_cast<NamedDecl *>(First); 396 397 case OverloadedDeclFromIdResolver: 398 return MaybeConstructOverloadSet(*Context, 399 IdentifierResolver::iterator::getFromOpaqueValue(First), 400 IdentifierResolver::iterator::getFromOpaqueValue(Last)); 401 402 case OverloadedDeclFromDeclContext: 403 return MaybeConstructOverloadSet(*Context, 404 reinterpret_cast<DeclContext::lookup_iterator>(First), 405 reinterpret_cast<DeclContext::lookup_iterator>(Last)); 406 407 case OverloadedDeclSingleDecl: 408 return reinterpret_cast<OverloadedFunctionDecl*>(First); 409 410 case AmbiguousLookupStoresDecls: 411 case AmbiguousLookupStoresBasePaths: 412 assert(false && 413 "Name lookup returned an ambiguity that could not be handled"); 414 break; 415 } 416 417 return 0; 418} 419 420/// @brief Retrieves the BasePaths structure describing an ambiguous 421/// name lookup, or null. 422BasePaths *Sema::LookupResult::getBasePaths() const { 423 if (StoredKind == AmbiguousLookupStoresBasePaths) 424 return reinterpret_cast<BasePaths *>(First); 425 return 0; 426} 427 428Sema::LookupResult::iterator::reference 429Sema::LookupResult::iterator::operator*() const { 430 switch (Result->StoredKind) { 431 case SingleDecl: 432 return reinterpret_cast<NamedDecl*>(Current); 433 434 case OverloadedDeclSingleDecl: 435 return *reinterpret_cast<NamedDecl**>(Current); 436 437 case OverloadedDeclFromIdResolver: 438 return *IdentifierResolver::iterator::getFromOpaqueValue(Current); 439 440 case OverloadedDeclFromDeclContext: 441 return *reinterpret_cast<DeclContext::lookup_iterator>(Current); 442 443 case AmbiguousLookupStoresDecls: 444 case AmbiguousLookupStoresBasePaths: 445 assert(false && "Cannot look into ambiguous lookup results"); 446 break; 447 } 448 449 return 0; 450} 451 452Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() { 453 switch (Result->StoredKind) { 454 case SingleDecl: 455 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0); 456 break; 457 458 case OverloadedDeclSingleDecl: { 459 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current); 460 ++I; 461 Current = reinterpret_cast<uintptr_t>(I); 462 break; 463 } 464 465 case OverloadedDeclFromIdResolver: { 466 IdentifierResolver::iterator I 467 = IdentifierResolver::iterator::getFromOpaqueValue(Current); 468 ++I; 469 Current = I.getAsOpaqueValue(); 470 break; 471 } 472 473 case OverloadedDeclFromDeclContext: { 474 DeclContext::lookup_iterator I 475 = reinterpret_cast<DeclContext::lookup_iterator>(Current); 476 ++I; 477 Current = reinterpret_cast<uintptr_t>(I); 478 break; 479 } 480 481 case AmbiguousLookupStoresDecls: 482 case AmbiguousLookupStoresBasePaths: 483 assert(false && "Cannot look into ambiguous lookup results"); 484 break; 485 } 486 487 return *this; 488} 489 490Sema::LookupResult::iterator Sema::LookupResult::begin() { 491 assert(!isAmbiguous() && "Lookup into an ambiguous result"); 492 if (StoredKind != OverloadedDeclSingleDecl) 493 return iterator(this, First); 494 OverloadedFunctionDecl * Ovl = 495 reinterpret_cast<OverloadedFunctionDecl*>(First); 496 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_begin()))); 497} 498 499Sema::LookupResult::iterator Sema::LookupResult::end() { 500 assert(!isAmbiguous() && "Lookup into an ambiguous result"); 501 if (StoredKind != OverloadedDeclSingleDecl) 502 return iterator(this, Last); 503 OverloadedFunctionDecl * Ovl = 504 reinterpret_cast<OverloadedFunctionDecl*>(First); 505 return iterator(this, reinterpret_cast<uintptr_t>(&(*Ovl->function_end()))); 506} 507 508static void 509CppNamespaceLookup(ASTContext &Context, DeclContext *NS, 510 DeclarationName Name, Sema::LookupNameKind NameKind, 511 unsigned IDNS, LookupResultsTy &Results, 512 UsingDirectivesTy *UDirs = 0) { 513 514 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 515 516 // Perform qualified name lookup into the LookupCtx. 517 DeclContext::lookup_iterator I, E; 518 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I) 519 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) { 520 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E)); 521 break; 522 } 523 524 if (UDirs) { 525 // For each UsingDirectiveDecl, which common ancestor is equal 526 // to NS, we preform qualified name lookup into namespace nominated by it. 527 UsingDirectivesTy::const_iterator UI, UEnd; 528 llvm::tie(UI, UEnd) = 529 std::equal_range(UDirs->begin(), UDirs->end(), NS, 530 UsingDirAncestorCompare()); 531 532 for (; UI != UEnd; ++UI) 533 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(), 534 Name, NameKind, IDNS, Results); 535 } 536} 537 538static bool isNamespaceOrTranslationUnitScope(Scope *S) { 539 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 540 return Ctx->isFileContext(); 541 return false; 542} 543 544std::pair<bool, Sema::LookupResult> 545Sema::CppLookupName(Scope *S, DeclarationName Name, 546 LookupNameKind NameKind, bool RedeclarationOnly) { 547 assert(getLangOptions().CPlusPlus && 548 "Can perform only C++ lookup"); 549 unsigned IDNS 550 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true); 551 Scope *Initial = S; 552 DeclContext *OutOfLineCtx = 0; 553 IdentifierResolver::iterator 554 I = IdResolver.begin(Name), 555 IEnd = IdResolver.end(); 556 557 // First we lookup local scope. 558 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 559 // ...During unqualified name lookup (3.4.1), the names appear as if 560 // they were declared in the nearest enclosing namespace which contains 561 // both the using-directive and the nominated namespace. 562 // [Note: in this context, “contains” means “contains directly or 563 // indirectly”. 564 // 565 // For example: 566 // namespace A { int i; } 567 // void foo() { 568 // int i; 569 // { 570 // using namespace A; 571 // ++i; // finds local 'i', A::i appears at global scope 572 // } 573 // } 574 // 575 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 576 // Check whether the IdResolver has anything in this scope. 577 for (; I != IEnd && S->isDeclScope(*I); ++I) { 578 if (isAcceptableLookupResult(*I, NameKind, IDNS)) { 579 // We found something. Look for anything else in our scope 580 // with this same name and in an acceptable identifier 581 // namespace, so that we can construct an overload set if we 582 // need to. 583 IdentifierResolver::iterator LastI = I; 584 for (++LastI; LastI != IEnd; ++LastI) { 585 if (!S->isDeclScope(*LastI)) 586 break; 587 } 588 LookupResult Result = 589 LookupResult::CreateLookupResult(Context, I, LastI); 590 return std::make_pair(true, Result); 591 } 592 } 593 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { 594 LookupResult R; 595 // Perform member lookup into struct. 596 // FIXME: In some cases, we know that every name that could be 597 // found by this qualified name lookup will also be on the 598 // identifier chain. For example, inside a class without any 599 // base classes, we never need to perform qualified lookup 600 // because all of the members are on top of the identifier 601 // chain. 602 if (isa<RecordDecl>(Ctx) && 603 (R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly))) 604 return std::make_pair(true, R); 605 606 if (Ctx->getParent() != Ctx->getLexicalParent()) { 607 // It is out of line defined C++ method or struct, we continue 608 // doing name lookup in parent context. Once we will find namespace 609 // or translation-unit we save it for possible checking 610 // using-directives later. 611 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext(); 612 OutOfLineCtx = OutOfLineCtx->getParent()) { 613 if ((R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, 614 RedeclarationOnly))) 615 return std::make_pair(true, R); 616 } 617 } 618 } 619 } 620 621 // Collect UsingDirectiveDecls in all scopes, and recursively all 622 // nominated namespaces by those using-directives. 623 // UsingDirectives are pushed to heap, in common ancestor pointer 624 // value order. 625 // FIXME: Cache this sorted list in Scope structure, and DeclContext, 626 // so we don't build it for each lookup! 627 UsingDirectivesTy UDirs; 628 for (Scope *SC = Initial; SC; SC = SC->getParent()) 629 if (SC->getFlags() & Scope::DeclScope) 630 AddScopeUsingDirectives(SC, UDirs); 631 632 // Sort heapified UsingDirectiveDecls. 633 std::sort_heap(UDirs.begin(), UDirs.end()); 634 635 // Lookup namespace scope, and global scope. 636 // Unqualified name lookup in C++ requires looking into scopes 637 // that aren't strictly lexical, and therefore we walk through the 638 // context as well as walking through the scopes. 639 640 LookupResultsTy LookupResults; 641 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) && 642 "We should have been looking only at file context here already."); 643 bool LookedInCtx = false; 644 LookupResult Result; 645 while (OutOfLineCtx && 646 OutOfLineCtx != S->getEntity() && 647 OutOfLineCtx->isNamespace()) { 648 LookedInCtx = true; 649 650 // Look into context considering using-directives. 651 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS, 652 LookupResults, &UDirs); 653 654 if ((Result = MergeLookupResults(Context, LookupResults)) || 655 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext())) 656 return std::make_pair(true, Result); 657 658 OutOfLineCtx = OutOfLineCtx->getParent(); 659 } 660 661 for (; S; S = S->getParent()) { 662 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 663 assert(Ctx && Ctx->isFileContext() && 664 "We should have been looking only at file context here already."); 665 666 // Check whether the IdResolver has anything in this scope. 667 for (; I != IEnd && S->isDeclScope(*I); ++I) { 668 if (isAcceptableLookupResult(*I, NameKind, IDNS)) { 669 // We found something. Look for anything else in our scope 670 // with this same name and in an acceptable identifier 671 // namespace, so that we can construct an overload set if we 672 // need to. 673 IdentifierResolver::iterator LastI = I; 674 for (++LastI; LastI != IEnd; ++LastI) { 675 if (!S->isDeclScope(*LastI)) 676 break; 677 } 678 679 // We store name lookup result, and continue trying to look into 680 // associated context, and maybe namespaces nominated by 681 // using-directives. 682 LookupResults.push_back( 683 LookupResult::CreateLookupResult(Context, I, LastI)); 684 break; 685 } 686 } 687 688 LookedInCtx = true; 689 // Look into context considering using-directives. 690 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS, 691 LookupResults, &UDirs); 692 693 if ((Result = MergeLookupResults(Context, LookupResults)) || 694 (RedeclarationOnly && !Ctx->isTransparentContext())) 695 return std::make_pair(true, Result); 696 } 697 698 if (!(LookedInCtx || LookupResults.empty())) { 699 // We didn't Performed lookup in Scope entity, so we return 700 // result form IdentifierResolver. 701 assert((LookupResults.size() == 1) && "Wrong size!"); 702 return std::make_pair(true, LookupResults.front()); 703 } 704 return std::make_pair(false, LookupResult()); 705} 706 707/// @brief Perform unqualified name lookup starting from a given 708/// scope. 709/// 710/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 711/// used to find names within the current scope. For example, 'x' in 712/// @code 713/// int x; 714/// int f() { 715/// return x; // unqualified name look finds 'x' in the global scope 716/// } 717/// @endcode 718/// 719/// Different lookup criteria can find different names. For example, a 720/// particular scope can have both a struct and a function of the same 721/// name, and each can be found by certain lookup criteria. For more 722/// information about lookup criteria, see the documentation for the 723/// class LookupCriteria. 724/// 725/// @param S The scope from which unqualified name lookup will 726/// begin. If the lookup criteria permits, name lookup may also search 727/// in the parent scopes. 728/// 729/// @param Name The name of the entity that we are searching for. 730/// 731/// @param Loc If provided, the source location where we're performing 732/// name lookup. At present, this is only used to produce diagnostics when 733/// C library functions (like "malloc") are implicitly declared. 734/// 735/// @returns The result of name lookup, which includes zero or more 736/// declarations and possibly additional information used to diagnose 737/// ambiguities. 738Sema::LookupResult 739Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind, 740 bool RedeclarationOnly, bool AllowBuiltinCreation, 741 SourceLocation Loc) { 742 if (!Name) return LookupResult::CreateLookupResult(Context, 0); 743 744 if (!getLangOptions().CPlusPlus) { 745 // Unqualified name lookup in C/Objective-C is purely lexical, so 746 // search in the declarations attached to the name. 747 unsigned IDNS = 0; 748 switch (NameKind) { 749 case Sema::LookupOrdinaryName: 750 IDNS = Decl::IDNS_Ordinary; 751 break; 752 753 case Sema::LookupTagName: 754 IDNS = Decl::IDNS_Tag; 755 break; 756 757 case Sema::LookupMemberName: 758 IDNS = Decl::IDNS_Member; 759 break; 760 761 case Sema::LookupOperatorName: 762 case Sema::LookupNestedNameSpecifierName: 763 case Sema::LookupNamespaceName: 764 assert(false && "C does not perform these kinds of name lookup"); 765 break; 766 } 767 768 // Scan up the scope chain looking for a decl that matches this 769 // identifier that is in the appropriate namespace. This search 770 // should not take long, as shadowing of names is uncommon, and 771 // deep shadowing is extremely uncommon. 772 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 773 IEnd = IdResolver.end(); 774 I != IEnd; ++I) 775 if ((*I)->isInIdentifierNamespace(IDNS)) { 776 if ((*I)->getAttr<OverloadableAttr>()) { 777 // If this declaration has the "overloadable" attribute, we 778 // might have a set of overloaded functions. 779 780 // Figure out what scope the identifier is in. 781 while (!(S->getFlags() & Scope::DeclScope) || !S->isDeclScope(*I)) 782 S = S->getParent(); 783 784 // Find the last declaration in this scope (with the same 785 // name, naturally). 786 IdentifierResolver::iterator LastI = I; 787 for (++LastI; LastI != IEnd; ++LastI) { 788 if (!S->isDeclScope(*LastI)) 789 break; 790 } 791 792 return LookupResult::CreateLookupResult(Context, I, LastI); 793 } 794 795 // We have a single lookup result. 796 return LookupResult::CreateLookupResult(Context, *I); 797 } 798 } else { 799 // Perform C++ unqualified name lookup. 800 std::pair<bool, LookupResult> MaybeResult = 801 CppLookupName(S, Name, NameKind, RedeclarationOnly); 802 if (MaybeResult.first) 803 return MaybeResult.second; 804 } 805 806 // If we didn't find a use of this identifier, and if the identifier 807 // corresponds to a compiler builtin, create the decl object for the builtin 808 // now, injecting it into translation unit scope, and return it. 809 if (NameKind == LookupOrdinaryName) { 810 IdentifierInfo *II = Name.getAsIdentifierInfo(); 811 if (II && AllowBuiltinCreation) { 812 // If this is a builtin on this (or all) targets, create the decl. 813 if (unsigned BuiltinID = II->getBuiltinID()) { 814 // In C++, we don't have any predefined library functions like 815 // 'malloc'. Instead, we'll just error. 816 if (getLangOptions().CPlusPlus && 817 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 818 return LookupResult::CreateLookupResult(Context, 0); 819 820 return LookupResult::CreateLookupResult(Context, 821 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 822 S, RedeclarationOnly, Loc)); 823 } 824 } 825 if (getLangOptions().ObjC1 && II) { 826 // @interface and @compatibility_alias introduce typedef-like names. 827 // Unlike typedef's, they can only be introduced at file-scope (and are 828 // therefore not scoped decls). They can, however, be shadowed by 829 // other names in IDNS_Ordinary. 830 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II); 831 if (IDI != ObjCInterfaceDecls.end()) 832 return LookupResult::CreateLookupResult(Context, IDI->second); 833 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II); 834 if (I != ObjCAliasDecls.end()) 835 return LookupResult::CreateLookupResult(Context, 836 I->second->getClassInterface()); 837 } 838 } 839 return LookupResult::CreateLookupResult(Context, 0); 840} 841 842/// @brief Perform qualified name lookup into a given context. 843/// 844/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 845/// names when the context of those names is explicit specified, e.g., 846/// "std::vector" or "x->member". 847/// 848/// Different lookup criteria can find different names. For example, a 849/// particular scope can have both a struct and a function of the same 850/// name, and each can be found by certain lookup criteria. For more 851/// information about lookup criteria, see the documentation for the 852/// class LookupCriteria. 853/// 854/// @param LookupCtx The context in which qualified name lookup will 855/// search. If the lookup criteria permits, name lookup may also search 856/// in the parent contexts or (for C++ classes) base classes. 857/// 858/// @param Name The name of the entity that we are searching for. 859/// 860/// @param Criteria The criteria that this routine will use to 861/// determine which names are visible and which names will be 862/// found. Note that name lookup will find a name that is visible by 863/// the given criteria, but the entity itself may not be semantically 864/// correct or even the kind of entity expected based on the 865/// lookup. For example, searching for a nested-name-specifier name 866/// might result in an EnumDecl, which is visible but is not permitted 867/// as a nested-name-specifier in C++03. 868/// 869/// @returns The result of name lookup, which includes zero or more 870/// declarations and possibly additional information used to diagnose 871/// ambiguities. 872Sema::LookupResult 873Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name, 874 LookupNameKind NameKind, bool RedeclarationOnly) { 875 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 876 877 if (!Name) return LookupResult::CreateLookupResult(Context, 0); 878 879 // If we're performing qualified name lookup (e.g., lookup into a 880 // struct), find fields as part of ordinary name lookup. 881 unsigned IDNS 882 = getIdentifierNamespacesFromLookupNameKind(NameKind, 883 getLangOptions().CPlusPlus); 884 if (NameKind == LookupOrdinaryName) 885 IDNS |= Decl::IDNS_Member; 886 887 // Perform qualified name lookup into the LookupCtx. 888 DeclContext::lookup_iterator I, E; 889 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I) 890 if (isAcceptableLookupResult(*I, NameKind, IDNS)) 891 return LookupResult::CreateLookupResult(Context, I, E); 892 893 // If this isn't a C++ class or we aren't allowed to look into base 894 // classes, we're done. 895 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx)) 896 return LookupResult::CreateLookupResult(Context, 0); 897 898 // Perform lookup into our base classes. 899 BasePaths Paths; 900 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx))); 901 902 // Look for this member in our base classes 903 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx), 904 MemberLookupCriteria(Name, NameKind, IDNS), Paths)) 905 return LookupResult::CreateLookupResult(Context, 0); 906 907 // C++ [class.member.lookup]p2: 908 // [...] If the resulting set of declarations are not all from 909 // sub-objects of the same type, or the set has a nonstatic member 910 // and includes members from distinct sub-objects, there is an 911 // ambiguity and the program is ill-formed. Otherwise that set is 912 // the result of the lookup. 913 // FIXME: support using declarations! 914 QualType SubobjectType; 915 int SubobjectNumber = 0; 916 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 917 Path != PathEnd; ++Path) { 918 const BasePathElement &PathElement = Path->back(); 919 920 // Determine whether we're looking at a distinct sub-object or not. 921 if (SubobjectType.isNull()) { 922 // This is the first subobject we've looked at. Record it's type. 923 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 924 SubobjectNumber = PathElement.SubobjectNumber; 925 } else if (SubobjectType 926 != Context.getCanonicalType(PathElement.Base->getType())) { 927 // We found members of the given name in two subobjects of 928 // different types. This lookup is ambiguous. 929 BasePaths *PathsOnHeap = new BasePaths; 930 PathsOnHeap->swap(Paths); 931 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true); 932 } else if (SubobjectNumber != PathElement.SubobjectNumber) { 933 // We have a different subobject of the same type. 934 935 // C++ [class.member.lookup]p5: 936 // A static member, a nested type or an enumerator defined in 937 // a base class T can unambiguously be found even if an object 938 // has more than one base class subobject of type T. 939 Decl *FirstDecl = *Path->Decls.first; 940 if (isa<VarDecl>(FirstDecl) || 941 isa<TypeDecl>(FirstDecl) || 942 isa<EnumConstantDecl>(FirstDecl)) 943 continue; 944 945 if (isa<CXXMethodDecl>(FirstDecl)) { 946 // Determine whether all of the methods are static. 947 bool AllMethodsAreStatic = true; 948 for (DeclContext::lookup_iterator Func = Path->Decls.first; 949 Func != Path->Decls.second; ++Func) { 950 if (!isa<CXXMethodDecl>(*Func)) { 951 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl"); 952 break; 953 } 954 955 if (!cast<CXXMethodDecl>(*Func)->isStatic()) { 956 AllMethodsAreStatic = false; 957 break; 958 } 959 } 960 961 if (AllMethodsAreStatic) 962 continue; 963 } 964 965 // We have found a nonstatic member name in multiple, distinct 966 // subobjects. Name lookup is ambiguous. 967 BasePaths *PathsOnHeap = new BasePaths; 968 PathsOnHeap->swap(Paths); 969 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false); 970 } 971 } 972 973 // Lookup in a base class succeeded; return these results. 974 975 // If we found a function declaration, return an overload set. 976 if (isa<FunctionDecl>(*Paths.front().Decls.first)) 977 return LookupResult::CreateLookupResult(Context, 978 Paths.front().Decls.first, Paths.front().Decls.second); 979 980 // We found a non-function declaration; return a single declaration. 981 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first); 982} 983 984/// @brief Performs name lookup for a name that was parsed in the 985/// source code, and may contain a C++ scope specifier. 986/// 987/// This routine is a convenience routine meant to be called from 988/// contexts that receive a name and an optional C++ scope specifier 989/// (e.g., "N::M::x"). It will then perform either qualified or 990/// unqualified name lookup (with LookupQualifiedName or LookupName, 991/// respectively) on the given name and return those results. 992/// 993/// @param S The scope from which unqualified name lookup will 994/// begin. 995/// 996/// @param SS An optional C++ scope-specified, e.g., "::N::M". 997/// 998/// @param Name The name of the entity that name lookup will 999/// search for. 1000/// 1001/// @param Loc If provided, the source location where we're performing 1002/// name lookup. At present, this is only used to produce diagnostics when 1003/// C library functions (like "malloc") are implicitly declared. 1004/// 1005/// @returns The result of qualified or unqualified name lookup. 1006Sema::LookupResult 1007Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS, 1008 DeclarationName Name, LookupNameKind NameKind, 1009 bool RedeclarationOnly, bool AllowBuiltinCreation, 1010 SourceLocation Loc) { 1011 if (SS) { 1012 if (SS->isInvalid()) 1013 return LookupResult::CreateLookupResult(Context, 0); 1014 1015 if (SS->isSet()) 1016 return LookupQualifiedName(static_cast<DeclContext *>(SS->getScopeRep()), 1017 Name, NameKind, RedeclarationOnly); 1018 } 1019 1020 return LookupName(S, Name, NameKind, RedeclarationOnly, 1021 AllowBuiltinCreation, Loc); 1022} 1023 1024 1025/// @brief Produce a diagnostic describing the ambiguity that resulted 1026/// from name lookup. 1027/// 1028/// @param Result The ambiguous name lookup result. 1029/// 1030/// @param Name The name of the entity that name lookup was 1031/// searching for. 1032/// 1033/// @param NameLoc The location of the name within the source code. 1034/// 1035/// @param LookupRange A source range that provides more 1036/// source-location information concerning the lookup itself. For 1037/// example, this range might highlight a nested-name-specifier that 1038/// precedes the name. 1039/// 1040/// @returns true 1041bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name, 1042 SourceLocation NameLoc, 1043 SourceRange LookupRange) { 1044 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1045 1046 if (BasePaths *Paths = Result.getBasePaths()) 1047 { 1048 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) { 1049 QualType SubobjectType = Paths->front().back().Base->getType(); 1050 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1051 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1052 << LookupRange; 1053 1054 DeclContext::lookup_iterator Found = Paths->front().Decls.first; 1055 while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic()) 1056 ++Found; 1057 1058 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1059 1060 return true; 1061 } 1062 1063 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes && 1064 "Unhandled form of name lookup ambiguity"); 1065 1066 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1067 << Name << LookupRange; 1068 1069 std::set<Decl *> DeclsPrinted; 1070 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end(); 1071 Path != PathEnd; ++Path) { 1072 Decl *D = *Path->Decls.first; 1073 if (DeclsPrinted.insert(D).second) 1074 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1075 } 1076 1077 delete Paths; 1078 return true; 1079 } else if (Result.getKind() == LookupResult::AmbiguousReference) { 1080 1081 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1082 1083 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First), 1084 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last); 1085 1086 for (; DI != DEnd; ++DI) 1087 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1088 1089 delete[] reinterpret_cast<NamedDecl **>(Result.First); 1090 1091 return true; 1092 } 1093 1094 assert(false && "Unhandled form of name lookup ambiguity"); 1095 1096 // We can't reach here. 1097 return true; 1098} 1099 1100// \brief Add the associated classes and namespaces for 1101// argument-dependent lookup with an argument of class type 1102// (C++ [basic.lookup.koenig]p2). 1103static void 1104addAssociatedClassesAndNamespaces(CXXRecordDecl *Class, 1105 ASTContext &Context, 1106 Sema::AssociatedNamespaceSet &AssociatedNamespaces, 1107 Sema::AssociatedClassSet &AssociatedClasses) { 1108 // C++ [basic.lookup.koenig]p2: 1109 // [...] 1110 // -- If T is a class type (including unions), its associated 1111 // classes are: the class itself; the class of which it is a 1112 // member, if any; and its direct and indirect base 1113 // classes. Its associated namespaces are the namespaces in 1114 // which its associated classes are defined. 1115 1116 // Add the class of which it is a member, if any. 1117 DeclContext *Ctx = Class->getDeclContext(); 1118 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1119 AssociatedClasses.insert(EnclosingClass); 1120 1121 // Add the associated namespace for this class. 1122 while (Ctx->isRecord()) 1123 Ctx = Ctx->getParent(); 1124 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx)) 1125 AssociatedNamespaces.insert(EnclosingNamespace); 1126 1127 // Add the class itself. If we've already seen this class, we don't 1128 // need to visit base classes. 1129 if (!AssociatedClasses.insert(Class)) 1130 return; 1131 1132 // FIXME: Handle class template specializations 1133 1134 // Add direct and indirect base classes along with their associated 1135 // namespaces. 1136 llvm::SmallVector<CXXRecordDecl *, 32> Bases; 1137 Bases.push_back(Class); 1138 while (!Bases.empty()) { 1139 // Pop this class off the stack. 1140 Class = Bases.back(); 1141 Bases.pop_back(); 1142 1143 // Visit the base classes. 1144 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(), 1145 BaseEnd = Class->bases_end(); 1146 Base != BaseEnd; ++Base) { 1147 const RecordType *BaseType = Base->getType()->getAsRecordType(); 1148 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 1149 if (AssociatedClasses.insert(BaseDecl)) { 1150 // Find the associated namespace for this base class. 1151 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 1152 while (BaseCtx->isRecord()) 1153 BaseCtx = BaseCtx->getParent(); 1154 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx)) 1155 AssociatedNamespaces.insert(EnclosingNamespace); 1156 1157 // Make sure we visit the bases of this base class. 1158 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 1159 Bases.push_back(BaseDecl); 1160 } 1161 } 1162 } 1163} 1164 1165// \brief Add the associated classes and namespaces for 1166// argument-dependent lookup with an argument of type T 1167// (C++ [basic.lookup.koenig]p2). 1168static void 1169addAssociatedClassesAndNamespaces(QualType T, 1170 ASTContext &Context, 1171 Sema::AssociatedNamespaceSet &AssociatedNamespaces, 1172 Sema::AssociatedClassSet &AssociatedClasses) { 1173 // C++ [basic.lookup.koenig]p2: 1174 // 1175 // For each argument type T in the function call, there is a set 1176 // of zero or more associated namespaces and a set of zero or more 1177 // associated classes to be considered. The sets of namespaces and 1178 // classes is determined entirely by the types of the function 1179 // arguments (and the namespace of any template template 1180 // argument). Typedef names and using-declarations used to specify 1181 // the types do not contribute to this set. The sets of namespaces 1182 // and classes are determined in the following way: 1183 T = Context.getCanonicalType(T).getUnqualifiedType(); 1184 1185 // -- If T is a pointer to U or an array of U, its associated 1186 // namespaces and classes are those associated with U. 1187 // 1188 // We handle this by unwrapping pointer and array types immediately, 1189 // to avoid unnecessary recursion. 1190 while (true) { 1191 if (const PointerType *Ptr = T->getAsPointerType()) 1192 T = Ptr->getPointeeType(); 1193 else if (const ArrayType *Ptr = Context.getAsArrayType(T)) 1194 T = Ptr->getElementType(); 1195 else 1196 break; 1197 } 1198 1199 // -- If T is a fundamental type, its associated sets of 1200 // namespaces and classes are both empty. 1201 if (T->getAsBuiltinType()) 1202 return; 1203 1204 // -- If T is a class type (including unions), its associated 1205 // classes are: the class itself; the class of which it is a 1206 // member, if any; and its direct and indirect base 1207 // classes. Its associated namespaces are the namespaces in 1208 // which its associated classes are defined. 1209 if (const CXXRecordType *ClassType 1210 = dyn_cast_or_null<CXXRecordType>(T->getAsRecordType())) { 1211 addAssociatedClassesAndNamespaces(ClassType->getDecl(), 1212 Context, AssociatedNamespaces, 1213 AssociatedClasses); 1214 return; 1215 } 1216 1217 // -- If T is an enumeration type, its associated namespace is 1218 // the namespace in which it is defined. If it is class 1219 // member, its associated class is the member’s class; else 1220 // it has no associated class. 1221 if (const EnumType *EnumT = T->getAsEnumType()) { 1222 EnumDecl *Enum = EnumT->getDecl(); 1223 1224 DeclContext *Ctx = Enum->getDeclContext(); 1225 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1226 AssociatedClasses.insert(EnclosingClass); 1227 1228 // Add the associated namespace for this class. 1229 while (Ctx->isRecord()) 1230 Ctx = Ctx->getParent(); 1231 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx)) 1232 AssociatedNamespaces.insert(EnclosingNamespace); 1233 1234 return; 1235 } 1236 1237 // -- If T is a function type, its associated namespaces and 1238 // classes are those associated with the function parameter 1239 // types and those associated with the return type. 1240 if (const FunctionType *FunctionType = T->getAsFunctionType()) { 1241 // Return type 1242 addAssociatedClassesAndNamespaces(FunctionType->getResultType(), 1243 Context, 1244 AssociatedNamespaces, AssociatedClasses); 1245 1246 const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FunctionType); 1247 if (!Proto) 1248 return; 1249 1250 // Argument types 1251 for (FunctionTypeProto::arg_type_iterator Arg = Proto->arg_type_begin(), 1252 ArgEnd = Proto->arg_type_end(); 1253 Arg != ArgEnd; ++Arg) 1254 addAssociatedClassesAndNamespaces(*Arg, Context, 1255 AssociatedNamespaces, AssociatedClasses); 1256 1257 return; 1258 } 1259 1260 // -- If T is a pointer to a member function of a class X, its 1261 // associated namespaces and classes are those associated 1262 // with the function parameter types and return type, 1263 // together with those associated with X. 1264 // 1265 // -- If T is a pointer to a data member of class X, its 1266 // associated namespaces and classes are those associated 1267 // with the member type together with those associated with 1268 // X. 1269 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) { 1270 // Handle the type that the pointer to member points to. 1271 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(), 1272 Context, 1273 AssociatedNamespaces, AssociatedClasses); 1274 1275 // Handle the class type into which this points. 1276 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType()) 1277 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()), 1278 Context, 1279 AssociatedNamespaces, AssociatedClasses); 1280 1281 return; 1282 } 1283 1284 // FIXME: What about block pointers? 1285 // FIXME: What about Objective-C message sends? 1286} 1287 1288/// \brief Find the associated classes and namespaces for 1289/// argument-dependent lookup for a call with the given set of 1290/// arguments. 1291/// 1292/// This routine computes the sets of associated classes and associated 1293/// namespaces searched by argument-dependent lookup 1294/// (C++ [basic.lookup.argdep]) for a given set of arguments. 1295void 1296Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1297 AssociatedNamespaceSet &AssociatedNamespaces, 1298 AssociatedClassSet &AssociatedClasses) { 1299 AssociatedNamespaces.clear(); 1300 AssociatedClasses.clear(); 1301 1302 // C++ [basic.lookup.koenig]p2: 1303 // For each argument type T in the function call, there is a set 1304 // of zero or more associated namespaces and a set of zero or more 1305 // associated classes to be considered. The sets of namespaces and 1306 // classes is determined entirely by the types of the function 1307 // arguments (and the namespace of any template template 1308 // argument). 1309 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) { 1310 Expr *Arg = Args[ArgIdx]; 1311 1312 if (Arg->getType() != Context.OverloadTy) { 1313 addAssociatedClassesAndNamespaces(Arg->getType(), Context, 1314 AssociatedNamespaces, AssociatedClasses); 1315 continue; 1316 } 1317 1318 // [...] In addition, if the argument is the name or address of a 1319 // set of overloaded functions and/or function templates, its 1320 // associated classes and namespaces are the union of those 1321 // associated with each of the members of the set: the namespace 1322 // in which the function or function template is defined and the 1323 // classes and namespaces associated with its (non-dependent) 1324 // parameter types and return type. 1325 DeclRefExpr *DRE = 0; 1326 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) { 1327 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) 1328 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr()); 1329 } else 1330 DRE = dyn_cast<DeclRefExpr>(Arg); 1331 if (!DRE) 1332 continue; 1333 1334 OverloadedFunctionDecl *Ovl 1335 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl()); 1336 if (!Ovl) 1337 continue; 1338 1339 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 1340 FuncEnd = Ovl->function_end(); 1341 Func != FuncEnd; ++Func) { 1342 FunctionDecl *FDecl = cast<FunctionDecl>(*Func); 1343 1344 // Add the namespace in which this function was defined. Note 1345 // that, if this is a member function, we do *not* consider the 1346 // enclosing namespace of its class. 1347 DeclContext *Ctx = FDecl->getDeclContext(); 1348 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx)) 1349 AssociatedNamespaces.insert(EnclosingNamespace); 1350 1351 // Add the classes and namespaces associated with the parameter 1352 // types and return type of this function. 1353 addAssociatedClassesAndNamespaces(FDecl->getType(), Context, 1354 AssociatedNamespaces, AssociatedClasses); 1355 } 1356 } 1357} 1358