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