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