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