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