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