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