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/Lookup.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclLookups.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/Basic/Builtins.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/Sema/DeclSpec.h" 27 #include "clang/Sema/ExternalSemaSource.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/Scope.h" 30 #include "clang/Sema/ScopeInfo.h" 31 #include "clang/Sema/Sema.h" 32 #include "clang/Sema/SemaInternal.h" 33 #include "clang/Sema/TemplateDeduction.h" 34 #include "clang/Sema/TypoCorrection.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/SetVector.h" 37 #include "llvm/ADT/SmallPtrSet.h" 38 #include "llvm/ADT/StringMap.h" 39 #include "llvm/ADT/TinyPtrVector.h" 40 #include "llvm/ADT/edit_distance.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include <algorithm> 43 #include <iterator> 44 #include <limits> 45 #include <list> 46 #include <map> 47 #include <set> 48 #include <utility> 49 #include <vector> 50 51 using namespace clang; 52 using namespace sema; 53 54 namespace { 55 class UnqualUsingEntry { 56 const DeclContext *Nominated; 57 const DeclContext *CommonAncestor; 58 59 public: 60 UnqualUsingEntry(const DeclContext *Nominated, 61 const DeclContext *CommonAncestor) 62 : Nominated(Nominated), CommonAncestor(CommonAncestor) { 63 } 64 65 const DeclContext *getCommonAncestor() const { 66 return CommonAncestor; 67 } 68 69 const DeclContext *getNominatedNamespace() const { 70 return Nominated; 71 } 72 73 // Sort by the pointer value of the common ancestor. 74 struct Comparator { 75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { 76 return L.getCommonAncestor() < R.getCommonAncestor(); 77 } 78 79 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { 80 return E.getCommonAncestor() < DC; 81 } 82 83 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { 84 return DC < E.getCommonAncestor(); 85 } 86 }; 87 }; 88 89 /// A collection of using directives, as used by C++ unqualified 90 /// lookup. 91 class UnqualUsingDirectiveSet { 92 typedef SmallVector<UnqualUsingEntry, 8> ListTy; 93 94 ListTy list; 95 llvm::SmallPtrSet<DeclContext*, 8> visited; 96 97 public: 98 UnqualUsingDirectiveSet() {} 99 100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) { 101 // C++ [namespace.udir]p1: 102 // During unqualified name lookup, the names appear as if they 103 // were declared in the nearest enclosing namespace which contains 104 // both the using-directive and the nominated namespace. 105 DeclContext *InnermostFileDC 106 = static_cast<DeclContext*>(InnermostFileScope->getEntity()); 107 assert(InnermostFileDC && InnermostFileDC->isFileContext()); 108 109 for (; S; S = S->getParent()) { 110 // C++ [namespace.udir]p1: 111 // A using-directive shall not appear in class scope, but may 112 // appear in namespace scope or in block scope. 113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 114 if (Ctx && Ctx->isFileContext()) { 115 visit(Ctx, Ctx); 116 } else if (!Ctx || Ctx->isFunctionOrMethod()) { 117 Scope::udir_iterator I = S->using_directives_begin(), 118 End = S->using_directives_end(); 119 for (; I != End; ++I) 120 visit(*I, InnermostFileDC); 121 } 122 } 123 } 124 125 // Visits a context and collect all of its using directives 126 // recursively. Treats all using directives as if they were 127 // declared in the context. 128 // 129 // A given context is only every visited once, so it is important 130 // that contexts be visited from the inside out in order to get 131 // the effective DCs right. 132 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 133 if (!visited.insert(DC)) 134 return; 135 136 addUsingDirectives(DC, EffectiveDC); 137 } 138 139 // Visits a using directive and collects all of its using 140 // directives recursively. Treats all using directives as if they 141 // were declared in the effective DC. 142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 143 DeclContext *NS = UD->getNominatedNamespace(); 144 if (!visited.insert(NS)) 145 return; 146 147 addUsingDirective(UD, EffectiveDC); 148 addUsingDirectives(NS, EffectiveDC); 149 } 150 151 // Adds all the using directives in a context (and those nominated 152 // by its using directives, transitively) as if they appeared in 153 // the given effective context. 154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 155 SmallVector<DeclContext*,4> queue; 156 while (true) { 157 DeclContext::udir_iterator I, End; 158 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) { 159 UsingDirectiveDecl *UD = *I; 160 DeclContext *NS = UD->getNominatedNamespace(); 161 if (visited.insert(NS)) { 162 addUsingDirective(UD, EffectiveDC); 163 queue.push_back(NS); 164 } 165 } 166 167 if (queue.empty()) 168 return; 169 170 DC = queue.pop_back_val(); 171 } 172 } 173 174 // Add a using directive as if it had been declared in the given 175 // context. This helps implement C++ [namespace.udir]p3: 176 // The using-directive is transitive: if a scope contains a 177 // using-directive that nominates a second namespace that itself 178 // contains using-directives, the effect is as if the 179 // using-directives from the second namespace also appeared in 180 // the first. 181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 182 // Find the common ancestor between the effective context and 183 // the nominated namespace. 184 DeclContext *Common = UD->getNominatedNamespace(); 185 while (!Common->Encloses(EffectiveDC)) 186 Common = Common->getParent(); 187 Common = Common->getPrimaryContext(); 188 189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 190 } 191 192 void done() { 193 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); 194 } 195 196 typedef ListTy::const_iterator const_iterator; 197 198 const_iterator begin() const { return list.begin(); } 199 const_iterator end() const { return list.end(); } 200 201 std::pair<const_iterator,const_iterator> 202 getNamespacesFor(DeclContext *DC) const { 203 return std::equal_range(begin(), end(), DC->getPrimaryContext(), 204 UnqualUsingEntry::Comparator()); 205 } 206 }; 207 } 208 209 // Retrieve the set of identifier namespaces that correspond to a 210 // specific kind of name lookup. 211 static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 212 bool CPlusPlus, 213 bool Redeclaration) { 214 unsigned IDNS = 0; 215 switch (NameKind) { 216 case Sema::LookupObjCImplicitSelfParam: 217 case Sema::LookupOrdinaryName: 218 case Sema::LookupRedeclarationWithLinkage: 219 case Sema::LookupLocalFriendName: 220 IDNS = Decl::IDNS_Ordinary; 221 if (CPlusPlus) { 222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 223 if (Redeclaration) 224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 225 } 226 if (Redeclaration) 227 IDNS |= Decl::IDNS_LocalExtern; 228 break; 229 230 case Sema::LookupOperatorName: 231 // Operator lookup is its own crazy thing; it is not the same 232 // as (e.g.) looking up an operator name for redeclaration. 233 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 234 IDNS = Decl::IDNS_NonMemberOperator; 235 break; 236 237 case Sema::LookupTagName: 238 if (CPlusPlus) { 239 IDNS = Decl::IDNS_Type; 240 241 // When looking for a redeclaration of a tag name, we add: 242 // 1) TagFriend to find undeclared friend decls 243 // 2) Namespace because they can't "overload" with tag decls. 244 // 3) Tag because it includes class templates, which can't 245 // "overload" with tag decls. 246 if (Redeclaration) 247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 248 } else { 249 IDNS = Decl::IDNS_Tag; 250 } 251 break; 252 case Sema::LookupLabel: 253 IDNS = Decl::IDNS_Label; 254 break; 255 256 case Sema::LookupMemberName: 257 IDNS = Decl::IDNS_Member; 258 if (CPlusPlus) 259 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 260 break; 261 262 case Sema::LookupNestedNameSpecifierName: 263 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 264 break; 265 266 case Sema::LookupNamespaceName: 267 IDNS = Decl::IDNS_Namespace; 268 break; 269 270 case Sema::LookupUsingDeclName: 271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag 272 | Decl::IDNS_Member | Decl::IDNS_Using; 273 break; 274 275 case Sema::LookupObjCProtocolName: 276 IDNS = Decl::IDNS_ObjCProtocol; 277 break; 278 279 case Sema::LookupAnyName: 280 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member 281 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol 282 | Decl::IDNS_Type; 283 break; 284 } 285 return IDNS; 286 } 287 288 void LookupResult::configure() { 289 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus, 290 isForRedeclaration()); 291 292 if (!isForRedeclaration()) { 293 // If we're looking for one of the allocation or deallocation 294 // operators, make sure that the implicitly-declared new and delete 295 // operators can be found. 296 switch (NameInfo.getName().getCXXOverloadedOperator()) { 297 case OO_New: 298 case OO_Delete: 299 case OO_Array_New: 300 case OO_Array_Delete: 301 SemaRef.DeclareGlobalNewDelete(); 302 break; 303 304 default: 305 break; 306 } 307 308 // Compiler builtins are always visible, regardless of where they end 309 // up being declared. 310 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { 311 if (unsigned BuiltinID = Id->getBuiltinID()) { 312 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 313 AllowHidden = true; 314 } 315 } 316 } 317 } 318 319 void LookupResult::sanityImpl() const { 320 // Note that this function is never called by NDEBUG builds. See 321 // LookupResult::sanity(). 322 assert(ResultKind != NotFound || Decls.size() == 0); 323 assert(ResultKind != Found || Decls.size() == 1); 324 assert(ResultKind != FoundOverloaded || Decls.size() > 1 || 325 (Decls.size() == 1 && 326 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))); 327 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved()); 328 assert(ResultKind != Ambiguous || Decls.size() > 1 || 329 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || 330 Ambiguity == AmbiguousBaseSubobjectTypes))); 331 assert((Paths != NULL) == (ResultKind == Ambiguous && 332 (Ambiguity == AmbiguousBaseSubobjectTypes || 333 Ambiguity == AmbiguousBaseSubobjects))); 334 } 335 336 // Necessary because CXXBasePaths is not complete in Sema.h 337 void LookupResult::deletePaths(CXXBasePaths *Paths) { 338 delete Paths; 339 } 340 341 /// Resolves the result kind of this lookup. 342 void LookupResult::resolveKind() { 343 unsigned N = Decls.size(); 344 345 // Fast case: no possible ambiguity. 346 if (N == 0) { 347 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation); 348 return; 349 } 350 351 // If there's a single decl, we need to examine it to decide what 352 // kind of lookup this is. 353 if (N == 1) { 354 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); 355 if (isa<FunctionTemplateDecl>(D)) 356 ResultKind = FoundOverloaded; 357 else if (isa<UnresolvedUsingValueDecl>(D)) 358 ResultKind = FoundUnresolvedValue; 359 return; 360 } 361 362 // Don't do any extra resolution if we've already resolved as ambiguous. 363 if (ResultKind == Ambiguous) return; 364 365 llvm::SmallPtrSet<NamedDecl*, 16> Unique; 366 llvm::SmallPtrSet<QualType, 16> UniqueTypes; 367 368 bool Ambiguous = false; 369 bool HasTag = false, HasFunction = false, HasNonFunction = false; 370 bool HasFunctionTemplate = false, HasUnresolved = false; 371 372 unsigned UniqueTagIndex = 0; 373 374 unsigned I = 0; 375 while (I < N) { 376 NamedDecl *D = Decls[I]->getUnderlyingDecl(); 377 D = cast<NamedDecl>(D->getCanonicalDecl()); 378 379 // Ignore an invalid declaration unless it's the only one left. 380 if (D->isInvalidDecl() && I < N-1) { 381 Decls[I] = Decls[--N]; 382 continue; 383 } 384 385 // Redeclarations of types via typedef can occur both within a scope 386 // and, through using declarations and directives, across scopes. There is 387 // no ambiguity if they all refer to the same type, so unique based on the 388 // canonical type. 389 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) { 390 if (!TD->getDeclContext()->isRecord()) { 391 QualType T = SemaRef.Context.getTypeDeclType(TD); 392 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) { 393 // The type is not unique; pull something off the back and continue 394 // at this index. 395 Decls[I] = Decls[--N]; 396 continue; 397 } 398 } 399 } 400 401 if (!Unique.insert(D)) { 402 // If it's not unique, pull something off the back (and 403 // continue at this index). 404 Decls[I] = Decls[--N]; 405 continue; 406 } 407 408 // Otherwise, do some decl type analysis and then continue. 409 410 if (isa<UnresolvedUsingValueDecl>(D)) { 411 HasUnresolved = true; 412 } else if (isa<TagDecl>(D)) { 413 if (HasTag) 414 Ambiguous = true; 415 UniqueTagIndex = I; 416 HasTag = true; 417 } else if (isa<FunctionTemplateDecl>(D)) { 418 HasFunction = true; 419 HasFunctionTemplate = true; 420 } else if (isa<FunctionDecl>(D)) { 421 HasFunction = true; 422 } else { 423 if (HasNonFunction) 424 Ambiguous = true; 425 HasNonFunction = true; 426 } 427 I++; 428 } 429 430 // C++ [basic.scope.hiding]p2: 431 // A class name or enumeration name can be hidden by the name of 432 // an object, function, or enumerator declared in the same 433 // scope. If a class or enumeration name and an object, function, 434 // or enumerator are declared in the same scope (in any order) 435 // with the same name, the class or enumeration name is hidden 436 // wherever the object, function, or enumerator name is visible. 437 // But it's still an error if there are distinct tag types found, 438 // even if they're not visible. (ref?) 439 if (HideTags && HasTag && !Ambiguous && 440 (HasFunction || HasNonFunction || HasUnresolved)) { 441 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals( 442 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext())) 443 Decls[UniqueTagIndex] = Decls[--N]; 444 else 445 Ambiguous = true; 446 } 447 448 Decls.set_size(N); 449 450 if (HasNonFunction && (HasFunction || HasUnresolved)) 451 Ambiguous = true; 452 453 if (Ambiguous) 454 setAmbiguous(LookupResult::AmbiguousReference); 455 else if (HasUnresolved) 456 ResultKind = LookupResult::FoundUnresolvedValue; 457 else if (N > 1 || HasFunctionTemplate) 458 ResultKind = LookupResult::FoundOverloaded; 459 else 460 ResultKind = LookupResult::Found; 461 } 462 463 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { 464 CXXBasePaths::const_paths_iterator I, E; 465 for (I = P.begin(), E = P.end(); I != E; ++I) 466 for (DeclContext::lookup_iterator DI = I->Decls.begin(), 467 DE = I->Decls.end(); DI != DE; ++DI) 468 addDecl(*DI); 469 } 470 471 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 472 Paths = new CXXBasePaths; 473 Paths->swap(P); 474 addDeclsFromBasePaths(*Paths); 475 resolveKind(); 476 setAmbiguous(AmbiguousBaseSubobjects); 477 } 478 479 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 480 Paths = new CXXBasePaths; 481 Paths->swap(P); 482 addDeclsFromBasePaths(*Paths); 483 resolveKind(); 484 setAmbiguous(AmbiguousBaseSubobjectTypes); 485 } 486 487 void LookupResult::print(raw_ostream &Out) { 488 Out << Decls.size() << " result(s)"; 489 if (isAmbiguous()) Out << ", ambiguous"; 490 if (Paths) Out << ", base paths present"; 491 492 for (iterator I = begin(), E = end(); I != E; ++I) { 493 Out << "\n"; 494 (*I)->print(Out, 2); 495 } 496 } 497 498 /// \brief Lookup a builtin function, when name lookup would otherwise 499 /// fail. 500 static bool LookupBuiltin(Sema &S, LookupResult &R) { 501 Sema::LookupNameKind NameKind = R.getLookupKind(); 502 503 // If we didn't find a use of this identifier, and if the identifier 504 // corresponds to a compiler builtin, create the decl object for the builtin 505 // now, injecting it into translation unit scope, and return it. 506 if (NameKind == Sema::LookupOrdinaryName || 507 NameKind == Sema::LookupRedeclarationWithLinkage) { 508 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); 509 if (II) { 510 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode && 511 II == S.getFloat128Identifier()) { 512 // libstdc++4.7's type_traits expects type __float128 to exist, so 513 // insert a dummy type to make that header build in gnu++11 mode. 514 R.addDecl(S.getASTContext().getFloat128StubType()); 515 return true; 516 } 517 518 // If this is a builtin on this (or all) targets, create the decl. 519 if (unsigned BuiltinID = II->getBuiltinID()) { 520 // In C++, we don't have any predefined library functions like 521 // 'malloc'. Instead, we'll just error. 522 if (S.getLangOpts().CPlusPlus && 523 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 524 return false; 525 526 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, 527 BuiltinID, S.TUScope, 528 R.isForRedeclaration(), 529 R.getNameLoc())) { 530 R.addDecl(D); 531 return true; 532 } 533 534 if (R.isForRedeclaration()) { 535 // If we're redeclaring this function anyway, forget that 536 // this was a builtin at all. 537 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents); 538 } 539 540 return false; 541 } 542 } 543 } 544 545 return false; 546 } 547 548 /// \brief Determine whether we can declare a special member function within 549 /// the class at this point. 550 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) { 551 // We need to have a definition for the class. 552 if (!Class->getDefinition() || Class->isDependentContext()) 553 return false; 554 555 // We can't be in the middle of defining the class. 556 return !Class->isBeingDefined(); 557 } 558 559 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { 560 if (!CanDeclareSpecialMemberFunction(Class)) 561 return; 562 563 // If the default constructor has not yet been declared, do so now. 564 if (Class->needsImplicitDefaultConstructor()) 565 DeclareImplicitDefaultConstructor(Class); 566 567 // If the copy constructor has not yet been declared, do so now. 568 if (Class->needsImplicitCopyConstructor()) 569 DeclareImplicitCopyConstructor(Class); 570 571 // If the copy assignment operator has not yet been declared, do so now. 572 if (Class->needsImplicitCopyAssignment()) 573 DeclareImplicitCopyAssignment(Class); 574 575 if (getLangOpts().CPlusPlus11) { 576 // If the move constructor has not yet been declared, do so now. 577 if (Class->needsImplicitMoveConstructor()) 578 DeclareImplicitMoveConstructor(Class); // might not actually do it 579 580 // If the move assignment operator has not yet been declared, do so now. 581 if (Class->needsImplicitMoveAssignment()) 582 DeclareImplicitMoveAssignment(Class); // might not actually do it 583 } 584 585 // If the destructor has not yet been declared, do so now. 586 if (Class->needsImplicitDestructor()) 587 DeclareImplicitDestructor(Class); 588 } 589 590 /// \brief Determine whether this is the name of an implicitly-declared 591 /// special member function. 592 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { 593 switch (Name.getNameKind()) { 594 case DeclarationName::CXXConstructorName: 595 case DeclarationName::CXXDestructorName: 596 return true; 597 598 case DeclarationName::CXXOperatorName: 599 return Name.getCXXOverloadedOperator() == OO_Equal; 600 601 default: 602 break; 603 } 604 605 return false; 606 } 607 608 /// \brief If there are any implicit member functions with the given name 609 /// that need to be declared in the given declaration context, do so. 610 static void DeclareImplicitMemberFunctionsWithName(Sema &S, 611 DeclarationName Name, 612 const DeclContext *DC) { 613 if (!DC) 614 return; 615 616 switch (Name.getNameKind()) { 617 case DeclarationName::CXXConstructorName: 618 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 619 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 620 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 621 if (Record->needsImplicitDefaultConstructor()) 622 S.DeclareImplicitDefaultConstructor(Class); 623 if (Record->needsImplicitCopyConstructor()) 624 S.DeclareImplicitCopyConstructor(Class); 625 if (S.getLangOpts().CPlusPlus11 && 626 Record->needsImplicitMoveConstructor()) 627 S.DeclareImplicitMoveConstructor(Class); 628 } 629 break; 630 631 case DeclarationName::CXXDestructorName: 632 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 633 if (Record->getDefinition() && Record->needsImplicitDestructor() && 634 CanDeclareSpecialMemberFunction(Record)) 635 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); 636 break; 637 638 case DeclarationName::CXXOperatorName: 639 if (Name.getCXXOverloadedOperator() != OO_Equal) 640 break; 641 642 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) { 643 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 644 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 645 if (Record->needsImplicitCopyAssignment()) 646 S.DeclareImplicitCopyAssignment(Class); 647 if (S.getLangOpts().CPlusPlus11 && 648 Record->needsImplicitMoveAssignment()) 649 S.DeclareImplicitMoveAssignment(Class); 650 } 651 } 652 break; 653 654 default: 655 break; 656 } 657 } 658 659 // Adds all qualifying matches for a name within a decl context to the 660 // given lookup result. Returns true if any matches were found. 661 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { 662 bool Found = false; 663 664 // Lazily declare C++ special member functions. 665 if (S.getLangOpts().CPlusPlus) 666 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC); 667 668 // Perform lookup into this declaration context. 669 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName()); 670 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E; 671 ++I) { 672 NamedDecl *D = *I; 673 if ((D = R.getAcceptableDecl(D))) { 674 R.addDecl(D); 675 Found = true; 676 } 677 } 678 679 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R)) 680 return true; 681 682 if (R.getLookupName().getNameKind() 683 != DeclarationName::CXXConversionFunctionName || 684 R.getLookupName().getCXXNameType()->isDependentType() || 685 !isa<CXXRecordDecl>(DC)) 686 return Found; 687 688 // C++ [temp.mem]p6: 689 // A specialization of a conversion function template is not found by 690 // name lookup. Instead, any conversion function templates visible in the 691 // context of the use are considered. [...] 692 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 693 if (!Record->isCompleteDefinition()) 694 return Found; 695 696 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(), 697 UEnd = Record->conversion_end(); U != UEnd; ++U) { 698 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); 699 if (!ConvTemplate) 700 continue; 701 702 // When we're performing lookup for the purposes of redeclaration, just 703 // add the conversion function template. When we deduce template 704 // arguments for specializations, we'll end up unifying the return 705 // type of the new declaration with the type of the function template. 706 if (R.isForRedeclaration()) { 707 R.addDecl(ConvTemplate); 708 Found = true; 709 continue; 710 } 711 712 // C++ [temp.mem]p6: 713 // [...] For each such operator, if argument deduction succeeds 714 // (14.9.2.3), the resulting specialization is used as if found by 715 // name lookup. 716 // 717 // When referencing a conversion function for any purpose other than 718 // a redeclaration (such that we'll be building an expression with the 719 // result), perform template argument deduction and place the 720 // specialization into the result set. We do this to avoid forcing all 721 // callers to perform special deduction for conversion functions. 722 TemplateDeductionInfo Info(R.getNameLoc()); 723 FunctionDecl *Specialization = 0; 724 725 const FunctionProtoType *ConvProto 726 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); 727 assert(ConvProto && "Nonsensical conversion function template type"); 728 729 // Compute the type of the function that we would expect the conversion 730 // function to have, if it were to match the name given. 731 // FIXME: Calling convention! 732 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo(); 733 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C); 734 EPI.ExceptionSpecType = EST_None; 735 EPI.NumExceptions = 0; 736 QualType ExpectedType 737 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(), 738 None, EPI); 739 740 // Perform template argument deduction against the type that we would 741 // expect the function to have. 742 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType, 743 Specialization, Info) 744 == Sema::TDK_Success) { 745 R.addDecl(Specialization); 746 Found = true; 747 } 748 } 749 750 return Found; 751 } 752 753 // Performs C++ unqualified lookup into the given file context. 754 static bool 755 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 756 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) { 757 758 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 759 760 // Perform direct name lookup into the LookupCtx. 761 bool Found = LookupDirect(S, R, NS); 762 763 // Perform direct name lookup into the namespaces nominated by the 764 // using directives whose common ancestor is this namespace. 765 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 766 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS); 767 768 for (; UI != UEnd; ++UI) 769 if (LookupDirect(S, R, UI->getNominatedNamespace())) 770 Found = true; 771 772 R.resolveKind(); 773 774 return Found; 775 } 776 777 static bool isNamespaceOrTranslationUnitScope(Scope *S) { 778 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 779 return Ctx->isFileContext(); 780 return false; 781 } 782 783 // Find the next outer declaration context from this scope. This 784 // routine actually returns the semantic outer context, which may 785 // differ from the lexical context (encoded directly in the Scope 786 // stack) when we are parsing a member of a class template. In this 787 // case, the second element of the pair will be true, to indicate that 788 // name lookup should continue searching in this semantic context when 789 // it leaves the current template parameter scope. 790 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) { 791 DeclContext *DC = static_cast<DeclContext *>(S->getEntity()); 792 DeclContext *Lexical = 0; 793 for (Scope *OuterS = S->getParent(); OuterS; 794 OuterS = OuterS->getParent()) { 795 if (OuterS->getEntity()) { 796 Lexical = static_cast<DeclContext *>(OuterS->getEntity()); 797 break; 798 } 799 } 800 801 // C++ [temp.local]p8: 802 // In the definition of a member of a class template that appears 803 // outside of the namespace containing the class template 804 // definition, the name of a template-parameter hides the name of 805 // a member of this namespace. 806 // 807 // Example: 808 // 809 // namespace N { 810 // class C { }; 811 // 812 // template<class T> class B { 813 // void f(T); 814 // }; 815 // } 816 // 817 // template<class C> void N::B<C>::f(C) { 818 // C b; // C is the template parameter, not N::C 819 // } 820 // 821 // In this example, the lexical context we return is the 822 // TranslationUnit, while the semantic context is the namespace N. 823 if (!Lexical || !DC || !S->getParent() || 824 !S->getParent()->isTemplateParamScope()) 825 return std::make_pair(Lexical, false); 826 827 // Find the outermost template parameter scope. 828 // For the example, this is the scope for the template parameters of 829 // template<class C>. 830 Scope *OutermostTemplateScope = S->getParent(); 831 while (OutermostTemplateScope->getParent() && 832 OutermostTemplateScope->getParent()->isTemplateParamScope()) 833 OutermostTemplateScope = OutermostTemplateScope->getParent(); 834 835 // Find the namespace context in which the original scope occurs. In 836 // the example, this is namespace N. 837 DeclContext *Semantic = DC; 838 while (!Semantic->isFileContext()) 839 Semantic = Semantic->getParent(); 840 841 // Find the declaration context just outside of the template 842 // parameter scope. This is the context in which the template is 843 // being lexically declaration (a namespace context). In the 844 // example, this is the global scope. 845 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) && 846 Lexical->Encloses(Semantic)) 847 return std::make_pair(Semantic, true); 848 849 return std::make_pair(Lexical, false); 850 } 851 852 namespace { 853 /// An RAII object to specify that we want to find block scope extern 854 /// declarations. 855 struct FindLocalExternScope { 856 FindLocalExternScope(LookupResult &R) 857 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() & 858 Decl::IDNS_LocalExtern) { 859 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary); 860 } 861 void restore() { 862 R.setFindLocalExtern(OldFindLocalExtern); 863 } 864 ~FindLocalExternScope() { 865 restore(); 866 } 867 LookupResult &R; 868 bool OldFindLocalExtern; 869 }; 870 } 871 872 bool Sema::CppLookupName(LookupResult &R, Scope *S) { 873 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup"); 874 875 DeclarationName Name = R.getLookupName(); 876 Sema::LookupNameKind NameKind = R.getLookupKind(); 877 878 // If this is the name of an implicitly-declared special member function, 879 // go through the scope stack to implicitly declare 880 if (isImplicitlyDeclaredMemberFunctionName(Name)) { 881 for (Scope *PreS = S; PreS; PreS = PreS->getParent()) 882 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity())) 883 DeclareImplicitMemberFunctionsWithName(*this, Name, DC); 884 } 885 886 // Implicitly declare member functions with the name we're looking for, if in 887 // fact we are in a scope where it matters. 888 889 Scope *Initial = S; 890 IdentifierResolver::iterator 891 I = IdResolver.begin(Name), 892 IEnd = IdResolver.end(); 893 894 // First we lookup local scope. 895 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 896 // ...During unqualified name lookup (3.4.1), the names appear as if 897 // they were declared in the nearest enclosing namespace which contains 898 // both the using-directive and the nominated namespace. 899 // [Note: in this context, "contains" means "contains directly or 900 // indirectly". 901 // 902 // For example: 903 // namespace A { int i; } 904 // void foo() { 905 // int i; 906 // { 907 // using namespace A; 908 // ++i; // finds local 'i', A::i appears at global scope 909 // } 910 // } 911 // 912 UnqualUsingDirectiveSet UDirs; 913 bool VisitedUsingDirectives = false; 914 bool LeftStartingScope = false; 915 DeclContext *OutsideOfTemplateParamDC = 0; 916 917 // When performing a scope lookup, we want to find local extern decls. 918 FindLocalExternScope FindLocals(R); 919 920 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 921 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 922 923 // Check whether the IdResolver has anything in this scope. 924 bool Found = false; 925 for (; I != IEnd && S->isDeclScope(*I); ++I) { 926 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 927 if (NameKind == LookupRedeclarationWithLinkage) { 928 // Determine whether this (or a previous) declaration is 929 // out-of-scope. 930 if (!LeftStartingScope && !Initial->isDeclScope(*I)) 931 LeftStartingScope = true; 932 933 // If we found something outside of our starting scope that 934 // does not have linkage, skip it. 935 if (LeftStartingScope && !((*I)->hasLinkage())) { 936 R.setShadowed(); 937 continue; 938 } 939 } 940 941 Found = true; 942 R.addDecl(ND); 943 } 944 } 945 if (Found) { 946 R.resolveKind(); 947 if (S->isClassScope()) 948 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 949 R.setNamingClass(Record); 950 return true; 951 } 952 953 if (NameKind == LookupLocalFriendName && !S->isClassScope()) { 954 // C++11 [class.friend]p11: 955 // If a friend declaration appears in a local class and the name 956 // specified is an unqualified name, a prior declaration is 957 // looked up without considering scopes that are outside the 958 // innermost enclosing non-class scope. 959 return false; 960 } 961 962 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 963 S->getParent() && !S->getParent()->isTemplateParamScope()) { 964 // We've just searched the last template parameter scope and 965 // found nothing, so look into the contexts between the 966 // lexical and semantic declaration contexts returned by 967 // findOuterContext(). This implements the name lookup behavior 968 // of C++ [temp.local]p8. 969 Ctx = OutsideOfTemplateParamDC; 970 OutsideOfTemplateParamDC = 0; 971 } 972 973 if (Ctx) { 974 DeclContext *OuterCtx; 975 bool SearchAfterTemplateScope; 976 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 977 if (SearchAfterTemplateScope) 978 OutsideOfTemplateParamDC = OuterCtx; 979 980 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 981 // We do not directly look into transparent contexts, since 982 // those entities will be found in the nearest enclosing 983 // non-transparent context. 984 if (Ctx->isTransparentContext()) 985 continue; 986 987 // We do not look directly into function or method contexts, 988 // since all of the local variables and parameters of the 989 // function/method are present within the Scope. 990 if (Ctx->isFunctionOrMethod()) { 991 // If we have an Objective-C instance method, look for ivars 992 // in the corresponding interface. 993 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 994 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) 995 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { 996 ObjCInterfaceDecl *ClassDeclared; 997 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( 998 Name.getAsIdentifierInfo(), 999 ClassDeclared)) { 1000 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) { 1001 R.addDecl(ND); 1002 R.resolveKind(); 1003 return true; 1004 } 1005 } 1006 } 1007 } 1008 1009 continue; 1010 } 1011 1012 // If this is a file context, we need to perform unqualified name 1013 // lookup considering using directives. 1014 if (Ctx->isFileContext()) { 1015 // If we haven't handled using directives yet, do so now. 1016 if (!VisitedUsingDirectives) { 1017 // Add using directives from this context up to the top level. 1018 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) { 1019 if (UCtx->isTransparentContext()) 1020 continue; 1021 1022 UDirs.visit(UCtx, UCtx); 1023 } 1024 1025 // Find the innermost file scope, so we can add using directives 1026 // from local scopes. 1027 Scope *InnermostFileScope = S; 1028 while (InnermostFileScope && 1029 !isNamespaceOrTranslationUnitScope(InnermostFileScope)) 1030 InnermostFileScope = InnermostFileScope->getParent(); 1031 UDirs.visitScopeChain(Initial, InnermostFileScope); 1032 1033 UDirs.done(); 1034 1035 VisitedUsingDirectives = true; 1036 } 1037 1038 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) { 1039 R.resolveKind(); 1040 return true; 1041 } 1042 1043 continue; 1044 } 1045 1046 // Perform qualified name lookup into this context. 1047 // FIXME: In some cases, we know that every name that could be found by 1048 // this qualified name lookup will also be on the identifier chain. For 1049 // example, inside a class without any base classes, we never need to 1050 // perform qualified lookup because all of the members are on top of the 1051 // identifier chain. 1052 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) 1053 return true; 1054 } 1055 } 1056 } 1057 1058 // Stop if we ran out of scopes. 1059 // FIXME: This really, really shouldn't be happening. 1060 if (!S) return false; 1061 1062 // If we are looking for members, no need to look into global/namespace scope. 1063 if (NameKind == LookupMemberName) 1064 return false; 1065 1066 // Collect UsingDirectiveDecls in all scopes, and recursively all 1067 // nominated namespaces by those using-directives. 1068 // 1069 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 1070 // don't build it for each lookup! 1071 if (!VisitedUsingDirectives) { 1072 UDirs.visitScopeChain(Initial, S); 1073 UDirs.done(); 1074 } 1075 1076 // If we're not performing redeclaration lookup, do not look for local 1077 // extern declarations outside of a function scope. 1078 if (!R.isForRedeclaration()) 1079 FindLocals.restore(); 1080 1081 // Lookup namespace scope, and global scope. 1082 // Unqualified name lookup in C++ requires looking into scopes 1083 // that aren't strictly lexical, and therefore we walk through the 1084 // context as well as walking through the scopes. 1085 for (; S; S = S->getParent()) { 1086 // Check whether the IdResolver has anything in this scope. 1087 bool Found = false; 1088 for (; I != IEnd && S->isDeclScope(*I); ++I) { 1089 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 1090 // We found something. Look for anything else in our scope 1091 // with this same name and in an acceptable identifier 1092 // namespace, so that we can construct an overload set if we 1093 // need to. 1094 Found = true; 1095 R.addDecl(ND); 1096 } 1097 } 1098 1099 if (Found && S->isTemplateParamScope()) { 1100 R.resolveKind(); 1101 return true; 1102 } 1103 1104 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 1105 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 1106 S->getParent() && !S->getParent()->isTemplateParamScope()) { 1107 // We've just searched the last template parameter scope and 1108 // found nothing, so look into the contexts between the 1109 // lexical and semantic declaration contexts returned by 1110 // findOuterContext(). This implements the name lookup behavior 1111 // of C++ [temp.local]p8. 1112 Ctx = OutsideOfTemplateParamDC; 1113 OutsideOfTemplateParamDC = 0; 1114 } 1115 1116 if (Ctx) { 1117 DeclContext *OuterCtx; 1118 bool SearchAfterTemplateScope; 1119 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 1120 if (SearchAfterTemplateScope) 1121 OutsideOfTemplateParamDC = OuterCtx; 1122 1123 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 1124 // We do not directly look into transparent contexts, since 1125 // those entities will be found in the nearest enclosing 1126 // non-transparent context. 1127 if (Ctx->isTransparentContext()) 1128 continue; 1129 1130 // If we have a context, and it's not a context stashed in the 1131 // template parameter scope for an out-of-line definition, also 1132 // look into that context. 1133 if (!(Found && S && S->isTemplateParamScope())) { 1134 assert(Ctx->isFileContext() && 1135 "We should have been looking only at file context here already."); 1136 1137 // Look into context considering using-directives. 1138 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) 1139 Found = true; 1140 } 1141 1142 if (Found) { 1143 R.resolveKind(); 1144 return true; 1145 } 1146 1147 if (R.isForRedeclaration() && !Ctx->isTransparentContext()) 1148 return false; 1149 } 1150 } 1151 1152 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) 1153 return false; 1154 } 1155 1156 return !R.empty(); 1157 } 1158 1159 /// \brief Find the declaration that a class temploid member specialization was 1160 /// instantiated from, or the member itself if it is an explicit specialization. 1161 static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) { 1162 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom(); 1163 } 1164 1165 /// \brief Find the module in which the given declaration was defined. 1166 static Module *getDefiningModule(Decl *Entity) { 1167 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) { 1168 // If this function was instantiated from a template, the defining module is 1169 // the module containing the pattern. 1170 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 1171 Entity = Pattern; 1172 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) { 1173 // If it's a class template specialization, find the template or partial 1174 // specialization from which it was instantiated. 1175 if (ClassTemplateSpecializationDecl *SpecRD = 1176 dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 1177 llvm::PointerUnion<ClassTemplateDecl*, 1178 ClassTemplatePartialSpecializationDecl*> From = 1179 SpecRD->getInstantiatedFrom(); 1180 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>()) 1181 Entity = FromTemplate->getTemplatedDecl(); 1182 else if (From) 1183 Entity = From.get<ClassTemplatePartialSpecializationDecl*>(); 1184 // Otherwise, it's an explicit specialization. 1185 } else if (MemberSpecializationInfo *MSInfo = 1186 RD->getMemberSpecializationInfo()) 1187 Entity = getInstantiatedFrom(RD, MSInfo); 1188 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) { 1189 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo()) 1190 Entity = getInstantiatedFrom(ED, MSInfo); 1191 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) { 1192 // FIXME: Map from variable template specializations back to the template. 1193 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) 1194 Entity = getInstantiatedFrom(VD, MSInfo); 1195 } 1196 1197 // Walk up to the containing context. That might also have been instantiated 1198 // from a template. 1199 DeclContext *Context = Entity->getDeclContext(); 1200 if (Context->isFileContext()) 1201 return Entity->getOwningModule(); 1202 return getDefiningModule(cast<Decl>(Context)); 1203 } 1204 1205 llvm::DenseSet<Module*> &Sema::getLookupModules() { 1206 unsigned N = ActiveTemplateInstantiations.size(); 1207 for (unsigned I = ActiveTemplateInstantiationLookupModules.size(); 1208 I != N; ++I) { 1209 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity); 1210 if (M && !LookupModulesCache.insert(M).second) 1211 M = 0; 1212 ActiveTemplateInstantiationLookupModules.push_back(M); 1213 } 1214 return LookupModulesCache; 1215 } 1216 1217 /// \brief Determine whether a declaration is visible to name lookup. 1218 /// 1219 /// This routine determines whether the declaration D is visible in the current 1220 /// lookup context, taking into account the current template instantiation 1221 /// stack. During template instantiation, a declaration is visible if it is 1222 /// visible from a module containing any entity on the template instantiation 1223 /// path (by instantiating a template, you allow it to see the declarations that 1224 /// your module can see, including those later on in your module). 1225 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) { 1226 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() && 1227 "should not call this: not in slow case"); 1228 Module *DeclModule = D->getOwningModule(); 1229 assert(DeclModule && "hidden decl not from a module"); 1230 1231 // Find the extra places where we need to look. 1232 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules(); 1233 if (LookupModules.empty()) 1234 return false; 1235 1236 // If our lookup set contains the decl's module, it's visible. 1237 if (LookupModules.count(DeclModule)) 1238 return true; 1239 1240 // If the declaration isn't exported, it's not visible in any other module. 1241 if (D->isModulePrivate()) 1242 return false; 1243 1244 // Check whether DeclModule is transitively exported to an import of 1245 // the lookup set. 1246 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(), 1247 E = LookupModules.end(); 1248 I != E; ++I) 1249 if ((*I)->isModuleVisible(DeclModule)) 1250 return true; 1251 return false; 1252 } 1253 1254 /// \brief Retrieve the visible declaration corresponding to D, if any. 1255 /// 1256 /// This routine determines whether the declaration D is visible in the current 1257 /// module, with the current imports. If not, it checks whether any 1258 /// redeclaration of D is visible, and if so, returns that declaration. 1259 /// 1260 /// \returns D, or a visible previous declaration of D, whichever is more recent 1261 /// and visible. If no declaration of D is visible, returns null. 1262 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 1263 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 1264 1265 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end(); 1266 RD != RDEnd; ++RD) { 1267 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) { 1268 if (LookupResult::isVisible(SemaRef, ND)) 1269 return ND; 1270 } 1271 } 1272 1273 return 0; 1274 } 1275 1276 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const { 1277 return findAcceptableDecl(SemaRef, D); 1278 } 1279 1280 /// @brief Perform unqualified name lookup starting from a given 1281 /// scope. 1282 /// 1283 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 1284 /// used to find names within the current scope. For example, 'x' in 1285 /// @code 1286 /// int x; 1287 /// int f() { 1288 /// return x; // unqualified name look finds 'x' in the global scope 1289 /// } 1290 /// @endcode 1291 /// 1292 /// Different lookup criteria can find different names. For example, a 1293 /// particular scope can have both a struct and a function of the same 1294 /// name, and each can be found by certain lookup criteria. For more 1295 /// information about lookup criteria, see the documentation for the 1296 /// class LookupCriteria. 1297 /// 1298 /// @param S The scope from which unqualified name lookup will 1299 /// begin. If the lookup criteria permits, name lookup may also search 1300 /// in the parent scopes. 1301 /// 1302 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to 1303 /// look up and the lookup kind), and is updated with the results of lookup 1304 /// including zero or more declarations and possibly additional information 1305 /// used to diagnose ambiguities. 1306 /// 1307 /// @returns \c true if lookup succeeded and false otherwise. 1308 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { 1309 DeclarationName Name = R.getLookupName(); 1310 if (!Name) return false; 1311 1312 LookupNameKind NameKind = R.getLookupKind(); 1313 1314 if (!getLangOpts().CPlusPlus) { 1315 // Unqualified name lookup in C/Objective-C is purely lexical, so 1316 // search in the declarations attached to the name. 1317 if (NameKind == Sema::LookupRedeclarationWithLinkage) { 1318 // Find the nearest non-transparent declaration scope. 1319 while (!(S->getFlags() & Scope::DeclScope) || 1320 (S->getEntity() && 1321 static_cast<DeclContext *>(S->getEntity()) 1322 ->isTransparentContext())) 1323 S = S->getParent(); 1324 } 1325 1326 // When performing a scope lookup, we want to find local extern decls. 1327 FindLocalExternScope FindLocals(R); 1328 1329 // Scan up the scope chain looking for a decl that matches this 1330 // identifier that is in the appropriate namespace. This search 1331 // should not take long, as shadowing of names is uncommon, and 1332 // deep shadowing is extremely uncommon. 1333 bool LeftStartingScope = false; 1334 1335 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 1336 IEnd = IdResolver.end(); 1337 I != IEnd; ++I) 1338 if (NamedDecl *D = R.getAcceptableDecl(*I)) { 1339 if (NameKind == LookupRedeclarationWithLinkage) { 1340 // Determine whether this (or a previous) declaration is 1341 // out-of-scope. 1342 if (!LeftStartingScope && !S->isDeclScope(*I)) 1343 LeftStartingScope = true; 1344 1345 // If we found something outside of our starting scope that 1346 // does not have linkage, skip it. 1347 if (LeftStartingScope && !((*I)->hasLinkage())) { 1348 R.setShadowed(); 1349 continue; 1350 } 1351 } 1352 else if (NameKind == LookupObjCImplicitSelfParam && 1353 !isa<ImplicitParamDecl>(*I)) 1354 continue; 1355 1356 R.addDecl(D); 1357 1358 // Check whether there are any other declarations with the same name 1359 // and in the same scope. 1360 if (I != IEnd) { 1361 // Find the scope in which this declaration was declared (if it 1362 // actually exists in a Scope). 1363 while (S && !S->isDeclScope(D)) 1364 S = S->getParent(); 1365 1366 // If the scope containing the declaration is the translation unit, 1367 // then we'll need to perform our checks based on the matching 1368 // DeclContexts rather than matching scopes. 1369 if (S && isNamespaceOrTranslationUnitScope(S)) 1370 S = 0; 1371 1372 // Compute the DeclContext, if we need it. 1373 DeclContext *DC = 0; 1374 if (!S) 1375 DC = (*I)->getDeclContext()->getRedeclContext(); 1376 1377 IdentifierResolver::iterator LastI = I; 1378 for (++LastI; LastI != IEnd; ++LastI) { 1379 if (S) { 1380 // Match based on scope. 1381 if (!S->isDeclScope(*LastI)) 1382 break; 1383 } else { 1384 // Match based on DeclContext. 1385 DeclContext *LastDC 1386 = (*LastI)->getDeclContext()->getRedeclContext(); 1387 if (!LastDC->Equals(DC)) 1388 break; 1389 } 1390 1391 // If the declaration is in the right namespace and visible, add it. 1392 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI)) 1393 R.addDecl(LastD); 1394 } 1395 1396 R.resolveKind(); 1397 } 1398 1399 return true; 1400 } 1401 } else { 1402 // Perform C++ unqualified name lookup. 1403 if (CppLookupName(R, S)) 1404 return true; 1405 } 1406 1407 // If we didn't find a use of this identifier, and if the identifier 1408 // corresponds to a compiler builtin, create the decl object for the builtin 1409 // now, injecting it into translation unit scope, and return it. 1410 if (AllowBuiltinCreation && LookupBuiltin(*this, R)) 1411 return true; 1412 1413 // If we didn't find a use of this identifier, the ExternalSource 1414 // may be able to handle the situation. 1415 // Note: some lookup failures are expected! 1416 // See e.g. R.isForRedeclaration(). 1417 return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); 1418 } 1419 1420 /// @brief Perform qualified name lookup in the namespaces nominated by 1421 /// using directives by the given context. 1422 /// 1423 /// C++98 [namespace.qual]p2: 1424 /// Given X::m (where X is a user-declared namespace), or given \::m 1425 /// (where X is the global namespace), let S be the set of all 1426 /// declarations of m in X and in the transitive closure of all 1427 /// namespaces nominated by using-directives in X and its used 1428 /// namespaces, except that using-directives are ignored in any 1429 /// namespace, including X, directly containing one or more 1430 /// declarations of m. No namespace is searched more than once in 1431 /// the lookup of a name. If S is the empty set, the program is 1432 /// ill-formed. Otherwise, if S has exactly one member, or if the 1433 /// context of the reference is a using-declaration 1434 /// (namespace.udecl), S is the required set of declarations of 1435 /// m. Otherwise if the use of m is not one that allows a unique 1436 /// declaration to be chosen from S, the program is ill-formed. 1437 /// 1438 /// C++98 [namespace.qual]p5: 1439 /// During the lookup of a qualified namespace member name, if the 1440 /// lookup finds more than one declaration of the member, and if one 1441 /// declaration introduces a class name or enumeration name and the 1442 /// other declarations either introduce the same object, the same 1443 /// enumerator or a set of functions, the non-type name hides the 1444 /// class or enumeration name if and only if the declarations are 1445 /// from the same namespace; otherwise (the declarations are from 1446 /// different namespaces), the program is ill-formed. 1447 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, 1448 DeclContext *StartDC) { 1449 assert(StartDC->isFileContext() && "start context is not a file context"); 1450 1451 DeclContext::udir_iterator I = StartDC->using_directives_begin(); 1452 DeclContext::udir_iterator E = StartDC->using_directives_end(); 1453 1454 if (I == E) return false; 1455 1456 // We have at least added all these contexts to the queue. 1457 llvm::SmallPtrSet<DeclContext*, 8> Visited; 1458 Visited.insert(StartDC); 1459 1460 // We have not yet looked into these namespaces, much less added 1461 // their "using-children" to the queue. 1462 SmallVector<NamespaceDecl*, 8> Queue; 1463 1464 // We have already looked into the initial namespace; seed the queue 1465 // with its using-children. 1466 for (; I != E; ++I) { 1467 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace(); 1468 if (Visited.insert(ND)) 1469 Queue.push_back(ND); 1470 } 1471 1472 // The easiest way to implement the restriction in [namespace.qual]p5 1473 // is to check whether any of the individual results found a tag 1474 // and, if so, to declare an ambiguity if the final result is not 1475 // a tag. 1476 bool FoundTag = false; 1477 bool FoundNonTag = false; 1478 1479 LookupResult LocalR(LookupResult::Temporary, R); 1480 1481 bool Found = false; 1482 while (!Queue.empty()) { 1483 NamespaceDecl *ND = Queue.pop_back_val(); 1484 1485 // We go through some convolutions here to avoid copying results 1486 // between LookupResults. 1487 bool UseLocal = !R.empty(); 1488 LookupResult &DirectR = UseLocal ? LocalR : R; 1489 bool FoundDirect = LookupDirect(S, DirectR, ND); 1490 1491 if (FoundDirect) { 1492 // First do any local hiding. 1493 DirectR.resolveKind(); 1494 1495 // If the local result is a tag, remember that. 1496 if (DirectR.isSingleTagDecl()) 1497 FoundTag = true; 1498 else 1499 FoundNonTag = true; 1500 1501 // Append the local results to the total results if necessary. 1502 if (UseLocal) { 1503 R.addAllDecls(LocalR); 1504 LocalR.clear(); 1505 } 1506 } 1507 1508 // If we find names in this namespace, ignore its using directives. 1509 if (FoundDirect) { 1510 Found = true; 1511 continue; 1512 } 1513 1514 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) { 1515 NamespaceDecl *Nom = (*I)->getNominatedNamespace(); 1516 if (Visited.insert(Nom)) 1517 Queue.push_back(Nom); 1518 } 1519 } 1520 1521 if (Found) { 1522 if (FoundTag && FoundNonTag) 1523 R.setAmbiguousQualifiedTagHiding(); 1524 else 1525 R.resolveKind(); 1526 } 1527 1528 return Found; 1529 } 1530 1531 /// \brief Callback that looks for any member of a class with the given name. 1532 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, 1533 CXXBasePath &Path, 1534 void *Name) { 1535 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 1536 1537 DeclarationName N = DeclarationName::getFromOpaquePtr(Name); 1538 Path.Decls = BaseRecord->lookup(N); 1539 return !Path.Decls.empty(); 1540 } 1541 1542 /// \brief Determine whether the given set of member declarations contains only 1543 /// static members, nested types, and enumerators. 1544 template<typename InputIterator> 1545 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) { 1546 Decl *D = (*First)->getUnderlyingDecl(); 1547 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D)) 1548 return true; 1549 1550 if (isa<CXXMethodDecl>(D)) { 1551 // Determine whether all of the methods are static. 1552 bool AllMethodsAreStatic = true; 1553 for(; First != Last; ++First) { 1554 D = (*First)->getUnderlyingDecl(); 1555 1556 if (!isa<CXXMethodDecl>(D)) { 1557 assert(isa<TagDecl>(D) && "Non-function must be a tag decl"); 1558 break; 1559 } 1560 1561 if (!cast<CXXMethodDecl>(D)->isStatic()) { 1562 AllMethodsAreStatic = false; 1563 break; 1564 } 1565 } 1566 1567 if (AllMethodsAreStatic) 1568 return true; 1569 } 1570 1571 return false; 1572 } 1573 1574 /// \brief Perform qualified name lookup into a given context. 1575 /// 1576 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 1577 /// names when the context of those names is explicit specified, e.g., 1578 /// "std::vector" or "x->member", or as part of unqualified name lookup. 1579 /// 1580 /// Different lookup criteria can find different names. For example, a 1581 /// particular scope can have both a struct and a function of the same 1582 /// name, and each can be found by certain lookup criteria. For more 1583 /// information about lookup criteria, see the documentation for the 1584 /// class LookupCriteria. 1585 /// 1586 /// \param R captures both the lookup criteria and any lookup results found. 1587 /// 1588 /// \param LookupCtx The context in which qualified name lookup will 1589 /// search. If the lookup criteria permits, name lookup may also search 1590 /// in the parent contexts or (for C++ classes) base classes. 1591 /// 1592 /// \param InUnqualifiedLookup true if this is qualified name lookup that 1593 /// occurs as part of unqualified name lookup. 1594 /// 1595 /// \returns true if lookup succeeded, false if it failed. 1596 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1597 bool InUnqualifiedLookup) { 1598 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 1599 1600 if (!R.getLookupName()) 1601 return false; 1602 1603 // Make sure that the declaration context is complete. 1604 assert((!isa<TagDecl>(LookupCtx) || 1605 LookupCtx->isDependentContext() || 1606 cast<TagDecl>(LookupCtx)->isCompleteDefinition() || 1607 cast<TagDecl>(LookupCtx)->isBeingDefined()) && 1608 "Declaration context must already be complete!"); 1609 1610 // Perform qualified name lookup into the LookupCtx. 1611 if (LookupDirect(*this, R, LookupCtx)) { 1612 R.resolveKind(); 1613 if (isa<CXXRecordDecl>(LookupCtx)) 1614 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 1615 return true; 1616 } 1617 1618 // Don't descend into implied contexts for redeclarations. 1619 // C++98 [namespace.qual]p6: 1620 // In a declaration for a namespace member in which the 1621 // declarator-id is a qualified-id, given that the qualified-id 1622 // for the namespace member has the form 1623 // nested-name-specifier unqualified-id 1624 // the unqualified-id shall name a member of the namespace 1625 // designated by the nested-name-specifier. 1626 // See also [class.mfct]p5 and [class.static.data]p2. 1627 if (R.isForRedeclaration()) 1628 return false; 1629 1630 // If this is a namespace, look it up in the implied namespaces. 1631 if (LookupCtx->isFileContext()) 1632 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 1633 1634 // If this isn't a C++ class, we aren't allowed to look into base 1635 // classes, we're done. 1636 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 1637 if (!LookupRec || !LookupRec->getDefinition()) 1638 return false; 1639 1640 // If we're performing qualified name lookup into a dependent class, 1641 // then we are actually looking into a current instantiation. If we have any 1642 // dependent base classes, then we either have to delay lookup until 1643 // template instantiation time (at which point all bases will be available) 1644 // or we have to fail. 1645 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 1646 LookupRec->hasAnyDependentBases()) { 1647 R.setNotFoundInCurrentInstantiation(); 1648 return false; 1649 } 1650 1651 // Perform lookup into our base classes. 1652 CXXBasePaths Paths; 1653 Paths.setOrigin(LookupRec); 1654 1655 // Look for this member in our base classes 1656 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0; 1657 switch (R.getLookupKind()) { 1658 case LookupObjCImplicitSelfParam: 1659 case LookupOrdinaryName: 1660 case LookupMemberName: 1661 case LookupRedeclarationWithLinkage: 1662 case LookupLocalFriendName: 1663 BaseCallback = &CXXRecordDecl::FindOrdinaryMember; 1664 break; 1665 1666 case LookupTagName: 1667 BaseCallback = &CXXRecordDecl::FindTagMember; 1668 break; 1669 1670 case LookupAnyName: 1671 BaseCallback = &LookupAnyMember; 1672 break; 1673 1674 case LookupUsingDeclName: 1675 // This lookup is for redeclarations only. 1676 1677 case LookupOperatorName: 1678 case LookupNamespaceName: 1679 case LookupObjCProtocolName: 1680 case LookupLabel: 1681 // These lookups will never find a member in a C++ class (or base class). 1682 return false; 1683 1684 case LookupNestedNameSpecifierName: 1685 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; 1686 break; 1687 } 1688 1689 if (!LookupRec->lookupInBases(BaseCallback, 1690 R.getLookupName().getAsOpaquePtr(), Paths)) 1691 return false; 1692 1693 R.setNamingClass(LookupRec); 1694 1695 // C++ [class.member.lookup]p2: 1696 // [...] If the resulting set of declarations are not all from 1697 // sub-objects of the same type, or the set has a nonstatic member 1698 // and includes members from distinct sub-objects, there is an 1699 // ambiguity and the program is ill-formed. Otherwise that set is 1700 // the result of the lookup. 1701 QualType SubobjectType; 1702 int SubobjectNumber = 0; 1703 AccessSpecifier SubobjectAccess = AS_none; 1704 1705 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 1706 Path != PathEnd; ++Path) { 1707 const CXXBasePathElement &PathElement = Path->back(); 1708 1709 // Pick the best (i.e. most permissive i.e. numerically lowest) access 1710 // across all paths. 1711 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 1712 1713 // Determine whether we're looking at a distinct sub-object or not. 1714 if (SubobjectType.isNull()) { 1715 // This is the first subobject we've looked at. Record its type. 1716 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 1717 SubobjectNumber = PathElement.SubobjectNumber; 1718 continue; 1719 } 1720 1721 if (SubobjectType 1722 != Context.getCanonicalType(PathElement.Base->getType())) { 1723 // We found members of the given name in two subobjects of 1724 // different types. If the declaration sets aren't the same, this 1725 // this lookup is ambiguous. 1726 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) { 1727 CXXBasePaths::paths_iterator FirstPath = Paths.begin(); 1728 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin(); 1729 DeclContext::lookup_iterator CurrentD = Path->Decls.begin(); 1730 1731 while (FirstD != FirstPath->Decls.end() && 1732 CurrentD != Path->Decls.end()) { 1733 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() != 1734 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl()) 1735 break; 1736 1737 ++FirstD; 1738 ++CurrentD; 1739 } 1740 1741 if (FirstD == FirstPath->Decls.end() && 1742 CurrentD == Path->Decls.end()) 1743 continue; 1744 } 1745 1746 R.setAmbiguousBaseSubobjectTypes(Paths); 1747 return true; 1748 } 1749 1750 if (SubobjectNumber != PathElement.SubobjectNumber) { 1751 // We have a different subobject of the same type. 1752 1753 // C++ [class.member.lookup]p5: 1754 // A static member, a nested type or an enumerator defined in 1755 // a base class T can unambiguously be found even if an object 1756 // has more than one base class subobject of type T. 1757 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) 1758 continue; 1759 1760 // We have found a nonstatic member name in multiple, distinct 1761 // subobjects. Name lookup is ambiguous. 1762 R.setAmbiguousBaseSubobjects(Paths); 1763 return true; 1764 } 1765 } 1766 1767 // Lookup in a base class succeeded; return these results. 1768 1769 DeclContext::lookup_result DR = Paths.front().Decls; 1770 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) { 1771 NamedDecl *D = *I; 1772 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 1773 D->getAccess()); 1774 R.addDecl(D, AS); 1775 } 1776 R.resolveKind(); 1777 return true; 1778 } 1779 1780 /// @brief Performs name lookup for a name that was parsed in the 1781 /// source code, and may contain a C++ scope specifier. 1782 /// 1783 /// This routine is a convenience routine meant to be called from 1784 /// contexts that receive a name and an optional C++ scope specifier 1785 /// (e.g., "N::M::x"). It will then perform either qualified or 1786 /// unqualified name lookup (with LookupQualifiedName or LookupName, 1787 /// respectively) on the given name and return those results. 1788 /// 1789 /// @param S The scope from which unqualified name lookup will 1790 /// begin. 1791 /// 1792 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 1793 /// 1794 /// @param EnteringContext Indicates whether we are going to enter the 1795 /// context of the scope-specifier SS (if present). 1796 /// 1797 /// @returns True if any decls were found (but possibly ambiguous) 1798 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1799 bool AllowBuiltinCreation, bool EnteringContext) { 1800 if (SS && SS->isInvalid()) { 1801 // When the scope specifier is invalid, don't even look for 1802 // anything. 1803 return false; 1804 } 1805 1806 if (SS && SS->isSet()) { 1807 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 1808 // We have resolved the scope specifier to a particular declaration 1809 // contex, and will perform name lookup in that context. 1810 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 1811 return false; 1812 1813 R.setContextRange(SS->getRange()); 1814 return LookupQualifiedName(R, DC); 1815 } 1816 1817 // We could not resolve the scope specified to a specific declaration 1818 // context, which means that SS refers to an unknown specialization. 1819 // Name lookup can't find anything in this case. 1820 R.setNotFoundInCurrentInstantiation(); 1821 R.setContextRange(SS->getRange()); 1822 return false; 1823 } 1824 1825 // Perform unqualified name lookup starting in the given scope. 1826 return LookupName(R, S, AllowBuiltinCreation); 1827 } 1828 1829 1830 /// \brief Produce a diagnostic describing the ambiguity that resulted 1831 /// from name lookup. 1832 /// 1833 /// \param Result The result of the ambiguous lookup to be diagnosed. 1834 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 1835 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1836 1837 DeclarationName Name = Result.getLookupName(); 1838 SourceLocation NameLoc = Result.getNameLoc(); 1839 SourceRange LookupRange = Result.getContextRange(); 1840 1841 switch (Result.getAmbiguityKind()) { 1842 case LookupResult::AmbiguousBaseSubobjects: { 1843 CXXBasePaths *Paths = Result.getBasePaths(); 1844 QualType SubobjectType = Paths->front().back().Base->getType(); 1845 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1846 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1847 << LookupRange; 1848 1849 DeclContext::lookup_iterator Found = Paths->front().Decls.begin(); 1850 while (isa<CXXMethodDecl>(*Found) && 1851 cast<CXXMethodDecl>(*Found)->isStatic()) 1852 ++Found; 1853 1854 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1855 break; 1856 } 1857 1858 case LookupResult::AmbiguousBaseSubobjectTypes: { 1859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1860 << Name << LookupRange; 1861 1862 CXXBasePaths *Paths = Result.getBasePaths(); 1863 std::set<Decl *> DeclsPrinted; 1864 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 1865 PathEnd = Paths->end(); 1866 Path != PathEnd; ++Path) { 1867 Decl *D = Path->Decls.front(); 1868 if (DeclsPrinted.insert(D).second) 1869 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1870 } 1871 break; 1872 } 1873 1874 case LookupResult::AmbiguousTagHiding: { 1875 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 1876 1877 llvm::SmallPtrSet<NamedDecl*,8> TagDecls; 1878 1879 LookupResult::iterator DI, DE = Result.end(); 1880 for (DI = Result.begin(); DI != DE; ++DI) 1881 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) { 1882 TagDecls.insert(TD); 1883 Diag(TD->getLocation(), diag::note_hidden_tag); 1884 } 1885 1886 for (DI = Result.begin(); DI != DE; ++DI) 1887 if (!isa<TagDecl>(*DI)) 1888 Diag((*DI)->getLocation(), diag::note_hiding_object); 1889 1890 // For recovery purposes, go ahead and implement the hiding. 1891 LookupResult::Filter F = Result.makeFilter(); 1892 while (F.hasNext()) { 1893 if (TagDecls.count(F.next())) 1894 F.erase(); 1895 } 1896 F.done(); 1897 break; 1898 } 1899 1900 case LookupResult::AmbiguousReference: { 1901 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1902 1903 LookupResult::iterator DI = Result.begin(), DE = Result.end(); 1904 for (; DI != DE; ++DI) 1905 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1906 break; 1907 } 1908 } 1909 } 1910 1911 namespace { 1912 struct AssociatedLookup { 1913 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, 1914 Sema::AssociatedNamespaceSet &Namespaces, 1915 Sema::AssociatedClassSet &Classes) 1916 : S(S), Namespaces(Namespaces), Classes(Classes), 1917 InstantiationLoc(InstantiationLoc) { 1918 } 1919 1920 Sema &S; 1921 Sema::AssociatedNamespaceSet &Namespaces; 1922 Sema::AssociatedClassSet &Classes; 1923 SourceLocation InstantiationLoc; 1924 }; 1925 } 1926 1927 static void 1928 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 1929 1930 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 1931 DeclContext *Ctx) { 1932 // Add the associated namespace for this class. 1933 1934 // We don't use DeclContext::getEnclosingNamespaceContext() as this may 1935 // be a locally scoped record. 1936 1937 // We skip out of inline namespaces. The innermost non-inline namespace 1938 // contains all names of all its nested inline namespaces anyway, so we can 1939 // replace the entire inline namespace tree with its root. 1940 while (Ctx->isRecord() || Ctx->isTransparentContext() || 1941 Ctx->isInlineNamespace()) 1942 Ctx = Ctx->getParent(); 1943 1944 if (Ctx->isFileContext()) 1945 Namespaces.insert(Ctx->getPrimaryContext()); 1946 } 1947 1948 // \brief Add the associated classes and namespaces for argument-dependent 1949 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 1950 static void 1951 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1952 const TemplateArgument &Arg) { 1953 // C++ [basic.lookup.koenig]p2, last bullet: 1954 // -- [...] ; 1955 switch (Arg.getKind()) { 1956 case TemplateArgument::Null: 1957 break; 1958 1959 case TemplateArgument::Type: 1960 // [...] the namespaces and classes associated with the types of the 1961 // template arguments provided for template type parameters (excluding 1962 // template template parameters) 1963 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 1964 break; 1965 1966 case TemplateArgument::Template: 1967 case TemplateArgument::TemplateExpansion: { 1968 // [...] the namespaces in which any template template arguments are 1969 // defined; and the classes in which any member templates used as 1970 // template template arguments are defined. 1971 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 1972 if (ClassTemplateDecl *ClassTemplate 1973 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 1974 DeclContext *Ctx = ClassTemplate->getDeclContext(); 1975 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1976 Result.Classes.insert(EnclosingClass); 1977 // Add the associated namespace for this class. 1978 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1979 } 1980 break; 1981 } 1982 1983 case TemplateArgument::Declaration: 1984 case TemplateArgument::Integral: 1985 case TemplateArgument::Expression: 1986 case TemplateArgument::NullPtr: 1987 // [Note: non-type template arguments do not contribute to the set of 1988 // associated namespaces. ] 1989 break; 1990 1991 case TemplateArgument::Pack: 1992 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), 1993 PEnd = Arg.pack_end(); 1994 P != PEnd; ++P) 1995 addAssociatedClassesAndNamespaces(Result, *P); 1996 break; 1997 } 1998 } 1999 2000 // \brief Add the associated classes and namespaces for 2001 // argument-dependent lookup with an argument of class type 2002 // (C++ [basic.lookup.koenig]p2). 2003 static void 2004 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2005 CXXRecordDecl *Class) { 2006 2007 // Just silently ignore anything whose name is __va_list_tag. 2008 if (Class->getDeclName() == Result.S.VAListTagName) 2009 return; 2010 2011 // C++ [basic.lookup.koenig]p2: 2012 // [...] 2013 // -- If T is a class type (including unions), its associated 2014 // classes are: the class itself; the class of which it is a 2015 // member, if any; and its direct and indirect base 2016 // classes. Its associated namespaces are the namespaces in 2017 // which its associated classes are defined. 2018 2019 // Add the class of which it is a member, if any. 2020 DeclContext *Ctx = Class->getDeclContext(); 2021 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2022 Result.Classes.insert(EnclosingClass); 2023 // Add the associated namespace for this class. 2024 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2025 2026 // Add the class itself. If we've already seen this class, we don't 2027 // need to visit base classes. 2028 if (!Result.Classes.insert(Class)) 2029 return; 2030 2031 // -- If T is a template-id, its associated namespaces and classes are 2032 // the namespace in which the template is defined; for member 2033 // templates, the member template's class; the namespaces and classes 2034 // associated with the types of the template arguments provided for 2035 // template type parameters (excluding template template parameters); the 2036 // namespaces in which any template template arguments are defined; and 2037 // the classes in which any member templates used as template template 2038 // arguments are defined. [Note: non-type template arguments do not 2039 // contribute to the set of associated namespaces. ] 2040 if (ClassTemplateSpecializationDecl *Spec 2041 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 2042 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 2043 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2044 Result.Classes.insert(EnclosingClass); 2045 // Add the associated namespace for this class. 2046 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2047 2048 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 2049 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 2050 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 2051 } 2052 2053 // Only recurse into base classes for complete types. 2054 if (!Class->hasDefinition()) { 2055 QualType type = Result.S.Context.getTypeDeclType(Class); 2056 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type, 2057 /*no diagnostic*/ 0)) 2058 return; 2059 } 2060 2061 // Add direct and indirect base classes along with their associated 2062 // namespaces. 2063 SmallVector<CXXRecordDecl *, 32> Bases; 2064 Bases.push_back(Class); 2065 while (!Bases.empty()) { 2066 // Pop this class off the stack. 2067 Class = Bases.pop_back_val(); 2068 2069 // Visit the base classes. 2070 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(), 2071 BaseEnd = Class->bases_end(); 2072 Base != BaseEnd; ++Base) { 2073 const RecordType *BaseType = Base->getType()->getAs<RecordType>(); 2074 // In dependent contexts, we do ADL twice, and the first time around, 2075 // the base type might be a dependent TemplateSpecializationType, or a 2076 // TemplateTypeParmType. If that happens, simply ignore it. 2077 // FIXME: If we want to support export, we probably need to add the 2078 // namespace of the template in a TemplateSpecializationType, or even 2079 // the classes and namespaces of known non-dependent arguments. 2080 if (!BaseType) 2081 continue; 2082 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 2083 if (Result.Classes.insert(BaseDecl)) { 2084 // Find the associated namespace for this base class. 2085 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 2086 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 2087 2088 // Make sure we visit the bases of this base class. 2089 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 2090 Bases.push_back(BaseDecl); 2091 } 2092 } 2093 } 2094 } 2095 2096 // \brief Add the associated classes and namespaces for 2097 // argument-dependent lookup with an argument of type T 2098 // (C++ [basic.lookup.koenig]p2). 2099 static void 2100 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 2101 // C++ [basic.lookup.koenig]p2: 2102 // 2103 // For each argument type T in the function call, there is a set 2104 // of zero or more associated namespaces and a set of zero or more 2105 // associated classes to be considered. The sets of namespaces and 2106 // classes is determined entirely by the types of the function 2107 // arguments (and the namespace of any template template 2108 // argument). Typedef names and using-declarations used to specify 2109 // the types do not contribute to this set. The sets of namespaces 2110 // and classes are determined in the following way: 2111 2112 SmallVector<const Type *, 16> Queue; 2113 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 2114 2115 while (true) { 2116 switch (T->getTypeClass()) { 2117 2118 #define TYPE(Class, Base) 2119 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2120 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2121 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2122 #define ABSTRACT_TYPE(Class, Base) 2123 #include "clang/AST/TypeNodes.def" 2124 // T is canonical. We can also ignore dependent types because 2125 // we don't need to do ADL at the definition point, but if we 2126 // wanted to implement template export (or if we find some other 2127 // use for associated classes and namespaces...) this would be 2128 // wrong. 2129 break; 2130 2131 // -- If T is a pointer to U or an array of U, its associated 2132 // namespaces and classes are those associated with U. 2133 case Type::Pointer: 2134 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 2135 continue; 2136 case Type::ConstantArray: 2137 case Type::IncompleteArray: 2138 case Type::VariableArray: 2139 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 2140 continue; 2141 2142 // -- If T is a fundamental type, its associated sets of 2143 // namespaces and classes are both empty. 2144 case Type::Builtin: 2145 break; 2146 2147 // -- If T is a class type (including unions), its associated 2148 // classes are: the class itself; the class of which it is a 2149 // member, if any; and its direct and indirect base 2150 // classes. Its associated namespaces are the namespaces in 2151 // which its associated classes are defined. 2152 case Type::Record: { 2153 CXXRecordDecl *Class 2154 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 2155 addAssociatedClassesAndNamespaces(Result, Class); 2156 break; 2157 } 2158 2159 // -- If T is an enumeration type, its associated namespace is 2160 // the namespace in which it is defined. If it is class 2161 // member, its associated class is the member's class; else 2162 // it has no associated class. 2163 case Type::Enum: { 2164 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 2165 2166 DeclContext *Ctx = Enum->getDeclContext(); 2167 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2168 Result.Classes.insert(EnclosingClass); 2169 2170 // Add the associated namespace for this class. 2171 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2172 2173 break; 2174 } 2175 2176 // -- If T is a function type, its associated namespaces and 2177 // classes are those associated with the function parameter 2178 // types and those associated with the return type. 2179 case Type::FunctionProto: { 2180 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2181 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), 2182 ArgEnd = Proto->arg_type_end(); 2183 Arg != ArgEnd; ++Arg) 2184 Queue.push_back(Arg->getTypePtr()); 2185 // fallthrough 2186 } 2187 case Type::FunctionNoProto: { 2188 const FunctionType *FnType = cast<FunctionType>(T); 2189 T = FnType->getResultType().getTypePtr(); 2190 continue; 2191 } 2192 2193 // -- If T is a pointer to a member function of a class X, its 2194 // associated namespaces and classes are those associated 2195 // with the function parameter types and return type, 2196 // together with those associated with X. 2197 // 2198 // -- If T is a pointer to a data member of class X, its 2199 // associated namespaces and classes are those associated 2200 // with the member type together with those associated with 2201 // X. 2202 case Type::MemberPointer: { 2203 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 2204 2205 // Queue up the class type into which this points. 2206 Queue.push_back(MemberPtr->getClass()); 2207 2208 // And directly continue with the pointee type. 2209 T = MemberPtr->getPointeeType().getTypePtr(); 2210 continue; 2211 } 2212 2213 // As an extension, treat this like a normal pointer. 2214 case Type::BlockPointer: 2215 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 2216 continue; 2217 2218 // References aren't covered by the standard, but that's such an 2219 // obvious defect that we cover them anyway. 2220 case Type::LValueReference: 2221 case Type::RValueReference: 2222 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 2223 continue; 2224 2225 // These are fundamental types. 2226 case Type::Vector: 2227 case Type::ExtVector: 2228 case Type::Complex: 2229 break; 2230 2231 // Non-deduced auto types only get here for error cases. 2232 case Type::Auto: 2233 break; 2234 2235 // If T is an Objective-C object or interface type, or a pointer to an 2236 // object or interface type, the associated namespace is the global 2237 // namespace. 2238 case Type::ObjCObject: 2239 case Type::ObjCInterface: 2240 case Type::ObjCObjectPointer: 2241 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); 2242 break; 2243 2244 // Atomic types are just wrappers; use the associations of the 2245 // contained type. 2246 case Type::Atomic: 2247 T = cast<AtomicType>(T)->getValueType().getTypePtr(); 2248 continue; 2249 } 2250 2251 if (Queue.empty()) 2252 break; 2253 T = Queue.pop_back_val(); 2254 } 2255 } 2256 2257 /// \brief Find the associated classes and namespaces for 2258 /// argument-dependent lookup for a call with the given set of 2259 /// arguments. 2260 /// 2261 /// This routine computes the sets of associated classes and associated 2262 /// namespaces searched by argument-dependent lookup 2263 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 2264 void Sema::FindAssociatedClassesAndNamespaces( 2265 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 2266 AssociatedNamespaceSet &AssociatedNamespaces, 2267 AssociatedClassSet &AssociatedClasses) { 2268 AssociatedNamespaces.clear(); 2269 AssociatedClasses.clear(); 2270 2271 AssociatedLookup Result(*this, InstantiationLoc, 2272 AssociatedNamespaces, AssociatedClasses); 2273 2274 // C++ [basic.lookup.koenig]p2: 2275 // For each argument type T in the function call, there is a set 2276 // of zero or more associated namespaces and a set of zero or more 2277 // associated classes to be considered. The sets of namespaces and 2278 // classes is determined entirely by the types of the function 2279 // arguments (and the namespace of any template template 2280 // argument). 2281 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 2282 Expr *Arg = Args[ArgIdx]; 2283 2284 if (Arg->getType() != Context.OverloadTy) { 2285 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 2286 continue; 2287 } 2288 2289 // [...] In addition, if the argument is the name or address of a 2290 // set of overloaded functions and/or function templates, its 2291 // associated classes and namespaces are the union of those 2292 // associated with each of the members of the set: the namespace 2293 // in which the function or function template is defined and the 2294 // classes and namespaces associated with its (non-dependent) 2295 // parameter types and return type. 2296 Arg = Arg->IgnoreParens(); 2297 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) 2298 if (unaryOp->getOpcode() == UO_AddrOf) 2299 Arg = unaryOp->getSubExpr(); 2300 2301 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); 2302 if (!ULE) continue; 2303 2304 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end(); 2305 I != E; ++I) { 2306 // Look through any using declarations to find the underlying function. 2307 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 2308 2309 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn); 2310 if (!FDecl) 2311 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl(); 2312 2313 // Add the classes and namespaces associated with the parameter 2314 // types and return type of this function. 2315 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 2316 } 2317 } 2318 } 2319 2320 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 2321 /// an acceptable non-member overloaded operator for a call whose 2322 /// arguments have types T1 (and, if non-empty, T2). This routine 2323 /// implements the check in C++ [over.match.oper]p3b2 concerning 2324 /// enumeration types. 2325 static bool 2326 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 2327 QualType T1, QualType T2, 2328 ASTContext &Context) { 2329 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 2330 return true; 2331 2332 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 2333 return true; 2334 2335 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 2336 if (Proto->getNumArgs() < 1) 2337 return false; 2338 2339 if (T1->isEnumeralType()) { 2340 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 2341 if (Context.hasSameUnqualifiedType(T1, ArgType)) 2342 return true; 2343 } 2344 2345 if (Proto->getNumArgs() < 2) 2346 return false; 2347 2348 if (!T2.isNull() && T2->isEnumeralType()) { 2349 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 2350 if (Context.hasSameUnqualifiedType(T2, ArgType)) 2351 return true; 2352 } 2353 2354 return false; 2355 } 2356 2357 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 2358 SourceLocation Loc, 2359 LookupNameKind NameKind, 2360 RedeclarationKind Redecl) { 2361 LookupResult R(*this, Name, Loc, NameKind, Redecl); 2362 LookupName(R, S); 2363 return R.getAsSingle<NamedDecl>(); 2364 } 2365 2366 /// \brief Find the protocol with the given name, if any. 2367 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 2368 SourceLocation IdLoc, 2369 RedeclarationKind Redecl) { 2370 Decl *D = LookupSingleName(TUScope, II, IdLoc, 2371 LookupObjCProtocolName, Redecl); 2372 return cast_or_null<ObjCProtocolDecl>(D); 2373 } 2374 2375 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2376 QualType T1, QualType T2, 2377 UnresolvedSetImpl &Functions) { 2378 // C++ [over.match.oper]p3: 2379 // -- The set of non-member candidates is the result of the 2380 // unqualified lookup of operator@ in the context of the 2381 // expression according to the usual rules for name lookup in 2382 // unqualified function calls (3.4.2) except that all member 2383 // functions are ignored. However, if no operand has a class 2384 // type, only those non-member functions in the lookup set 2385 // that have a first parameter of type T1 or "reference to 2386 // (possibly cv-qualified) T1", when T1 is an enumeration 2387 // type, or (if there is a right operand) a second parameter 2388 // of type T2 or "reference to (possibly cv-qualified) T2", 2389 // when T2 is an enumeration type, are candidate functions. 2390 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2391 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 2392 LookupName(Operators, S); 2393 2394 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 2395 2396 if (Operators.empty()) 2397 return; 2398 2399 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end(); 2400 Op != OpEnd; ++Op) { 2401 NamedDecl *Found = (*Op)->getUnderlyingDecl(); 2402 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) { 2403 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 2404 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD 2405 } else if (FunctionTemplateDecl *FunTmpl 2406 = dyn_cast<FunctionTemplateDecl>(Found)) { 2407 // FIXME: friend operators? 2408 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate, 2409 // later? 2410 if (!FunTmpl->getDeclContext()->isRecord()) 2411 Functions.addDecl(*Op, Op.getAccess()); 2412 } 2413 } 2414 } 2415 2416 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD, 2417 CXXSpecialMember SM, 2418 bool ConstArg, 2419 bool VolatileArg, 2420 bool RValueThis, 2421 bool ConstThis, 2422 bool VolatileThis) { 2423 assert(CanDeclareSpecialMemberFunction(RD) && 2424 "doing special member lookup into record that isn't fully complete"); 2425 RD = RD->getDefinition(); 2426 if (RValueThis || ConstThis || VolatileThis) 2427 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && 2428 "constructors and destructors always have unqualified lvalue this"); 2429 if (ConstArg || VolatileArg) 2430 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && 2431 "parameter-less special members can't have qualified arguments"); 2432 2433 llvm::FoldingSetNodeID ID; 2434 ID.AddPointer(RD); 2435 ID.AddInteger(SM); 2436 ID.AddInteger(ConstArg); 2437 ID.AddInteger(VolatileArg); 2438 ID.AddInteger(RValueThis); 2439 ID.AddInteger(ConstThis); 2440 ID.AddInteger(VolatileThis); 2441 2442 void *InsertPoint; 2443 SpecialMemberOverloadResult *Result = 2444 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); 2445 2446 // This was already cached 2447 if (Result) 2448 return Result; 2449 2450 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>(); 2451 Result = new (Result) SpecialMemberOverloadResult(ID); 2452 SpecialMemberCache.InsertNode(Result, InsertPoint); 2453 2454 if (SM == CXXDestructor) { 2455 if (RD->needsImplicitDestructor()) 2456 DeclareImplicitDestructor(RD); 2457 CXXDestructorDecl *DD = RD->getDestructor(); 2458 assert(DD && "record without a destructor"); 2459 Result->setMethod(DD); 2460 Result->setKind(DD->isDeleted() ? 2461 SpecialMemberOverloadResult::NoMemberOrDeleted : 2462 SpecialMemberOverloadResult::Success); 2463 return Result; 2464 } 2465 2466 // Prepare for overload resolution. Here we construct a synthetic argument 2467 // if necessary and make sure that implicit functions are declared. 2468 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); 2469 DeclarationName Name; 2470 Expr *Arg = 0; 2471 unsigned NumArgs; 2472 2473 QualType ArgType = CanTy; 2474 ExprValueKind VK = VK_LValue; 2475 2476 if (SM == CXXDefaultConstructor) { 2477 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 2478 NumArgs = 0; 2479 if (RD->needsImplicitDefaultConstructor()) 2480 DeclareImplicitDefaultConstructor(RD); 2481 } else { 2482 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { 2483 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 2484 if (RD->needsImplicitCopyConstructor()) 2485 DeclareImplicitCopyConstructor(RD); 2486 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) 2487 DeclareImplicitMoveConstructor(RD); 2488 } else { 2489 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2490 if (RD->needsImplicitCopyAssignment()) 2491 DeclareImplicitCopyAssignment(RD); 2492 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) 2493 DeclareImplicitMoveAssignment(RD); 2494 } 2495 2496 if (ConstArg) 2497 ArgType.addConst(); 2498 if (VolatileArg) 2499 ArgType.addVolatile(); 2500 2501 // This isn't /really/ specified by the standard, but it's implied 2502 // we should be working from an RValue in the case of move to ensure 2503 // that we prefer to bind to rvalue references, and an LValue in the 2504 // case of copy to ensure we don't bind to rvalue references. 2505 // Possibly an XValue is actually correct in the case of move, but 2506 // there is no semantic difference for class types in this restricted 2507 // case. 2508 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) 2509 VK = VK_LValue; 2510 else 2511 VK = VK_RValue; 2512 } 2513 2514 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK); 2515 2516 if (SM != CXXDefaultConstructor) { 2517 NumArgs = 1; 2518 Arg = &FakeArg; 2519 } 2520 2521 // Create the object argument 2522 QualType ThisTy = CanTy; 2523 if (ConstThis) 2524 ThisTy.addConst(); 2525 if (VolatileThis) 2526 ThisTy.addVolatile(); 2527 Expr::Classification Classification = 2528 OpaqueValueExpr(SourceLocation(), ThisTy, 2529 RValueThis ? VK_RValue : VK_LValue).Classify(Context); 2530 2531 // Now we perform lookup on the name we computed earlier and do overload 2532 // resolution. Lookup is only performed directly into the class since there 2533 // will always be a (possibly implicit) declaration to shadow any others. 2534 OverloadCandidateSet OCS((SourceLocation())); 2535 DeclContext::lookup_result R = RD->lookup(Name); 2536 assert(!R.empty() && 2537 "lookup for a constructor or assignment operator was empty"); 2538 2539 // Copy the candidates as our processing of them may load new declarations 2540 // from an external source and invalidate lookup_result. 2541 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); 2542 2543 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(), 2544 E = Candidates.end(); 2545 I != E; ++I) { 2546 NamedDecl *Cand = *I; 2547 2548 if (Cand->isInvalidDecl()) 2549 continue; 2550 2551 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) { 2552 // FIXME: [namespace.udecl]p15 says that we should only consider a 2553 // using declaration here if it does not match a declaration in the 2554 // derived class. We do not implement this correctly in other cases 2555 // either. 2556 Cand = U->getTargetDecl(); 2557 2558 if (Cand->isInvalidDecl()) 2559 continue; 2560 } 2561 2562 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) { 2563 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 2564 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy, 2565 Classification, llvm::makeArrayRef(&Arg, NumArgs), 2566 OCS, true); 2567 else 2568 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), 2569 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 2570 } else if (FunctionTemplateDecl *Tmpl = 2571 dyn_cast<FunctionTemplateDecl>(Cand)) { 2572 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 2573 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 2574 RD, 0, ThisTy, Classification, 2575 llvm::makeArrayRef(&Arg, NumArgs), 2576 OCS, true); 2577 else 2578 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 2579 0, llvm::makeArrayRef(&Arg, NumArgs), 2580 OCS, true); 2581 } else { 2582 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl"); 2583 } 2584 } 2585 2586 OverloadCandidateSet::iterator Best; 2587 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) { 2588 case OR_Success: 2589 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 2590 Result->setKind(SpecialMemberOverloadResult::Success); 2591 break; 2592 2593 case OR_Deleted: 2594 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 2595 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 2596 break; 2597 2598 case OR_Ambiguous: 2599 Result->setMethod(0); 2600 Result->setKind(SpecialMemberOverloadResult::Ambiguous); 2601 break; 2602 2603 case OR_No_Viable_Function: 2604 Result->setMethod(0); 2605 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 2606 break; 2607 } 2608 2609 return Result; 2610 } 2611 2612 /// \brief Look up the default constructor for the given class. 2613 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { 2614 SpecialMemberOverloadResult *Result = 2615 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, 2616 false, false); 2617 2618 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2619 } 2620 2621 /// \brief Look up the copying constructor for the given class. 2622 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, 2623 unsigned Quals) { 2624 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2625 "non-const, non-volatile qualifiers for copy ctor arg"); 2626 SpecialMemberOverloadResult *Result = 2627 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, 2628 Quals & Qualifiers::Volatile, false, false, false); 2629 2630 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2631 } 2632 2633 /// \brief Look up the moving constructor for the given class. 2634 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, 2635 unsigned Quals) { 2636 SpecialMemberOverloadResult *Result = 2637 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, 2638 Quals & Qualifiers::Volatile, false, false, false); 2639 2640 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2641 } 2642 2643 /// \brief Look up the constructors for the given class. 2644 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 2645 // If the implicit constructors have not yet been declared, do so now. 2646 if (CanDeclareSpecialMemberFunction(Class)) { 2647 if (Class->needsImplicitDefaultConstructor()) 2648 DeclareImplicitDefaultConstructor(Class); 2649 if (Class->needsImplicitCopyConstructor()) 2650 DeclareImplicitCopyConstructor(Class); 2651 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) 2652 DeclareImplicitMoveConstructor(Class); 2653 } 2654 2655 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 2656 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 2657 return Class->lookup(Name); 2658 } 2659 2660 /// \brief Look up the copying assignment operator for the given class. 2661 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, 2662 unsigned Quals, bool RValueThis, 2663 unsigned ThisQuals) { 2664 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2665 "non-const, non-volatile qualifiers for copy assignment arg"); 2666 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2667 "non-const, non-volatile qualifiers for copy assignment this"); 2668 SpecialMemberOverloadResult *Result = 2669 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, 2670 Quals & Qualifiers::Volatile, RValueThis, 2671 ThisQuals & Qualifiers::Const, 2672 ThisQuals & Qualifiers::Volatile); 2673 2674 return Result->getMethod(); 2675 } 2676 2677 /// \brief Look up the moving assignment operator for the given class. 2678 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, 2679 unsigned Quals, 2680 bool RValueThis, 2681 unsigned ThisQuals) { 2682 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2683 "non-const, non-volatile qualifiers for copy assignment this"); 2684 SpecialMemberOverloadResult *Result = 2685 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, 2686 Quals & Qualifiers::Volatile, RValueThis, 2687 ThisQuals & Qualifiers::Const, 2688 ThisQuals & Qualifiers::Volatile); 2689 2690 return Result->getMethod(); 2691 } 2692 2693 /// \brief Look for the destructor of the given class. 2694 /// 2695 /// During semantic analysis, this routine should be used in lieu of 2696 /// CXXRecordDecl::getDestructor(). 2697 /// 2698 /// \returns The destructor for this class. 2699 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 2700 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor, 2701 false, false, false, 2702 false, false)->getMethod()); 2703 } 2704 2705 /// LookupLiteralOperator - Determine which literal operator should be used for 2706 /// a user-defined literal, per C++11 [lex.ext]. 2707 /// 2708 /// Normal overload resolution is not used to select which literal operator to 2709 /// call for a user-defined literal. Look up the provided literal operator name, 2710 /// and filter the results to the appropriate set for the given argument types. 2711 Sema::LiteralOperatorLookupResult 2712 Sema::LookupLiteralOperator(Scope *S, LookupResult &R, 2713 ArrayRef<QualType> ArgTys, 2714 bool AllowRawAndTemplate) { 2715 LookupName(R, S); 2716 assert(R.getResultKind() != LookupResult::Ambiguous && 2717 "literal operator lookup can't be ambiguous"); 2718 2719 // Filter the lookup results appropriately. 2720 LookupResult::Filter F = R.makeFilter(); 2721 2722 bool FoundTemplate = false; 2723 bool FoundRaw = false; 2724 bool FoundExactMatch = false; 2725 2726 while (F.hasNext()) { 2727 Decl *D = F.next(); 2728 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 2729 D = USD->getTargetDecl(); 2730 2731 bool IsTemplate = isa<FunctionTemplateDecl>(D); 2732 bool IsRaw = false; 2733 bool IsExactMatch = false; 2734 2735 // If the declaration we found is invalid, skip it. 2736 if (D->isInvalidDecl()) { 2737 F.erase(); 2738 continue; 2739 } 2740 2741 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2742 if (FD->getNumParams() == 1 && 2743 FD->getParamDecl(0)->getType()->getAs<PointerType>()) 2744 IsRaw = true; 2745 else if (FD->getNumParams() == ArgTys.size()) { 2746 IsExactMatch = true; 2747 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { 2748 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); 2749 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { 2750 IsExactMatch = false; 2751 break; 2752 } 2753 } 2754 } 2755 } 2756 2757 if (IsExactMatch) { 2758 FoundExactMatch = true; 2759 AllowRawAndTemplate = false; 2760 if (FoundRaw || FoundTemplate) { 2761 // Go through again and remove the raw and template decls we've 2762 // already found. 2763 F.restart(); 2764 FoundRaw = FoundTemplate = false; 2765 } 2766 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) { 2767 FoundTemplate |= IsTemplate; 2768 FoundRaw |= IsRaw; 2769 } else { 2770 F.erase(); 2771 } 2772 } 2773 2774 F.done(); 2775 2776 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching 2777 // parameter type, that is used in preference to a raw literal operator 2778 // or literal operator template. 2779 if (FoundExactMatch) 2780 return LOLR_Cooked; 2781 2782 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal 2783 // operator template, but not both. 2784 if (FoundRaw && FoundTemplate) { 2785 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 2786 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2787 Decl *D = *I; 2788 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 2789 D = USD->getTargetDecl(); 2790 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 2791 D = FunTmpl->getTemplatedDecl(); 2792 NoteOverloadCandidate(cast<FunctionDecl>(D)); 2793 } 2794 return LOLR_Error; 2795 } 2796 2797 if (FoundRaw) 2798 return LOLR_Raw; 2799 2800 if (FoundTemplate) 2801 return LOLR_Template; 2802 2803 // Didn't find anything we could use. 2804 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) 2805 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] 2806 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate; 2807 return LOLR_Error; 2808 } 2809 2810 void ADLResult::insert(NamedDecl *New) { 2811 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 2812 2813 // If we haven't yet seen a decl for this key, or the last decl 2814 // was exactly this one, we're done. 2815 if (Old == 0 || Old == New) { 2816 Old = New; 2817 return; 2818 } 2819 2820 // Otherwise, decide which is a more recent redeclaration. 2821 FunctionDecl *OldFD, *NewFD; 2822 if (isa<FunctionTemplateDecl>(New)) { 2823 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl(); 2824 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl(); 2825 } else { 2826 OldFD = cast<FunctionDecl>(Old); 2827 NewFD = cast<FunctionDecl>(New); 2828 } 2829 2830 FunctionDecl *Cursor = NewFD; 2831 while (true) { 2832 Cursor = Cursor->getPreviousDecl(); 2833 2834 // If we got to the end without finding OldFD, OldFD is the newer 2835 // declaration; leave things as they are. 2836 if (!Cursor) return; 2837 2838 // If we do find OldFD, then NewFD is newer. 2839 if (Cursor == OldFD) break; 2840 2841 // Otherwise, keep looking. 2842 } 2843 2844 Old = New; 2845 } 2846 2847 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator, 2848 SourceLocation Loc, ArrayRef<Expr *> Args, 2849 ADLResult &Result) { 2850 // Find all of the associated namespaces and classes based on the 2851 // arguments we have. 2852 AssociatedNamespaceSet AssociatedNamespaces; 2853 AssociatedClassSet AssociatedClasses; 2854 FindAssociatedClassesAndNamespaces(Loc, Args, 2855 AssociatedNamespaces, 2856 AssociatedClasses); 2857 2858 QualType T1, T2; 2859 if (Operator) { 2860 T1 = Args[0]->getType(); 2861 if (Args.size() >= 2) 2862 T2 = Args[1]->getType(); 2863 } 2864 2865 // C++ [basic.lookup.argdep]p3: 2866 // Let X be the lookup set produced by unqualified lookup (3.4.1) 2867 // and let Y be the lookup set produced by argument dependent 2868 // lookup (defined as follows). If X contains [...] then Y is 2869 // empty. Otherwise Y is the set of declarations found in the 2870 // namespaces associated with the argument types as described 2871 // below. The set of declarations found by the lookup of the name 2872 // is the union of X and Y. 2873 // 2874 // Here, we compute Y and add its members to the overloaded 2875 // candidate set. 2876 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), 2877 NSEnd = AssociatedNamespaces.end(); 2878 NS != NSEnd; ++NS) { 2879 // When considering an associated namespace, the lookup is the 2880 // same as the lookup performed when the associated namespace is 2881 // used as a qualifier (3.4.3.2) except that: 2882 // 2883 // -- Any using-directives in the associated namespace are 2884 // ignored. 2885 // 2886 // -- Any namespace-scope friend functions declared in 2887 // associated classes are visible within their respective 2888 // namespaces even if they are not visible during an ordinary 2889 // lookup (11.4). 2890 DeclContext::lookup_result R = (*NS)->lookup(Name); 2891 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 2892 ++I) { 2893 NamedDecl *D = *I; 2894 // If the only declaration here is an ordinary friend, consider 2895 // it only if it was declared in an associated classes. 2896 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) { 2897 // If it's neither ordinarily visible nor a friend, we can't find it. 2898 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0) 2899 continue; 2900 2901 bool DeclaredInAssociatedClass = false; 2902 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) { 2903 DeclContext *LexDC = DI->getLexicalDeclContext(); 2904 if (isa<CXXRecordDecl>(LexDC) && 2905 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) { 2906 DeclaredInAssociatedClass = true; 2907 break; 2908 } 2909 } 2910 if (!DeclaredInAssociatedClass) 2911 continue; 2912 } 2913 2914 if (isa<UsingShadowDecl>(D)) 2915 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2916 2917 if (isa<FunctionDecl>(D)) { 2918 if (Operator && 2919 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D), 2920 T1, T2, Context)) 2921 continue; 2922 } else if (!isa<FunctionTemplateDecl>(D)) 2923 continue; 2924 2925 Result.insert(D); 2926 } 2927 } 2928 } 2929 2930 //---------------------------------------------------------------------------- 2931 // Search for all visible declarations. 2932 //---------------------------------------------------------------------------- 2933 VisibleDeclConsumer::~VisibleDeclConsumer() { } 2934 2935 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } 2936 2937 namespace { 2938 2939 class ShadowContextRAII; 2940 2941 class VisibleDeclsRecord { 2942 public: 2943 /// \brief An entry in the shadow map, which is optimized to store a 2944 /// single declaration (the common case) but can also store a list 2945 /// of declarations. 2946 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; 2947 2948 private: 2949 /// \brief A mapping from declaration names to the declarations that have 2950 /// this name within a particular scope. 2951 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 2952 2953 /// \brief A list of shadow maps, which is used to model name hiding. 2954 std::list<ShadowMap> ShadowMaps; 2955 2956 /// \brief The declaration contexts we have already visited. 2957 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 2958 2959 friend class ShadowContextRAII; 2960 2961 public: 2962 /// \brief Determine whether we have already visited this context 2963 /// (and, if not, note that we are going to visit that context now). 2964 bool visitedContext(DeclContext *Ctx) { 2965 return !VisitedContexts.insert(Ctx); 2966 } 2967 2968 bool alreadyVisitedContext(DeclContext *Ctx) { 2969 return VisitedContexts.count(Ctx); 2970 } 2971 2972 /// \brief Determine whether the given declaration is hidden in the 2973 /// current scope. 2974 /// 2975 /// \returns the declaration that hides the given declaration, or 2976 /// NULL if no such declaration exists. 2977 NamedDecl *checkHidden(NamedDecl *ND); 2978 2979 /// \brief Add a declaration to the current shadow map. 2980 void add(NamedDecl *ND) { 2981 ShadowMaps.back()[ND->getDeclName()].push_back(ND); 2982 } 2983 }; 2984 2985 /// \brief RAII object that records when we've entered a shadow context. 2986 class ShadowContextRAII { 2987 VisibleDeclsRecord &Visible; 2988 2989 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 2990 2991 public: 2992 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 2993 Visible.ShadowMaps.push_back(ShadowMap()); 2994 } 2995 2996 ~ShadowContextRAII() { 2997 Visible.ShadowMaps.pop_back(); 2998 } 2999 }; 3000 3001 } // end anonymous namespace 3002 3003 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 3004 // Look through using declarations. 3005 ND = ND->getUnderlyingDecl(); 3006 3007 unsigned IDNS = ND->getIdentifierNamespace(); 3008 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 3009 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 3010 SM != SMEnd; ++SM) { 3011 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 3012 if (Pos == SM->end()) 3013 continue; 3014 3015 for (ShadowMapEntry::iterator I = Pos->second.begin(), 3016 IEnd = Pos->second.end(); 3017 I != IEnd; ++I) { 3018 // A tag declaration does not hide a non-tag declaration. 3019 if ((*I)->hasTagIdentifierNamespace() && 3020 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 3021 Decl::IDNS_ObjCProtocol))) 3022 continue; 3023 3024 // Protocols are in distinct namespaces from everything else. 3025 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 3026 || (IDNS & Decl::IDNS_ObjCProtocol)) && 3027 (*I)->getIdentifierNamespace() != IDNS) 3028 continue; 3029 3030 // Functions and function templates in the same scope overload 3031 // rather than hide. FIXME: Look for hiding based on function 3032 // signatures! 3033 if ((*I)->isFunctionOrFunctionTemplate() && 3034 ND->isFunctionOrFunctionTemplate() && 3035 SM == ShadowMaps.rbegin()) 3036 continue; 3037 3038 // We've found a declaration that hides this one. 3039 return *I; 3040 } 3041 } 3042 3043 return 0; 3044 } 3045 3046 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, 3047 bool QualifiedNameLookup, 3048 bool InBaseClass, 3049 VisibleDeclConsumer &Consumer, 3050 VisibleDeclsRecord &Visited) { 3051 if (!Ctx) 3052 return; 3053 3054 // Make sure we don't visit the same context twice. 3055 if (Visited.visitedContext(Ctx->getPrimaryContext())) 3056 return; 3057 3058 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 3059 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 3060 3061 // Enumerate all of the results in this context. 3062 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(), 3063 LEnd = Ctx->lookups_end(); 3064 L != LEnd; ++L) { 3065 DeclContext::lookup_result R = *L; 3066 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 3067 ++I) { 3068 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) { 3069 if ((ND = Result.getAcceptableDecl(ND))) { 3070 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 3071 Visited.add(ND); 3072 } 3073 } 3074 } 3075 } 3076 3077 // Traverse using directives for qualified name lookup. 3078 if (QualifiedNameLookup) { 3079 ShadowContextRAII Shadow(Visited); 3080 DeclContext::udir_iterator I, E; 3081 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) { 3082 LookupVisibleDecls((*I)->getNominatedNamespace(), Result, 3083 QualifiedNameLookup, InBaseClass, Consumer, Visited); 3084 } 3085 } 3086 3087 // Traverse the contexts of inherited C++ classes. 3088 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 3089 if (!Record->hasDefinition()) 3090 return; 3091 3092 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(), 3093 BEnd = Record->bases_end(); 3094 B != BEnd; ++B) { 3095 QualType BaseType = B->getType(); 3096 3097 // Don't look into dependent bases, because name lookup can't look 3098 // there anyway. 3099 if (BaseType->isDependentType()) 3100 continue; 3101 3102 const RecordType *Record = BaseType->getAs<RecordType>(); 3103 if (!Record) 3104 continue; 3105 3106 // FIXME: It would be nice to be able to determine whether referencing 3107 // a particular member would be ambiguous. For example, given 3108 // 3109 // struct A { int member; }; 3110 // struct B { int member; }; 3111 // struct C : A, B { }; 3112 // 3113 // void f(C *c) { c->### } 3114 // 3115 // accessing 'member' would result in an ambiguity. However, we 3116 // could be smart enough to qualify the member with the base 3117 // class, e.g., 3118 // 3119 // c->B::member 3120 // 3121 // or 3122 // 3123 // c->A::member 3124 3125 // Find results in this base class (and its bases). 3126 ShadowContextRAII Shadow(Visited); 3127 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, 3128 true, Consumer, Visited); 3129 } 3130 } 3131 3132 // Traverse the contexts of Objective-C classes. 3133 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 3134 // Traverse categories. 3135 for (ObjCInterfaceDecl::visible_categories_iterator 3136 Cat = IFace->visible_categories_begin(), 3137 CatEnd = IFace->visible_categories_end(); 3138 Cat != CatEnd; ++Cat) { 3139 ShadowContextRAII Shadow(Visited); 3140 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false, 3141 Consumer, Visited); 3142 } 3143 3144 // Traverse protocols. 3145 for (ObjCInterfaceDecl::all_protocol_iterator 3146 I = IFace->all_referenced_protocol_begin(), 3147 E = IFace->all_referenced_protocol_end(); I != E; ++I) { 3148 ShadowContextRAII Shadow(Visited); 3149 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 3150 Visited); 3151 } 3152 3153 // Traverse the superclass. 3154 if (IFace->getSuperClass()) { 3155 ShadowContextRAII Shadow(Visited); 3156 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, 3157 true, Consumer, Visited); 3158 } 3159 3160 // If there is an implementation, traverse it. We do this to find 3161 // synthesized ivars. 3162 if (IFace->getImplementation()) { 3163 ShadowContextRAII Shadow(Visited); 3164 LookupVisibleDecls(IFace->getImplementation(), Result, 3165 QualifiedNameLookup, InBaseClass, Consumer, Visited); 3166 } 3167 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 3168 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(), 3169 E = Protocol->protocol_end(); I != E; ++I) { 3170 ShadowContextRAII Shadow(Visited); 3171 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 3172 Visited); 3173 } 3174 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 3175 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(), 3176 E = Category->protocol_end(); I != E; ++I) { 3177 ShadowContextRAII Shadow(Visited); 3178 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 3179 Visited); 3180 } 3181 3182 // If there is an implementation, traverse it. 3183 if (Category->getImplementation()) { 3184 ShadowContextRAII Shadow(Visited); 3185 LookupVisibleDecls(Category->getImplementation(), Result, 3186 QualifiedNameLookup, true, Consumer, Visited); 3187 } 3188 } 3189 } 3190 3191 static void LookupVisibleDecls(Scope *S, LookupResult &Result, 3192 UnqualUsingDirectiveSet &UDirs, 3193 VisibleDeclConsumer &Consumer, 3194 VisibleDeclsRecord &Visited) { 3195 if (!S) 3196 return; 3197 3198 if (!S->getEntity() || 3199 (!S->getParent() && 3200 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) || 3201 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) { 3202 FindLocalExternScope FindLocals(Result); 3203 // Walk through the declarations in this Scope. 3204 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 3205 D != DEnd; ++D) { 3206 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 3207 if ((ND = Result.getAcceptableDecl(ND))) { 3208 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false); 3209 Visited.add(ND); 3210 } 3211 } 3212 } 3213 3214 // FIXME: C++ [temp.local]p8 3215 DeclContext *Entity = 0; 3216 if (S->getEntity()) { 3217 // Look into this scope's declaration context, along with any of its 3218 // parent lookup contexts (e.g., enclosing classes), up to the point 3219 // where we hit the context stored in the next outer scope. 3220 Entity = (DeclContext *)S->getEntity(); 3221 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME 3222 3223 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 3224 Ctx = Ctx->getLookupParent()) { 3225 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 3226 if (Method->isInstanceMethod()) { 3227 // For instance methods, look for ivars in the method's interface. 3228 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 3229 Result.getNameLoc(), Sema::LookupMemberName); 3230 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { 3231 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 3232 /*InBaseClass=*/false, Consumer, Visited); 3233 } 3234 } 3235 3236 // We've already performed all of the name lookup that we need 3237 // to for Objective-C methods; the next context will be the 3238 // outer scope. 3239 break; 3240 } 3241 3242 if (Ctx->isFunctionOrMethod()) 3243 continue; 3244 3245 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 3246 /*InBaseClass=*/false, Consumer, Visited); 3247 } 3248 } else if (!S->getParent()) { 3249 // Look into the translation unit scope. We walk through the translation 3250 // unit's declaration context, because the Scope itself won't have all of 3251 // the declarations if we loaded a precompiled header. 3252 // FIXME: We would like the translation unit's Scope object to point to the 3253 // translation unit, so we don't need this special "if" branch. However, 3254 // doing so would force the normal C++ name-lookup code to look into the 3255 // translation unit decl when the IdentifierInfo chains would suffice. 3256 // Once we fix that problem (which is part of a more general "don't look 3257 // in DeclContexts unless we have to" optimization), we can eliminate this. 3258 Entity = Result.getSema().Context.getTranslationUnitDecl(); 3259 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 3260 /*InBaseClass=*/false, Consumer, Visited); 3261 } 3262 3263 if (Entity) { 3264 // Lookup visible declarations in any namespaces found by using 3265 // directives. 3266 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 3267 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity); 3268 for (; UI != UEnd; ++UI) 3269 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()), 3270 Result, /*QualifiedNameLookup=*/false, 3271 /*InBaseClass=*/false, Consumer, Visited); 3272 } 3273 3274 // Lookup names in the parent scope. 3275 ShadowContextRAII Shadow(Visited); 3276 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited); 3277 } 3278 3279 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 3280 VisibleDeclConsumer &Consumer, 3281 bool IncludeGlobalScope) { 3282 // Determine the set of using directives available during 3283 // unqualified name lookup. 3284 Scope *Initial = S; 3285 UnqualUsingDirectiveSet UDirs; 3286 if (getLangOpts().CPlusPlus) { 3287 // Find the first namespace or translation-unit scope. 3288 while (S && !isNamespaceOrTranslationUnitScope(S)) 3289 S = S->getParent(); 3290 3291 UDirs.visitScopeChain(Initial, S); 3292 } 3293 UDirs.done(); 3294 3295 // Look for visible declarations. 3296 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 3297 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3298 VisibleDeclsRecord Visited; 3299 if (!IncludeGlobalScope) 3300 Visited.visitedContext(Context.getTranslationUnitDecl()); 3301 ShadowContextRAII Shadow(Visited); 3302 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited); 3303 } 3304 3305 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 3306 VisibleDeclConsumer &Consumer, 3307 bool IncludeGlobalScope) { 3308 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 3309 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3310 VisibleDeclsRecord Visited; 3311 if (!IncludeGlobalScope) 3312 Visited.visitedContext(Context.getTranslationUnitDecl()); 3313 ShadowContextRAII Shadow(Visited); 3314 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 3315 /*InBaseClass=*/false, Consumer, Visited); 3316 } 3317 3318 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 3319 /// If GnuLabelLoc is a valid source location, then this is a definition 3320 /// of an __label__ label name, otherwise it is a normal label definition 3321 /// or use. 3322 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, 3323 SourceLocation GnuLabelLoc) { 3324 // Do a lookup to see if we have a label with this name already. 3325 NamedDecl *Res = 0; 3326 3327 if (GnuLabelLoc.isValid()) { 3328 // Local label definitions always shadow existing labels. 3329 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); 3330 Scope *S = CurScope; 3331 PushOnScopeChains(Res, S, true); 3332 return cast<LabelDecl>(Res); 3333 } 3334 3335 // Not a GNU local label. 3336 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); 3337 // If we found a label, check to see if it is in the same context as us. 3338 // When in a Block, we don't want to reuse a label in an enclosing function. 3339 if (Res && Res->getDeclContext() != CurContext) 3340 Res = 0; 3341 if (Res == 0) { 3342 // If not forward referenced or defined already, create the backing decl. 3343 Res = LabelDecl::Create(Context, CurContext, Loc, II); 3344 Scope *S = CurScope->getFnParent(); 3345 assert(S && "Not in a function?"); 3346 PushOnScopeChains(Res, S, true); 3347 } 3348 return cast<LabelDecl>(Res); 3349 } 3350 3351 //===----------------------------------------------------------------------===// 3352 // Typo correction 3353 //===----------------------------------------------------------------------===// 3354 3355 namespace { 3356 3357 typedef SmallVector<TypoCorrection, 1> TypoResultList; 3358 typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap; 3359 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap; 3360 3361 static const unsigned MaxTypoDistanceResultSets = 5; 3362 3363 class TypoCorrectionConsumer : public VisibleDeclConsumer { 3364 /// \brief The name written that is a typo in the source. 3365 StringRef Typo; 3366 3367 /// \brief The results found that have the smallest edit distance 3368 /// found (so far) with the typo name. 3369 /// 3370 /// The pointer value being set to the current DeclContext indicates 3371 /// whether there is a keyword with this name. 3372 TypoEditDistanceMap CorrectionResults; 3373 3374 Sema &SemaRef; 3375 3376 public: 3377 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo) 3378 : Typo(Typo->getName()), 3379 SemaRef(SemaRef) {} 3380 3381 bool includeHiddenDecls() const { return true; } 3382 3383 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 3384 bool InBaseClass); 3385 void FoundName(StringRef Name); 3386 void addKeywordResult(StringRef Keyword); 3387 void addName(StringRef Name, NamedDecl *ND, unsigned Distance, 3388 NestedNameSpecifier *NNS=NULL, bool isKeyword=false); 3389 void addCorrection(TypoCorrection Correction); 3390 3391 typedef TypoResultsMap::iterator result_iterator; 3392 typedef TypoEditDistanceMap::iterator distance_iterator; 3393 distance_iterator begin() { return CorrectionResults.begin(); } 3394 distance_iterator end() { return CorrectionResults.end(); } 3395 void erase(distance_iterator I) { CorrectionResults.erase(I); } 3396 unsigned size() const { return CorrectionResults.size(); } 3397 bool empty() const { return CorrectionResults.empty(); } 3398 3399 TypoResultList &operator[](StringRef Name) { 3400 return CorrectionResults.begin()->second[Name]; 3401 } 3402 3403 unsigned getBestEditDistance(bool Normalized) { 3404 if (CorrectionResults.empty()) 3405 return (std::numeric_limits<unsigned>::max)(); 3406 3407 unsigned BestED = CorrectionResults.begin()->first; 3408 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED; 3409 } 3410 3411 TypoResultsMap &getBestResults() { 3412 return CorrectionResults.begin()->second; 3413 } 3414 3415 }; 3416 3417 } 3418 3419 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 3420 DeclContext *Ctx, bool InBaseClass) { 3421 // Don't consider hidden names for typo correction. 3422 if (Hiding) 3423 return; 3424 3425 // Only consider entities with identifiers for names, ignoring 3426 // special names (constructors, overloaded operators, selectors, 3427 // etc.). 3428 IdentifierInfo *Name = ND->getIdentifier(); 3429 if (!Name) 3430 return; 3431 3432 // Only consider visible declarations and declarations from modules with 3433 // names that exactly match. 3434 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo && 3435 !findAcceptableDecl(SemaRef, ND)) 3436 return; 3437 3438 FoundName(Name->getName()); 3439 } 3440 3441 void TypoCorrectionConsumer::FoundName(StringRef Name) { 3442 // Use a simple length-based heuristic to determine the minimum possible 3443 // edit distance. If the minimum isn't good enough, bail out early. 3444 unsigned MinED = abs((int)Name.size() - (int)Typo.size()); 3445 if (MinED && Typo.size() / MinED < 3) 3446 return; 3447 3448 // Compute an upper bound on the allowable edit distance, so that the 3449 // edit-distance algorithm can short-circuit. 3450 unsigned UpperBound = (Typo.size() + 2) / 3; 3451 3452 // Compute the edit distance between the typo and the name of this 3453 // entity, and add the identifier to the list of results. 3454 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound)); 3455 } 3456 3457 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { 3458 // Compute the edit distance between the typo and this keyword, 3459 // and add the keyword to the list of results. 3460 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true); 3461 } 3462 3463 void TypoCorrectionConsumer::addName(StringRef Name, 3464 NamedDecl *ND, 3465 unsigned Distance, 3466 NestedNameSpecifier *NNS, 3467 bool isKeyword) { 3468 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance); 3469 if (isKeyword) TC.makeKeyword(); 3470 addCorrection(TC); 3471 } 3472 3473 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { 3474 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); 3475 TypoResultList &CList = 3476 CorrectionResults[Correction.getEditDistance(false)][Name]; 3477 3478 if (!CList.empty() && !CList.back().isResolved()) 3479 CList.pop_back(); 3480 if (NamedDecl *NewND = Correction.getCorrectionDecl()) { 3481 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts()); 3482 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end(); 3483 RI != RIEnd; ++RI) { 3484 // If the Correction refers to a decl already in the result list, 3485 // replace the existing result if the string representation of Correction 3486 // comes before the current result alphabetically, then stop as there is 3487 // nothing more to be done to add Correction to the candidate set. 3488 if (RI->getCorrectionDecl() == NewND) { 3489 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts())) 3490 *RI = Correction; 3491 return; 3492 } 3493 } 3494 } 3495 if (CList.empty() || Correction.isResolved()) 3496 CList.push_back(Correction); 3497 3498 while (CorrectionResults.size() > MaxTypoDistanceResultSets) 3499 erase(llvm::prior(CorrectionResults.end())); 3500 } 3501 3502 // Fill the supplied vector with the IdentifierInfo pointers for each piece of 3503 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", 3504 // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). 3505 static void getNestedNameSpecifierIdentifiers( 3506 NestedNameSpecifier *NNS, 3507 SmallVectorImpl<const IdentifierInfo*> &Identifiers) { 3508 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) 3509 getNestedNameSpecifierIdentifiers(Prefix, Identifiers); 3510 else 3511 Identifiers.clear(); 3512 3513 const IdentifierInfo *II = NULL; 3514 3515 switch (NNS->getKind()) { 3516 case NestedNameSpecifier::Identifier: 3517 II = NNS->getAsIdentifier(); 3518 break; 3519 3520 case NestedNameSpecifier::Namespace: 3521 if (NNS->getAsNamespace()->isAnonymousNamespace()) 3522 return; 3523 II = NNS->getAsNamespace()->getIdentifier(); 3524 break; 3525 3526 case NestedNameSpecifier::NamespaceAlias: 3527 II = NNS->getAsNamespaceAlias()->getIdentifier(); 3528 break; 3529 3530 case NestedNameSpecifier::TypeSpecWithTemplate: 3531 case NestedNameSpecifier::TypeSpec: 3532 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); 3533 break; 3534 3535 case NestedNameSpecifier::Global: 3536 return; 3537 } 3538 3539 if (II) 3540 Identifiers.push_back(II); 3541 } 3542 3543 namespace { 3544 3545 class SpecifierInfo { 3546 public: 3547 DeclContext* DeclCtx; 3548 NestedNameSpecifier* NameSpecifier; 3549 unsigned EditDistance; 3550 3551 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED) 3552 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {} 3553 }; 3554 3555 typedef SmallVector<DeclContext*, 4> DeclContextList; 3556 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList; 3557 3558 class NamespaceSpecifierSet { 3559 ASTContext &Context; 3560 DeclContextList CurContextChain; 3561 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers; 3562 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers; 3563 bool isSorted; 3564 3565 SpecifierInfoList Specifiers; 3566 llvm::SmallSetVector<unsigned, 4> Distances; 3567 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap; 3568 3569 /// \brief Helper for building the list of DeclContexts between the current 3570 /// context and the top of the translation unit 3571 static DeclContextList BuildContextChain(DeclContext *Start); 3572 3573 void SortNamespaces(); 3574 3575 public: 3576 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext, 3577 CXXScopeSpec *CurScopeSpec) 3578 : Context(Context), CurContextChain(BuildContextChain(CurContext)), 3579 isSorted(false) { 3580 if (CurScopeSpec && CurScopeSpec->getScopeRep()) 3581 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(), 3582 CurNameSpecifierIdentifiers); 3583 // Build the list of identifiers that would be used for an absolute 3584 // (from the global context) NestedNameSpecifier referring to the current 3585 // context. 3586 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3587 CEnd = CurContextChain.rend(); 3588 C != CEnd; ++C) { 3589 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) 3590 CurContextIdentifiers.push_back(ND->getIdentifier()); 3591 } 3592 3593 // Add the global context as a NestedNameSpecifier 3594 Distances.insert(1); 3595 DistanceMap[1].push_back( 3596 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()), 3597 NestedNameSpecifier::GlobalSpecifier(Context), 1)); 3598 } 3599 3600 /// \brief Add the namespace to the set, computing the corresponding 3601 /// NestedNameSpecifier and its distance in the process. 3602 void AddNamespace(NamespaceDecl *ND); 3603 3604 /// \brief Add the record to the set, computing the corresponding 3605 /// NestedNameSpecifier and its distance in the process. 3606 void AddRecord(RecordDecl *RD); 3607 3608 typedef SpecifierInfoList::iterator iterator; 3609 iterator begin() { 3610 if (!isSorted) SortNamespaces(); 3611 return Specifiers.begin(); 3612 } 3613 iterator end() { return Specifiers.end(); } 3614 }; 3615 3616 } 3617 3618 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) { 3619 assert(Start && "Building a context chain from a null context"); 3620 DeclContextList Chain; 3621 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL; 3622 DC = DC->getLookupParent()) { 3623 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); 3624 if (!DC->isInlineNamespace() && !DC->isTransparentContext() && 3625 !(ND && ND->isAnonymousNamespace())) 3626 Chain.push_back(DC->getPrimaryContext()); 3627 } 3628 return Chain; 3629 } 3630 3631 void NamespaceSpecifierSet::SortNamespaces() { 3632 SmallVector<unsigned, 4> sortedDistances; 3633 sortedDistances.append(Distances.begin(), Distances.end()); 3634 3635 if (sortedDistances.size() > 1) 3636 std::sort(sortedDistances.begin(), sortedDistances.end()); 3637 3638 Specifiers.clear(); 3639 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(), 3640 DIEnd = sortedDistances.end(); 3641 DI != DIEnd; ++DI) { 3642 SpecifierInfoList &SpecList = DistanceMap[*DI]; 3643 Specifiers.append(SpecList.begin(), SpecList.end()); 3644 } 3645 3646 isSorted = true; 3647 } 3648 3649 void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) { 3650 DeclContext *Ctx = cast<DeclContext>(ND); 3651 NestedNameSpecifier *NNS = NULL; 3652 unsigned NumSpecifiers = 0; 3653 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx)); 3654 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 3655 3656 // Eliminate common elements from the two DeclContext chains. 3657 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3658 CEnd = CurContextChain.rend(); 3659 C != CEnd && !NamespaceDeclChain.empty() && 3660 NamespaceDeclChain.back() == *C; ++C) { 3661 NamespaceDeclChain.pop_back(); 3662 } 3663 3664 // Add an explicit leading '::' specifier if needed. 3665 if (NamespaceDeclChain.empty()) { 3666 NamespaceDeclChain = FullNamespaceDeclChain; 3667 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3668 } else if (NamespaceDecl *ND = 3669 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) { 3670 IdentifierInfo *Name = ND->getIdentifier(); 3671 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(), 3672 Name) != CurContextIdentifiers.end() || 3673 std::find(CurNameSpecifierIdentifiers.begin(), 3674 CurNameSpecifierIdentifiers.end(), 3675 Name) != CurNameSpecifierIdentifiers.end()) { 3676 NamespaceDeclChain = FullNamespaceDeclChain; 3677 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3678 } 3679 } 3680 3681 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 3682 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(), 3683 CEnd = NamespaceDeclChain.rend(); 3684 C != CEnd; ++C) { 3685 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C); 3686 if (ND) { 3687 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 3688 ++NumSpecifiers; 3689 } 3690 } 3691 3692 // If the built NestedNameSpecifier would be replacing an existing 3693 // NestedNameSpecifier, use the number of component identifiers that 3694 // would need to be changed as the edit distance instead of the number 3695 // of components in the built NestedNameSpecifier. 3696 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 3697 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 3698 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 3699 NumSpecifiers = llvm::ComputeEditDistance( 3700 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers), 3701 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers)); 3702 } 3703 3704 isSorted = false; 3705 Distances.insert(NumSpecifiers); 3706 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers)); 3707 } 3708 3709 void NamespaceSpecifierSet::AddRecord(RecordDecl *RD) { 3710 if (!RD->isBeingDefined() && !RD->isCompleteDefinition()) 3711 return; 3712 3713 DeclContext *Ctx = cast<DeclContext>(RD); 3714 NestedNameSpecifier *NNS = NULL; 3715 unsigned NumSpecifiers = 0; 3716 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx)); 3717 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 3718 3719 // Eliminate common elements from the two DeclContext chains. 3720 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3721 CEnd = CurContextChain.rend(); 3722 C != CEnd && !NamespaceDeclChain.empty() && 3723 NamespaceDeclChain.back() == *C; ++C) { 3724 NamespaceDeclChain.pop_back(); 3725 } 3726 3727 // Add an explicit leading '::' specifier if needed. 3728 if (NamespaceDeclChain.empty()) { 3729 NamespaceDeclChain = FullNamespaceDeclChain; 3730 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3731 } else if (NamespaceDecl *ND = 3732 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) { 3733 IdentifierInfo *Name = ND->getIdentifier(); 3734 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(), 3735 Name) != CurContextIdentifiers.end() || 3736 std::find(CurNameSpecifierIdentifiers.begin(), 3737 CurNameSpecifierIdentifiers.end(), 3738 Name) != CurNameSpecifierIdentifiers.end()) { 3739 NamespaceDeclChain = FullNamespaceDeclChain; 3740 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3741 } 3742 } 3743 3744 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 3745 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(), 3746 CEnd = NamespaceDeclChain.rend(); 3747 C != CEnd; ++C) { 3748 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) { 3749 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 3750 ++NumSpecifiers; 3751 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) { 3752 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), 3753 RD->getTypeForDecl()); 3754 ++NumSpecifiers; 3755 } 3756 } 3757 3758 // If the built NestedNameSpecifier would be replacing an existing 3759 // NestedNameSpecifier, use the number of component identifiers that 3760 // would need to be changed as the edit distance instead of the number 3761 // of components in the built NestedNameSpecifier. 3762 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 3763 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 3764 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 3765 NumSpecifiers = llvm::ComputeEditDistance( 3766 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers), 3767 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers)); 3768 } 3769 3770 isSorted = false; 3771 Distances.insert(NumSpecifiers); 3772 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers)); 3773 } 3774 3775 /// \brief Perform name lookup for a possible result for typo correction. 3776 static void LookupPotentialTypoResult(Sema &SemaRef, 3777 LookupResult &Res, 3778 IdentifierInfo *Name, 3779 Scope *S, CXXScopeSpec *SS, 3780 DeclContext *MemberContext, 3781 bool EnteringContext, 3782 bool isObjCIvarLookup, 3783 bool FindHidden) { 3784 Res.suppressDiagnostics(); 3785 Res.clear(); 3786 Res.setLookupName(Name); 3787 Res.setAllowHidden(FindHidden); 3788 if (MemberContext) { 3789 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { 3790 if (isObjCIvarLookup) { 3791 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { 3792 Res.addDecl(Ivar); 3793 Res.resolveKind(); 3794 return; 3795 } 3796 } 3797 3798 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) { 3799 Res.addDecl(Prop); 3800 Res.resolveKind(); 3801 return; 3802 } 3803 } 3804 3805 SemaRef.LookupQualifiedName(Res, MemberContext); 3806 return; 3807 } 3808 3809 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 3810 EnteringContext); 3811 3812 // Fake ivar lookup; this should really be part of 3813 // LookupParsedName. 3814 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 3815 if (Method->isInstanceMethod() && Method->getClassInterface() && 3816 (Res.empty() || 3817 (Res.isSingleResult() && 3818 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { 3819 if (ObjCIvarDecl *IV 3820 = Method->getClassInterface()->lookupInstanceVariable(Name)) { 3821 Res.addDecl(IV); 3822 Res.resolveKind(); 3823 } 3824 } 3825 } 3826 } 3827 3828 /// \brief Add keywords to the consumer as possible typo corrections. 3829 static void AddKeywordsToConsumer(Sema &SemaRef, 3830 TypoCorrectionConsumer &Consumer, 3831 Scope *S, CorrectionCandidateCallback &CCC, 3832 bool AfterNestedNameSpecifier) { 3833 if (AfterNestedNameSpecifier) { 3834 // For 'X::', we know exactly which keywords can appear next. 3835 Consumer.addKeywordResult("template"); 3836 if (CCC.WantExpressionKeywords) 3837 Consumer.addKeywordResult("operator"); 3838 return; 3839 } 3840 3841 if (CCC.WantObjCSuper) 3842 Consumer.addKeywordResult("super"); 3843 3844 if (CCC.WantTypeSpecifiers) { 3845 // Add type-specifier keywords to the set of results. 3846 static const char *const CTypeSpecs[] = { 3847 "char", "const", "double", "enum", "float", "int", "long", "short", 3848 "signed", "struct", "union", "unsigned", "void", "volatile", 3849 "_Complex", "_Imaginary", 3850 // storage-specifiers as well 3851 "extern", "inline", "static", "typedef" 3852 }; 3853 3854 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); 3855 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 3856 Consumer.addKeywordResult(CTypeSpecs[I]); 3857 3858 if (SemaRef.getLangOpts().C99) 3859 Consumer.addKeywordResult("restrict"); 3860 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) 3861 Consumer.addKeywordResult("bool"); 3862 else if (SemaRef.getLangOpts().C99) 3863 Consumer.addKeywordResult("_Bool"); 3864 3865 if (SemaRef.getLangOpts().CPlusPlus) { 3866 Consumer.addKeywordResult("class"); 3867 Consumer.addKeywordResult("typename"); 3868 Consumer.addKeywordResult("wchar_t"); 3869 3870 if (SemaRef.getLangOpts().CPlusPlus11) { 3871 Consumer.addKeywordResult("char16_t"); 3872 Consumer.addKeywordResult("char32_t"); 3873 Consumer.addKeywordResult("constexpr"); 3874 Consumer.addKeywordResult("decltype"); 3875 Consumer.addKeywordResult("thread_local"); 3876 } 3877 } 3878 3879 if (SemaRef.getLangOpts().GNUMode) 3880 Consumer.addKeywordResult("typeof"); 3881 } 3882 3883 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { 3884 Consumer.addKeywordResult("const_cast"); 3885 Consumer.addKeywordResult("dynamic_cast"); 3886 Consumer.addKeywordResult("reinterpret_cast"); 3887 Consumer.addKeywordResult("static_cast"); 3888 } 3889 3890 if (CCC.WantExpressionKeywords) { 3891 Consumer.addKeywordResult("sizeof"); 3892 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { 3893 Consumer.addKeywordResult("false"); 3894 Consumer.addKeywordResult("true"); 3895 } 3896 3897 if (SemaRef.getLangOpts().CPlusPlus) { 3898 static const char *const CXXExprs[] = { 3899 "delete", "new", "operator", "throw", "typeid" 3900 }; 3901 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); 3902 for (unsigned I = 0; I != NumCXXExprs; ++I) 3903 Consumer.addKeywordResult(CXXExprs[I]); 3904 3905 if (isa<CXXMethodDecl>(SemaRef.CurContext) && 3906 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) 3907 Consumer.addKeywordResult("this"); 3908 3909 if (SemaRef.getLangOpts().CPlusPlus11) { 3910 Consumer.addKeywordResult("alignof"); 3911 Consumer.addKeywordResult("nullptr"); 3912 } 3913 } 3914 3915 if (SemaRef.getLangOpts().C11) { 3916 // FIXME: We should not suggest _Alignof if the alignof macro 3917 // is present. 3918 Consumer.addKeywordResult("_Alignof"); 3919 } 3920 } 3921 3922 if (CCC.WantRemainingKeywords) { 3923 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { 3924 // Statements. 3925 static const char *const CStmts[] = { 3926 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 3927 const unsigned NumCStmts = llvm::array_lengthof(CStmts); 3928 for (unsigned I = 0; I != NumCStmts; ++I) 3929 Consumer.addKeywordResult(CStmts[I]); 3930 3931 if (SemaRef.getLangOpts().CPlusPlus) { 3932 Consumer.addKeywordResult("catch"); 3933 Consumer.addKeywordResult("try"); 3934 } 3935 3936 if (S && S->getBreakParent()) 3937 Consumer.addKeywordResult("break"); 3938 3939 if (S && S->getContinueParent()) 3940 Consumer.addKeywordResult("continue"); 3941 3942 if (!SemaRef.getCurFunction()->SwitchStack.empty()) { 3943 Consumer.addKeywordResult("case"); 3944 Consumer.addKeywordResult("default"); 3945 } 3946 } else { 3947 if (SemaRef.getLangOpts().CPlusPlus) { 3948 Consumer.addKeywordResult("namespace"); 3949 Consumer.addKeywordResult("template"); 3950 } 3951 3952 if (S && S->isClassScope()) { 3953 Consumer.addKeywordResult("explicit"); 3954 Consumer.addKeywordResult("friend"); 3955 Consumer.addKeywordResult("mutable"); 3956 Consumer.addKeywordResult("private"); 3957 Consumer.addKeywordResult("protected"); 3958 Consumer.addKeywordResult("public"); 3959 Consumer.addKeywordResult("virtual"); 3960 } 3961 } 3962 3963 if (SemaRef.getLangOpts().CPlusPlus) { 3964 Consumer.addKeywordResult("using"); 3965 3966 if (SemaRef.getLangOpts().CPlusPlus11) 3967 Consumer.addKeywordResult("static_assert"); 3968 } 3969 } 3970 } 3971 3972 static bool isCandidateViable(CorrectionCandidateCallback &CCC, 3973 TypoCorrection &Candidate) { 3974 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); 3975 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; 3976 } 3977 3978 /// \brief Check whether the declarations found for a typo correction are 3979 /// visible, and if none of them are, convert the correction to an 'import 3980 /// a module' correction. 3981 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC, 3982 DeclarationName TypoName) { 3983 if (TC.begin() == TC.end()) 3984 return; 3985 3986 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); 3987 3988 for (/**/; DI != DE; ++DI) 3989 if (!LookupResult::isVisible(SemaRef, *DI)) 3990 break; 3991 // Nothing to do if all decls are visible. 3992 if (DI == DE) 3993 return; 3994 3995 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); 3996 bool AnyVisibleDecls = !NewDecls.empty(); 3997 3998 for (/**/; DI != DE; ++DI) { 3999 NamedDecl *VisibleDecl = *DI; 4000 if (!LookupResult::isVisible(SemaRef, *DI)) 4001 VisibleDecl = findAcceptableDecl(SemaRef, *DI); 4002 4003 if (VisibleDecl) { 4004 if (!AnyVisibleDecls) { 4005 // Found a visible decl, discard all hidden ones. 4006 AnyVisibleDecls = true; 4007 NewDecls.clear(); 4008 } 4009 NewDecls.push_back(VisibleDecl); 4010 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) 4011 NewDecls.push_back(*DI); 4012 } 4013 4014 if (NewDecls.empty()) 4015 TC = TypoCorrection(); 4016 else { 4017 TC.setCorrectionDecls(NewDecls); 4018 TC.setRequiresImport(!AnyVisibleDecls); 4019 } 4020 } 4021 4022 /// \brief Try to "correct" a typo in the source code by finding 4023 /// visible declarations whose names are similar to the name that was 4024 /// present in the source code. 4025 /// 4026 /// \param TypoName the \c DeclarationNameInfo structure that contains 4027 /// the name that was present in the source code along with its location. 4028 /// 4029 /// \param LookupKind the name-lookup criteria used to search for the name. 4030 /// 4031 /// \param S the scope in which name lookup occurs. 4032 /// 4033 /// \param SS the nested-name-specifier that precedes the name we're 4034 /// looking for, if present. 4035 /// 4036 /// \param CCC A CorrectionCandidateCallback object that provides further 4037 /// validation of typo correction candidates. It also provides flags for 4038 /// determining the set of keywords permitted. 4039 /// 4040 /// \param MemberContext if non-NULL, the context in which to look for 4041 /// a member access expression. 4042 /// 4043 /// \param EnteringContext whether we're entering the context described by 4044 /// the nested-name-specifier SS. 4045 /// 4046 /// \param OPT when non-NULL, the search for visible declarations will 4047 /// also walk the protocols in the qualified interfaces of \p OPT. 4048 /// 4049 /// \returns a \c TypoCorrection containing the corrected name if the typo 4050 /// along with information such as the \c NamedDecl where the corrected name 4051 /// was declared, and any additional \c NestedNameSpecifier needed to access 4052 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 4053 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, 4054 Sema::LookupNameKind LookupKind, 4055 Scope *S, CXXScopeSpec *SS, 4056 CorrectionCandidateCallback &CCC, 4057 DeclContext *MemberContext, 4058 bool EnteringContext, 4059 const ObjCObjectPointerType *OPT) { 4060 // Always let the ExternalSource have the first chance at correction, even 4061 // if we would otherwise have given up. 4062 if (ExternalSource) { 4063 if (TypoCorrection Correction = ExternalSource->CorrectTypo( 4064 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT)) 4065 return Correction; 4066 } 4067 4068 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || 4069 DisableTypoCorrection) 4070 return TypoCorrection(); 4071 4072 // In Microsoft mode, don't perform typo correction in a template member 4073 // function dependent context because it interferes with the "lookup into 4074 // dependent bases of class templates" feature. 4075 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 4076 isa<CXXMethodDecl>(CurContext)) 4077 return TypoCorrection(); 4078 4079 // We only attempt to correct typos for identifiers. 4080 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 4081 if (!Typo) 4082 return TypoCorrection(); 4083 4084 // If the scope specifier itself was invalid, don't try to correct 4085 // typos. 4086 if (SS && SS->isInvalid()) 4087 return TypoCorrection(); 4088 4089 // Never try to correct typos during template deduction or 4090 // instantiation. 4091 if (!ActiveTemplateInstantiations.empty()) 4092 return TypoCorrection(); 4093 4094 // Don't try to correct 'super'. 4095 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) 4096 return TypoCorrection(); 4097 4098 NamespaceSpecifierSet Namespaces(Context, CurContext, SS); 4099 4100 TypoCorrectionConsumer Consumer(*this, Typo); 4101 4102 // If a callback object considers an empty typo correction candidate to be 4103 // viable, assume it does not do any actual validation of the candidates. 4104 TypoCorrection EmptyCorrection; 4105 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection); 4106 4107 // Perform name lookup to find visible, similarly-named entities. 4108 bool IsUnqualifiedLookup = false; 4109 DeclContext *QualifiedDC = MemberContext; 4110 if (MemberContext) { 4111 LookupVisibleDecls(MemberContext, LookupKind, Consumer); 4112 4113 // Look in qualified interfaces. 4114 if (OPT) { 4115 for (ObjCObjectPointerType::qual_iterator 4116 I = OPT->qual_begin(), E = OPT->qual_end(); 4117 I != E; ++I) 4118 LookupVisibleDecls(*I, LookupKind, Consumer); 4119 } 4120 } else if (SS && SS->isSet()) { 4121 QualifiedDC = computeDeclContext(*SS, EnteringContext); 4122 if (!QualifiedDC) 4123 return TypoCorrection(); 4124 4125 // Provide a stop gap for files that are just seriously broken. Trying 4126 // to correct all typos can turn into a HUGE performance penalty, causing 4127 // some files to take minutes to get rejected by the parser. 4128 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 4129 return TypoCorrection(); 4130 ++TyposCorrected; 4131 4132 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer); 4133 } else { 4134 IsUnqualifiedLookup = true; 4135 UnqualifiedTyposCorrectedMap::iterator Cached 4136 = UnqualifiedTyposCorrected.find(Typo); 4137 if (Cached != UnqualifiedTyposCorrected.end()) { 4138 // Add the cached value, unless it's a keyword or fails validation. In the 4139 // keyword case, we'll end up adding the keyword below. 4140 if (Cached->second) { 4141 if (!Cached->second.isKeyword() && 4142 isCandidateViable(CCC, Cached->second)) 4143 Consumer.addCorrection(Cached->second); 4144 } else { 4145 // Only honor no-correction cache hits when a callback that will validate 4146 // correction candidates is not being used. 4147 if (!ValidatingCallback) 4148 return TypoCorrection(); 4149 } 4150 } 4151 if (Cached == UnqualifiedTyposCorrected.end()) { 4152 // Provide a stop gap for files that are just seriously broken. Trying 4153 // to correct all typos can turn into a HUGE performance penalty, causing 4154 // some files to take minutes to get rejected by the parser. 4155 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 4156 return TypoCorrection(); 4157 } 4158 } 4159 4160 // Determine whether we are going to search in the various namespaces for 4161 // corrections. 4162 bool SearchNamespaces 4163 = getLangOpts().CPlusPlus && 4164 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace())); 4165 // In a few cases we *only* want to search for corrections based on just 4166 // adding or changing the nested name specifier. 4167 bool AllowOnlyNNSChanges = Typo->getName().size() < 3; 4168 4169 if (IsUnqualifiedLookup || SearchNamespaces) { 4170 // For unqualified lookup, look through all of the names that we have 4171 // seen in this translation unit. 4172 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4173 for (IdentifierTable::iterator I = Context.Idents.begin(), 4174 IEnd = Context.Idents.end(); 4175 I != IEnd; ++I) 4176 Consumer.FoundName(I->getKey()); 4177 4178 // Walk through identifiers in external identifier sources. 4179 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4180 if (IdentifierInfoLookup *External 4181 = Context.Idents.getExternalIdentifierLookup()) { 4182 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers()); 4183 do { 4184 StringRef Name = Iter->Next(); 4185 if (Name.empty()) 4186 break; 4187 4188 Consumer.FoundName(Name); 4189 } while (true); 4190 } 4191 } 4192 4193 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty()); 4194 4195 // If we haven't found anything, we're done. 4196 if (Consumer.empty()) { 4197 // If this was an unqualified lookup, note that no correction was found. 4198 if (IsUnqualifiedLookup) 4199 (void)UnqualifiedTyposCorrected[Typo]; 4200 4201 return TypoCorrection(); 4202 } 4203 4204 // Make sure the best edit distance (prior to adding any namespace qualifiers) 4205 // is not more that about a third of the length of the typo's identifier. 4206 unsigned ED = Consumer.getBestEditDistance(true); 4207 if (ED > 0 && Typo->getName().size() / ED < 3) { 4208 // If this was an unqualified lookup, note that no correction was found. 4209 if (IsUnqualifiedLookup) 4210 (void)UnqualifiedTyposCorrected[Typo]; 4211 4212 return TypoCorrection(); 4213 } 4214 4215 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going 4216 // to search those namespaces. 4217 if (SearchNamespaces) { 4218 // Load any externally-known namespaces. 4219 if (ExternalSource && !LoadedExternalKnownNamespaces) { 4220 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; 4221 LoadedExternalKnownNamespaces = true; 4222 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); 4223 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I) 4224 KnownNamespaces[ExternalKnownNamespaces[I]] = true; 4225 } 4226 4227 for (llvm::MapVector<NamespaceDecl*, bool>::iterator 4228 KNI = KnownNamespaces.begin(), 4229 KNIEnd = KnownNamespaces.end(); 4230 KNI != KNIEnd; ++KNI) 4231 Namespaces.AddNamespace(KNI->first); 4232 4233 for (ASTContext::type_iterator TI = Context.types_begin(), 4234 TIEnd = Context.types_end(); 4235 TI != TIEnd; ++TI) { 4236 if (CXXRecordDecl *CD = (*TI)->getAsCXXRecordDecl()) { 4237 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && 4238 !CD->isUnion()) 4239 Namespaces.AddRecord(CD); 4240 } 4241 } 4242 } 4243 4244 // Weed out any names that could not be found by name lookup or, if a 4245 // CorrectionCandidateCallback object was provided, failed validation. 4246 SmallVector<TypoCorrection, 16> QualifiedResults; 4247 LookupResult TmpRes(*this, TypoName, LookupKind); 4248 TmpRes.suppressDiagnostics(); 4249 while (!Consumer.empty()) { 4250 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin(); 4251 unsigned ED = DI->first; 4252 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(), 4253 IEnd = DI->second.end(); 4254 I != IEnd; /* Increment in loop. */) { 4255 // If we only want nested name specifier corrections, ignore potential 4256 // corrections that have a different base identifier from the typo. 4257 if (AllowOnlyNNSChanges && 4258 I->second.front().getCorrectionAsIdentifierInfo() != Typo) { 4259 TypoCorrectionConsumer::result_iterator Prev = I; 4260 ++I; 4261 DI->second.erase(Prev); 4262 continue; 4263 } 4264 4265 // If the item already has been looked up or is a keyword, keep it. 4266 // If a validator callback object was given, drop the correction 4267 // unless it passes validation. 4268 bool Viable = false; 4269 for (TypoResultList::iterator RI = I->second.begin(); 4270 RI != I->second.end(); /* Increment in loop. */) { 4271 TypoResultList::iterator Prev = RI; 4272 ++RI; 4273 if (Prev->isResolved()) { 4274 if (!isCandidateViable(CCC, *Prev)) 4275 RI = I->second.erase(Prev); 4276 else 4277 Viable = true; 4278 } 4279 } 4280 if (Viable || I->second.empty()) { 4281 TypoCorrectionConsumer::result_iterator Prev = I; 4282 ++I; 4283 if (!Viable) 4284 DI->second.erase(Prev); 4285 continue; 4286 } 4287 assert(I->second.size() == 1 && "Expected a single unresolved candidate"); 4288 4289 // Perform name lookup on this name. 4290 TypoCorrection &Candidate = I->second.front(); 4291 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); 4292 DeclContext *TempMemberContext = MemberContext; 4293 CXXScopeSpec *TempSS = SS; 4294 retry_lookup: 4295 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS, 4296 TempMemberContext, EnteringContext, 4297 CCC.IsObjCIvarLookup, 4298 Name == TypoName.getName() && 4299 !Candidate.WillReplaceSpecifier()); 4300 4301 switch (TmpRes.getResultKind()) { 4302 case LookupResult::NotFound: 4303 case LookupResult::NotFoundInCurrentInstantiation: 4304 case LookupResult::FoundUnresolvedValue: 4305 if (TempSS) { 4306 // Immediately retry the lookup without the given CXXScopeSpec 4307 TempSS = NULL; 4308 Candidate.WillReplaceSpecifier(true); 4309 goto retry_lookup; 4310 } 4311 if (TempMemberContext) { 4312 if (SS && !TempSS) 4313 TempSS = SS; 4314 TempMemberContext = NULL; 4315 goto retry_lookup; 4316 } 4317 QualifiedResults.push_back(Candidate); 4318 // We didn't find this name in our scope, or didn't like what we found; 4319 // ignore it. 4320 { 4321 TypoCorrectionConsumer::result_iterator Next = I; 4322 ++Next; 4323 DI->second.erase(I); 4324 I = Next; 4325 } 4326 break; 4327 4328 case LookupResult::Ambiguous: 4329 // We don't deal with ambiguities. 4330 return TypoCorrection(); 4331 4332 case LookupResult::FoundOverloaded: { 4333 TypoCorrectionConsumer::result_iterator Prev = I; 4334 // Store all of the Decls for overloaded symbols 4335 for (LookupResult::iterator TRD = TmpRes.begin(), 4336 TRDEnd = TmpRes.end(); 4337 TRD != TRDEnd; ++TRD) 4338 Candidate.addCorrectionDecl(*TRD); 4339 ++I; 4340 if (!isCandidateViable(CCC, Candidate)) { 4341 QualifiedResults.push_back(Candidate); 4342 DI->second.erase(Prev); 4343 } 4344 break; 4345 } 4346 4347 case LookupResult::Found: { 4348 TypoCorrectionConsumer::result_iterator Prev = I; 4349 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>()); 4350 ++I; 4351 if (!isCandidateViable(CCC, Candidate)) { 4352 QualifiedResults.push_back(Candidate); 4353 DI->second.erase(Prev); 4354 } 4355 break; 4356 } 4357 4358 } 4359 } 4360 4361 if (DI->second.empty()) 4362 Consumer.erase(DI); 4363 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED) 4364 // If there are results in the closest possible bucket, stop 4365 break; 4366 4367 // Only perform the qualified lookups for C++ 4368 if (SearchNamespaces) { 4369 TmpRes.suppressDiagnostics(); 4370 for (SmallVector<TypoCorrection, 4371 16>::iterator QRI = QualifiedResults.begin(), 4372 QRIEnd = QualifiedResults.end(); 4373 QRI != QRIEnd; ++QRI) { 4374 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(), 4375 NIEnd = Namespaces.end(); 4376 NI != NIEnd; ++NI) { 4377 DeclContext *Ctx = NI->DeclCtx; 4378 const Type *NSType = NI->NameSpecifier->getAsType(); 4379 4380 // If the current NestedNameSpecifier refers to a class and the 4381 // current correction candidate is the name of that class, then skip 4382 // it as it is unlikely a qualified version of the class' constructor 4383 // is an appropriate correction. 4384 if (CXXRecordDecl *NSDecl = 4385 NSType ? NSType->getAsCXXRecordDecl() : 0) { 4386 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo()) 4387 continue; 4388 } 4389 4390 // FIXME: Stop searching once the namespaces are too far away to create 4391 // acceptable corrections for this identifier (since the namespaces 4392 // are sorted in ascending order by edit distance). 4393 4394 TmpRes.clear(); 4395 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo()); 4396 if (!LookupQualifiedName(TmpRes, Ctx)) continue; 4397 4398 // Any corrections added below will be validated in subsequent 4399 // iterations of the main while() loop over the Consumer's contents. 4400 switch (TmpRes.getResultKind()) { 4401 case LookupResult::Found: 4402 case LookupResult::FoundOverloaded: { 4403 TypoCorrection TC(*QRI); 4404 TC.ClearCorrectionDecls(); 4405 TC.setCorrectionSpecifier(NI->NameSpecifier); 4406 TC.setQualifierDistance(NI->EditDistance); 4407 TC.setCallbackDistance(0); // Reset the callback distance 4408 for (LookupResult::iterator TRD = TmpRes.begin(), 4409 TRDEnd = TmpRes.end(); 4410 TRD != TRDEnd; ++TRD) { 4411 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(), 4412 NSType ? NSType->getAsCXXRecordDecl() : 0, 4413 *TRD) == AR_accessible) 4414 TC.addCorrectionDecl(*TRD); 4415 } 4416 if (TC.isResolved()) 4417 Consumer.addCorrection(TC); 4418 break; 4419 } 4420 case LookupResult::NotFound: 4421 case LookupResult::NotFoundInCurrentInstantiation: 4422 case LookupResult::Ambiguous: 4423 case LookupResult::FoundUnresolvedValue: 4424 break; 4425 } 4426 } 4427 } 4428 } 4429 4430 QualifiedResults.clear(); 4431 } 4432 4433 // No corrections remain... 4434 if (Consumer.empty()) return TypoCorrection(); 4435 4436 TypoResultsMap &BestResults = Consumer.getBestResults(); 4437 ED = Consumer.getBestEditDistance(true); 4438 4439 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) { 4440 // If this was an unqualified lookup and we believe the callback 4441 // object wouldn't have filtered out possible corrections, note 4442 // that no correction was found. 4443 if (IsUnqualifiedLookup && !ValidatingCallback) 4444 (void)UnqualifiedTyposCorrected[Typo]; 4445 4446 return TypoCorrection(); 4447 } 4448 4449 // If only a single name remains, return that result. 4450 if (BestResults.size() == 1) { 4451 const TypoResultList &CorrectionList = BestResults.begin()->second; 4452 const TypoCorrection &Result = CorrectionList.front(); 4453 if (CorrectionList.size() != 1) return TypoCorrection(); 4454 4455 // Don't correct to a keyword that's the same as the typo; the keyword 4456 // wasn't actually in scope. 4457 if (ED == 0 && Result.isKeyword()) return TypoCorrection(); 4458 4459 // Record the correction for unqualified lookup. 4460 if (IsUnqualifiedLookup) 4461 UnqualifiedTyposCorrected[Typo] = Result; 4462 4463 TypoCorrection TC = Result; 4464 TC.setCorrectionRange(SS, TypoName); 4465 checkCorrectionVisibility(*this, TC, TypoName.getName()); 4466 return TC; 4467 } 4468 else if (BestResults.size() > 1 4469 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; 4470 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for 4471 // some instances of CTC_Unknown, while WantRemainingKeywords is true 4472 // for CTC_Unknown but not for CTC_ObjCMessageReceiver. 4473 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords 4474 && BestResults["super"].front().isKeyword()) { 4475 // Prefer 'super' when we're completing in a message-receiver 4476 // context. 4477 4478 // Don't correct to a keyword that's the same as the typo; the keyword 4479 // wasn't actually in scope. 4480 if (ED == 0) return TypoCorrection(); 4481 4482 // Record the correction for unqualified lookup. 4483 if (IsUnqualifiedLookup) 4484 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front(); 4485 4486 TypoCorrection TC = BestResults["super"].front(); 4487 TC.setCorrectionRange(SS, TypoName); 4488 return TC; 4489 } 4490 4491 // If this was an unqualified lookup and we believe the callback object did 4492 // not filter out possible corrections, note that no correction was found. 4493 if (IsUnqualifiedLookup && !ValidatingCallback) 4494 (void)UnqualifiedTyposCorrected[Typo]; 4495 4496 return TypoCorrection(); 4497 } 4498 4499 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { 4500 if (!CDecl) return; 4501 4502 if (isKeyword()) 4503 CorrectionDecls.clear(); 4504 4505 CorrectionDecls.push_back(CDecl->getUnderlyingDecl()); 4506 4507 if (!CorrectionName) 4508 CorrectionName = CDecl->getDeclName(); 4509 } 4510 4511 std::string TypoCorrection::getAsString(const LangOptions &LO) const { 4512 if (CorrectionNameSpec) { 4513 std::string tmpBuffer; 4514 llvm::raw_string_ostream PrefixOStream(tmpBuffer); 4515 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); 4516 PrefixOStream << CorrectionName; 4517 return PrefixOStream.str(); 4518 } 4519 4520 return CorrectionName.getAsString(); 4521 } 4522 4523 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) { 4524 if (!candidate.isResolved()) 4525 return true; 4526 4527 if (candidate.isKeyword()) 4528 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || 4529 WantRemainingKeywords || WantObjCSuper; 4530 4531 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 4532 CDeclEnd = candidate.end(); 4533 CDecl != CDeclEnd; ++CDecl) { 4534 if (!isa<TypeDecl>(*CDecl)) 4535 return true; 4536 } 4537 4538 return WantTypeSpecifiers; 4539 } 4540 4541 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, 4542 bool HasExplicitTemplateArgs) 4543 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 4544 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 4545 WantRemainingKeywords = false; 4546 } 4547 4548 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { 4549 if (!candidate.getCorrectionDecl()) 4550 return candidate.isKeyword(); 4551 4552 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 4553 DIEnd = candidate.end(); 4554 DI != DIEnd; ++DI) { 4555 FunctionDecl *FD = 0; 4556 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 4557 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 4558 FD = FTD->getTemplatedDecl(); 4559 if (!HasExplicitTemplateArgs && !FD) { 4560 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 4561 // If the Decl is neither a function nor a template function, 4562 // determine if it is a pointer or reference to a function. If so, 4563 // check against the number of arguments expected for the pointee. 4564 QualType ValType = cast<ValueDecl>(ND)->getType(); 4565 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 4566 ValType = ValType->getPointeeType(); 4567 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 4568 if (FPT->getNumArgs() == NumArgs) 4569 return true; 4570 } 4571 } 4572 if (FD && FD->getNumParams() >= NumArgs && 4573 FD->getMinRequiredArguments() <= NumArgs) 4574 return true; 4575 } 4576 return false; 4577 } 4578 4579 void Sema::diagnoseTypo(const TypoCorrection &Correction, 4580 const PartialDiagnostic &TypoDiag, 4581 bool ErrorRecovery) { 4582 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), 4583 ErrorRecovery); 4584 } 4585 4586 /// Find which declaration we should import to provide the definition of 4587 /// the given declaration. 4588 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) { 4589 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4590 return VD->getDefinition(); 4591 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4592 return FD->isDefined(FD) ? FD : 0; 4593 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 4594 return TD->getDefinition(); 4595 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) 4596 return ID->getDefinition(); 4597 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) 4598 return PD->getDefinition(); 4599 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 4600 return getDefinitionToImport(TD->getTemplatedDecl()); 4601 return 0; 4602 } 4603 4604 /// \brief Diagnose a successfully-corrected typo. Separated from the correction 4605 /// itself to allow external validation of the result, etc. 4606 /// 4607 /// \param Correction The result of performing typo correction. 4608 /// \param TypoDiag The diagnostic to produce. This will have the corrected 4609 /// string added to it (and usually also a fixit). 4610 /// \param PrevNote A note to use when indicating the location of the entity to 4611 /// which we are correcting. Will have the correction string added to it. 4612 /// \param ErrorRecovery If \c true (the default), the caller is going to 4613 /// recover from the typo as if the corrected string had been typed. 4614 /// In this case, \c PDiag must be an error, and we will attach a fixit 4615 /// to it. 4616 void Sema::diagnoseTypo(const TypoCorrection &Correction, 4617 const PartialDiagnostic &TypoDiag, 4618 const PartialDiagnostic &PrevNote, 4619 bool ErrorRecovery) { 4620 std::string CorrectedStr = Correction.getAsString(getLangOpts()); 4621 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); 4622 FixItHint FixTypo = FixItHint::CreateReplacement( 4623 Correction.getCorrectionRange(), CorrectedStr); 4624 4625 // Maybe we're just missing a module import. 4626 if (Correction.requiresImport()) { 4627 NamedDecl *Decl = Correction.getCorrectionDecl(); 4628 assert(Decl && "import required but no declaration to import"); 4629 4630 // Suggest importing a module providing the definition of this entity, if 4631 // possible. 4632 const NamedDecl *Def = getDefinitionToImport(Decl); 4633 if (!Def) 4634 Def = Decl; 4635 Module *Owner = Def->getOwningModule(); 4636 assert(Owner && "definition of hidden declaration is not in a module"); 4637 4638 Diag(Correction.getCorrectionRange().getBegin(), 4639 diag::err_module_private_declaration) 4640 << Def << Owner->getFullModuleName(); 4641 Diag(Def->getLocation(), diag::note_previous_declaration); 4642 4643 // Recover by implicitly importing this module. 4644 if (!isSFINAEContext() && ErrorRecovery) 4645 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(), 4646 Owner); 4647 return; 4648 } 4649 4650 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) 4651 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); 4652 4653 NamedDecl *ChosenDecl = 4654 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl(); 4655 if (PrevNote.getDiagID() && ChosenDecl) 4656 Diag(ChosenDecl->getLocation(), PrevNote) 4657 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); 4658 } 4659