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