SemaLookup.cpp revision cac0eaf6caa1035b6a971b32adeea895ba14715c
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/DeclTemplate.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/Parse/DeclSpec.h" 24#include "clang/Basic/Builtins.h" 25#include "clang/Basic/LangOptions.h" 26#include "llvm/ADT/STLExtras.h" 27#include "llvm/ADT/SmallPtrSet.h" 28#include <set> 29#include <vector> 30#include <iterator> 31#include <utility> 32#include <algorithm> 33 34using namespace clang; 35 36typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy; 37typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet; 38typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy; 39 40/// UsingDirAncestorCompare - Implements strict weak ordering of 41/// UsingDirectives. It orders them by address of its common ancestor. 42struct UsingDirAncestorCompare { 43 44 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext. 45 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const { 46 return U->getCommonAncestor() < Ctx; 47 } 48 49 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext. 50 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const { 51 return Ctx < U->getCommonAncestor(); 52 } 53 54 /// @brief Compares UsingDirectiveDecl common ancestors. 55 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const { 56 return U1->getCommonAncestor() < U2->getCommonAncestor(); 57 } 58}; 59 60/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs 61/// (ordered by common ancestors), found in namespace NS, 62/// including all found (recursively) in their nominated namespaces. 63void AddNamespaceUsingDirectives(ASTContext &Context, 64 DeclContext *NS, 65 UsingDirectivesTy &UDirs, 66 NamespaceSet &Visited) { 67 DeclContext::udir_iterator I, End; 68 69 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) { 70 UDirs.push_back(*I); 71 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); 72 NamespaceDecl *Nominated = (*I)->getNominatedNamespace(); 73 if (Visited.insert(Nominated).second) 74 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited); 75 } 76} 77 78/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S, 79/// including all found in the namespaces they nominate. 80static void AddScopeUsingDirectives(ASTContext &Context, Scope *S, 81 UsingDirectivesTy &UDirs) { 82 NamespaceSet VisitedNS; 83 84 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { 85 86 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx)) 87 VisitedNS.insert(NS); 88 89 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS); 90 91 } else { 92 Scope::udir_iterator I = S->using_directives_begin(), 93 End = S->using_directives_end(); 94 95 for (; I != End; ++I) { 96 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>(); 97 UDirs.push_back(UD); 98 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); 99 100 NamespaceDecl *Nominated = UD->getNominatedNamespace(); 101 if (!VisitedNS.count(Nominated)) { 102 VisitedNS.insert(Nominated); 103 AddNamespaceUsingDirectives(Context, Nominated, UDirs, 104 /*ref*/ VisitedNS); 105 } 106 } 107 } 108} 109 110/// MaybeConstructOverloadSet - Name lookup has determined that the 111/// elements in [I, IEnd) have the name that we are looking for, and 112/// *I is a match for the namespace. This routine returns an 113/// appropriate Decl for name lookup, which may either be *I or an 114/// OverloadedFunctionDecl that represents the overloaded functions in 115/// [I, IEnd). 116/// 117/// The existance of this routine is temporary; users of LookupResult 118/// should be able to handle multiple results, to deal with cases of 119/// ambiguity and overloaded functions without needing to create a 120/// Decl node. 121template<typename DeclIterator> 122static NamedDecl * 123MaybeConstructOverloadSet(ASTContext &Context, 124 DeclIterator I, DeclIterator IEnd) { 125 assert(I != IEnd && "Iterator range cannot be empty"); 126 assert(!isa<OverloadedFunctionDecl>(*I) && 127 "Cannot have an overloaded function"); 128 129 if ((*I)->isFunctionOrFunctionTemplate()) { 130 // If we found a function, there might be more functions. If 131 // so, collect them into an overload set. 132 DeclIterator Last = I; 133 OverloadedFunctionDecl *Ovl = 0; 134 for (++Last; 135 Last != IEnd && (*Last)->isFunctionOrFunctionTemplate(); 136 ++Last) { 137 if (!Ovl) { 138 // FIXME: We leak this overload set. Eventually, we want to stop 139 // building the declarations for these overload sets, so there will be 140 // nothing to leak. 141 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(), 142 (*I)->getDeclName()); 143 NamedDecl *ND = (*I)->getUnderlyingDecl(); 144 if (isa<FunctionDecl>(ND)) 145 Ovl->addOverload(cast<FunctionDecl>(ND)); 146 else 147 Ovl->addOverload(cast<FunctionTemplateDecl>(ND)); 148 } 149 150 NamedDecl *ND = (*Last)->getUnderlyingDecl(); 151 if (isa<FunctionDecl>(ND)) 152 Ovl->addOverload(cast<FunctionDecl>(ND)); 153 else 154 Ovl->addOverload(cast<FunctionTemplateDecl>(ND)); 155 } 156 157 // If we had more than one function, we built an overload 158 // set. Return it. 159 if (Ovl) 160 return Ovl; 161 } 162 163 return *I; 164} 165 166/// Merges together multiple LookupResults dealing with duplicated Decl's. 167static Sema::LookupResult 168MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) { 169 typedef Sema::LookupResult LResult; 170 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy; 171 172 // Remove duplicated Decl pointing at same Decl, by storing them in 173 // associative collection. This might be case for code like: 174 // 175 // namespace A { int i; } 176 // namespace B { using namespace A; } 177 // namespace C { using namespace A; } 178 // 179 // void foo() { 180 // using namespace B; 181 // using namespace C; 182 // ++i; // finds A::i, from both namespace B and C at global scope 183 // } 184 // 185 // C++ [namespace.qual].p3: 186 // The same declaration found more than once is not an ambiguity 187 // (because it is still a unique declaration). 188 DeclsSetTy FoundDecls; 189 190 // Counter of tag names, and functions for resolving ambiguity 191 // and name hiding. 192 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0; 193 194 LookupResultsTy::iterator I = Results.begin(), End = Results.end(); 195 196 // No name lookup results, return early. 197 if (I == End) return LResult::CreateLookupResult(Context, 0); 198 199 // Keep track of the tag declaration we found. We only use this if 200 // we find a single tag declaration. 201 TagDecl *TagFound = 0; 202 203 for (; I != End; ++I) { 204 switch (I->getKind()) { 205 case LResult::NotFound: 206 assert(false && 207 "Should be always successful name lookup result here."); 208 break; 209 210 case LResult::AmbiguousReference: 211 case LResult::AmbiguousBaseSubobjectTypes: 212 case LResult::AmbiguousBaseSubobjects: 213 assert(false && "Shouldn't get ambiguous lookup here."); 214 break; 215 216 case LResult::Found: { 217 NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl(); 218 219 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) { 220 TagFound = TD->getCanonicalDecl(); 221 TagNames += FoundDecls.insert(TagFound)? 1 : 0; 222 } else if (ND->isFunctionOrFunctionTemplate()) 223 Functions += FoundDecls.insert(ND)? 1 : 0; 224 else 225 FoundDecls.insert(ND); 226 break; 227 } 228 229 case LResult::FoundOverloaded: 230 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI) 231 Functions += FoundDecls.insert(*FI)? 1 : 0; 232 break; 233 } 234 } 235 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions; 236 bool Ambiguous = false, NameHidesTags = false; 237 238 if (FoundDecls.size() == 1) { 239 // 1) Exactly one result. 240 } else if (TagNames > 1) { 241 // 2) Multiple tag names (even though they may be hidden by an 242 // object name). 243 Ambiguous = true; 244 } else if (FoundDecls.size() - TagNames == 1) { 245 // 3) Ordinary name hides (optional) tag. 246 NameHidesTags = TagFound; 247 } else if (Functions) { 248 // C++ [basic.lookup].p1: 249 // ... Name lookup may associate more than one declaration with 250 // a name if it finds the name to be a function name; the declarations 251 // are said to form a set of overloaded functions (13.1). 252 // Overload resolution (13.3) takes place after name lookup has succeeded. 253 // 254 if (!OrdinaryNonFunc) { 255 // 4) Functions hide tag names. 256 NameHidesTags = TagFound; 257 } else { 258 // 5) Functions + ordinary names. 259 Ambiguous = true; 260 } 261 } else { 262 // 6) Multiple non-tag names 263 Ambiguous = true; 264 } 265 266 if (Ambiguous) 267 return LResult::CreateLookupResult(Context, 268 FoundDecls.begin(), FoundDecls.size()); 269 if (NameHidesTags) { 270 // There's only one tag, TagFound. Remove it. 271 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?"); 272 FoundDecls.erase(TagFound); 273 } 274 275 // Return successful name lookup result. 276 return LResult::CreateLookupResult(Context, 277 MaybeConstructOverloadSet(Context, 278 FoundDecls.begin(), 279 FoundDecls.end())); 280} 281 282// Retrieve the set of identifier namespaces that correspond to a 283// specific kind of name lookup. 284inline unsigned 285getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind, 286 bool CPlusPlus) { 287 unsigned IDNS = 0; 288 switch (NameKind) { 289 case Sema::LookupOrdinaryName: 290 case Sema::LookupOperatorName: 291 case Sema::LookupRedeclarationWithLinkage: 292 IDNS = Decl::IDNS_Ordinary; 293 if (CPlusPlus) 294 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member; 295 break; 296 297 case Sema::LookupTagName: 298 IDNS = Decl::IDNS_Tag; 299 break; 300 301 case Sema::LookupMemberName: 302 IDNS = Decl::IDNS_Member; 303 if (CPlusPlus) 304 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 305 break; 306 307 case Sema::LookupNestedNameSpecifierName: 308 case Sema::LookupNamespaceName: 309 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member; 310 break; 311 312 case Sema::LookupObjCProtocolName: 313 IDNS = Decl::IDNS_ObjCProtocol; 314 break; 315 316 case Sema::LookupObjCImplementationName: 317 IDNS = Decl::IDNS_ObjCImplementation; 318 break; 319 320 case Sema::LookupObjCCategoryImplName: 321 IDNS = Decl::IDNS_ObjCCategoryImpl; 322 break; 323 } 324 return IDNS; 325} 326 327Sema::LookupResult 328Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) { 329 if (D) 330 D = D->getUnderlyingDecl(); 331 332 LookupResult Result; 333 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))? 334 OverloadedDeclSingleDecl : SingleDecl; 335 Result.First = reinterpret_cast<uintptr_t>(D); 336 Result.Last = 0; 337 Result.Context = &Context; 338 return Result; 339} 340 341/// @brief Moves the name-lookup results from Other to this LookupResult. 342Sema::LookupResult 343Sema::LookupResult::CreateLookupResult(ASTContext &Context, 344 IdentifierResolver::iterator F, 345 IdentifierResolver::iterator L) { 346 LookupResult Result; 347 Result.Context = &Context; 348 349 if (F != L && (*F)->isFunctionOrFunctionTemplate()) { 350 IdentifierResolver::iterator Next = F; 351 ++Next; 352 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) { 353 Result.StoredKind = OverloadedDeclFromIdResolver; 354 Result.First = F.getAsOpaqueValue(); 355 Result.Last = L.getAsOpaqueValue(); 356 return Result; 357 } 358 } 359 360 NamedDecl *D = *F; 361 if (D) 362 D = D->getUnderlyingDecl(); 363 364 Result.StoredKind = SingleDecl; 365 Result.First = reinterpret_cast<uintptr_t>(D); 366 Result.Last = 0; 367 return Result; 368} 369 370Sema::LookupResult 371Sema::LookupResult::CreateLookupResult(ASTContext &Context, 372 DeclContext::lookup_iterator F, 373 DeclContext::lookup_iterator L) { 374 LookupResult Result; 375 Result.Context = &Context; 376 377 if (F != L && (*F)->isFunctionOrFunctionTemplate()) { 378 DeclContext::lookup_iterator Next = F; 379 ++Next; 380 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) { 381 Result.StoredKind = OverloadedDeclFromDeclContext; 382 Result.First = reinterpret_cast<uintptr_t>(F); 383 Result.Last = reinterpret_cast<uintptr_t>(L); 384 return Result; 385 } 386 } 387 388 NamedDecl *D = *F; 389 if (D) 390 D = D->getUnderlyingDecl(); 391 392 Result.StoredKind = SingleDecl; 393 Result.First = reinterpret_cast<uintptr_t>(D); 394 Result.Last = 0; 395 return Result; 396} 397 398/// @brief Determine the result of name lookup. 399Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const { 400 switch (StoredKind) { 401 case SingleDecl: 402 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound; 403 404 case OverloadedDeclSingleDecl: 405 case OverloadedDeclFromIdResolver: 406 case OverloadedDeclFromDeclContext: 407 return FoundOverloaded; 408 409 case AmbiguousLookupStoresBasePaths: 410 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects; 411 412 case AmbiguousLookupStoresDecls: 413 return AmbiguousReference; 414 } 415 416 // We can't ever get here. 417 return NotFound; 418} 419 420/// @brief Converts the result of name lookup into a single (possible 421/// NULL) pointer to a declaration. 422/// 423/// The resulting declaration will either be the declaration we found 424/// (if only a single declaration was found), an 425/// OverloadedFunctionDecl (if an overloaded function was found), or 426/// NULL (if no declaration was found). This conversion must not be 427/// used anywhere where name lookup could result in an ambiguity. 428/// 429/// The OverloadedFunctionDecl conversion is meant as a stop-gap 430/// solution, since it causes the OverloadedFunctionDecl to be 431/// leaked. FIXME: Eventually, there will be a better way to iterate 432/// over the set of overloaded functions returned by name lookup. 433NamedDecl *Sema::LookupResult::getAsDecl() const { 434 switch (StoredKind) { 435 case SingleDecl: 436 return reinterpret_cast<NamedDecl *>(First); 437 438 case OverloadedDeclFromIdResolver: 439 return MaybeConstructOverloadSet(*Context, 440 IdentifierResolver::iterator::getFromOpaqueValue(First), 441 IdentifierResolver::iterator::getFromOpaqueValue(Last)); 442 443 case OverloadedDeclFromDeclContext: 444 return MaybeConstructOverloadSet(*Context, 445 reinterpret_cast<DeclContext::lookup_iterator>(First), 446 reinterpret_cast<DeclContext::lookup_iterator>(Last)); 447 448 case OverloadedDeclSingleDecl: 449 return reinterpret_cast<OverloadedFunctionDecl*>(First); 450 451 case AmbiguousLookupStoresDecls: 452 case AmbiguousLookupStoresBasePaths: 453 assert(false && 454 "Name lookup returned an ambiguity that could not be handled"); 455 break; 456 } 457 458 return 0; 459} 460 461/// @brief Retrieves the BasePaths structure describing an ambiguous 462/// name lookup, or null. 463BasePaths *Sema::LookupResult::getBasePaths() const { 464 if (StoredKind == AmbiguousLookupStoresBasePaths) 465 return reinterpret_cast<BasePaths *>(First); 466 return 0; 467} 468 469Sema::LookupResult::iterator::reference 470Sema::LookupResult::iterator::operator*() const { 471 switch (Result->StoredKind) { 472 case SingleDecl: 473 return reinterpret_cast<NamedDecl*>(Current); 474 475 case OverloadedDeclSingleDecl: 476 return *reinterpret_cast<NamedDecl**>(Current); 477 478 case OverloadedDeclFromIdResolver: 479 return *IdentifierResolver::iterator::getFromOpaqueValue(Current); 480 481 case AmbiguousLookupStoresBasePaths: 482 if (Result->Last) 483 return *reinterpret_cast<NamedDecl**>(Current); 484 485 // Fall through to handle the DeclContext::lookup_iterator we're 486 // storing. 487 488 case OverloadedDeclFromDeclContext: 489 case AmbiguousLookupStoresDecls: 490 return *reinterpret_cast<DeclContext::lookup_iterator>(Current); 491 } 492 493 return 0; 494} 495 496Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() { 497 switch (Result->StoredKind) { 498 case SingleDecl: 499 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0); 500 break; 501 502 case OverloadedDeclSingleDecl: { 503 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current); 504 ++I; 505 Current = reinterpret_cast<uintptr_t>(I); 506 break; 507 } 508 509 case OverloadedDeclFromIdResolver: { 510 IdentifierResolver::iterator I 511 = IdentifierResolver::iterator::getFromOpaqueValue(Current); 512 ++I; 513 Current = I.getAsOpaqueValue(); 514 break; 515 } 516 517 case AmbiguousLookupStoresBasePaths: 518 if (Result->Last) { 519 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current); 520 ++I; 521 Current = reinterpret_cast<uintptr_t>(I); 522 break; 523 } 524 // Fall through to handle the DeclContext::lookup_iterator we're 525 // storing. 526 527 case OverloadedDeclFromDeclContext: 528 case AmbiguousLookupStoresDecls: { 529 DeclContext::lookup_iterator I 530 = reinterpret_cast<DeclContext::lookup_iterator>(Current); 531 ++I; 532 Current = reinterpret_cast<uintptr_t>(I); 533 break; 534 } 535 } 536 537 return *this; 538} 539 540Sema::LookupResult::iterator Sema::LookupResult::begin() { 541 switch (StoredKind) { 542 case SingleDecl: 543 case OverloadedDeclFromIdResolver: 544 case OverloadedDeclFromDeclContext: 545 case AmbiguousLookupStoresDecls: 546 return iterator(this, First); 547 548 case OverloadedDeclSingleDecl: { 549 OverloadedFunctionDecl * Ovl = 550 reinterpret_cast<OverloadedFunctionDecl*>(First); 551 return iterator(this, 552 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin()))); 553 } 554 555 case AmbiguousLookupStoresBasePaths: 556 if (Last) 557 return iterator(this, 558 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin())); 559 else 560 return iterator(this, 561 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first)); 562 } 563 564 // Required to suppress GCC warning. 565 return iterator(); 566} 567 568Sema::LookupResult::iterator Sema::LookupResult::end() { 569 switch (StoredKind) { 570 case SingleDecl: 571 case OverloadedDeclFromIdResolver: 572 case OverloadedDeclFromDeclContext: 573 case AmbiguousLookupStoresDecls: 574 return iterator(this, Last); 575 576 case OverloadedDeclSingleDecl: { 577 OverloadedFunctionDecl * Ovl = 578 reinterpret_cast<OverloadedFunctionDecl*>(First); 579 return iterator(this, 580 reinterpret_cast<uintptr_t>(&(*Ovl->function_end()))); 581 } 582 583 case AmbiguousLookupStoresBasePaths: 584 if (Last) 585 return iterator(this, 586 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end())); 587 else 588 return iterator(this, reinterpret_cast<uintptr_t>( 589 getBasePaths()->front().Decls.second)); 590 } 591 592 // Required to suppress GCC warning. 593 return iterator(); 594} 595 596void Sema::LookupResult::Destroy() { 597 if (BasePaths *Paths = getBasePaths()) 598 delete Paths; 599 else if (getKind() == AmbiguousReference) 600 delete[] reinterpret_cast<NamedDecl **>(First); 601} 602 603static void 604CppNamespaceLookup(ASTContext &Context, DeclContext *NS, 605 DeclarationName Name, Sema::LookupNameKind NameKind, 606 unsigned IDNS, LookupResultsTy &Results, 607 UsingDirectivesTy *UDirs = 0) { 608 609 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 610 611 // Perform qualified name lookup into the LookupCtx. 612 DeclContext::lookup_iterator I, E; 613 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I) 614 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) { 615 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E)); 616 break; 617 } 618 619 if (UDirs) { 620 // For each UsingDirectiveDecl, which common ancestor is equal 621 // to NS, we preform qualified name lookup into namespace nominated by it. 622 UsingDirectivesTy::const_iterator UI, UEnd; 623 llvm::tie(UI, UEnd) = 624 std::equal_range(UDirs->begin(), UDirs->end(), NS, 625 UsingDirAncestorCompare()); 626 627 for (; UI != UEnd; ++UI) 628 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(), 629 Name, NameKind, IDNS, Results); 630 } 631} 632 633static bool isNamespaceOrTranslationUnitScope(Scope *S) { 634 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 635 return Ctx->isFileContext(); 636 return false; 637} 638 639// Find the next outer declaration context corresponding to this scope. 640static DeclContext *findOuterContext(Scope *S) { 641 for (S = S->getParent(); S; S = S->getParent()) 642 if (S->getEntity()) 643 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext(); 644 645 return 0; 646} 647 648std::pair<bool, Sema::LookupResult> 649Sema::CppLookupName(Scope *S, DeclarationName Name, 650 LookupNameKind NameKind, bool RedeclarationOnly) { 651 assert(getLangOptions().CPlusPlus && 652 "Can perform only C++ lookup"); 653 unsigned IDNS 654 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true); 655 656 // If we're testing for redeclarations, also look in the friend namespaces. 657 if (RedeclarationOnly) { 658 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend; 659 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend; 660 } 661 662 Scope *Initial = S; 663 DeclContext *OutOfLineCtx = 0; 664 IdentifierResolver::iterator 665 I = IdResolver.begin(Name), 666 IEnd = IdResolver.end(); 667 668 // First we lookup local scope. 669 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 670 // ...During unqualified name lookup (3.4.1), the names appear as if 671 // they were declared in the nearest enclosing namespace which contains 672 // both the using-directive and the nominated namespace. 673 // [Note: in this context, "contains" means "contains directly or 674 // indirectly". 675 // 676 // For example: 677 // namespace A { int i; } 678 // void foo() { 679 // int i; 680 // { 681 // using namespace A; 682 // ++i; // finds local 'i', A::i appears at global scope 683 // } 684 // } 685 // 686 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 687 // Check whether the IdResolver has anything in this scope. 688 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) { 689 if (isAcceptableLookupResult(*I, NameKind, IDNS)) { 690 // We found something. Look for anything else in our scope 691 // with this same name and in an acceptable identifier 692 // namespace, so that we can construct an overload set if we 693 // need to. 694 IdentifierResolver::iterator LastI = I; 695 for (++LastI; LastI != IEnd; ++LastI) { 696 if (!S->isDeclScope(DeclPtrTy::make(*LastI))) 697 break; 698 } 699 LookupResult Result = 700 LookupResult::CreateLookupResult(Context, I, LastI); 701 return std::make_pair(true, Result); 702 } 703 } 704 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { 705 LookupResult R; 706 707 DeclContext *OuterCtx = findOuterContext(S); 708 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx; 709 Ctx = Ctx->getLookupParent()) { 710 if (Ctx->isFunctionOrMethod()) 711 continue; 712 713 // Perform qualified name lookup into this context. 714 // FIXME: In some cases, we know that every name that could be found by 715 // this qualified name lookup will also be on the identifier chain. For 716 // example, inside a class without any base classes, we never need to 717 // perform qualified lookup because all of the members are on top of the 718 // identifier chain. 719 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly); 720 if (R) 721 return std::make_pair(true, R); 722 } 723 } 724 } 725 726 // Collect UsingDirectiveDecls in all scopes, and recursively all 727 // nominated namespaces by those using-directives. 728 // UsingDirectives are pushed to heap, in common ancestor pointer value order. 729 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 730 // don't build it for each lookup! 731 UsingDirectivesTy UDirs; 732 for (Scope *SC = Initial; SC; SC = SC->getParent()) 733 if (SC->getFlags() & Scope::DeclScope) 734 AddScopeUsingDirectives(Context, SC, UDirs); 735 736 // Sort heapified UsingDirectiveDecls. 737 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare()); 738 739 // Lookup namespace scope, and global scope. 740 // Unqualified name lookup in C++ requires looking into scopes 741 // that aren't strictly lexical, and therefore we walk through the 742 // context as well as walking through the scopes. 743 744 LookupResultsTy LookupResults; 745 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) && 746 "We should have been looking only at file context here already."); 747 bool LookedInCtx = false; 748 LookupResult Result; 749 while (OutOfLineCtx && 750 OutOfLineCtx != S->getEntity() && 751 OutOfLineCtx->isNamespace()) { 752 LookedInCtx = true; 753 754 // Look into context considering using-directives. 755 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS, 756 LookupResults, &UDirs); 757 758 if ((Result = MergeLookupResults(Context, LookupResults)) || 759 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext())) 760 return std::make_pair(true, Result); 761 762 OutOfLineCtx = OutOfLineCtx->getParent(); 763 } 764 765 for (; S; S = S->getParent()) { 766 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 767 if (Ctx->isTransparentContext()) 768 continue; 769 770 assert(Ctx && Ctx->isFileContext() && 771 "We should have been looking only at file context here already."); 772 773 // Check whether the IdResolver has anything in this scope. 774 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) { 775 if (isAcceptableLookupResult(*I, NameKind, IDNS)) { 776 // We found something. Look for anything else in our scope 777 // with this same name and in an acceptable identifier 778 // namespace, so that we can construct an overload set if we 779 // need to. 780 IdentifierResolver::iterator LastI = I; 781 for (++LastI; LastI != IEnd; ++LastI) { 782 if (!S->isDeclScope(DeclPtrTy::make(*LastI))) 783 break; 784 } 785 786 // We store name lookup result, and continue trying to look into 787 // associated context, and maybe namespaces nominated by 788 // using-directives. 789 LookupResults.push_back( 790 LookupResult::CreateLookupResult(Context, I, LastI)); 791 break; 792 } 793 } 794 795 LookedInCtx = true; 796 // Look into context considering using-directives. 797 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS, 798 LookupResults, &UDirs); 799 800 if ((Result = MergeLookupResults(Context, LookupResults)) || 801 (RedeclarationOnly && !Ctx->isTransparentContext())) 802 return std::make_pair(true, Result); 803 } 804 805 if (!(LookedInCtx || LookupResults.empty())) { 806 // We didn't Performed lookup in Scope entity, so we return 807 // result form IdentifierResolver. 808 assert((LookupResults.size() == 1) && "Wrong size!"); 809 return std::make_pair(true, LookupResults.front()); 810 } 811 return std::make_pair(false, LookupResult()); 812} 813 814/// @brief Perform unqualified name lookup starting from a given 815/// scope. 816/// 817/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 818/// used to find names within the current scope. For example, 'x' in 819/// @code 820/// int x; 821/// int f() { 822/// return x; // unqualified name look finds 'x' in the global scope 823/// } 824/// @endcode 825/// 826/// Different lookup criteria can find different names. For example, a 827/// particular scope can have both a struct and a function of the same 828/// name, and each can be found by certain lookup criteria. For more 829/// information about lookup criteria, see the documentation for the 830/// class LookupCriteria. 831/// 832/// @param S The scope from which unqualified name lookup will 833/// begin. If the lookup criteria permits, name lookup may also search 834/// in the parent scopes. 835/// 836/// @param Name The name of the entity that we are searching for. 837/// 838/// @param Loc If provided, the source location where we're performing 839/// name lookup. At present, this is only used to produce diagnostics when 840/// C library functions (like "malloc") are implicitly declared. 841/// 842/// @returns The result of name lookup, which includes zero or more 843/// declarations and possibly additional information used to diagnose 844/// ambiguities. 845Sema::LookupResult 846Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind, 847 bool RedeclarationOnly, bool AllowBuiltinCreation, 848 SourceLocation Loc) { 849 if (!Name) return LookupResult::CreateLookupResult(Context, 0); 850 851 if (!getLangOptions().CPlusPlus) { 852 // Unqualified name lookup in C/Objective-C is purely lexical, so 853 // search in the declarations attached to the name. 854 unsigned IDNS = 0; 855 switch (NameKind) { 856 case Sema::LookupOrdinaryName: 857 IDNS = Decl::IDNS_Ordinary; 858 break; 859 860 case Sema::LookupTagName: 861 IDNS = Decl::IDNS_Tag; 862 break; 863 864 case Sema::LookupMemberName: 865 IDNS = Decl::IDNS_Member; 866 break; 867 868 case Sema::LookupOperatorName: 869 case Sema::LookupNestedNameSpecifierName: 870 case Sema::LookupNamespaceName: 871 assert(false && "C does not perform these kinds of name lookup"); 872 break; 873 874 case Sema::LookupRedeclarationWithLinkage: 875 // Find the nearest non-transparent declaration scope. 876 while (!(S->getFlags() & Scope::DeclScope) || 877 (S->getEntity() && 878 static_cast<DeclContext *>(S->getEntity()) 879 ->isTransparentContext())) 880 S = S->getParent(); 881 IDNS = Decl::IDNS_Ordinary; 882 break; 883 884 case Sema::LookupObjCProtocolName: 885 IDNS = Decl::IDNS_ObjCProtocol; 886 break; 887 888 case Sema::LookupObjCImplementationName: 889 IDNS = Decl::IDNS_ObjCImplementation; 890 break; 891 892 case Sema::LookupObjCCategoryImplName: 893 IDNS = Decl::IDNS_ObjCCategoryImpl; 894 break; 895 } 896 897 // Scan up the scope chain looking for a decl that matches this 898 // identifier that is in the appropriate namespace. This search 899 // should not take long, as shadowing of names is uncommon, and 900 // deep shadowing is extremely uncommon. 901 bool LeftStartingScope = false; 902 903 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 904 IEnd = IdResolver.end(); 905 I != IEnd; ++I) 906 if ((*I)->isInIdentifierNamespace(IDNS)) { 907 if (NameKind == LookupRedeclarationWithLinkage) { 908 // Determine whether this (or a previous) declaration is 909 // out-of-scope. 910 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I))) 911 LeftStartingScope = true; 912 913 // If we found something outside of our starting scope that 914 // does not have linkage, skip it. 915 if (LeftStartingScope && !((*I)->hasLinkage())) 916 continue; 917 } 918 919 if ((*I)->getAttr<OverloadableAttr>()) { 920 // If this declaration has the "overloadable" attribute, we 921 // might have a set of overloaded functions. 922 923 // Figure out what scope the identifier is in. 924 while (!(S->getFlags() & Scope::DeclScope) || 925 !S->isDeclScope(DeclPtrTy::make(*I))) 926 S = S->getParent(); 927 928 // Find the last declaration in this scope (with the same 929 // name, naturally). 930 IdentifierResolver::iterator LastI = I; 931 for (++LastI; LastI != IEnd; ++LastI) { 932 if (!S->isDeclScope(DeclPtrTy::make(*LastI))) 933 break; 934 } 935 936 return LookupResult::CreateLookupResult(Context, I, LastI); 937 } 938 939 // We have a single lookup result. 940 return LookupResult::CreateLookupResult(Context, *I); 941 } 942 } else { 943 // Perform C++ unqualified name lookup. 944 std::pair<bool, LookupResult> MaybeResult = 945 CppLookupName(S, Name, NameKind, RedeclarationOnly); 946 if (MaybeResult.first) 947 return MaybeResult.second; 948 } 949 950 // If we didn't find a use of this identifier, and if the identifier 951 // corresponds to a compiler builtin, create the decl object for the builtin 952 // now, injecting it into translation unit scope, and return it. 953 if (NameKind == LookupOrdinaryName || 954 NameKind == LookupRedeclarationWithLinkage) { 955 IdentifierInfo *II = Name.getAsIdentifierInfo(); 956 if (II && AllowBuiltinCreation) { 957 // If this is a builtin on this (or all) targets, create the decl. 958 if (unsigned BuiltinID = II->getBuiltinID()) { 959 // In C++, we don't have any predefined library functions like 960 // 'malloc'. Instead, we'll just error. 961 if (getLangOptions().CPlusPlus && 962 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 963 return LookupResult::CreateLookupResult(Context, 0); 964 965 return LookupResult::CreateLookupResult(Context, 966 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 967 S, RedeclarationOnly, Loc)); 968 } 969 } 970 } 971 return LookupResult::CreateLookupResult(Context, 0); 972} 973 974/// @brief Perform qualified name lookup into a given context. 975/// 976/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 977/// names when the context of those names is explicit specified, e.g., 978/// "std::vector" or "x->member". 979/// 980/// Different lookup criteria can find different names. For example, a 981/// particular scope can have both a struct and a function of the same 982/// name, and each can be found by certain lookup criteria. For more 983/// information about lookup criteria, see the documentation for the 984/// class LookupCriteria. 985/// 986/// @param LookupCtx The context in which qualified name lookup will 987/// search. If the lookup criteria permits, name lookup may also search 988/// in the parent contexts or (for C++ classes) base classes. 989/// 990/// @param Name The name of the entity that we are searching for. 991/// 992/// @param Criteria The criteria that this routine will use to 993/// determine which names are visible and which names will be 994/// found. Note that name lookup will find a name that is visible by 995/// the given criteria, but the entity itself may not be semantically 996/// correct or even the kind of entity expected based on the 997/// lookup. For example, searching for a nested-name-specifier name 998/// might result in an EnumDecl, which is visible but is not permitted 999/// as a nested-name-specifier in C++03. 1000/// 1001/// @returns The result of name lookup, which includes zero or more 1002/// declarations and possibly additional information used to diagnose 1003/// ambiguities. 1004Sema::LookupResult 1005Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name, 1006 LookupNameKind NameKind, bool RedeclarationOnly) { 1007 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 1008 1009 if (!Name) 1010 return LookupResult::CreateLookupResult(Context, 0); 1011 1012 // If we're performing qualified name lookup (e.g., lookup into a 1013 // struct), find fields as part of ordinary name lookup. 1014 unsigned IDNS 1015 = getIdentifierNamespacesFromLookupNameKind(NameKind, 1016 getLangOptions().CPlusPlus); 1017 if (NameKind == LookupOrdinaryName) 1018 IDNS |= Decl::IDNS_Member; 1019 1020 // Make sure that the declaration context is complete. 1021 assert((!isa<TagDecl>(LookupCtx) || 1022 LookupCtx->isDependentContext() || 1023 cast<TagDecl>(LookupCtx)->isDefinition() || 1024 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>() 1025 ->isBeingDefined()) && 1026 "Declaration context must already be complete!"); 1027 1028 // Perform qualified name lookup into the LookupCtx. 1029 DeclContext::lookup_iterator I, E; 1030 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I) 1031 if (isAcceptableLookupResult(*I, NameKind, IDNS)) 1032 return LookupResult::CreateLookupResult(Context, I, E); 1033 1034 // If this isn't a C++ class, we aren't allowed to look into base 1035 // classes, we're done. 1036 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx)) 1037 return LookupResult::CreateLookupResult(Context, 0); 1038 1039 // Perform lookup into our base classes. 1040 BasePaths Paths; 1041 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx))); 1042 1043 // Look for this member in our base classes 1044 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx), 1045 MemberLookupCriteria(Name, NameKind, IDNS), Paths)) 1046 return LookupResult::CreateLookupResult(Context, 0); 1047 1048 // C++ [class.member.lookup]p2: 1049 // [...] If the resulting set of declarations are not all from 1050 // sub-objects of the same type, or the set has a nonstatic member 1051 // and includes members from distinct sub-objects, there is an 1052 // ambiguity and the program is ill-formed. Otherwise that set is 1053 // the result of the lookup. 1054 // FIXME: support using declarations! 1055 QualType SubobjectType; 1056 int SubobjectNumber = 0; 1057 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 1058 Path != PathEnd; ++Path) { 1059 const BasePathElement &PathElement = Path->back(); 1060 1061 // Determine whether we're looking at a distinct sub-object or not. 1062 if (SubobjectType.isNull()) { 1063 // This is the first subobject we've looked at. Record it's type. 1064 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 1065 SubobjectNumber = PathElement.SubobjectNumber; 1066 } else if (SubobjectType 1067 != Context.getCanonicalType(PathElement.Base->getType())) { 1068 // We found members of the given name in two subobjects of 1069 // different types. This lookup is ambiguous. 1070 BasePaths *PathsOnHeap = new BasePaths; 1071 PathsOnHeap->swap(Paths); 1072 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true); 1073 } else if (SubobjectNumber != PathElement.SubobjectNumber) { 1074 // We have a different subobject of the same type. 1075 1076 // C++ [class.member.lookup]p5: 1077 // A static member, a nested type or an enumerator defined in 1078 // a base class T can unambiguously be found even if an object 1079 // has more than one base class subobject of type T. 1080 Decl *FirstDecl = *Path->Decls.first; 1081 if (isa<VarDecl>(FirstDecl) || 1082 isa<TypeDecl>(FirstDecl) || 1083 isa<EnumConstantDecl>(FirstDecl)) 1084 continue; 1085 1086 if (isa<CXXMethodDecl>(FirstDecl)) { 1087 // Determine whether all of the methods are static. 1088 bool AllMethodsAreStatic = true; 1089 for (DeclContext::lookup_iterator Func = Path->Decls.first; 1090 Func != Path->Decls.second; ++Func) { 1091 if (!isa<CXXMethodDecl>(*Func)) { 1092 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl"); 1093 break; 1094 } 1095 1096 if (!cast<CXXMethodDecl>(*Func)->isStatic()) { 1097 AllMethodsAreStatic = false; 1098 break; 1099 } 1100 } 1101 1102 if (AllMethodsAreStatic) 1103 continue; 1104 } 1105 1106 // We have found a nonstatic member name in multiple, distinct 1107 // subobjects. Name lookup is ambiguous. 1108 BasePaths *PathsOnHeap = new BasePaths; 1109 PathsOnHeap->swap(Paths); 1110 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false); 1111 } 1112 } 1113 1114 // Lookup in a base class succeeded; return these results. 1115 1116 // If we found a function declaration, return an overload set. 1117 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate()) 1118 return LookupResult::CreateLookupResult(Context, 1119 Paths.front().Decls.first, Paths.front().Decls.second); 1120 1121 // We found a non-function declaration; return a single declaration. 1122 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first); 1123} 1124 1125/// @brief Performs name lookup for a name that was parsed in the 1126/// source code, and may contain a C++ scope specifier. 1127/// 1128/// This routine is a convenience routine meant to be called from 1129/// contexts that receive a name and an optional C++ scope specifier 1130/// (e.g., "N::M::x"). It will then perform either qualified or 1131/// unqualified name lookup (with LookupQualifiedName or LookupName, 1132/// respectively) on the given name and return those results. 1133/// 1134/// @param S The scope from which unqualified name lookup will 1135/// begin. 1136/// 1137/// @param SS An optional C++ scope-specifier, e.g., "::N::M". 1138/// 1139/// @param Name The name of the entity that name lookup will 1140/// search for. 1141/// 1142/// @param Loc If provided, the source location where we're performing 1143/// name lookup. At present, this is only used to produce diagnostics when 1144/// C library functions (like "malloc") are implicitly declared. 1145/// 1146/// @param EnteringContext Indicates whether we are going to enter the 1147/// context of the scope-specifier SS (if present). 1148/// 1149/// @returns The result of qualified or unqualified name lookup. 1150Sema::LookupResult 1151Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS, 1152 DeclarationName Name, LookupNameKind NameKind, 1153 bool RedeclarationOnly, bool AllowBuiltinCreation, 1154 SourceLocation Loc, 1155 bool EnteringContext) { 1156 if (SS && SS->isInvalid()) { 1157 // When the scope specifier is invalid, don't even look for 1158 // anything. 1159 return LookupResult::CreateLookupResult(Context, 0); 1160 } 1161 1162 if (SS && SS->isSet()) { 1163 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 1164 // We have resolved the scope specifier to a particular declaration 1165 // contex, and will perform name lookup in that context. 1166 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS)) 1167 return LookupResult::CreateLookupResult(Context, 0); 1168 1169 return LookupQualifiedName(DC, Name, NameKind, RedeclarationOnly); 1170 } 1171 1172 // We could not resolve the scope specified to a specific declaration 1173 // context, which means that SS refers to an unknown specialization. 1174 // Name lookup can't find anything in this case. 1175 return LookupResult::CreateLookupResult(Context, 0); 1176 } 1177 1178 // Perform unqualified name lookup starting in the given scope. 1179 return LookupName(S, Name, NameKind, RedeclarationOnly, AllowBuiltinCreation, 1180 Loc); 1181} 1182 1183 1184/// @brief Produce a diagnostic describing the ambiguity that resulted 1185/// from name lookup. 1186/// 1187/// @param Result The ambiguous name lookup result. 1188/// 1189/// @param Name The name of the entity that name lookup was 1190/// searching for. 1191/// 1192/// @param NameLoc The location of the name within the source code. 1193/// 1194/// @param LookupRange A source range that provides more 1195/// source-location information concerning the lookup itself. For 1196/// example, this range might highlight a nested-name-specifier that 1197/// precedes the name. 1198/// 1199/// @returns true 1200bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name, 1201 SourceLocation NameLoc, 1202 SourceRange LookupRange) { 1203 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1204 1205 if (BasePaths *Paths = Result.getBasePaths()) { 1206 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) { 1207 QualType SubobjectType = Paths->front().back().Base->getType(); 1208 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1209 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1210 << LookupRange; 1211 1212 DeclContext::lookup_iterator Found = Paths->front().Decls.first; 1213 while (isa<CXXMethodDecl>(*Found) && 1214 cast<CXXMethodDecl>(*Found)->isStatic()) 1215 ++Found; 1216 1217 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1218 1219 Result.Destroy(); 1220 return true; 1221 } 1222 1223 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes && 1224 "Unhandled form of name lookup ambiguity"); 1225 1226 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1227 << Name << LookupRange; 1228 1229 std::set<Decl *> DeclsPrinted; 1230 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end(); 1231 Path != PathEnd; ++Path) { 1232 Decl *D = *Path->Decls.first; 1233 if (DeclsPrinted.insert(D).second) 1234 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1235 } 1236 1237 Result.Destroy(); 1238 return true; 1239 } else if (Result.getKind() == LookupResult::AmbiguousReference) { 1240 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1241 1242 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First), 1243 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last); 1244 1245 for (; DI != DEnd; ++DI) 1246 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1247 1248 Result.Destroy(); 1249 return true; 1250 } 1251 1252 assert(false && "Unhandled form of name lookup ambiguity"); 1253 1254 // We can't reach here. 1255 return true; 1256} 1257 1258static void 1259addAssociatedClassesAndNamespaces(QualType T, 1260 ASTContext &Context, 1261 Sema::AssociatedNamespaceSet &AssociatedNamespaces, 1262 Sema::AssociatedClassSet &AssociatedClasses); 1263 1264static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces, 1265 DeclContext *Ctx) { 1266 if (Ctx->isFileContext()) 1267 Namespaces.insert(Ctx); 1268} 1269 1270// \brief Add the associated classes and namespaces for argument-dependent 1271// lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 1272static void 1273addAssociatedClassesAndNamespaces(const TemplateArgument &Arg, 1274 ASTContext &Context, 1275 Sema::AssociatedNamespaceSet &AssociatedNamespaces, 1276 Sema::AssociatedClassSet &AssociatedClasses) { 1277 // C++ [basic.lookup.koenig]p2, last bullet: 1278 // -- [...] ; 1279 switch (Arg.getKind()) { 1280 case TemplateArgument::Null: 1281 break; 1282 1283 case TemplateArgument::Type: 1284 // [...] the namespaces and classes associated with the types of the 1285 // template arguments provided for template type parameters (excluding 1286 // template template parameters) 1287 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context, 1288 AssociatedNamespaces, 1289 AssociatedClasses); 1290 break; 1291 1292 case TemplateArgument::Declaration: 1293 // [...] the namespaces in which any template template arguments are 1294 // defined; and the classes in which any member templates used as 1295 // template template arguments are defined. 1296 if (ClassTemplateDecl *ClassTemplate 1297 = dyn_cast<ClassTemplateDecl>(Arg.getAsDecl())) { 1298 DeclContext *Ctx = ClassTemplate->getDeclContext(); 1299 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1300 AssociatedClasses.insert(EnclosingClass); 1301 // Add the associated namespace for this class. 1302 while (Ctx->isRecord()) 1303 Ctx = Ctx->getParent(); 1304 CollectNamespace(AssociatedNamespaces, Ctx); 1305 } 1306 break; 1307 1308 case TemplateArgument::Integral: 1309 case TemplateArgument::Expression: 1310 // [Note: non-type template arguments do not contribute to the set of 1311 // associated namespaces. ] 1312 break; 1313 1314 case TemplateArgument::Pack: 1315 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), 1316 PEnd = Arg.pack_end(); 1317 P != PEnd; ++P) 1318 addAssociatedClassesAndNamespaces(*P, Context, 1319 AssociatedNamespaces, 1320 AssociatedClasses); 1321 break; 1322 } 1323} 1324 1325// \brief Add the associated classes and namespaces for 1326// argument-dependent lookup with an argument of class type 1327// (C++ [basic.lookup.koenig]p2). 1328static void 1329addAssociatedClassesAndNamespaces(CXXRecordDecl *Class, 1330 ASTContext &Context, 1331 Sema::AssociatedNamespaceSet &AssociatedNamespaces, 1332 Sema::AssociatedClassSet &AssociatedClasses) { 1333 // C++ [basic.lookup.koenig]p2: 1334 // [...] 1335 // -- If T is a class type (including unions), its associated 1336 // classes are: the class itself; the class of which it is a 1337 // member, if any; and its direct and indirect base 1338 // classes. Its associated namespaces are the namespaces in 1339 // which its associated classes are defined. 1340 1341 // Add the class of which it is a member, if any. 1342 DeclContext *Ctx = Class->getDeclContext(); 1343 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1344 AssociatedClasses.insert(EnclosingClass); 1345 // Add the associated namespace for this class. 1346 while (Ctx->isRecord()) 1347 Ctx = Ctx->getParent(); 1348 CollectNamespace(AssociatedNamespaces, Ctx); 1349 1350 // Add the class itself. If we've already seen this class, we don't 1351 // need to visit base classes. 1352 if (!AssociatedClasses.insert(Class)) 1353 return; 1354 1355 // -- If T is a template-id, its associated namespaces and classes are 1356 // the namespace in which the template is defined; for member 1357 // templates, the member template’s class; the namespaces and classes 1358 // associated with the types of the template arguments provided for 1359 // template type parameters (excluding template template parameters); the 1360 // namespaces in which any template template arguments are defined; and 1361 // the classes in which any member templates used as template template 1362 // arguments are defined. [Note: non-type template arguments do not 1363 // contribute to the set of associated namespaces. ] 1364 if (ClassTemplateSpecializationDecl *Spec 1365 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 1366 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 1367 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1368 AssociatedClasses.insert(EnclosingClass); 1369 // Add the associated namespace for this class. 1370 while (Ctx->isRecord()) 1371 Ctx = Ctx->getParent(); 1372 CollectNamespace(AssociatedNamespaces, Ctx); 1373 1374 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1375 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 1376 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context, 1377 AssociatedNamespaces, 1378 AssociatedClasses); 1379 } 1380 1381 // Add direct and indirect base classes along with their associated 1382 // namespaces. 1383 llvm::SmallVector<CXXRecordDecl *, 32> Bases; 1384 Bases.push_back(Class); 1385 while (!Bases.empty()) { 1386 // Pop this class off the stack. 1387 Class = Bases.back(); 1388 Bases.pop_back(); 1389 1390 // Visit the base classes. 1391 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(), 1392 BaseEnd = Class->bases_end(); 1393 Base != BaseEnd; ++Base) { 1394 const RecordType *BaseType = Base->getType()->getAs<RecordType>(); 1395 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 1396 if (AssociatedClasses.insert(BaseDecl)) { 1397 // Find the associated namespace for this base class. 1398 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 1399 while (BaseCtx->isRecord()) 1400 BaseCtx = BaseCtx->getParent(); 1401 CollectNamespace(AssociatedNamespaces, BaseCtx); 1402 1403 // Make sure we visit the bases of this base class. 1404 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 1405 Bases.push_back(BaseDecl); 1406 } 1407 } 1408 } 1409} 1410 1411// \brief Add the associated classes and namespaces for 1412// argument-dependent lookup with an argument of type T 1413// (C++ [basic.lookup.koenig]p2). 1414static void 1415addAssociatedClassesAndNamespaces(QualType T, 1416 ASTContext &Context, 1417 Sema::AssociatedNamespaceSet &AssociatedNamespaces, 1418 Sema::AssociatedClassSet &AssociatedClasses) { 1419 // C++ [basic.lookup.koenig]p2: 1420 // 1421 // For each argument type T in the function call, there is a set 1422 // of zero or more associated namespaces and a set of zero or more 1423 // associated classes to be considered. The sets of namespaces and 1424 // classes is determined entirely by the types of the function 1425 // arguments (and the namespace of any template template 1426 // argument). Typedef names and using-declarations used to specify 1427 // the types do not contribute to this set. The sets of namespaces 1428 // and classes are determined in the following way: 1429 T = Context.getCanonicalType(T).getUnqualifiedType(); 1430 1431 // -- If T is a pointer to U or an array of U, its associated 1432 // namespaces and classes are those associated with U. 1433 // 1434 // We handle this by unwrapping pointer and array types immediately, 1435 // to avoid unnecessary recursion. 1436 while (true) { 1437 if (const PointerType *Ptr = T->getAs<PointerType>()) 1438 T = Ptr->getPointeeType(); 1439 else if (const ArrayType *Ptr = Context.getAsArrayType(T)) 1440 T = Ptr->getElementType(); 1441 else 1442 break; 1443 } 1444 1445 // -- If T is a fundamental type, its associated sets of 1446 // namespaces and classes are both empty. 1447 if (T->getAs<BuiltinType>()) 1448 return; 1449 1450 // -- If T is a class type (including unions), its associated 1451 // classes are: the class itself; the class of which it is a 1452 // member, if any; and its direct and indirect base 1453 // classes. Its associated namespaces are the namespaces in 1454 // which its associated classes are defined. 1455 if (const RecordType *ClassType = T->getAs<RecordType>()) 1456 if (CXXRecordDecl *ClassDecl 1457 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) { 1458 addAssociatedClassesAndNamespaces(ClassDecl, Context, 1459 AssociatedNamespaces, 1460 AssociatedClasses); 1461 return; 1462 } 1463 1464 // -- If T is an enumeration type, its associated namespace is 1465 // the namespace in which it is defined. If it is class 1466 // member, its associated class is the member’s class; else 1467 // it has no associated class. 1468 if (const EnumType *EnumT = T->getAs<EnumType>()) { 1469 EnumDecl *Enum = EnumT->getDecl(); 1470 1471 DeclContext *Ctx = Enum->getDeclContext(); 1472 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1473 AssociatedClasses.insert(EnclosingClass); 1474 1475 // Add the associated namespace for this class. 1476 while (Ctx->isRecord()) 1477 Ctx = Ctx->getParent(); 1478 CollectNamespace(AssociatedNamespaces, Ctx); 1479 1480 return; 1481 } 1482 1483 // -- If T is a function type, its associated namespaces and 1484 // classes are those associated with the function parameter 1485 // types and those associated with the return type. 1486 if (const FunctionType *FnType = T->getAs<FunctionType>()) { 1487 // Return type 1488 addAssociatedClassesAndNamespaces(FnType->getResultType(), 1489 Context, 1490 AssociatedNamespaces, AssociatedClasses); 1491 1492 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 1493 if (!Proto) 1494 return; 1495 1496 // Argument types 1497 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), 1498 ArgEnd = Proto->arg_type_end(); 1499 Arg != ArgEnd; ++Arg) 1500 addAssociatedClassesAndNamespaces(*Arg, Context, 1501 AssociatedNamespaces, AssociatedClasses); 1502 1503 return; 1504 } 1505 1506 // -- If T is a pointer to a member function of a class X, its 1507 // associated namespaces and classes are those associated 1508 // with the function parameter types and return type, 1509 // together with those associated with X. 1510 // 1511 // -- If T is a pointer to a data member of class X, its 1512 // associated namespaces and classes are those associated 1513 // with the member type together with those associated with 1514 // X. 1515 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) { 1516 // Handle the type that the pointer to member points to. 1517 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(), 1518 Context, 1519 AssociatedNamespaces, 1520 AssociatedClasses); 1521 1522 // Handle the class type into which this points. 1523 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>()) 1524 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()), 1525 Context, 1526 AssociatedNamespaces, 1527 AssociatedClasses); 1528 1529 return; 1530 } 1531 1532 // FIXME: What about block pointers? 1533 // FIXME: What about Objective-C message sends? 1534} 1535 1536/// \brief Find the associated classes and namespaces for 1537/// argument-dependent lookup for a call with the given set of 1538/// arguments. 1539/// 1540/// This routine computes the sets of associated classes and associated 1541/// namespaces searched by argument-dependent lookup 1542/// (C++ [basic.lookup.argdep]) for a given set of arguments. 1543void 1544Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1545 AssociatedNamespaceSet &AssociatedNamespaces, 1546 AssociatedClassSet &AssociatedClasses) { 1547 AssociatedNamespaces.clear(); 1548 AssociatedClasses.clear(); 1549 1550 // C++ [basic.lookup.koenig]p2: 1551 // For each argument type T in the function call, there is a set 1552 // of zero or more associated namespaces and a set of zero or more 1553 // associated classes to be considered. The sets of namespaces and 1554 // classes is determined entirely by the types of the function 1555 // arguments (and the namespace of any template template 1556 // argument). 1557 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) { 1558 Expr *Arg = Args[ArgIdx]; 1559 1560 if (Arg->getType() != Context.OverloadTy) { 1561 addAssociatedClassesAndNamespaces(Arg->getType(), Context, 1562 AssociatedNamespaces, 1563 AssociatedClasses); 1564 continue; 1565 } 1566 1567 // [...] In addition, if the argument is the name or address of a 1568 // set of overloaded functions and/or function templates, its 1569 // associated classes and namespaces are the union of those 1570 // associated with each of the members of the set: the namespace 1571 // in which the function or function template is defined and the 1572 // classes and namespaces associated with its (non-dependent) 1573 // parameter types and return type. 1574 DeclRefExpr *DRE = 0; 1575 TemplateIdRefExpr *TIRE = 0; 1576 Arg = Arg->IgnoreParens(); 1577 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) { 1578 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) { 1579 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr()); 1580 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr()); 1581 } 1582 } else { 1583 DRE = dyn_cast<DeclRefExpr>(Arg); 1584 TIRE = dyn_cast<TemplateIdRefExpr>(Arg); 1585 } 1586 1587 OverloadedFunctionDecl *Ovl = 0; 1588 if (DRE) 1589 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl()); 1590 else if (TIRE) 1591 Ovl = TIRE->getTemplateName().getAsOverloadedFunctionDecl(); 1592 if (!Ovl) 1593 continue; 1594 1595 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 1596 FuncEnd = Ovl->function_end(); 1597 Func != FuncEnd; ++Func) { 1598 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func); 1599 if (!FDecl) 1600 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl(); 1601 1602 // Add the namespace in which this function was defined. Note 1603 // that, if this is a member function, we do *not* consider the 1604 // enclosing namespace of its class. 1605 DeclContext *Ctx = FDecl->getDeclContext(); 1606 CollectNamespace(AssociatedNamespaces, Ctx); 1607 1608 // Add the classes and namespaces associated with the parameter 1609 // types and return type of this function. 1610 addAssociatedClassesAndNamespaces(FDecl->getType(), Context, 1611 AssociatedNamespaces, 1612 AssociatedClasses); 1613 } 1614 } 1615} 1616 1617/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 1618/// an acceptable non-member overloaded operator for a call whose 1619/// arguments have types T1 (and, if non-empty, T2). This routine 1620/// implements the check in C++ [over.match.oper]p3b2 concerning 1621/// enumeration types. 1622static bool 1623IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 1624 QualType T1, QualType T2, 1625 ASTContext &Context) { 1626 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 1627 return true; 1628 1629 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 1630 return true; 1631 1632 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 1633 if (Proto->getNumArgs() < 1) 1634 return false; 1635 1636 if (T1->isEnumeralType()) { 1637 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 1638 if (Context.getCanonicalType(T1).getUnqualifiedType() 1639 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 1640 return true; 1641 } 1642 1643 if (Proto->getNumArgs() < 2) 1644 return false; 1645 1646 if (!T2.isNull() && T2->isEnumeralType()) { 1647 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 1648 if (Context.getCanonicalType(T2).getUnqualifiedType() 1649 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 1650 return true; 1651 } 1652 1653 return false; 1654} 1655 1656/// \brief Find the protocol with the given name, if any. 1657ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) { 1658 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl(); 1659 return cast_or_null<ObjCProtocolDecl>(D); 1660} 1661 1662/// \brief Find the Objective-C category implementation with the given 1663/// name, if any. 1664ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) { 1665 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl(); 1666 return cast_or_null<ObjCCategoryImplDecl>(D); 1667} 1668 1669// Attempts to find a declaration in the given declaration context 1670// with exactly the given type. Returns null if no such declaration 1671// was found. 1672Decl *Sema::LookupQualifiedNameWithType(DeclContext *DC, 1673 DeclarationName Name, 1674 QualType T) { 1675 LookupResult result = 1676 LookupQualifiedName(DC, Name, LookupOrdinaryName, true); 1677 1678 CanQualType CQT = Context.getCanonicalType(T); 1679 1680 for (LookupResult::iterator ir = result.begin(), ie = result.end(); 1681 ir != ie; ++ir) 1682 if (FunctionDecl *CurFD = dyn_cast<FunctionDecl>(*ir)) 1683 if (Context.getCanonicalType(CurFD->getType()) == CQT) 1684 return CurFD; 1685 1686 return NULL; 1687} 1688 1689void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 1690 QualType T1, QualType T2, 1691 FunctionSet &Functions) { 1692 // C++ [over.match.oper]p3: 1693 // -- The set of non-member candidates is the result of the 1694 // unqualified lookup of operator@ in the context of the 1695 // expression according to the usual rules for name lookup in 1696 // unqualified function calls (3.4.2) except that all member 1697 // functions are ignored. However, if no operand has a class 1698 // type, only those non-member functions in the lookup set 1699 // that have a first parameter of type T1 or "reference to 1700 // (possibly cv-qualified) T1", when T1 is an enumeration 1701 // type, or (if there is a right operand) a second parameter 1702 // of type T2 or "reference to (possibly cv-qualified) T2", 1703 // when T2 is an enumeration type, are candidate functions. 1704 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 1705 LookupResult Operators = LookupName(S, OpName, LookupOperatorName); 1706 1707 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 1708 1709 if (!Operators) 1710 return; 1711 1712 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end(); 1713 Op != OpEnd; ++Op) { 1714 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) { 1715 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 1716 Functions.insert(FD); // FIXME: canonical FD 1717 } else if (FunctionTemplateDecl *FunTmpl 1718 = dyn_cast<FunctionTemplateDecl>(*Op)) { 1719 // FIXME: friend operators? 1720 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate, 1721 // later? 1722 if (!FunTmpl->getDeclContext()->isRecord()) 1723 Functions.insert(FunTmpl); 1724 } 1725 } 1726} 1727 1728static void CollectFunctionDecl(Sema::FunctionSet &Functions, 1729 Decl *D) { 1730 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) 1731 Functions.insert(Func); 1732 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 1733 Functions.insert(FunTmpl); 1734} 1735 1736void Sema::ArgumentDependentLookup(DeclarationName Name, 1737 Expr **Args, unsigned NumArgs, 1738 FunctionSet &Functions) { 1739 // Find all of the associated namespaces and classes based on the 1740 // arguments we have. 1741 AssociatedNamespaceSet AssociatedNamespaces; 1742 AssociatedClassSet AssociatedClasses; 1743 FindAssociatedClassesAndNamespaces(Args, NumArgs, 1744 AssociatedNamespaces, 1745 AssociatedClasses); 1746 1747 // C++ [basic.lookup.argdep]p3: 1748 // Let X be the lookup set produced by unqualified lookup (3.4.1) 1749 // and let Y be the lookup set produced by argument dependent 1750 // lookup (defined as follows). If X contains [...] then Y is 1751 // empty. Otherwise Y is the set of declarations found in the 1752 // namespaces associated with the argument types as described 1753 // below. The set of declarations found by the lookup of the name 1754 // is the union of X and Y. 1755 // 1756 // Here, we compute Y and add its members to the overloaded 1757 // candidate set. 1758 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), 1759 NSEnd = AssociatedNamespaces.end(); 1760 NS != NSEnd; ++NS) { 1761 // When considering an associated namespace, the lookup is the 1762 // same as the lookup performed when the associated namespace is 1763 // used as a qualifier (3.4.3.2) except that: 1764 // 1765 // -- Any using-directives in the associated namespace are 1766 // ignored. 1767 // 1768 // -- Any namespace-scope friend functions declared in 1769 // associated classes are visible within their respective 1770 // namespaces even if they are not visible during an ordinary 1771 // lookup (11.4). 1772 DeclContext::lookup_iterator I, E; 1773 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) { 1774 Decl *D = *I; 1775 // If the only declaration here is an ordinary friend, consider 1776 // it only if it was declared in an associated classes. 1777 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) { 1778 DeclContext *LexDC = D->getLexicalDeclContext(); 1779 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) 1780 continue; 1781 } 1782 1783 CollectFunctionDecl(Functions, D); 1784 } 1785 } 1786} 1787