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 for (auto *I : S->using_directives()) 117 visit(I, InnermostFileDC); 118 } 119 } 120 } 121 122 // Visits a context and collect all of its using directives 123 // recursively. Treats all using directives as if they were 124 // declared in the context. 125 // 126 // A given context is only every visited once, so it is important 127 // that contexts be visited from the inside out in order to get 128 // the effective DCs right. 129 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 130 if (!visited.insert(DC)) 131 return; 132 133 addUsingDirectives(DC, EffectiveDC); 134 } 135 136 // Visits a using directive and collects all of its using 137 // directives recursively. Treats all using directives as if they 138 // were declared in the effective DC. 139 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 140 DeclContext *NS = UD->getNominatedNamespace(); 141 if (!visited.insert(NS)) 142 return; 143 144 addUsingDirective(UD, EffectiveDC); 145 addUsingDirectives(NS, EffectiveDC); 146 } 147 148 // Adds all the using directives in a context (and those nominated 149 // by its using directives, transitively) as if they appeared in 150 // the given effective context. 151 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 152 SmallVector<DeclContext*,4> queue; 153 while (true) { 154 for (auto UD : DC->using_directives()) { 155 DeclContext *NS = UD->getNominatedNamespace(); 156 if (visited.insert(NS)) { 157 addUsingDirective(UD, EffectiveDC); 158 queue.push_back(NS); 159 } 160 } 161 162 if (queue.empty()) 163 return; 164 165 DC = queue.pop_back_val(); 166 } 167 } 168 169 // Add a using directive as if it had been declared in the given 170 // context. This helps implement C++ [namespace.udir]p3: 171 // The using-directive is transitive: if a scope contains a 172 // using-directive that nominates a second namespace that itself 173 // contains using-directives, the effect is as if the 174 // using-directives from the second namespace also appeared in 175 // the first. 176 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 177 // Find the common ancestor between the effective context and 178 // the nominated namespace. 179 DeclContext *Common = UD->getNominatedNamespace(); 180 while (!Common->Encloses(EffectiveDC)) 181 Common = Common->getParent(); 182 Common = Common->getPrimaryContext(); 183 184 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 185 } 186 187 void done() { 188 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); 189 } 190 191 typedef ListTy::const_iterator const_iterator; 192 193 const_iterator begin() const { return list.begin(); } 194 const_iterator end() const { return list.end(); } 195 196 std::pair<const_iterator,const_iterator> 197 getNamespacesFor(DeclContext *DC) const { 198 return std::equal_range(begin(), end(), DC->getPrimaryContext(), 199 UnqualUsingEntry::Comparator()); 200 } 201 }; 202 } 203 204 // Retrieve the set of identifier namespaces that correspond to a 205 // specific kind of name lookup. 206 static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 207 bool CPlusPlus, 208 bool Redeclaration) { 209 unsigned IDNS = 0; 210 switch (NameKind) { 211 case Sema::LookupObjCImplicitSelfParam: 212 case Sema::LookupOrdinaryName: 213 case Sema::LookupRedeclarationWithLinkage: 214 case Sema::LookupLocalFriendName: 215 IDNS = Decl::IDNS_Ordinary; 216 if (CPlusPlus) { 217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 218 if (Redeclaration) 219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 220 } 221 if (Redeclaration) 222 IDNS |= Decl::IDNS_LocalExtern; 223 break; 224 225 case Sema::LookupOperatorName: 226 // Operator lookup is its own crazy thing; it is not the same 227 // as (e.g.) looking up an operator name for redeclaration. 228 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 229 IDNS = Decl::IDNS_NonMemberOperator; 230 break; 231 232 case Sema::LookupTagName: 233 if (CPlusPlus) { 234 IDNS = Decl::IDNS_Type; 235 236 // When looking for a redeclaration of a tag name, we add: 237 // 1) TagFriend to find undeclared friend decls 238 // 2) Namespace because they can't "overload" with tag decls. 239 // 3) Tag because it includes class templates, which can't 240 // "overload" with tag decls. 241 if (Redeclaration) 242 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 243 } else { 244 IDNS = Decl::IDNS_Tag; 245 } 246 break; 247 248 case Sema::LookupLabel: 249 IDNS = Decl::IDNS_Label; 250 break; 251 252 case Sema::LookupMemberName: 253 IDNS = Decl::IDNS_Member; 254 if (CPlusPlus) 255 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 256 break; 257 258 case Sema::LookupNestedNameSpecifierName: 259 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 260 break; 261 262 case Sema::LookupNamespaceName: 263 IDNS = Decl::IDNS_Namespace; 264 break; 265 266 case Sema::LookupUsingDeclName: 267 assert(Redeclaration && "should only be used for redecl lookup"); 268 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | 269 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend | 270 Decl::IDNS_LocalExtern; 271 break; 272 273 case Sema::LookupObjCProtocolName: 274 IDNS = Decl::IDNS_ObjCProtocol; 275 break; 276 277 case Sema::LookupAnyName: 278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member 279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol 280 | Decl::IDNS_Type; 281 break; 282 } 283 return IDNS; 284 } 285 286 void LookupResult::configure() { 287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus, 288 isForRedeclaration()); 289 290 // If we're looking for one of the allocation or deallocation 291 // operators, make sure that the implicitly-declared new and delete 292 // operators can be found. 293 switch (NameInfo.getName().getCXXOverloadedOperator()) { 294 case OO_New: 295 case OO_Delete: 296 case OO_Array_New: 297 case OO_Array_Delete: 298 SemaRef.DeclareGlobalNewDelete(); 299 break; 300 301 default: 302 break; 303 } 304 305 // Compiler builtins are always visible, regardless of where they end 306 // up being declared. 307 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { 308 if (unsigned BuiltinID = Id->getBuiltinID()) { 309 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 310 AllowHidden = true; 311 } 312 } 313 } 314 315 bool LookupResult::sanity() const { 316 // This function is never called by NDEBUG builds. 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_range UsingDirectives = StartDC->using_directives(); 1454 if (UsingDirectives.begin() == UsingDirectives.end()) return false; 1455 1456 // We have at least added all these contexts to the queue. 1457 llvm::SmallPtrSet<DeclContext*, 8> Visited; 1458 Visited.insert(StartDC); 1459 1460 // We have not yet looked into these namespaces, much less added 1461 // their "using-children" to the queue. 1462 SmallVector<NamespaceDecl*, 8> Queue; 1463 1464 // We have already looked into the initial namespace; seed the queue 1465 // with its using-children. 1466 for (auto *I : UsingDirectives) { 1467 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace(); 1468 if (Visited.insert(ND)) 1469 Queue.push_back(ND); 1470 } 1471 1472 // The easiest way to implement the restriction in [namespace.qual]p5 1473 // is to check whether any of the individual results found a tag 1474 // and, if so, to declare an ambiguity if the final result is not 1475 // a tag. 1476 bool FoundTag = false; 1477 bool FoundNonTag = false; 1478 1479 LookupResult LocalR(LookupResult::Temporary, R); 1480 1481 bool Found = false; 1482 while (!Queue.empty()) { 1483 NamespaceDecl *ND = Queue.pop_back_val(); 1484 1485 // We go through some convolutions here to avoid copying results 1486 // between LookupResults. 1487 bool UseLocal = !R.empty(); 1488 LookupResult &DirectR = UseLocal ? LocalR : R; 1489 bool FoundDirect = LookupDirect(S, DirectR, ND); 1490 1491 if (FoundDirect) { 1492 // First do any local hiding. 1493 DirectR.resolveKind(); 1494 1495 // If the local result is a tag, remember that. 1496 if (DirectR.isSingleTagDecl()) 1497 FoundTag = true; 1498 else 1499 FoundNonTag = true; 1500 1501 // Append the local results to the total results if necessary. 1502 if (UseLocal) { 1503 R.addAllDecls(LocalR); 1504 LocalR.clear(); 1505 } 1506 } 1507 1508 // If we find names in this namespace, ignore its using directives. 1509 if (FoundDirect) { 1510 Found = true; 1511 continue; 1512 } 1513 1514 for (auto I : ND->using_directives()) { 1515 NamespaceDecl *Nom = I->getNominatedNamespace(); 1516 if (Visited.insert(Nom)) 1517 Queue.push_back(Nom); 1518 } 1519 } 1520 1521 if (Found) { 1522 if (FoundTag && FoundNonTag) 1523 R.setAmbiguousQualifiedTagHiding(); 1524 else 1525 R.resolveKind(); 1526 } 1527 1528 return Found; 1529 } 1530 1531 /// \brief Callback that looks for any member of a class with the given name. 1532 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, 1533 CXXBasePath &Path, 1534 void *Name) { 1535 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 1536 1537 DeclarationName N = DeclarationName::getFromOpaquePtr(Name); 1538 Path.Decls = BaseRecord->lookup(N); 1539 return !Path.Decls.empty(); 1540 } 1541 1542 /// \brief Determine whether the given set of member declarations contains only 1543 /// static members, nested types, and enumerators. 1544 template<typename InputIterator> 1545 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) { 1546 Decl *D = (*First)->getUnderlyingDecl(); 1547 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D)) 1548 return true; 1549 1550 if (isa<CXXMethodDecl>(D)) { 1551 // Determine whether all of the methods are static. 1552 bool AllMethodsAreStatic = true; 1553 for(; First != Last; ++First) { 1554 D = (*First)->getUnderlyingDecl(); 1555 1556 if (!isa<CXXMethodDecl>(D)) { 1557 assert(isa<TagDecl>(D) && "Non-function must be a tag decl"); 1558 break; 1559 } 1560 1561 if (!cast<CXXMethodDecl>(D)->isStatic()) { 1562 AllMethodsAreStatic = false; 1563 break; 1564 } 1565 } 1566 1567 if (AllMethodsAreStatic) 1568 return true; 1569 } 1570 1571 return false; 1572 } 1573 1574 /// \brief Perform qualified name lookup into a given context. 1575 /// 1576 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 1577 /// names when the context of those names is explicit specified, e.g., 1578 /// "std::vector" or "x->member", or as part of unqualified name lookup. 1579 /// 1580 /// Different lookup criteria can find different names. For example, a 1581 /// particular scope can have both a struct and a function of the same 1582 /// name, and each can be found by certain lookup criteria. For more 1583 /// information about lookup criteria, see the documentation for the 1584 /// class LookupCriteria. 1585 /// 1586 /// \param R captures both the lookup criteria and any lookup results found. 1587 /// 1588 /// \param LookupCtx The context in which qualified name lookup will 1589 /// search. If the lookup criteria permits, name lookup may also search 1590 /// in the parent contexts or (for C++ classes) base classes. 1591 /// 1592 /// \param InUnqualifiedLookup true if this is qualified name lookup that 1593 /// occurs as part of unqualified name lookup. 1594 /// 1595 /// \returns true if lookup succeeded, false if it failed. 1596 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1597 bool InUnqualifiedLookup) { 1598 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 1599 1600 if (!R.getLookupName()) 1601 return false; 1602 1603 // Make sure that the declaration context is complete. 1604 assert((!isa<TagDecl>(LookupCtx) || 1605 LookupCtx->isDependentContext() || 1606 cast<TagDecl>(LookupCtx)->isCompleteDefinition() || 1607 cast<TagDecl>(LookupCtx)->isBeingDefined()) && 1608 "Declaration context must already be complete!"); 1609 1610 // Perform qualified name lookup into the LookupCtx. 1611 if (LookupDirect(*this, R, LookupCtx)) { 1612 R.resolveKind(); 1613 if (isa<CXXRecordDecl>(LookupCtx)) 1614 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 1615 return true; 1616 } 1617 1618 // Don't descend into implied contexts for redeclarations. 1619 // C++98 [namespace.qual]p6: 1620 // In a declaration for a namespace member in which the 1621 // declarator-id is a qualified-id, given that the qualified-id 1622 // for the namespace member has the form 1623 // nested-name-specifier unqualified-id 1624 // the unqualified-id shall name a member of the namespace 1625 // designated by the nested-name-specifier. 1626 // See also [class.mfct]p5 and [class.static.data]p2. 1627 if (R.isForRedeclaration()) 1628 return false; 1629 1630 // If this is a namespace, look it up in the implied namespaces. 1631 if (LookupCtx->isFileContext()) 1632 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 1633 1634 // If this isn't a C++ class, we aren't allowed to look into base 1635 // classes, we're done. 1636 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 1637 if (!LookupRec || !LookupRec->getDefinition()) 1638 return false; 1639 1640 // If we're performing qualified name lookup into a dependent class, 1641 // then we are actually looking into a current instantiation. If we have any 1642 // dependent base classes, then we either have to delay lookup until 1643 // template instantiation time (at which point all bases will be available) 1644 // or we have to fail. 1645 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 1646 LookupRec->hasAnyDependentBases()) { 1647 R.setNotFoundInCurrentInstantiation(); 1648 return false; 1649 } 1650 1651 // Perform lookup into our base classes. 1652 CXXBasePaths Paths; 1653 Paths.setOrigin(LookupRec); 1654 1655 // Look for this member in our base classes 1656 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0; 1657 switch (R.getLookupKind()) { 1658 case LookupObjCImplicitSelfParam: 1659 case LookupOrdinaryName: 1660 case LookupMemberName: 1661 case LookupRedeclarationWithLinkage: 1662 case LookupLocalFriendName: 1663 BaseCallback = &CXXRecordDecl::FindOrdinaryMember; 1664 break; 1665 1666 case LookupTagName: 1667 BaseCallback = &CXXRecordDecl::FindTagMember; 1668 break; 1669 1670 case LookupAnyName: 1671 BaseCallback = &LookupAnyMember; 1672 break; 1673 1674 case LookupUsingDeclName: 1675 // This lookup is for redeclarations only. 1676 1677 case LookupOperatorName: 1678 case LookupNamespaceName: 1679 case LookupObjCProtocolName: 1680 case LookupLabel: 1681 // These lookups will never find a member in a C++ class (or base class). 1682 return false; 1683 1684 case LookupNestedNameSpecifierName: 1685 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; 1686 break; 1687 } 1688 1689 if (!LookupRec->lookupInBases(BaseCallback, 1690 R.getLookupName().getAsOpaquePtr(), Paths)) 1691 return false; 1692 1693 R.setNamingClass(LookupRec); 1694 1695 // C++ [class.member.lookup]p2: 1696 // [...] If the resulting set of declarations are not all from 1697 // sub-objects of the same type, or the set has a nonstatic member 1698 // and includes members from distinct sub-objects, there is an 1699 // ambiguity and the program is ill-formed. Otherwise that set is 1700 // the result of the lookup. 1701 QualType SubobjectType; 1702 int SubobjectNumber = 0; 1703 AccessSpecifier SubobjectAccess = AS_none; 1704 1705 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 1706 Path != PathEnd; ++Path) { 1707 const CXXBasePathElement &PathElement = Path->back(); 1708 1709 // Pick the best (i.e. most permissive i.e. numerically lowest) access 1710 // across all paths. 1711 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 1712 1713 // Determine whether we're looking at a distinct sub-object or not. 1714 if (SubobjectType.isNull()) { 1715 // This is the first subobject we've looked at. Record its type. 1716 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 1717 SubobjectNumber = PathElement.SubobjectNumber; 1718 continue; 1719 } 1720 1721 if (SubobjectType 1722 != Context.getCanonicalType(PathElement.Base->getType())) { 1723 // We found members of the given name in two subobjects of 1724 // different types. If the declaration sets aren't the same, this 1725 // this lookup is ambiguous. 1726 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) { 1727 CXXBasePaths::paths_iterator FirstPath = Paths.begin(); 1728 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin(); 1729 DeclContext::lookup_iterator CurrentD = Path->Decls.begin(); 1730 1731 while (FirstD != FirstPath->Decls.end() && 1732 CurrentD != Path->Decls.end()) { 1733 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() != 1734 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl()) 1735 break; 1736 1737 ++FirstD; 1738 ++CurrentD; 1739 } 1740 1741 if (FirstD == FirstPath->Decls.end() && 1742 CurrentD == Path->Decls.end()) 1743 continue; 1744 } 1745 1746 R.setAmbiguousBaseSubobjectTypes(Paths); 1747 return true; 1748 } 1749 1750 if (SubobjectNumber != PathElement.SubobjectNumber) { 1751 // We have a different subobject of the same type. 1752 1753 // C++ [class.member.lookup]p5: 1754 // A static member, a nested type or an enumerator defined in 1755 // a base class T can unambiguously be found even if an object 1756 // has more than one base class subobject of type T. 1757 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) 1758 continue; 1759 1760 // We have found a nonstatic member name in multiple, distinct 1761 // subobjects. Name lookup is ambiguous. 1762 R.setAmbiguousBaseSubobjects(Paths); 1763 return true; 1764 } 1765 } 1766 1767 // Lookup in a base class succeeded; return these results. 1768 1769 DeclContext::lookup_result DR = Paths.front().Decls; 1770 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) { 1771 NamedDecl *D = *I; 1772 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 1773 D->getAccess()); 1774 R.addDecl(D, AS); 1775 } 1776 R.resolveKind(); 1777 return true; 1778 } 1779 1780 /// @brief Performs name lookup for a name that was parsed in the 1781 /// source code, and may contain a C++ scope specifier. 1782 /// 1783 /// This routine is a convenience routine meant to be called from 1784 /// contexts that receive a name and an optional C++ scope specifier 1785 /// (e.g., "N::M::x"). It will then perform either qualified or 1786 /// unqualified name lookup (with LookupQualifiedName or LookupName, 1787 /// respectively) on the given name and return those results. 1788 /// 1789 /// @param S The scope from which unqualified name lookup will 1790 /// begin. 1791 /// 1792 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 1793 /// 1794 /// @param EnteringContext Indicates whether we are going to enter the 1795 /// context of the scope-specifier SS (if present). 1796 /// 1797 /// @returns True if any decls were found (but possibly ambiguous) 1798 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1799 bool AllowBuiltinCreation, bool EnteringContext) { 1800 if (SS && SS->isInvalid()) { 1801 // When the scope specifier is invalid, don't even look for 1802 // anything. 1803 return false; 1804 } 1805 1806 if (SS && SS->isSet()) { 1807 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 1808 // We have resolved the scope specifier to a particular declaration 1809 // contex, and will perform name lookup in that context. 1810 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 1811 return false; 1812 1813 R.setContextRange(SS->getRange()); 1814 return LookupQualifiedName(R, DC); 1815 } 1816 1817 // We could not resolve the scope specified to a specific declaration 1818 // context, which means that SS refers to an unknown specialization. 1819 // Name lookup can't find anything in this case. 1820 R.setNotFoundInCurrentInstantiation(); 1821 R.setContextRange(SS->getRange()); 1822 return false; 1823 } 1824 1825 // Perform unqualified name lookup starting in the given scope. 1826 return LookupName(R, S, AllowBuiltinCreation); 1827 } 1828 1829 1830 /// \brief Produce a diagnostic describing the ambiguity that resulted 1831 /// from name lookup. 1832 /// 1833 /// \param Result The result of the ambiguous lookup to be diagnosed. 1834 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 1835 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1836 1837 DeclarationName Name = Result.getLookupName(); 1838 SourceLocation NameLoc = Result.getNameLoc(); 1839 SourceRange LookupRange = Result.getContextRange(); 1840 1841 switch (Result.getAmbiguityKind()) { 1842 case LookupResult::AmbiguousBaseSubobjects: { 1843 CXXBasePaths *Paths = Result.getBasePaths(); 1844 QualType SubobjectType = Paths->front().back().Base->getType(); 1845 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1846 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1847 << LookupRange; 1848 1849 DeclContext::lookup_iterator Found = Paths->front().Decls.begin(); 1850 while (isa<CXXMethodDecl>(*Found) && 1851 cast<CXXMethodDecl>(*Found)->isStatic()) 1852 ++Found; 1853 1854 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1855 break; 1856 } 1857 1858 case LookupResult::AmbiguousBaseSubobjectTypes: { 1859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1860 << Name << LookupRange; 1861 1862 CXXBasePaths *Paths = Result.getBasePaths(); 1863 std::set<Decl *> DeclsPrinted; 1864 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 1865 PathEnd = Paths->end(); 1866 Path != PathEnd; ++Path) { 1867 Decl *D = Path->Decls.front(); 1868 if (DeclsPrinted.insert(D).second) 1869 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1870 } 1871 break; 1872 } 1873 1874 case LookupResult::AmbiguousTagHiding: { 1875 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 1876 1877 llvm::SmallPtrSet<NamedDecl*,8> TagDecls; 1878 1879 LookupResult::iterator DI, DE = Result.end(); 1880 for (DI = Result.begin(); DI != DE; ++DI) 1881 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) { 1882 TagDecls.insert(TD); 1883 Diag(TD->getLocation(), diag::note_hidden_tag); 1884 } 1885 1886 for (DI = Result.begin(); DI != DE; ++DI) 1887 if (!isa<TagDecl>(*DI)) 1888 Diag((*DI)->getLocation(), diag::note_hiding_object); 1889 1890 // For recovery purposes, go ahead and implement the hiding. 1891 LookupResult::Filter F = Result.makeFilter(); 1892 while (F.hasNext()) { 1893 if (TagDecls.count(F.next())) 1894 F.erase(); 1895 } 1896 F.done(); 1897 break; 1898 } 1899 1900 case LookupResult::AmbiguousReference: { 1901 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1902 1903 LookupResult::iterator DI = Result.begin(), DE = Result.end(); 1904 for (; DI != DE; ++DI) 1905 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1906 break; 1907 } 1908 } 1909 } 1910 1911 namespace { 1912 struct AssociatedLookup { 1913 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, 1914 Sema::AssociatedNamespaceSet &Namespaces, 1915 Sema::AssociatedClassSet &Classes) 1916 : S(S), Namespaces(Namespaces), Classes(Classes), 1917 InstantiationLoc(InstantiationLoc) { 1918 } 1919 1920 Sema &S; 1921 Sema::AssociatedNamespaceSet &Namespaces; 1922 Sema::AssociatedClassSet &Classes; 1923 SourceLocation InstantiationLoc; 1924 }; 1925 } 1926 1927 static void 1928 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 1929 1930 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 1931 DeclContext *Ctx) { 1932 // Add the associated namespace for this class. 1933 1934 // We don't use DeclContext::getEnclosingNamespaceContext() as this may 1935 // be a locally scoped record. 1936 1937 // We skip out of inline namespaces. The innermost non-inline namespace 1938 // contains all names of all its nested inline namespaces anyway, so we can 1939 // replace the entire inline namespace tree with its root. 1940 while (Ctx->isRecord() || Ctx->isTransparentContext() || 1941 Ctx->isInlineNamespace()) 1942 Ctx = Ctx->getParent(); 1943 1944 if (Ctx->isFileContext()) 1945 Namespaces.insert(Ctx->getPrimaryContext()); 1946 } 1947 1948 // \brief Add the associated classes and namespaces for argument-dependent 1949 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 1950 static void 1951 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1952 const TemplateArgument &Arg) { 1953 // C++ [basic.lookup.koenig]p2, last bullet: 1954 // -- [...] ; 1955 switch (Arg.getKind()) { 1956 case TemplateArgument::Null: 1957 break; 1958 1959 case TemplateArgument::Type: 1960 // [...] the namespaces and classes associated with the types of the 1961 // template arguments provided for template type parameters (excluding 1962 // template template parameters) 1963 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 1964 break; 1965 1966 case TemplateArgument::Template: 1967 case TemplateArgument::TemplateExpansion: { 1968 // [...] the namespaces in which any template template arguments are 1969 // defined; and the classes in which any member templates used as 1970 // template template arguments are defined. 1971 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 1972 if (ClassTemplateDecl *ClassTemplate 1973 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 1974 DeclContext *Ctx = ClassTemplate->getDeclContext(); 1975 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1976 Result.Classes.insert(EnclosingClass); 1977 // Add the associated namespace for this class. 1978 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1979 } 1980 break; 1981 } 1982 1983 case TemplateArgument::Declaration: 1984 case TemplateArgument::Integral: 1985 case TemplateArgument::Expression: 1986 case TemplateArgument::NullPtr: 1987 // [Note: non-type template arguments do not contribute to the set of 1988 // associated namespaces. ] 1989 break; 1990 1991 case TemplateArgument::Pack: 1992 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), 1993 PEnd = Arg.pack_end(); 1994 P != PEnd; ++P) 1995 addAssociatedClassesAndNamespaces(Result, *P); 1996 break; 1997 } 1998 } 1999 2000 // \brief Add the associated classes and namespaces for 2001 // argument-dependent lookup with an argument of class type 2002 // (C++ [basic.lookup.koenig]p2). 2003 static void 2004 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2005 CXXRecordDecl *Class) { 2006 2007 // Just silently ignore anything whose name is __va_list_tag. 2008 if (Class->getDeclName() == Result.S.VAListTagName) 2009 return; 2010 2011 // C++ [basic.lookup.koenig]p2: 2012 // [...] 2013 // -- If T is a class type (including unions), its associated 2014 // classes are: the class itself; the class of which it is a 2015 // member, if any; and its direct and indirect base 2016 // classes. Its associated namespaces are the namespaces in 2017 // which its associated classes are defined. 2018 2019 // Add the class of which it is a member, if any. 2020 DeclContext *Ctx = Class->getDeclContext(); 2021 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2022 Result.Classes.insert(EnclosingClass); 2023 // Add the associated namespace for this class. 2024 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2025 2026 // Add the class itself. If we've already seen this class, we don't 2027 // need to visit base classes. 2028 // 2029 // FIXME: That's not correct, we may have added this class only because it 2030 // was the enclosing class of another class, and in that case we won't have 2031 // added its base classes yet. 2032 if (!Result.Classes.insert(Class)) 2033 return; 2034 2035 // -- If T is a template-id, its associated namespaces and classes are 2036 // the namespace in which the template is defined; for member 2037 // templates, the member template's class; the namespaces and classes 2038 // associated with the types of the template arguments provided for 2039 // template type parameters (excluding template template parameters); the 2040 // namespaces in which any template template arguments are defined; and 2041 // the classes in which any member templates used as template template 2042 // arguments are defined. [Note: non-type template arguments do not 2043 // contribute to the set of associated namespaces. ] 2044 if (ClassTemplateSpecializationDecl *Spec 2045 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 2046 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 2047 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2048 Result.Classes.insert(EnclosingClass); 2049 // Add the associated namespace for this class. 2050 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2051 2052 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 2053 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 2054 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 2055 } 2056 2057 // Only recurse into base classes for complete types. 2058 if (!Class->hasDefinition()) 2059 return; 2060 2061 // Add direct and indirect base classes along with their associated 2062 // namespaces. 2063 SmallVector<CXXRecordDecl *, 32> Bases; 2064 Bases.push_back(Class); 2065 while (!Bases.empty()) { 2066 // Pop this class off the stack. 2067 Class = Bases.pop_back_val(); 2068 2069 // Visit the base classes. 2070 for (const auto &Base : Class->bases()) { 2071 const RecordType *BaseType = Base.getType()->getAs<RecordType>(); 2072 // In dependent contexts, we do ADL twice, and the first time around, 2073 // the base type might be a dependent TemplateSpecializationType, or a 2074 // TemplateTypeParmType. If that happens, simply ignore it. 2075 // FIXME: If we want to support export, we probably need to add the 2076 // namespace of the template in a TemplateSpecializationType, or even 2077 // the classes and namespaces of known non-dependent arguments. 2078 if (!BaseType) 2079 continue; 2080 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 2081 if (Result.Classes.insert(BaseDecl)) { 2082 // Find the associated namespace for this base class. 2083 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 2084 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 2085 2086 // Make sure we visit the bases of this base class. 2087 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 2088 Bases.push_back(BaseDecl); 2089 } 2090 } 2091 } 2092 } 2093 2094 // \brief Add the associated classes and namespaces for 2095 // argument-dependent lookup with an argument of type T 2096 // (C++ [basic.lookup.koenig]p2). 2097 static void 2098 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 2099 // C++ [basic.lookup.koenig]p2: 2100 // 2101 // For each argument type T in the function call, there is a set 2102 // of zero or more associated namespaces and a set of zero or more 2103 // associated classes to be considered. The sets of namespaces and 2104 // classes is determined entirely by the types of the function 2105 // arguments (and the namespace of any template template 2106 // argument). Typedef names and using-declarations used to specify 2107 // the types do not contribute to this set. The sets of namespaces 2108 // and classes are determined in the following way: 2109 2110 SmallVector<const Type *, 16> Queue; 2111 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 2112 2113 while (true) { 2114 switch (T->getTypeClass()) { 2115 2116 #define TYPE(Class, Base) 2117 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2118 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2119 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2120 #define ABSTRACT_TYPE(Class, Base) 2121 #include "clang/AST/TypeNodes.def" 2122 // T is canonical. We can also ignore dependent types because 2123 // we don't need to do ADL at the definition point, but if we 2124 // wanted to implement template export (or if we find some other 2125 // use for associated classes and namespaces...) this would be 2126 // wrong. 2127 break; 2128 2129 // -- If T is a pointer to U or an array of U, its associated 2130 // namespaces and classes are those associated with U. 2131 case Type::Pointer: 2132 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 2133 continue; 2134 case Type::ConstantArray: 2135 case Type::IncompleteArray: 2136 case Type::VariableArray: 2137 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 2138 continue; 2139 2140 // -- If T is a fundamental type, its associated sets of 2141 // namespaces and classes are both empty. 2142 case Type::Builtin: 2143 break; 2144 2145 // -- If T is a class type (including unions), its associated 2146 // classes are: the class itself; the class of which it is a 2147 // member, if any; and its direct and indirect base 2148 // classes. Its associated namespaces are the namespaces in 2149 // which its associated classes are defined. 2150 case Type::Record: { 2151 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0), 2152 /*no diagnostic*/ 0); 2153 CXXRecordDecl *Class 2154 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 2155 addAssociatedClassesAndNamespaces(Result, Class); 2156 break; 2157 } 2158 2159 // -- If T is an enumeration type, its associated namespace is 2160 // the namespace in which it is defined. If it is class 2161 // member, its associated class is the member's class; else 2162 // it has no associated class. 2163 case Type::Enum: { 2164 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 2165 2166 DeclContext *Ctx = Enum->getDeclContext(); 2167 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2168 Result.Classes.insert(EnclosingClass); 2169 2170 // Add the associated namespace for this class. 2171 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2172 2173 break; 2174 } 2175 2176 // -- If T is a function type, its associated namespaces and 2177 // classes are those associated with the function parameter 2178 // types and those associated with the return type. 2179 case Type::FunctionProto: { 2180 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2181 for (const auto &Arg : Proto->param_types()) 2182 Queue.push_back(Arg.getTypePtr()); 2183 // fallthrough 2184 } 2185 case Type::FunctionNoProto: { 2186 const FunctionType *FnType = cast<FunctionType>(T); 2187 T = FnType->getReturnType().getTypePtr(); 2188 continue; 2189 } 2190 2191 // -- If T is a pointer to a member function of a class X, its 2192 // associated namespaces and classes are those associated 2193 // with the function parameter types and return type, 2194 // together with those associated with X. 2195 // 2196 // -- If T is a pointer to a data member of class X, its 2197 // associated namespaces and classes are those associated 2198 // with the member type together with those associated with 2199 // X. 2200 case Type::MemberPointer: { 2201 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 2202 2203 // Queue up the class type into which this points. 2204 Queue.push_back(MemberPtr->getClass()); 2205 2206 // And directly continue with the pointee type. 2207 T = MemberPtr->getPointeeType().getTypePtr(); 2208 continue; 2209 } 2210 2211 // As an extension, treat this like a normal pointer. 2212 case Type::BlockPointer: 2213 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 2214 continue; 2215 2216 // References aren't covered by the standard, but that's such an 2217 // obvious defect that we cover them anyway. 2218 case Type::LValueReference: 2219 case Type::RValueReference: 2220 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 2221 continue; 2222 2223 // These are fundamental types. 2224 case Type::Vector: 2225 case Type::ExtVector: 2226 case Type::Complex: 2227 break; 2228 2229 // Non-deduced auto types only get here for error cases. 2230 case Type::Auto: 2231 break; 2232 2233 // If T is an Objective-C object or interface type, or a pointer to an 2234 // object or interface type, the associated namespace is the global 2235 // namespace. 2236 case Type::ObjCObject: 2237 case Type::ObjCInterface: 2238 case Type::ObjCObjectPointer: 2239 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); 2240 break; 2241 2242 // Atomic types are just wrappers; use the associations of the 2243 // contained type. 2244 case Type::Atomic: 2245 T = cast<AtomicType>(T)->getValueType().getTypePtr(); 2246 continue; 2247 } 2248 2249 if (Queue.empty()) 2250 break; 2251 T = Queue.pop_back_val(); 2252 } 2253 } 2254 2255 /// \brief Find the associated classes and namespaces for 2256 /// argument-dependent lookup for a call with the given set of 2257 /// arguments. 2258 /// 2259 /// This routine computes the sets of associated classes and associated 2260 /// namespaces searched by argument-dependent lookup 2261 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 2262 void Sema::FindAssociatedClassesAndNamespaces( 2263 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 2264 AssociatedNamespaceSet &AssociatedNamespaces, 2265 AssociatedClassSet &AssociatedClasses) { 2266 AssociatedNamespaces.clear(); 2267 AssociatedClasses.clear(); 2268 2269 AssociatedLookup Result(*this, InstantiationLoc, 2270 AssociatedNamespaces, AssociatedClasses); 2271 2272 // C++ [basic.lookup.koenig]p2: 2273 // For each argument type T in the function call, there is a set 2274 // of zero or more associated namespaces and a set of zero or more 2275 // associated classes to be considered. The sets of namespaces and 2276 // classes is determined entirely by the types of the function 2277 // arguments (and the namespace of any template template 2278 // argument). 2279 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 2280 Expr *Arg = Args[ArgIdx]; 2281 2282 if (Arg->getType() != Context.OverloadTy) { 2283 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 2284 continue; 2285 } 2286 2287 // [...] In addition, if the argument is the name or address of a 2288 // set of overloaded functions and/or function templates, its 2289 // associated classes and namespaces are the union of those 2290 // associated with each of the members of the set: the namespace 2291 // in which the function or function template is defined and the 2292 // classes and namespaces associated with its (non-dependent) 2293 // parameter types and return type. 2294 Arg = Arg->IgnoreParens(); 2295 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) 2296 if (unaryOp->getOpcode() == UO_AddrOf) 2297 Arg = unaryOp->getSubExpr(); 2298 2299 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); 2300 if (!ULE) continue; 2301 2302 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end(); 2303 I != E; ++I) { 2304 // Look through any using declarations to find the underlying function. 2305 FunctionDecl *FDecl = (*I)->getUnderlyingDecl()->getAsFunction(); 2306 2307 // Add the classes and namespaces associated with the parameter 2308 // types and return type of this function. 2309 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 2310 } 2311 } 2312 } 2313 2314 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 2315 SourceLocation Loc, 2316 LookupNameKind NameKind, 2317 RedeclarationKind Redecl) { 2318 LookupResult R(*this, Name, Loc, NameKind, Redecl); 2319 LookupName(R, S); 2320 return R.getAsSingle<NamedDecl>(); 2321 } 2322 2323 /// \brief Find the protocol with the given name, if any. 2324 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 2325 SourceLocation IdLoc, 2326 RedeclarationKind Redecl) { 2327 Decl *D = LookupSingleName(TUScope, II, IdLoc, 2328 LookupObjCProtocolName, Redecl); 2329 return cast_or_null<ObjCProtocolDecl>(D); 2330 } 2331 2332 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2333 QualType T1, QualType T2, 2334 UnresolvedSetImpl &Functions) { 2335 // C++ [over.match.oper]p3: 2336 // -- The set of non-member candidates is the result of the 2337 // unqualified lookup of operator@ in the context of the 2338 // expression according to the usual rules for name lookup in 2339 // unqualified function calls (3.4.2) except that all member 2340 // functions are ignored. 2341 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2342 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 2343 LookupName(Operators, S); 2344 2345 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 2346 Functions.append(Operators.begin(), Operators.end()); 2347 } 2348 2349 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD, 2350 CXXSpecialMember SM, 2351 bool ConstArg, 2352 bool VolatileArg, 2353 bool RValueThis, 2354 bool ConstThis, 2355 bool VolatileThis) { 2356 assert(CanDeclareSpecialMemberFunction(RD) && 2357 "doing special member lookup into record that isn't fully complete"); 2358 RD = RD->getDefinition(); 2359 if (RValueThis || ConstThis || VolatileThis) 2360 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && 2361 "constructors and destructors always have unqualified lvalue this"); 2362 if (ConstArg || VolatileArg) 2363 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && 2364 "parameter-less special members can't have qualified arguments"); 2365 2366 llvm::FoldingSetNodeID ID; 2367 ID.AddPointer(RD); 2368 ID.AddInteger(SM); 2369 ID.AddInteger(ConstArg); 2370 ID.AddInteger(VolatileArg); 2371 ID.AddInteger(RValueThis); 2372 ID.AddInteger(ConstThis); 2373 ID.AddInteger(VolatileThis); 2374 2375 void *InsertPoint; 2376 SpecialMemberOverloadResult *Result = 2377 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); 2378 2379 // This was already cached 2380 if (Result) 2381 return Result; 2382 2383 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>(); 2384 Result = new (Result) SpecialMemberOverloadResult(ID); 2385 SpecialMemberCache.InsertNode(Result, InsertPoint); 2386 2387 if (SM == CXXDestructor) { 2388 if (RD->needsImplicitDestructor()) 2389 DeclareImplicitDestructor(RD); 2390 CXXDestructorDecl *DD = RD->getDestructor(); 2391 assert(DD && "record without a destructor"); 2392 Result->setMethod(DD); 2393 Result->setKind(DD->isDeleted() ? 2394 SpecialMemberOverloadResult::NoMemberOrDeleted : 2395 SpecialMemberOverloadResult::Success); 2396 return Result; 2397 } 2398 2399 // Prepare for overload resolution. Here we construct a synthetic argument 2400 // if necessary and make sure that implicit functions are declared. 2401 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); 2402 DeclarationName Name; 2403 Expr *Arg = 0; 2404 unsigned NumArgs; 2405 2406 QualType ArgType = CanTy; 2407 ExprValueKind VK = VK_LValue; 2408 2409 if (SM == CXXDefaultConstructor) { 2410 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 2411 NumArgs = 0; 2412 if (RD->needsImplicitDefaultConstructor()) 2413 DeclareImplicitDefaultConstructor(RD); 2414 } else { 2415 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { 2416 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 2417 if (RD->needsImplicitCopyConstructor()) 2418 DeclareImplicitCopyConstructor(RD); 2419 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) 2420 DeclareImplicitMoveConstructor(RD); 2421 } else { 2422 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2423 if (RD->needsImplicitCopyAssignment()) 2424 DeclareImplicitCopyAssignment(RD); 2425 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) 2426 DeclareImplicitMoveAssignment(RD); 2427 } 2428 2429 if (ConstArg) 2430 ArgType.addConst(); 2431 if (VolatileArg) 2432 ArgType.addVolatile(); 2433 2434 // This isn't /really/ specified by the standard, but it's implied 2435 // we should be working from an RValue in the case of move to ensure 2436 // that we prefer to bind to rvalue references, and an LValue in the 2437 // case of copy to ensure we don't bind to rvalue references. 2438 // Possibly an XValue is actually correct in the case of move, but 2439 // there is no semantic difference for class types in this restricted 2440 // case. 2441 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) 2442 VK = VK_LValue; 2443 else 2444 VK = VK_RValue; 2445 } 2446 2447 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK); 2448 2449 if (SM != CXXDefaultConstructor) { 2450 NumArgs = 1; 2451 Arg = &FakeArg; 2452 } 2453 2454 // Create the object argument 2455 QualType ThisTy = CanTy; 2456 if (ConstThis) 2457 ThisTy.addConst(); 2458 if (VolatileThis) 2459 ThisTy.addVolatile(); 2460 Expr::Classification Classification = 2461 OpaqueValueExpr(SourceLocation(), ThisTy, 2462 RValueThis ? VK_RValue : VK_LValue).Classify(Context); 2463 2464 // Now we perform lookup on the name we computed earlier and do overload 2465 // resolution. Lookup is only performed directly into the class since there 2466 // will always be a (possibly implicit) declaration to shadow any others. 2467 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal); 2468 DeclContext::lookup_result R = RD->lookup(Name); 2469 assert(!R.empty() && 2470 "lookup for a constructor or assignment operator was empty"); 2471 2472 // Copy the candidates as our processing of them may load new declarations 2473 // from an external source and invalidate lookup_result. 2474 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); 2475 2476 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(), 2477 E = Candidates.end(); 2478 I != E; ++I) { 2479 NamedDecl *Cand = *I; 2480 2481 if (Cand->isInvalidDecl()) 2482 continue; 2483 2484 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) { 2485 // FIXME: [namespace.udecl]p15 says that we should only consider a 2486 // using declaration here if it does not match a declaration in the 2487 // derived class. We do not implement this correctly in other cases 2488 // either. 2489 Cand = U->getTargetDecl(); 2490 2491 if (Cand->isInvalidDecl()) 2492 continue; 2493 } 2494 2495 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) { 2496 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 2497 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy, 2498 Classification, llvm::makeArrayRef(&Arg, NumArgs), 2499 OCS, true); 2500 else 2501 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), 2502 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 2503 } else if (FunctionTemplateDecl *Tmpl = 2504 dyn_cast<FunctionTemplateDecl>(Cand)) { 2505 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 2506 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 2507 RD, 0, ThisTy, Classification, 2508 llvm::makeArrayRef(&Arg, NumArgs), 2509 OCS, true); 2510 else 2511 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 2512 0, llvm::makeArrayRef(&Arg, NumArgs), 2513 OCS, true); 2514 } else { 2515 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl"); 2516 } 2517 } 2518 2519 OverloadCandidateSet::iterator Best; 2520 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) { 2521 case OR_Success: 2522 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 2523 Result->setKind(SpecialMemberOverloadResult::Success); 2524 break; 2525 2526 case OR_Deleted: 2527 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 2528 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 2529 break; 2530 2531 case OR_Ambiguous: 2532 Result->setMethod(0); 2533 Result->setKind(SpecialMemberOverloadResult::Ambiguous); 2534 break; 2535 2536 case OR_No_Viable_Function: 2537 Result->setMethod(0); 2538 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 2539 break; 2540 } 2541 2542 return Result; 2543 } 2544 2545 /// \brief Look up the default constructor for the given class. 2546 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { 2547 SpecialMemberOverloadResult *Result = 2548 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, 2549 false, false); 2550 2551 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2552 } 2553 2554 /// \brief Look up the copying constructor for the given class. 2555 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, 2556 unsigned Quals) { 2557 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2558 "non-const, non-volatile qualifiers for copy ctor arg"); 2559 SpecialMemberOverloadResult *Result = 2560 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, 2561 Quals & Qualifiers::Volatile, false, false, false); 2562 2563 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2564 } 2565 2566 /// \brief Look up the moving constructor for the given class. 2567 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, 2568 unsigned Quals) { 2569 SpecialMemberOverloadResult *Result = 2570 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, 2571 Quals & Qualifiers::Volatile, false, false, false); 2572 2573 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 2574 } 2575 2576 /// \brief Look up the constructors for the given class. 2577 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 2578 // If the implicit constructors have not yet been declared, do so now. 2579 if (CanDeclareSpecialMemberFunction(Class)) { 2580 if (Class->needsImplicitDefaultConstructor()) 2581 DeclareImplicitDefaultConstructor(Class); 2582 if (Class->needsImplicitCopyConstructor()) 2583 DeclareImplicitCopyConstructor(Class); 2584 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) 2585 DeclareImplicitMoveConstructor(Class); 2586 } 2587 2588 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 2589 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 2590 return Class->lookup(Name); 2591 } 2592 2593 /// \brief Look up the copying assignment operator for the given class. 2594 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, 2595 unsigned Quals, bool RValueThis, 2596 unsigned ThisQuals) { 2597 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2598 "non-const, non-volatile qualifiers for copy assignment arg"); 2599 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2600 "non-const, non-volatile qualifiers for copy assignment this"); 2601 SpecialMemberOverloadResult *Result = 2602 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, 2603 Quals & Qualifiers::Volatile, RValueThis, 2604 ThisQuals & Qualifiers::Const, 2605 ThisQuals & Qualifiers::Volatile); 2606 2607 return Result->getMethod(); 2608 } 2609 2610 /// \brief Look up the moving assignment operator for the given class. 2611 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, 2612 unsigned Quals, 2613 bool RValueThis, 2614 unsigned ThisQuals) { 2615 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 2616 "non-const, non-volatile qualifiers for copy assignment this"); 2617 SpecialMemberOverloadResult *Result = 2618 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, 2619 Quals & Qualifiers::Volatile, RValueThis, 2620 ThisQuals & Qualifiers::Const, 2621 ThisQuals & Qualifiers::Volatile); 2622 2623 return Result->getMethod(); 2624 } 2625 2626 /// \brief Look for the destructor of the given class. 2627 /// 2628 /// During semantic analysis, this routine should be used in lieu of 2629 /// CXXRecordDecl::getDestructor(). 2630 /// 2631 /// \returns The destructor for this class. 2632 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 2633 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor, 2634 false, false, false, 2635 false, false)->getMethod()); 2636 } 2637 2638 /// LookupLiteralOperator - Determine which literal operator should be used for 2639 /// a user-defined literal, per C++11 [lex.ext]. 2640 /// 2641 /// Normal overload resolution is not used to select which literal operator to 2642 /// call for a user-defined literal. Look up the provided literal operator name, 2643 /// and filter the results to the appropriate set for the given argument types. 2644 Sema::LiteralOperatorLookupResult 2645 Sema::LookupLiteralOperator(Scope *S, LookupResult &R, 2646 ArrayRef<QualType> ArgTys, 2647 bool AllowRaw, bool AllowTemplate, 2648 bool AllowStringTemplate) { 2649 LookupName(R, S); 2650 assert(R.getResultKind() != LookupResult::Ambiguous && 2651 "literal operator lookup can't be ambiguous"); 2652 2653 // Filter the lookup results appropriately. 2654 LookupResult::Filter F = R.makeFilter(); 2655 2656 bool FoundRaw = false; 2657 bool FoundTemplate = false; 2658 bool FoundStringTemplate = false; 2659 bool FoundExactMatch = false; 2660 2661 while (F.hasNext()) { 2662 Decl *D = F.next(); 2663 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 2664 D = USD->getTargetDecl(); 2665 2666 // If the declaration we found is invalid, skip it. 2667 if (D->isInvalidDecl()) { 2668 F.erase(); 2669 continue; 2670 } 2671 2672 bool IsRaw = false; 2673 bool IsTemplate = false; 2674 bool IsStringTemplate = false; 2675 bool IsExactMatch = false; 2676 2677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2678 if (FD->getNumParams() == 1 && 2679 FD->getParamDecl(0)->getType()->getAs<PointerType>()) 2680 IsRaw = true; 2681 else if (FD->getNumParams() == ArgTys.size()) { 2682 IsExactMatch = true; 2683 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { 2684 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); 2685 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { 2686 IsExactMatch = false; 2687 break; 2688 } 2689 } 2690 } 2691 } 2692 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) { 2693 TemplateParameterList *Params = FD->getTemplateParameters(); 2694 if (Params->size() == 1) 2695 IsTemplate = true; 2696 else 2697 IsStringTemplate = true; 2698 } 2699 2700 if (IsExactMatch) { 2701 FoundExactMatch = true; 2702 AllowRaw = false; 2703 AllowTemplate = false; 2704 AllowStringTemplate = false; 2705 if (FoundRaw || FoundTemplate || FoundStringTemplate) { 2706 // Go through again and remove the raw and template decls we've 2707 // already found. 2708 F.restart(); 2709 FoundRaw = FoundTemplate = FoundStringTemplate = false; 2710 } 2711 } else if (AllowRaw && IsRaw) { 2712 FoundRaw = true; 2713 } else if (AllowTemplate && IsTemplate) { 2714 FoundTemplate = true; 2715 } else if (AllowStringTemplate && IsStringTemplate) { 2716 FoundStringTemplate = true; 2717 } else { 2718 F.erase(); 2719 } 2720 } 2721 2722 F.done(); 2723 2724 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching 2725 // parameter type, that is used in preference to a raw literal operator 2726 // or literal operator template. 2727 if (FoundExactMatch) 2728 return LOLR_Cooked; 2729 2730 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal 2731 // operator template, but not both. 2732 if (FoundRaw && FoundTemplate) { 2733 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 2734 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 2735 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction()); 2736 return LOLR_Error; 2737 } 2738 2739 if (FoundRaw) 2740 return LOLR_Raw; 2741 2742 if (FoundTemplate) 2743 return LOLR_Template; 2744 2745 if (FoundStringTemplate) 2746 return LOLR_StringTemplate; 2747 2748 // Didn't find anything we could use. 2749 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) 2750 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] 2751 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw 2752 << (AllowTemplate || AllowStringTemplate); 2753 return LOLR_Error; 2754 } 2755 2756 void ADLResult::insert(NamedDecl *New) { 2757 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 2758 2759 // If we haven't yet seen a decl for this key, or the last decl 2760 // was exactly this one, we're done. 2761 if (Old == 0 || Old == New) { 2762 Old = New; 2763 return; 2764 } 2765 2766 // Otherwise, decide which is a more recent redeclaration. 2767 FunctionDecl *OldFD = Old->getAsFunction(); 2768 FunctionDecl *NewFD = New->getAsFunction(); 2769 2770 FunctionDecl *Cursor = NewFD; 2771 while (true) { 2772 Cursor = Cursor->getPreviousDecl(); 2773 2774 // If we got to the end without finding OldFD, OldFD is the newer 2775 // declaration; leave things as they are. 2776 if (!Cursor) return; 2777 2778 // If we do find OldFD, then NewFD is newer. 2779 if (Cursor == OldFD) break; 2780 2781 // Otherwise, keep looking. 2782 } 2783 2784 Old = New; 2785 } 2786 2787 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 2788 ArrayRef<Expr *> Args, ADLResult &Result) { 2789 // Find all of the associated namespaces and classes based on the 2790 // arguments we have. 2791 AssociatedNamespaceSet AssociatedNamespaces; 2792 AssociatedClassSet AssociatedClasses; 2793 FindAssociatedClassesAndNamespaces(Loc, Args, 2794 AssociatedNamespaces, 2795 AssociatedClasses); 2796 2797 // C++ [basic.lookup.argdep]p3: 2798 // Let X be the lookup set produced by unqualified lookup (3.4.1) 2799 // and let Y be the lookup set produced by argument dependent 2800 // lookup (defined as follows). If X contains [...] then Y is 2801 // empty. Otherwise Y is the set of declarations found in the 2802 // namespaces associated with the argument types as described 2803 // below. The set of declarations found by the lookup of the name 2804 // is the union of X and Y. 2805 // 2806 // Here, we compute Y and add its members to the overloaded 2807 // candidate set. 2808 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), 2809 NSEnd = AssociatedNamespaces.end(); 2810 NS != NSEnd; ++NS) { 2811 // When considering an associated namespace, the lookup is the 2812 // same as the lookup performed when the associated namespace is 2813 // used as a qualifier (3.4.3.2) except that: 2814 // 2815 // -- Any using-directives in the associated namespace are 2816 // ignored. 2817 // 2818 // -- Any namespace-scope friend functions declared in 2819 // associated classes are visible within their respective 2820 // namespaces even if they are not visible during an ordinary 2821 // lookup (11.4). 2822 DeclContext::lookup_result R = (*NS)->lookup(Name); 2823 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 2824 ++I) { 2825 NamedDecl *D = *I; 2826 // If the only declaration here is an ordinary friend, consider 2827 // it only if it was declared in an associated classes. 2828 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) { 2829 // If it's neither ordinarily visible nor a friend, we can't find it. 2830 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0) 2831 continue; 2832 2833 bool DeclaredInAssociatedClass = false; 2834 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) { 2835 DeclContext *LexDC = DI->getLexicalDeclContext(); 2836 if (isa<CXXRecordDecl>(LexDC) && 2837 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) { 2838 DeclaredInAssociatedClass = true; 2839 break; 2840 } 2841 } 2842 if (!DeclaredInAssociatedClass) 2843 continue; 2844 } 2845 2846 if (isa<UsingShadowDecl>(D)) 2847 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2848 2849 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) 2850 continue; 2851 2852 Result.insert(D); 2853 } 2854 } 2855 } 2856 2857 //---------------------------------------------------------------------------- 2858 // Search for all visible declarations. 2859 //---------------------------------------------------------------------------- 2860 VisibleDeclConsumer::~VisibleDeclConsumer() { } 2861 2862 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } 2863 2864 namespace { 2865 2866 class ShadowContextRAII; 2867 2868 class VisibleDeclsRecord { 2869 public: 2870 /// \brief An entry in the shadow map, which is optimized to store a 2871 /// single declaration (the common case) but can also store a list 2872 /// of declarations. 2873 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; 2874 2875 private: 2876 /// \brief A mapping from declaration names to the declarations that have 2877 /// this name within a particular scope. 2878 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 2879 2880 /// \brief A list of shadow maps, which is used to model name hiding. 2881 std::list<ShadowMap> ShadowMaps; 2882 2883 /// \brief The declaration contexts we have already visited. 2884 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 2885 2886 friend class ShadowContextRAII; 2887 2888 public: 2889 /// \brief Determine whether we have already visited this context 2890 /// (and, if not, note that we are going to visit that context now). 2891 bool visitedContext(DeclContext *Ctx) { 2892 return !VisitedContexts.insert(Ctx); 2893 } 2894 2895 bool alreadyVisitedContext(DeclContext *Ctx) { 2896 return VisitedContexts.count(Ctx); 2897 } 2898 2899 /// \brief Determine whether the given declaration is hidden in the 2900 /// current scope. 2901 /// 2902 /// \returns the declaration that hides the given declaration, or 2903 /// NULL if no such declaration exists. 2904 NamedDecl *checkHidden(NamedDecl *ND); 2905 2906 /// \brief Add a declaration to the current shadow map. 2907 void add(NamedDecl *ND) { 2908 ShadowMaps.back()[ND->getDeclName()].push_back(ND); 2909 } 2910 }; 2911 2912 /// \brief RAII object that records when we've entered a shadow context. 2913 class ShadowContextRAII { 2914 VisibleDeclsRecord &Visible; 2915 2916 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 2917 2918 public: 2919 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 2920 Visible.ShadowMaps.push_back(ShadowMap()); 2921 } 2922 2923 ~ShadowContextRAII() { 2924 Visible.ShadowMaps.pop_back(); 2925 } 2926 }; 2927 2928 } // end anonymous namespace 2929 2930 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 2931 // Look through using declarations. 2932 ND = ND->getUnderlyingDecl(); 2933 2934 unsigned IDNS = ND->getIdentifierNamespace(); 2935 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 2936 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 2937 SM != SMEnd; ++SM) { 2938 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 2939 if (Pos == SM->end()) 2940 continue; 2941 2942 for (ShadowMapEntry::iterator I = Pos->second.begin(), 2943 IEnd = Pos->second.end(); 2944 I != IEnd; ++I) { 2945 // A tag declaration does not hide a non-tag declaration. 2946 if ((*I)->hasTagIdentifierNamespace() && 2947 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 2948 Decl::IDNS_ObjCProtocol))) 2949 continue; 2950 2951 // Protocols are in distinct namespaces from everything else. 2952 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 2953 || (IDNS & Decl::IDNS_ObjCProtocol)) && 2954 (*I)->getIdentifierNamespace() != IDNS) 2955 continue; 2956 2957 // Functions and function templates in the same scope overload 2958 // rather than hide. FIXME: Look for hiding based on function 2959 // signatures! 2960 if ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 2961 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 2962 SM == ShadowMaps.rbegin()) 2963 continue; 2964 2965 // We've found a declaration that hides this one. 2966 return *I; 2967 } 2968 } 2969 2970 return 0; 2971 } 2972 2973 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, 2974 bool QualifiedNameLookup, 2975 bool InBaseClass, 2976 VisibleDeclConsumer &Consumer, 2977 VisibleDeclsRecord &Visited) { 2978 if (!Ctx) 2979 return; 2980 2981 // Make sure we don't visit the same context twice. 2982 if (Visited.visitedContext(Ctx->getPrimaryContext())) 2983 return; 2984 2985 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 2986 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 2987 2988 // Enumerate all of the results in this context. 2989 for (const auto &R : Ctx->lookups()) { 2990 for (auto *I : R) { 2991 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) { 2992 if ((ND = Result.getAcceptableDecl(ND))) { 2993 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 2994 Visited.add(ND); 2995 } 2996 } 2997 } 2998 } 2999 3000 // Traverse using directives for qualified name lookup. 3001 if (QualifiedNameLookup) { 3002 ShadowContextRAII Shadow(Visited); 3003 for (auto I : Ctx->using_directives()) { 3004 LookupVisibleDecls(I->getNominatedNamespace(), Result, 3005 QualifiedNameLookup, InBaseClass, Consumer, Visited); 3006 } 3007 } 3008 3009 // Traverse the contexts of inherited C++ classes. 3010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 3011 if (!Record->hasDefinition()) 3012 return; 3013 3014 for (const auto &B : Record->bases()) { 3015 QualType BaseType = B.getType(); 3016 3017 // Don't look into dependent bases, because name lookup can't look 3018 // there anyway. 3019 if (BaseType->isDependentType()) 3020 continue; 3021 3022 const RecordType *Record = BaseType->getAs<RecordType>(); 3023 if (!Record) 3024 continue; 3025 3026 // FIXME: It would be nice to be able to determine whether referencing 3027 // a particular member would be ambiguous. For example, given 3028 // 3029 // struct A { int member; }; 3030 // struct B { int member; }; 3031 // struct C : A, B { }; 3032 // 3033 // void f(C *c) { c->### } 3034 // 3035 // accessing 'member' would result in an ambiguity. However, we 3036 // could be smart enough to qualify the member with the base 3037 // class, e.g., 3038 // 3039 // c->B::member 3040 // 3041 // or 3042 // 3043 // c->A::member 3044 3045 // Find results in this base class (and its bases). 3046 ShadowContextRAII Shadow(Visited); 3047 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, 3048 true, Consumer, Visited); 3049 } 3050 } 3051 3052 // Traverse the contexts of Objective-C classes. 3053 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 3054 // Traverse categories. 3055 for (auto *Cat : IFace->visible_categories()) { 3056 ShadowContextRAII Shadow(Visited); 3057 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, 3058 Consumer, Visited); 3059 } 3060 3061 // Traverse protocols. 3062 for (auto *I : IFace->all_referenced_protocols()) { 3063 ShadowContextRAII Shadow(Visited); 3064 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 3065 Visited); 3066 } 3067 3068 // Traverse the superclass. 3069 if (IFace->getSuperClass()) { 3070 ShadowContextRAII Shadow(Visited); 3071 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, 3072 true, Consumer, Visited); 3073 } 3074 3075 // If there is an implementation, traverse it. We do this to find 3076 // synthesized ivars. 3077 if (IFace->getImplementation()) { 3078 ShadowContextRAII Shadow(Visited); 3079 LookupVisibleDecls(IFace->getImplementation(), Result, 3080 QualifiedNameLookup, InBaseClass, Consumer, Visited); 3081 } 3082 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 3083 for (auto *I : Protocol->protocols()) { 3084 ShadowContextRAII Shadow(Visited); 3085 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 3086 Visited); 3087 } 3088 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 3089 for (auto *I : Category->protocols()) { 3090 ShadowContextRAII Shadow(Visited); 3091 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 3092 Visited); 3093 } 3094 3095 // If there is an implementation, traverse it. 3096 if (Category->getImplementation()) { 3097 ShadowContextRAII Shadow(Visited); 3098 LookupVisibleDecls(Category->getImplementation(), Result, 3099 QualifiedNameLookup, true, Consumer, Visited); 3100 } 3101 } 3102 } 3103 3104 static void LookupVisibleDecls(Scope *S, LookupResult &Result, 3105 UnqualUsingDirectiveSet &UDirs, 3106 VisibleDeclConsumer &Consumer, 3107 VisibleDeclsRecord &Visited) { 3108 if (!S) 3109 return; 3110 3111 if (!S->getEntity() || 3112 (!S->getParent() && 3113 !Visited.alreadyVisitedContext(S->getEntity())) || 3114 (S->getEntity())->isFunctionOrMethod()) { 3115 FindLocalExternScope FindLocals(Result); 3116 // Walk through the declarations in this Scope. 3117 for (auto *D : S->decls()) { 3118 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3119 if ((ND = Result.getAcceptableDecl(ND))) { 3120 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false); 3121 Visited.add(ND); 3122 } 3123 } 3124 } 3125 3126 // FIXME: C++ [temp.local]p8 3127 DeclContext *Entity = 0; 3128 if (S->getEntity()) { 3129 // Look into this scope's declaration context, along with any of its 3130 // parent lookup contexts (e.g., enclosing classes), up to the point 3131 // where we hit the context stored in the next outer scope. 3132 Entity = S->getEntity(); 3133 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME 3134 3135 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 3136 Ctx = Ctx->getLookupParent()) { 3137 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 3138 if (Method->isInstanceMethod()) { 3139 // For instance methods, look for ivars in the method's interface. 3140 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 3141 Result.getNameLoc(), Sema::LookupMemberName); 3142 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { 3143 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 3144 /*InBaseClass=*/false, Consumer, Visited); 3145 } 3146 } 3147 3148 // We've already performed all of the name lookup that we need 3149 // to for Objective-C methods; the next context will be the 3150 // outer scope. 3151 break; 3152 } 3153 3154 if (Ctx->isFunctionOrMethod()) 3155 continue; 3156 3157 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 3158 /*InBaseClass=*/false, Consumer, Visited); 3159 } 3160 } else if (!S->getParent()) { 3161 // Look into the translation unit scope. We walk through the translation 3162 // unit's declaration context, because the Scope itself won't have all of 3163 // the declarations if we loaded a precompiled header. 3164 // FIXME: We would like the translation unit's Scope object to point to the 3165 // translation unit, so we don't need this special "if" branch. However, 3166 // doing so would force the normal C++ name-lookup code to look into the 3167 // translation unit decl when the IdentifierInfo chains would suffice. 3168 // Once we fix that problem (which is part of a more general "don't look 3169 // in DeclContexts unless we have to" optimization), we can eliminate this. 3170 Entity = Result.getSema().Context.getTranslationUnitDecl(); 3171 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 3172 /*InBaseClass=*/false, Consumer, Visited); 3173 } 3174 3175 if (Entity) { 3176 // Lookup visible declarations in any namespaces found by using 3177 // directives. 3178 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 3179 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity); 3180 for (; UI != UEnd; ++UI) 3181 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()), 3182 Result, /*QualifiedNameLookup=*/false, 3183 /*InBaseClass=*/false, Consumer, Visited); 3184 } 3185 3186 // Lookup names in the parent scope. 3187 ShadowContextRAII Shadow(Visited); 3188 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited); 3189 } 3190 3191 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 3192 VisibleDeclConsumer &Consumer, 3193 bool IncludeGlobalScope) { 3194 // Determine the set of using directives available during 3195 // unqualified name lookup. 3196 Scope *Initial = S; 3197 UnqualUsingDirectiveSet UDirs; 3198 if (getLangOpts().CPlusPlus) { 3199 // Find the first namespace or translation-unit scope. 3200 while (S && !isNamespaceOrTranslationUnitScope(S)) 3201 S = S->getParent(); 3202 3203 UDirs.visitScopeChain(Initial, S); 3204 } 3205 UDirs.done(); 3206 3207 // Look for visible declarations. 3208 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 3209 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3210 VisibleDeclsRecord Visited; 3211 if (!IncludeGlobalScope) 3212 Visited.visitedContext(Context.getTranslationUnitDecl()); 3213 ShadowContextRAII Shadow(Visited); 3214 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited); 3215 } 3216 3217 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 3218 VisibleDeclConsumer &Consumer, 3219 bool IncludeGlobalScope) { 3220 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 3221 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3222 VisibleDeclsRecord Visited; 3223 if (!IncludeGlobalScope) 3224 Visited.visitedContext(Context.getTranslationUnitDecl()); 3225 ShadowContextRAII Shadow(Visited); 3226 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 3227 /*InBaseClass=*/false, Consumer, Visited); 3228 } 3229 3230 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 3231 /// If GnuLabelLoc is a valid source location, then this is a definition 3232 /// of an __label__ label name, otherwise it is a normal label definition 3233 /// or use. 3234 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, 3235 SourceLocation GnuLabelLoc) { 3236 // Do a lookup to see if we have a label with this name already. 3237 NamedDecl *Res = 0; 3238 3239 if (GnuLabelLoc.isValid()) { 3240 // Local label definitions always shadow existing labels. 3241 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); 3242 Scope *S = CurScope; 3243 PushOnScopeChains(Res, S, true); 3244 return cast<LabelDecl>(Res); 3245 } 3246 3247 // Not a GNU local label. 3248 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); 3249 // If we found a label, check to see if it is in the same context as us. 3250 // When in a Block, we don't want to reuse a label in an enclosing function. 3251 if (Res && Res->getDeclContext() != CurContext) 3252 Res = 0; 3253 if (Res == 0) { 3254 // If not forward referenced or defined already, create the backing decl. 3255 Res = LabelDecl::Create(Context, CurContext, Loc, II); 3256 Scope *S = CurScope->getFnParent(); 3257 assert(S && "Not in a function?"); 3258 PushOnScopeChains(Res, S, true); 3259 } 3260 return cast<LabelDecl>(Res); 3261 } 3262 3263 //===----------------------------------------------------------------------===// 3264 // Typo correction 3265 //===----------------------------------------------------------------------===// 3266 3267 namespace { 3268 3269 typedef SmallVector<TypoCorrection, 1> TypoResultList; 3270 typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap; 3271 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap; 3272 3273 static const unsigned MaxTypoDistanceResultSets = 5; 3274 3275 class TypoCorrectionConsumer : public VisibleDeclConsumer { 3276 /// \brief The name written that is a typo in the source. 3277 StringRef Typo; 3278 3279 /// \brief The results found that have the smallest edit distance 3280 /// found (so far) with the typo name. 3281 /// 3282 /// The pointer value being set to the current DeclContext indicates 3283 /// whether there is a keyword with this name. 3284 TypoEditDistanceMap CorrectionResults; 3285 3286 Sema &SemaRef; 3287 3288 public: 3289 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo) 3290 : Typo(Typo->getName()), 3291 SemaRef(SemaRef) {} 3292 3293 bool includeHiddenDecls() const override { return true; } 3294 3295 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 3296 bool InBaseClass) override; 3297 void FoundName(StringRef Name); 3298 void addKeywordResult(StringRef Keyword); 3299 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL, 3300 bool isKeyword = false); 3301 void addCorrection(TypoCorrection Correction); 3302 3303 typedef TypoResultsMap::iterator result_iterator; 3304 typedef TypoEditDistanceMap::iterator distance_iterator; 3305 distance_iterator begin() { return CorrectionResults.begin(); } 3306 distance_iterator end() { return CorrectionResults.end(); } 3307 void erase(distance_iterator I) { CorrectionResults.erase(I); } 3308 unsigned size() const { return CorrectionResults.size(); } 3309 bool empty() const { return CorrectionResults.empty(); } 3310 3311 TypoResultList &operator[](StringRef Name) { 3312 return CorrectionResults.begin()->second[Name]; 3313 } 3314 3315 unsigned getBestEditDistance(bool Normalized) { 3316 if (CorrectionResults.empty()) 3317 return (std::numeric_limits<unsigned>::max)(); 3318 3319 unsigned BestED = CorrectionResults.begin()->first; 3320 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED; 3321 } 3322 3323 TypoResultsMap &getBestResults() { 3324 return CorrectionResults.begin()->second; 3325 } 3326 3327 }; 3328 3329 } 3330 3331 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 3332 DeclContext *Ctx, bool InBaseClass) { 3333 // Don't consider hidden names for typo correction. 3334 if (Hiding) 3335 return; 3336 3337 // Only consider entities with identifiers for names, ignoring 3338 // special names (constructors, overloaded operators, selectors, 3339 // etc.). 3340 IdentifierInfo *Name = ND->getIdentifier(); 3341 if (!Name) 3342 return; 3343 3344 // Only consider visible declarations and declarations from modules with 3345 // names that exactly match. 3346 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo && 3347 !findAcceptableDecl(SemaRef, ND)) 3348 return; 3349 3350 FoundName(Name->getName()); 3351 } 3352 3353 void TypoCorrectionConsumer::FoundName(StringRef Name) { 3354 // Compute the edit distance between the typo and the name of this 3355 // entity, and add the identifier to the list of results. 3356 addName(Name, NULL); 3357 } 3358 3359 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { 3360 // Compute the edit distance between the typo and this keyword, 3361 // and add the keyword to the list of results. 3362 addName(Keyword, NULL, NULL, true); 3363 } 3364 3365 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, 3366 NestedNameSpecifier *NNS, bool isKeyword) { 3367 // Use a simple length-based heuristic to determine the minimum possible 3368 // edit distance. If the minimum isn't good enough, bail out early. 3369 unsigned MinED = abs((int)Name.size() - (int)Typo.size()); 3370 if (MinED && Typo.size() / MinED < 3) 3371 return; 3372 3373 // Compute an upper bound on the allowable edit distance, so that the 3374 // edit-distance algorithm can short-circuit. 3375 unsigned UpperBound = (Typo.size() + 2) / 3 + 1; 3376 unsigned ED = Typo.edit_distance(Name, true, UpperBound); 3377 if (ED >= UpperBound) return; 3378 3379 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); 3380 if (isKeyword) TC.makeKeyword(); 3381 addCorrection(TC); 3382 } 3383 3384 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { 3385 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); 3386 TypoResultList &CList = 3387 CorrectionResults[Correction.getEditDistance(false)][Name]; 3388 3389 if (!CList.empty() && !CList.back().isResolved()) 3390 CList.pop_back(); 3391 if (NamedDecl *NewND = Correction.getCorrectionDecl()) { 3392 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts()); 3393 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end(); 3394 RI != RIEnd; ++RI) { 3395 // If the Correction refers to a decl already in the result list, 3396 // replace the existing result if the string representation of Correction 3397 // comes before the current result alphabetically, then stop as there is 3398 // nothing more to be done to add Correction to the candidate set. 3399 if (RI->getCorrectionDecl() == NewND) { 3400 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts())) 3401 *RI = Correction; 3402 return; 3403 } 3404 } 3405 } 3406 if (CList.empty() || Correction.isResolved()) 3407 CList.push_back(Correction); 3408 3409 while (CorrectionResults.size() > MaxTypoDistanceResultSets) 3410 erase(std::prev(CorrectionResults.end())); 3411 } 3412 3413 // Fill the supplied vector with the IdentifierInfo pointers for each piece of 3414 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", 3415 // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). 3416 static void getNestedNameSpecifierIdentifiers( 3417 NestedNameSpecifier *NNS, 3418 SmallVectorImpl<const IdentifierInfo*> &Identifiers) { 3419 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) 3420 getNestedNameSpecifierIdentifiers(Prefix, Identifiers); 3421 else 3422 Identifiers.clear(); 3423 3424 const IdentifierInfo *II = NULL; 3425 3426 switch (NNS->getKind()) { 3427 case NestedNameSpecifier::Identifier: 3428 II = NNS->getAsIdentifier(); 3429 break; 3430 3431 case NestedNameSpecifier::Namespace: 3432 if (NNS->getAsNamespace()->isAnonymousNamespace()) 3433 return; 3434 II = NNS->getAsNamespace()->getIdentifier(); 3435 break; 3436 3437 case NestedNameSpecifier::NamespaceAlias: 3438 II = NNS->getAsNamespaceAlias()->getIdentifier(); 3439 break; 3440 3441 case NestedNameSpecifier::TypeSpecWithTemplate: 3442 case NestedNameSpecifier::TypeSpec: 3443 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); 3444 break; 3445 3446 case NestedNameSpecifier::Global: 3447 return; 3448 } 3449 3450 if (II) 3451 Identifiers.push_back(II); 3452 } 3453 3454 namespace { 3455 3456 class SpecifierInfo { 3457 public: 3458 DeclContext* DeclCtx; 3459 NestedNameSpecifier* NameSpecifier; 3460 unsigned EditDistance; 3461 3462 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED) 3463 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {} 3464 }; 3465 3466 typedef SmallVector<DeclContext*, 4> DeclContextList; 3467 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList; 3468 3469 class NamespaceSpecifierSet { 3470 ASTContext &Context; 3471 DeclContextList CurContextChain; 3472 std::string CurNameSpecifier; 3473 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers; 3474 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers; 3475 bool isSorted; 3476 3477 SpecifierInfoList Specifiers; 3478 llvm::SmallSetVector<unsigned, 4> Distances; 3479 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap; 3480 3481 /// \brief Helper for building the list of DeclContexts between the current 3482 /// context and the top of the translation unit 3483 static DeclContextList BuildContextChain(DeclContext *Start); 3484 3485 void SortNamespaces(); 3486 3487 public: 3488 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext, 3489 CXXScopeSpec *CurScopeSpec) 3490 : Context(Context), CurContextChain(BuildContextChain(CurContext)), 3491 isSorted(false) { 3492 if (NestedNameSpecifier *NNS = 3493 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) { 3494 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); 3495 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 3496 3497 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers); 3498 } 3499 // Build the list of identifiers that would be used for an absolute 3500 // (from the global context) NestedNameSpecifier referring to the current 3501 // context. 3502 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3503 CEnd = CurContextChain.rend(); 3504 C != CEnd; ++C) { 3505 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) 3506 CurContextIdentifiers.push_back(ND->getIdentifier()); 3507 } 3508 3509 // Add the global context as a NestedNameSpecifier 3510 Distances.insert(1); 3511 DistanceMap[1].push_back( 3512 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()), 3513 NestedNameSpecifier::GlobalSpecifier(Context), 1)); 3514 } 3515 3516 /// \brief Add the DeclContext (a namespace or record) to the set, computing 3517 /// the corresponding NestedNameSpecifier and its distance in the process. 3518 void AddNameSpecifier(DeclContext *Ctx); 3519 3520 typedef SpecifierInfoList::iterator iterator; 3521 iterator begin() { 3522 if (!isSorted) SortNamespaces(); 3523 return Specifiers.begin(); 3524 } 3525 iterator end() { return Specifiers.end(); } 3526 }; 3527 3528 } 3529 3530 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) { 3531 assert(Start && "Building a context chain from a null context"); 3532 DeclContextList Chain; 3533 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL; 3534 DC = DC->getLookupParent()) { 3535 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); 3536 if (!DC->isInlineNamespace() && !DC->isTransparentContext() && 3537 !(ND && ND->isAnonymousNamespace())) 3538 Chain.push_back(DC->getPrimaryContext()); 3539 } 3540 return Chain; 3541 } 3542 3543 void NamespaceSpecifierSet::SortNamespaces() { 3544 SmallVector<unsigned, 4> sortedDistances; 3545 sortedDistances.append(Distances.begin(), Distances.end()); 3546 3547 if (sortedDistances.size() > 1) 3548 std::sort(sortedDistances.begin(), sortedDistances.end()); 3549 3550 Specifiers.clear(); 3551 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(), 3552 DIEnd = sortedDistances.end(); 3553 DI != DIEnd; ++DI) { 3554 SpecifierInfoList &SpecList = DistanceMap[*DI]; 3555 Specifiers.append(SpecList.begin(), SpecList.end()); 3556 } 3557 3558 isSorted = true; 3559 } 3560 3561 static unsigned BuildNestedNameSpecifier(ASTContext &Context, 3562 DeclContextList &DeclChain, 3563 NestedNameSpecifier *&NNS) { 3564 unsigned NumSpecifiers = 0; 3565 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(), 3566 CEnd = DeclChain.rend(); 3567 C != CEnd; ++C) { 3568 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) { 3569 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 3570 ++NumSpecifiers; 3571 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) { 3572 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), 3573 RD->getTypeForDecl()); 3574 ++NumSpecifiers; 3575 } 3576 } 3577 return NumSpecifiers; 3578 } 3579 3580 void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) { 3581 NestedNameSpecifier *NNS = NULL; 3582 unsigned NumSpecifiers = 0; 3583 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx)); 3584 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 3585 3586 // Eliminate common elements from the two DeclContext chains. 3587 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 3588 CEnd = CurContextChain.rend(); 3589 C != CEnd && !NamespaceDeclChain.empty() && 3590 NamespaceDeclChain.back() == *C; ++C) { 3591 NamespaceDeclChain.pop_back(); 3592 } 3593 3594 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 3595 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS); 3596 3597 // Add an explicit leading '::' specifier if needed. 3598 if (NamespaceDeclChain.empty()) { 3599 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 3600 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3601 NumSpecifiers = 3602 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS); 3603 } else if (NamedDecl *ND = 3604 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) { 3605 IdentifierInfo *Name = ND->getIdentifier(); 3606 bool SameNameSpecifier = false; 3607 if (std::find(CurNameSpecifierIdentifiers.begin(), 3608 CurNameSpecifierIdentifiers.end(), 3609 Name) != CurNameSpecifierIdentifiers.end()) { 3610 std::string NewNameSpecifier; 3611 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); 3612 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; 3613 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 3614 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 3615 SpecifierOStream.flush(); 3616 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; 3617 } 3618 if (SameNameSpecifier || 3619 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(), 3620 Name) != CurContextIdentifiers.end()) { 3621 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 3622 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 3623 NumSpecifiers = 3624 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS); 3625 } 3626 } 3627 3628 // If the built NestedNameSpecifier would be replacing an existing 3629 // NestedNameSpecifier, use the number of component identifiers that 3630 // would need to be changed as the edit distance instead of the number 3631 // of components in the built NestedNameSpecifier. 3632 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 3633 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 3634 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 3635 NumSpecifiers = llvm::ComputeEditDistance( 3636 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers), 3637 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers)); 3638 } 3639 3640 isSorted = false; 3641 Distances.insert(NumSpecifiers); 3642 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers)); 3643 } 3644 3645 /// \brief Perform name lookup for a possible result for typo correction. 3646 static void LookupPotentialTypoResult(Sema &SemaRef, 3647 LookupResult &Res, 3648 IdentifierInfo *Name, 3649 Scope *S, CXXScopeSpec *SS, 3650 DeclContext *MemberContext, 3651 bool EnteringContext, 3652 bool isObjCIvarLookup, 3653 bool FindHidden) { 3654 Res.suppressDiagnostics(); 3655 Res.clear(); 3656 Res.setLookupName(Name); 3657 Res.setAllowHidden(FindHidden); 3658 if (MemberContext) { 3659 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { 3660 if (isObjCIvarLookup) { 3661 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { 3662 Res.addDecl(Ivar); 3663 Res.resolveKind(); 3664 return; 3665 } 3666 } 3667 3668 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) { 3669 Res.addDecl(Prop); 3670 Res.resolveKind(); 3671 return; 3672 } 3673 } 3674 3675 SemaRef.LookupQualifiedName(Res, MemberContext); 3676 return; 3677 } 3678 3679 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 3680 EnteringContext); 3681 3682 // Fake ivar lookup; this should really be part of 3683 // LookupParsedName. 3684 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 3685 if (Method->isInstanceMethod() && Method->getClassInterface() && 3686 (Res.empty() || 3687 (Res.isSingleResult() && 3688 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { 3689 if (ObjCIvarDecl *IV 3690 = Method->getClassInterface()->lookupInstanceVariable(Name)) { 3691 Res.addDecl(IV); 3692 Res.resolveKind(); 3693 } 3694 } 3695 } 3696 } 3697 3698 /// \brief Add keywords to the consumer as possible typo corrections. 3699 static void AddKeywordsToConsumer(Sema &SemaRef, 3700 TypoCorrectionConsumer &Consumer, 3701 Scope *S, CorrectionCandidateCallback &CCC, 3702 bool AfterNestedNameSpecifier) { 3703 if (AfterNestedNameSpecifier) { 3704 // For 'X::', we know exactly which keywords can appear next. 3705 Consumer.addKeywordResult("template"); 3706 if (CCC.WantExpressionKeywords) 3707 Consumer.addKeywordResult("operator"); 3708 return; 3709 } 3710 3711 if (CCC.WantObjCSuper) 3712 Consumer.addKeywordResult("super"); 3713 3714 if (CCC.WantTypeSpecifiers) { 3715 // Add type-specifier keywords to the set of results. 3716 static const char *const CTypeSpecs[] = { 3717 "char", "const", "double", "enum", "float", "int", "long", "short", 3718 "signed", "struct", "union", "unsigned", "void", "volatile", 3719 "_Complex", "_Imaginary", 3720 // storage-specifiers as well 3721 "extern", "inline", "static", "typedef" 3722 }; 3723 3724 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); 3725 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 3726 Consumer.addKeywordResult(CTypeSpecs[I]); 3727 3728 if (SemaRef.getLangOpts().C99) 3729 Consumer.addKeywordResult("restrict"); 3730 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) 3731 Consumer.addKeywordResult("bool"); 3732 else if (SemaRef.getLangOpts().C99) 3733 Consumer.addKeywordResult("_Bool"); 3734 3735 if (SemaRef.getLangOpts().CPlusPlus) { 3736 Consumer.addKeywordResult("class"); 3737 Consumer.addKeywordResult("typename"); 3738 Consumer.addKeywordResult("wchar_t"); 3739 3740 if (SemaRef.getLangOpts().CPlusPlus11) { 3741 Consumer.addKeywordResult("char16_t"); 3742 Consumer.addKeywordResult("char32_t"); 3743 Consumer.addKeywordResult("constexpr"); 3744 Consumer.addKeywordResult("decltype"); 3745 Consumer.addKeywordResult("thread_local"); 3746 } 3747 } 3748 3749 if (SemaRef.getLangOpts().GNUMode) 3750 Consumer.addKeywordResult("typeof"); 3751 } 3752 3753 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { 3754 Consumer.addKeywordResult("const_cast"); 3755 Consumer.addKeywordResult("dynamic_cast"); 3756 Consumer.addKeywordResult("reinterpret_cast"); 3757 Consumer.addKeywordResult("static_cast"); 3758 } 3759 3760 if (CCC.WantExpressionKeywords) { 3761 Consumer.addKeywordResult("sizeof"); 3762 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { 3763 Consumer.addKeywordResult("false"); 3764 Consumer.addKeywordResult("true"); 3765 } 3766 3767 if (SemaRef.getLangOpts().CPlusPlus) { 3768 static const char *const CXXExprs[] = { 3769 "delete", "new", "operator", "throw", "typeid" 3770 }; 3771 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); 3772 for (unsigned I = 0; I != NumCXXExprs; ++I) 3773 Consumer.addKeywordResult(CXXExprs[I]); 3774 3775 if (isa<CXXMethodDecl>(SemaRef.CurContext) && 3776 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) 3777 Consumer.addKeywordResult("this"); 3778 3779 if (SemaRef.getLangOpts().CPlusPlus11) { 3780 Consumer.addKeywordResult("alignof"); 3781 Consumer.addKeywordResult("nullptr"); 3782 } 3783 } 3784 3785 if (SemaRef.getLangOpts().C11) { 3786 // FIXME: We should not suggest _Alignof if the alignof macro 3787 // is present. 3788 Consumer.addKeywordResult("_Alignof"); 3789 } 3790 } 3791 3792 if (CCC.WantRemainingKeywords) { 3793 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { 3794 // Statements. 3795 static const char *const CStmts[] = { 3796 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 3797 const unsigned NumCStmts = llvm::array_lengthof(CStmts); 3798 for (unsigned I = 0; I != NumCStmts; ++I) 3799 Consumer.addKeywordResult(CStmts[I]); 3800 3801 if (SemaRef.getLangOpts().CPlusPlus) { 3802 Consumer.addKeywordResult("catch"); 3803 Consumer.addKeywordResult("try"); 3804 } 3805 3806 if (S && S->getBreakParent()) 3807 Consumer.addKeywordResult("break"); 3808 3809 if (S && S->getContinueParent()) 3810 Consumer.addKeywordResult("continue"); 3811 3812 if (!SemaRef.getCurFunction()->SwitchStack.empty()) { 3813 Consumer.addKeywordResult("case"); 3814 Consumer.addKeywordResult("default"); 3815 } 3816 } else { 3817 if (SemaRef.getLangOpts().CPlusPlus) { 3818 Consumer.addKeywordResult("namespace"); 3819 Consumer.addKeywordResult("template"); 3820 } 3821 3822 if (S && S->isClassScope()) { 3823 Consumer.addKeywordResult("explicit"); 3824 Consumer.addKeywordResult("friend"); 3825 Consumer.addKeywordResult("mutable"); 3826 Consumer.addKeywordResult("private"); 3827 Consumer.addKeywordResult("protected"); 3828 Consumer.addKeywordResult("public"); 3829 Consumer.addKeywordResult("virtual"); 3830 } 3831 } 3832 3833 if (SemaRef.getLangOpts().CPlusPlus) { 3834 Consumer.addKeywordResult("using"); 3835 3836 if (SemaRef.getLangOpts().CPlusPlus11) 3837 Consumer.addKeywordResult("static_assert"); 3838 } 3839 } 3840 } 3841 3842 static bool isCandidateViable(CorrectionCandidateCallback &CCC, 3843 TypoCorrection &Candidate) { 3844 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); 3845 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; 3846 } 3847 3848 /// \brief Check whether the declarations found for a typo correction are 3849 /// visible, and if none of them are, convert the correction to an 'import 3850 /// a module' correction. 3851 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC, 3852 DeclarationName TypoName) { 3853 if (TC.begin() == TC.end()) 3854 return; 3855 3856 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); 3857 3858 for (/**/; DI != DE; ++DI) 3859 if (!LookupResult::isVisible(SemaRef, *DI)) 3860 break; 3861 // Nothing to do if all decls are visible. 3862 if (DI == DE) 3863 return; 3864 3865 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); 3866 bool AnyVisibleDecls = !NewDecls.empty(); 3867 3868 for (/**/; DI != DE; ++DI) { 3869 NamedDecl *VisibleDecl = *DI; 3870 if (!LookupResult::isVisible(SemaRef, *DI)) 3871 VisibleDecl = findAcceptableDecl(SemaRef, *DI); 3872 3873 if (VisibleDecl) { 3874 if (!AnyVisibleDecls) { 3875 // Found a visible decl, discard all hidden ones. 3876 AnyVisibleDecls = true; 3877 NewDecls.clear(); 3878 } 3879 NewDecls.push_back(VisibleDecl); 3880 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) 3881 NewDecls.push_back(*DI); 3882 } 3883 3884 if (NewDecls.empty()) 3885 TC = TypoCorrection(); 3886 else { 3887 TC.setCorrectionDecls(NewDecls); 3888 TC.setRequiresImport(!AnyVisibleDecls); 3889 } 3890 } 3891 3892 /// \brief Try to "correct" a typo in the source code by finding 3893 /// visible declarations whose names are similar to the name that was 3894 /// present in the source code. 3895 /// 3896 /// \param TypoName the \c DeclarationNameInfo structure that contains 3897 /// the name that was present in the source code along with its location. 3898 /// 3899 /// \param LookupKind the name-lookup criteria used to search for the name. 3900 /// 3901 /// \param S the scope in which name lookup occurs. 3902 /// 3903 /// \param SS the nested-name-specifier that precedes the name we're 3904 /// looking for, if present. 3905 /// 3906 /// \param CCC A CorrectionCandidateCallback object that provides further 3907 /// validation of typo correction candidates. It also provides flags for 3908 /// determining the set of keywords permitted. 3909 /// 3910 /// \param MemberContext if non-NULL, the context in which to look for 3911 /// a member access expression. 3912 /// 3913 /// \param EnteringContext whether we're entering the context described by 3914 /// the nested-name-specifier SS. 3915 /// 3916 /// \param OPT when non-NULL, the search for visible declarations will 3917 /// also walk the protocols in the qualified interfaces of \p OPT. 3918 /// 3919 /// \returns a \c TypoCorrection containing the corrected name if the typo 3920 /// along with information such as the \c NamedDecl where the corrected name 3921 /// was declared, and any additional \c NestedNameSpecifier needed to access 3922 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 3923 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, 3924 Sema::LookupNameKind LookupKind, 3925 Scope *S, CXXScopeSpec *SS, 3926 CorrectionCandidateCallback &CCC, 3927 DeclContext *MemberContext, 3928 bool EnteringContext, 3929 const ObjCObjectPointerType *OPT, 3930 bool RecordFailure) { 3931 // Always let the ExternalSource have the first chance at correction, even 3932 // if we would otherwise have given up. 3933 if (ExternalSource) { 3934 if (TypoCorrection Correction = ExternalSource->CorrectTypo( 3935 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT)) 3936 return Correction; 3937 } 3938 3939 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || 3940 DisableTypoCorrection) 3941 return TypoCorrection(); 3942 3943 // In Microsoft mode, don't perform typo correction in a template member 3944 // function dependent context because it interferes with the "lookup into 3945 // dependent bases of class templates" feature. 3946 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 3947 isa<CXXMethodDecl>(CurContext)) 3948 return TypoCorrection(); 3949 3950 // We only attempt to correct typos for identifiers. 3951 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 3952 if (!Typo) 3953 return TypoCorrection(); 3954 3955 // If the scope specifier itself was invalid, don't try to correct 3956 // typos. 3957 if (SS && SS->isInvalid()) 3958 return TypoCorrection(); 3959 3960 // Never try to correct typos during template deduction or 3961 // instantiation. 3962 if (!ActiveTemplateInstantiations.empty()) 3963 return TypoCorrection(); 3964 3965 // Don't try to correct 'super'. 3966 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) 3967 return TypoCorrection(); 3968 3969 // Abort if typo correction already failed for this specific typo. 3970 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo); 3971 if (locs != TypoCorrectionFailures.end() && 3972 locs->second.count(TypoName.getLoc())) 3973 return TypoCorrection(); 3974 3975 // Don't try to correct the identifier "vector" when in AltiVec mode. 3976 // TODO: Figure out why typo correction misbehaves in this case, fix it, and 3977 // remove this workaround. 3978 if (getLangOpts().AltiVec && Typo->isStr("vector")) 3979 return TypoCorrection(); 3980 3981 NamespaceSpecifierSet Namespaces(Context, CurContext, SS); 3982 3983 TypoCorrectionConsumer Consumer(*this, Typo); 3984 3985 // If a callback object considers an empty typo correction candidate to be 3986 // viable, assume it does not do any actual validation of the candidates. 3987 TypoCorrection EmptyCorrection; 3988 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection); 3989 3990 // Perform name lookup to find visible, similarly-named entities. 3991 bool IsUnqualifiedLookup = false; 3992 DeclContext *QualifiedDC = MemberContext; 3993 if (MemberContext) { 3994 LookupVisibleDecls(MemberContext, LookupKind, Consumer); 3995 3996 // Look in qualified interfaces. 3997 if (OPT) { 3998 for (auto *I : OPT->quals()) 3999 LookupVisibleDecls(I, LookupKind, Consumer); 4000 } 4001 } else if (SS && SS->isSet()) { 4002 QualifiedDC = computeDeclContext(*SS, EnteringContext); 4003 if (!QualifiedDC) 4004 return TypoCorrection(); 4005 4006 // Provide a stop gap for files that are just seriously broken. Trying 4007 // to correct all typos can turn into a HUGE performance penalty, causing 4008 // some files to take minutes to get rejected by the parser. 4009 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 4010 return TypoCorrection(); 4011 ++TyposCorrected; 4012 4013 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer); 4014 } else { 4015 IsUnqualifiedLookup = true; 4016 UnqualifiedTyposCorrectedMap::iterator Cached 4017 = UnqualifiedTyposCorrected.find(Typo); 4018 if (Cached != UnqualifiedTyposCorrected.end()) { 4019 // Add the cached value, unless it's a keyword or fails validation. In the 4020 // keyword case, we'll end up adding the keyword below. 4021 if (Cached->second) { 4022 if (!Cached->second.isKeyword() && 4023 isCandidateViable(CCC, Cached->second)) { 4024 // Do not use correction that is unaccessible in the given scope. 4025 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl(); 4026 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(), 4027 CorrectionDecl->getLocation()); 4028 LookupResult R(*this, NameInfo, LookupOrdinaryName); 4029 if (LookupName(R, S)) 4030 Consumer.addCorrection(Cached->second); 4031 } 4032 } else { 4033 // Only honor no-correction cache hits when a callback that will validate 4034 // correction candidates is not being used. 4035 if (!ValidatingCallback) 4036 return TypoCorrection(); 4037 } 4038 } 4039 if (Cached == UnqualifiedTyposCorrected.end()) { 4040 // Provide a stop gap for files that are just seriously broken. Trying 4041 // to correct all typos can turn into a HUGE performance penalty, causing 4042 // some files to take minutes to get rejected by the parser. 4043 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 4044 return TypoCorrection(); 4045 } 4046 } 4047 4048 // Determine whether we are going to search in the various namespaces for 4049 // corrections. 4050 bool SearchNamespaces 4051 = getLangOpts().CPlusPlus && 4052 (IsUnqualifiedLookup || (SS && SS->isSet())); 4053 // In a few cases we *only* want to search for corrections based on just 4054 // adding or changing the nested name specifier. 4055 unsigned TypoLen = Typo->getName().size(); 4056 bool AllowOnlyNNSChanges = TypoLen < 3; 4057 4058 if (IsUnqualifiedLookup || SearchNamespaces) { 4059 // For unqualified lookup, look through all of the names that we have 4060 // seen in this translation unit. 4061 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4062 for (IdentifierTable::iterator I = Context.Idents.begin(), 4063 IEnd = Context.Idents.end(); 4064 I != IEnd; ++I) 4065 Consumer.FoundName(I->getKey()); 4066 4067 // Walk through identifiers in external identifier sources. 4068 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4069 if (IdentifierInfoLookup *External 4070 = Context.Idents.getExternalIdentifierLookup()) { 4071 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 4072 do { 4073 StringRef Name = Iter->Next(); 4074 if (Name.empty()) 4075 break; 4076 4077 Consumer.FoundName(Name); 4078 } while (true); 4079 } 4080 } 4081 4082 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty()); 4083 4084 // If we haven't found anything, we're done. 4085 if (Consumer.empty()) 4086 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4087 IsUnqualifiedLookup); 4088 4089 // Make sure the best edit distance (prior to adding any namespace qualifiers) 4090 // is not more that about a third of the length of the typo's identifier. 4091 unsigned ED = Consumer.getBestEditDistance(true); 4092 if (ED > 0 && TypoLen / ED < 3) 4093 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4094 IsUnqualifiedLookup); 4095 4096 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going 4097 // to search those namespaces. 4098 if (SearchNamespaces) { 4099 // Load any externally-known namespaces. 4100 if (ExternalSource && !LoadedExternalKnownNamespaces) { 4101 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; 4102 LoadedExternalKnownNamespaces = true; 4103 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); 4104 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I) 4105 KnownNamespaces[ExternalKnownNamespaces[I]] = true; 4106 } 4107 4108 for (auto KNPair : KnownNamespaces) 4109 Namespaces.AddNameSpecifier(KNPair.first); 4110 4111 bool SSIsTemplate = false; 4112 if (NestedNameSpecifier *NNS = 4113 (SS && SS->isValid()) ? SS->getScopeRep() : 0) { 4114 if (const Type *T = NNS->getAsType()) 4115 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; 4116 } 4117 for (const auto *TI : Context.types()) { 4118 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { 4119 CD = CD->getCanonicalDecl(); 4120 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && 4121 !CD->isUnion() && CD->getIdentifier() && 4122 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) && 4123 (CD->isBeingDefined() || CD->isCompleteDefinition())) 4124 Namespaces.AddNameSpecifier(CD); 4125 } 4126 } 4127 } 4128 4129 // Weed out any names that could not be found by name lookup or, if a 4130 // CorrectionCandidateCallback object was provided, failed validation. 4131 SmallVector<TypoCorrection, 16> QualifiedResults; 4132 LookupResult TmpRes(*this, TypoName, LookupKind); 4133 TmpRes.suppressDiagnostics(); 4134 while (!Consumer.empty()) { 4135 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin(); 4136 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(), 4137 IEnd = DI->second.end(); 4138 I != IEnd; /* Increment in loop. */) { 4139 // If we only want nested name specifier corrections, ignore potential 4140 // corrections that have a different base identifier from the typo or 4141 // which have a normalized edit distance longer than the typo itself. 4142 if (AllowOnlyNNSChanges) { 4143 TypoCorrection &TC = I->second.front(); 4144 if (TC.getCorrectionAsIdentifierInfo() != Typo || 4145 TC.getEditDistance(true) > TypoLen) { 4146 TypoCorrectionConsumer::result_iterator Prev = I; 4147 ++I; 4148 DI->second.erase(Prev); 4149 continue; 4150 } 4151 } 4152 4153 // If the item already has been looked up or is a keyword, keep it. 4154 // If a validator callback object was given, drop the correction 4155 // unless it passes validation. 4156 bool Viable = false; 4157 for (TypoResultList::iterator RI = I->second.begin(); 4158 RI != I->second.end(); /* Increment in loop. */) { 4159 TypoResultList::iterator Prev = RI; 4160 ++RI; 4161 if (Prev->isResolved()) { 4162 if (!isCandidateViable(CCC, *Prev)) 4163 RI = I->second.erase(Prev); 4164 else 4165 Viable = true; 4166 } 4167 } 4168 if (Viable || I->second.empty()) { 4169 TypoCorrectionConsumer::result_iterator Prev = I; 4170 ++I; 4171 if (!Viable) 4172 DI->second.erase(Prev); 4173 continue; 4174 } 4175 assert(I->second.size() == 1 && "Expected a single unresolved candidate"); 4176 4177 // Perform name lookup on this name. 4178 TypoCorrection &Candidate = I->second.front(); 4179 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); 4180 DeclContext *TempMemberContext = MemberContext; 4181 CXXScopeSpec *TempSS = SS; 4182 retry_lookup: 4183 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS, 4184 TempMemberContext, EnteringContext, 4185 CCC.IsObjCIvarLookup, 4186 Name == TypoName.getName() && 4187 !Candidate.WillReplaceSpecifier()); 4188 4189 switch (TmpRes.getResultKind()) { 4190 case LookupResult::NotFound: 4191 case LookupResult::NotFoundInCurrentInstantiation: 4192 case LookupResult::FoundUnresolvedValue: 4193 if (TempSS) { 4194 // Immediately retry the lookup without the given CXXScopeSpec 4195 TempSS = NULL; 4196 Candidate.WillReplaceSpecifier(true); 4197 goto retry_lookup; 4198 } 4199 if (TempMemberContext) { 4200 if (SS && !TempSS) 4201 TempSS = SS; 4202 TempMemberContext = NULL; 4203 goto retry_lookup; 4204 } 4205 QualifiedResults.push_back(Candidate); 4206 // We didn't find this name in our scope, or didn't like what we found; 4207 // ignore it. 4208 { 4209 TypoCorrectionConsumer::result_iterator Next = I; 4210 ++Next; 4211 DI->second.erase(I); 4212 I = Next; 4213 } 4214 break; 4215 4216 case LookupResult::Ambiguous: 4217 // We don't deal with ambiguities. 4218 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4219 4220 case LookupResult::FoundOverloaded: { 4221 TypoCorrectionConsumer::result_iterator Prev = I; 4222 // Store all of the Decls for overloaded symbols 4223 for (auto *TRD : TmpRes) 4224 Candidate.addCorrectionDecl(TRD); 4225 ++I; 4226 if (!isCandidateViable(CCC, Candidate)) { 4227 QualifiedResults.push_back(Candidate); 4228 DI->second.erase(Prev); 4229 } 4230 break; 4231 } 4232 4233 case LookupResult::Found: { 4234 TypoCorrectionConsumer::result_iterator Prev = I; 4235 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>()); 4236 ++I; 4237 if (!isCandidateViable(CCC, Candidate)) { 4238 QualifiedResults.push_back(Candidate); 4239 DI->second.erase(Prev); 4240 } 4241 break; 4242 } 4243 4244 } 4245 } 4246 4247 if (DI->second.empty()) 4248 Consumer.erase(DI); 4249 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first) 4250 // If there are results in the closest possible bucket, stop 4251 break; 4252 4253 // Only perform the qualified lookups for C++ 4254 if (SearchNamespaces) { 4255 TmpRes.suppressDiagnostics(); 4256 for (auto QR : QualifiedResults) { 4257 for (auto NSI : Namespaces) { 4258 DeclContext *Ctx = NSI.DeclCtx; 4259 const Type *NSType = NSI.NameSpecifier->getAsType(); 4260 4261 // If the current NestedNameSpecifier refers to a class and the 4262 // current correction candidate is the name of that class, then skip 4263 // it as it is unlikely a qualified version of the class' constructor 4264 // is an appropriate correction. 4265 if (CXXRecordDecl *NSDecl = 4266 NSType ? NSType->getAsCXXRecordDecl() : 0) { 4267 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) 4268 continue; 4269 } 4270 4271 TypoCorrection TC(QR); 4272 TC.ClearCorrectionDecls(); 4273 TC.setCorrectionSpecifier(NSI.NameSpecifier); 4274 TC.setQualifierDistance(NSI.EditDistance); 4275 TC.setCallbackDistance(0); // Reset the callback distance 4276 4277 // If the current correction candidate and namespace combination are 4278 // too far away from the original typo based on the normalized edit 4279 // distance, then skip performing a qualified name lookup. 4280 unsigned TmpED = TC.getEditDistance(true); 4281 if (QR.getCorrectionAsIdentifierInfo() != Typo && 4282 TmpED && TypoLen / TmpED < 3) 4283 continue; 4284 4285 TmpRes.clear(); 4286 TmpRes.setLookupName(QR.getCorrectionAsIdentifierInfo()); 4287 if (!LookupQualifiedName(TmpRes, Ctx)) continue; 4288 4289 // Any corrections added below will be validated in subsequent 4290 // iterations of the main while() loop over the Consumer's contents. 4291 switch (TmpRes.getResultKind()) { 4292 case LookupResult::Found: 4293 case LookupResult::FoundOverloaded: { 4294 if (SS && SS->isValid()) { 4295 std::string NewQualified = TC.getAsString(getLangOpts()); 4296 std::string OldQualified; 4297 llvm::raw_string_ostream OldOStream(OldQualified); 4298 SS->getScopeRep()->print(OldOStream, getPrintingPolicy()); 4299 OldOStream << TypoName; 4300 // If correction candidate would be an identical written qualified 4301 // identifer, then the existing CXXScopeSpec probably included a 4302 // typedef that didn't get accounted for properly. 4303 if (OldOStream.str() == NewQualified) 4304 break; 4305 } 4306 for (LookupResult::iterator TRD = TmpRes.begin(), 4307 TRDEnd = TmpRes.end(); 4308 TRD != TRDEnd; ++TRD) { 4309 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(), 4310 NSType ? NSType->getAsCXXRecordDecl() : 0, 4311 TRD.getPair()) == AR_accessible) 4312 TC.addCorrectionDecl(*TRD); 4313 } 4314 if (TC.isResolved()) 4315 Consumer.addCorrection(TC); 4316 break; 4317 } 4318 case LookupResult::NotFound: 4319 case LookupResult::NotFoundInCurrentInstantiation: 4320 case LookupResult::Ambiguous: 4321 case LookupResult::FoundUnresolvedValue: 4322 break; 4323 } 4324 } 4325 } 4326 } 4327 4328 QualifiedResults.clear(); 4329 } 4330 4331 // No corrections remain... 4332 if (Consumer.empty()) 4333 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4334 4335 TypoResultsMap &BestResults = Consumer.getBestResults(); 4336 ED = Consumer.getBestEditDistance(true); 4337 4338 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) { 4339 // If this was an unqualified lookup and we believe the callback 4340 // object wouldn't have filtered out possible corrections, note 4341 // that no correction was found. 4342 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 4343 IsUnqualifiedLookup && !ValidatingCallback); 4344 } 4345 4346 // If only a single name remains, return that result. 4347 if (BestResults.size() == 1) { 4348 const TypoResultList &CorrectionList = BestResults.begin()->second; 4349 const TypoCorrection &Result = CorrectionList.front(); 4350 if (CorrectionList.size() != 1) 4351 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4352 4353 // Don't correct to a keyword that's the same as the typo; the keyword 4354 // wasn't actually in scope. 4355 if (ED == 0 && Result.isKeyword()) 4356 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4357 4358 // Record the correction for unqualified lookup. 4359 if (IsUnqualifiedLookup) 4360 UnqualifiedTyposCorrected[Typo] = Result; 4361 4362 TypoCorrection TC = Result; 4363 TC.setCorrectionRange(SS, TypoName); 4364 checkCorrectionVisibility(*this, TC, TypoName.getName()); 4365 return TC; 4366 } 4367 else if (BestResults.size() > 1 4368 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; 4369 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for 4370 // some instances of CTC_Unknown, while WantRemainingKeywords is true 4371 // for CTC_Unknown but not for CTC_ObjCMessageReceiver. 4372 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords 4373 && BestResults["super"].front().isKeyword()) { 4374 // Prefer 'super' when we're completing in a message-receiver 4375 // context. 4376 4377 // Don't correct to a keyword that's the same as the typo; the keyword 4378 // wasn't actually in scope. 4379 if (ED == 0) 4380 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4381 4382 // Record the correction for unqualified lookup. 4383 if (IsUnqualifiedLookup) 4384 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front(); 4385 4386 TypoCorrection TC = BestResults["super"].front(); 4387 TC.setCorrectionRange(SS, TypoName); 4388 return TC; 4389 } 4390 4391 // If this was an unqualified lookup and we believe the callback object did 4392 // not filter out possible corrections, note that no correction was found. 4393 if (IsUnqualifiedLookup && !ValidatingCallback) 4394 (void)UnqualifiedTyposCorrected[Typo]; 4395 4396 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 4397 } 4398 4399 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { 4400 if (!CDecl) return; 4401 4402 if (isKeyword()) 4403 CorrectionDecls.clear(); 4404 4405 CorrectionDecls.push_back(CDecl->getUnderlyingDecl()); 4406 4407 if (!CorrectionName) 4408 CorrectionName = CDecl->getDeclName(); 4409 } 4410 4411 std::string TypoCorrection::getAsString(const LangOptions &LO) const { 4412 if (CorrectionNameSpec) { 4413 std::string tmpBuffer; 4414 llvm::raw_string_ostream PrefixOStream(tmpBuffer); 4415 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); 4416 PrefixOStream << CorrectionName; 4417 return PrefixOStream.str(); 4418 } 4419 4420 return CorrectionName.getAsString(); 4421 } 4422 4423 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) { 4424 if (!candidate.isResolved()) 4425 return true; 4426 4427 if (candidate.isKeyword()) 4428 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || 4429 WantRemainingKeywords || WantObjCSuper; 4430 4431 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 4432 CDeclEnd = candidate.end(); 4433 CDecl != CDeclEnd; ++CDecl) { 4434 if (!isa<TypeDecl>(*CDecl)) 4435 return true; 4436 } 4437 4438 return WantTypeSpecifiers; 4439 } 4440 4441 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, 4442 bool HasExplicitTemplateArgs, 4443 MemberExpr *ME) 4444 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), 4445 CurContext(SemaRef.CurContext), MemberFn(ME) { 4446 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 4447 WantRemainingKeywords = false; 4448 } 4449 4450 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { 4451 if (!candidate.getCorrectionDecl()) 4452 return candidate.isKeyword(); 4453 4454 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 4455 DIEnd = candidate.end(); 4456 DI != DIEnd; ++DI) { 4457 FunctionDecl *FD = 0; 4458 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 4459 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 4460 FD = FTD->getTemplatedDecl(); 4461 if (!HasExplicitTemplateArgs && !FD) { 4462 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 4463 // If the Decl is neither a function nor a template function, 4464 // determine if it is a pointer or reference to a function. If so, 4465 // check against the number of arguments expected for the pointee. 4466 QualType ValType = cast<ValueDecl>(ND)->getType(); 4467 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 4468 ValType = ValType->getPointeeType(); 4469 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 4470 if (FPT->getNumParams() == NumArgs) 4471 return true; 4472 } 4473 } 4474 4475 // Skip the current candidate if it is not a FunctionDecl or does not accept 4476 // the current number of arguments. 4477 if (!FD || !(FD->getNumParams() >= NumArgs && 4478 FD->getMinRequiredArguments() <= NumArgs)) 4479 continue; 4480 4481 // If the current candidate is a non-static C++ method, skip the candidate 4482 // unless the method being corrected--or the current DeclContext, if the 4483 // function being corrected is not a method--is a method in the same class 4484 // or a descendent class of the candidate's parent class. 4485 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 4486 if (MemberFn || !MD->isStatic()) { 4487 CXXMethodDecl *CurMD = 4488 MemberFn 4489 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl()) 4490 : dyn_cast_or_null<CXXMethodDecl>(CurContext); 4491 CXXRecordDecl *CurRD = 4492 CurMD ? CurMD->getParent()->getCanonicalDecl() : 0; 4493 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); 4494 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD))) 4495 continue; 4496 } 4497 } 4498 return true; 4499 } 4500 return false; 4501 } 4502 4503 void Sema::diagnoseTypo(const TypoCorrection &Correction, 4504 const PartialDiagnostic &TypoDiag, 4505 bool ErrorRecovery) { 4506 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), 4507 ErrorRecovery); 4508 } 4509 4510 /// Find which declaration we should import to provide the definition of 4511 /// the given declaration. 4512 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) { 4513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4514 return VD->getDefinition(); 4515 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4516 return FD->isDefined(FD) ? FD : 0; 4517 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 4518 return TD->getDefinition(); 4519 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) 4520 return ID->getDefinition(); 4521 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) 4522 return PD->getDefinition(); 4523 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 4524 return getDefinitionToImport(TD->getTemplatedDecl()); 4525 return 0; 4526 } 4527 4528 /// \brief Diagnose a successfully-corrected typo. Separated from the correction 4529 /// itself to allow external validation of the result, etc. 4530 /// 4531 /// \param Correction The result of performing typo correction. 4532 /// \param TypoDiag The diagnostic to produce. This will have the corrected 4533 /// string added to it (and usually also a fixit). 4534 /// \param PrevNote A note to use when indicating the location of the entity to 4535 /// which we are correcting. Will have the correction string added to it. 4536 /// \param ErrorRecovery If \c true (the default), the caller is going to 4537 /// recover from the typo as if the corrected string had been typed. 4538 /// In this case, \c PDiag must be an error, and we will attach a fixit 4539 /// to it. 4540 void Sema::diagnoseTypo(const TypoCorrection &Correction, 4541 const PartialDiagnostic &TypoDiag, 4542 const PartialDiagnostic &PrevNote, 4543 bool ErrorRecovery) { 4544 std::string CorrectedStr = Correction.getAsString(getLangOpts()); 4545 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); 4546 FixItHint FixTypo = FixItHint::CreateReplacement( 4547 Correction.getCorrectionRange(), CorrectedStr); 4548 4549 // Maybe we're just missing a module import. 4550 if (Correction.requiresImport()) { 4551 NamedDecl *Decl = Correction.getCorrectionDecl(); 4552 assert(Decl && "import required but no declaration to import"); 4553 4554 // Suggest importing a module providing the definition of this entity, if 4555 // possible. 4556 const NamedDecl *Def = getDefinitionToImport(Decl); 4557 if (!Def) 4558 Def = Decl; 4559 Module *Owner = Def->getOwningModule(); 4560 assert(Owner && "definition of hidden declaration is not in a module"); 4561 4562 Diag(Correction.getCorrectionRange().getBegin(), 4563 diag::err_module_private_declaration) 4564 << Def << Owner->getFullModuleName(); 4565 Diag(Def->getLocation(), diag::note_previous_declaration); 4566 4567 // Recover by implicitly importing this module. 4568 if (!isSFINAEContext() && ErrorRecovery) 4569 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(), 4570 Owner); 4571 return; 4572 } 4573 4574 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) 4575 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); 4576 4577 NamedDecl *ChosenDecl = 4578 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl(); 4579 if (PrevNote.getDiagID() && ChosenDecl) 4580 Diag(ChosenDecl->getLocation(), PrevNote) 4581 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); 4582 } 4583