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