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