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