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