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