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