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