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