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