clang API Documentation
00001 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements name lookup for C, C++, Objective-C, and 00011 // Objective-C++. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 #include "clang/Sema/Lookup.h" 00015 #include "clang/AST/ASTContext.h" 00016 #include "clang/AST/CXXInheritance.h" 00017 #include "clang/AST/Decl.h" 00018 #include "clang/AST/DeclCXX.h" 00019 #include "clang/AST/DeclLookups.h" 00020 #include "clang/AST/DeclObjC.h" 00021 #include "clang/AST/DeclTemplate.h" 00022 #include "clang/AST/Expr.h" 00023 #include "clang/AST/ExprCXX.h" 00024 #include "clang/Basic/Builtins.h" 00025 #include "clang/Basic/LangOptions.h" 00026 #include "clang/Lex/ModuleLoader.h" 00027 #include "clang/Sema/DeclSpec.h" 00028 #include "clang/Sema/ExternalSemaSource.h" 00029 #include "clang/Sema/Overload.h" 00030 #include "clang/Sema/Scope.h" 00031 #include "clang/Sema/ScopeInfo.h" 00032 #include "clang/Sema/Sema.h" 00033 #include "clang/Sema/SemaInternal.h" 00034 #include "clang/Sema/TemplateDeduction.h" 00035 #include "clang/Sema/TypoCorrection.h" 00036 #include "llvm/ADT/STLExtras.h" 00037 #include "llvm/ADT/SetVector.h" 00038 #include "llvm/ADT/SmallPtrSet.h" 00039 #include "llvm/ADT/StringMap.h" 00040 #include "llvm/ADT/TinyPtrVector.h" 00041 #include "llvm/ADT/edit_distance.h" 00042 #include "llvm/Support/ErrorHandling.h" 00043 #include <algorithm> 00044 #include <iterator> 00045 #include <limits> 00046 #include <list> 00047 #include <map> 00048 #include <set> 00049 #include <utility> 00050 #include <vector> 00051 00052 using namespace clang; 00053 using namespace sema; 00054 00055 namespace { 00056 class UnqualUsingEntry { 00057 const DeclContext *Nominated; 00058 const DeclContext *CommonAncestor; 00059 00060 public: 00061 UnqualUsingEntry(const DeclContext *Nominated, 00062 const DeclContext *CommonAncestor) 00063 : Nominated(Nominated), CommonAncestor(CommonAncestor) { 00064 } 00065 00066 const DeclContext *getCommonAncestor() const { 00067 return CommonAncestor; 00068 } 00069 00070 const DeclContext *getNominatedNamespace() const { 00071 return Nominated; 00072 } 00073 00074 // Sort by the pointer value of the common ancestor. 00075 struct Comparator { 00076 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { 00077 return L.getCommonAncestor() < R.getCommonAncestor(); 00078 } 00079 00080 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { 00081 return E.getCommonAncestor() < DC; 00082 } 00083 00084 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { 00085 return DC < E.getCommonAncestor(); 00086 } 00087 }; 00088 }; 00089 00090 /// A collection of using directives, as used by C++ unqualified 00091 /// lookup. 00092 class UnqualUsingDirectiveSet { 00093 typedef SmallVector<UnqualUsingEntry, 8> ListTy; 00094 00095 ListTy list; 00096 llvm::SmallPtrSet<DeclContext*, 8> visited; 00097 00098 public: 00099 UnqualUsingDirectiveSet() {} 00100 00101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) { 00102 // C++ [namespace.udir]p1: 00103 // During unqualified name lookup, the names appear as if they 00104 // were declared in the nearest enclosing namespace which contains 00105 // both the using-directive and the nominated namespace. 00106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity(); 00107 assert(InnermostFileDC && InnermostFileDC->isFileContext()); 00108 00109 for (; S; S = S->getParent()) { 00110 // C++ [namespace.udir]p1: 00111 // A using-directive shall not appear in class scope, but may 00112 // appear in namespace scope or in block scope. 00113 DeclContext *Ctx = S->getEntity(); 00114 if (Ctx && Ctx->isFileContext()) { 00115 visit(Ctx, Ctx); 00116 } else if (!Ctx || Ctx->isFunctionOrMethod()) { 00117 for (auto *I : S->using_directives()) 00118 visit(I, InnermostFileDC); 00119 } 00120 } 00121 } 00122 00123 // Visits a context and collect all of its using directives 00124 // recursively. Treats all using directives as if they were 00125 // declared in the context. 00126 // 00127 // A given context is only every visited once, so it is important 00128 // that contexts be visited from the inside out in order to get 00129 // the effective DCs right. 00130 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 00131 if (!visited.insert(DC)) 00132 return; 00133 00134 addUsingDirectives(DC, EffectiveDC); 00135 } 00136 00137 // Visits a using directive and collects all of its using 00138 // directives recursively. Treats all using directives as if they 00139 // were declared in the effective DC. 00140 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 00141 DeclContext *NS = UD->getNominatedNamespace(); 00142 if (!visited.insert(NS)) 00143 return; 00144 00145 addUsingDirective(UD, EffectiveDC); 00146 addUsingDirectives(NS, EffectiveDC); 00147 } 00148 00149 // Adds all the using directives in a context (and those nominated 00150 // by its using directives, transitively) as if they appeared in 00151 // the given effective context. 00152 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 00153 SmallVector<DeclContext*,4> queue; 00154 while (true) { 00155 for (auto UD : DC->using_directives()) { 00156 DeclContext *NS = UD->getNominatedNamespace(); 00157 if (visited.insert(NS)) { 00158 addUsingDirective(UD, EffectiveDC); 00159 queue.push_back(NS); 00160 } 00161 } 00162 00163 if (queue.empty()) 00164 return; 00165 00166 DC = queue.pop_back_val(); 00167 } 00168 } 00169 00170 // Add a using directive as if it had been declared in the given 00171 // context. This helps implement C++ [namespace.udir]p3: 00172 // The using-directive is transitive: if a scope contains a 00173 // using-directive that nominates a second namespace that itself 00174 // contains using-directives, the effect is as if the 00175 // using-directives from the second namespace also appeared in 00176 // the first. 00177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 00178 // Find the common ancestor between the effective context and 00179 // the nominated namespace. 00180 DeclContext *Common = UD->getNominatedNamespace(); 00181 while (!Common->Encloses(EffectiveDC)) 00182 Common = Common->getParent(); 00183 Common = Common->getPrimaryContext(); 00184 00185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 00186 } 00187 00188 void done() { 00189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); 00190 } 00191 00192 typedef ListTy::const_iterator const_iterator; 00193 00194 const_iterator begin() const { return list.begin(); } 00195 const_iterator end() const { return list.end(); } 00196 00197 std::pair<const_iterator,const_iterator> 00198 getNamespacesFor(DeclContext *DC) const { 00199 return std::equal_range(begin(), end(), DC->getPrimaryContext(), 00200 UnqualUsingEntry::Comparator()); 00201 } 00202 }; 00203 } 00204 00205 // Retrieve the set of identifier namespaces that correspond to a 00206 // specific kind of name lookup. 00207 static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 00208 bool CPlusPlus, 00209 bool Redeclaration) { 00210 unsigned IDNS = 0; 00211 switch (NameKind) { 00212 case Sema::LookupObjCImplicitSelfParam: 00213 case Sema::LookupOrdinaryName: 00214 case Sema::LookupRedeclarationWithLinkage: 00215 case Sema::LookupLocalFriendName: 00216 IDNS = Decl::IDNS_Ordinary; 00217 if (CPlusPlus) { 00218 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 00219 if (Redeclaration) 00220 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 00221 } 00222 if (Redeclaration) 00223 IDNS |= Decl::IDNS_LocalExtern; 00224 break; 00225 00226 case Sema::LookupOperatorName: 00227 // Operator lookup is its own crazy thing; it is not the same 00228 // as (e.g.) looking up an operator name for redeclaration. 00229 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 00230 IDNS = Decl::IDNS_NonMemberOperator; 00231 break; 00232 00233 case Sema::LookupTagName: 00234 if (CPlusPlus) { 00235 IDNS = Decl::IDNS_Type; 00236 00237 // When looking for a redeclaration of a tag name, we add: 00238 // 1) TagFriend to find undeclared friend decls 00239 // 2) Namespace because they can't "overload" with tag decls. 00240 // 3) Tag because it includes class templates, which can't 00241 // "overload" with tag decls. 00242 if (Redeclaration) 00243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 00244 } else { 00245 IDNS = Decl::IDNS_Tag; 00246 } 00247 break; 00248 00249 case Sema::LookupLabel: 00250 IDNS = Decl::IDNS_Label; 00251 break; 00252 00253 case Sema::LookupMemberName: 00254 IDNS = Decl::IDNS_Member; 00255 if (CPlusPlus) 00256 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 00257 break; 00258 00259 case Sema::LookupNestedNameSpecifierName: 00260 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 00261 break; 00262 00263 case Sema::LookupNamespaceName: 00264 IDNS = Decl::IDNS_Namespace; 00265 break; 00266 00267 case Sema::LookupUsingDeclName: 00268 assert(Redeclaration && "should only be used for redecl lookup"); 00269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | 00270 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend | 00271 Decl::IDNS_LocalExtern; 00272 break; 00273 00274 case Sema::LookupObjCProtocolName: 00275 IDNS = Decl::IDNS_ObjCProtocol; 00276 break; 00277 00278 case Sema::LookupAnyName: 00279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member 00280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol 00281 | Decl::IDNS_Type; 00282 break; 00283 } 00284 return IDNS; 00285 } 00286 00287 void LookupResult::configure() { 00288 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus, 00289 isForRedeclaration()); 00290 00291 // If we're looking for one of the allocation or deallocation 00292 // operators, make sure that the implicitly-declared new and delete 00293 // operators can be found. 00294 switch (NameInfo.getName().getCXXOverloadedOperator()) { 00295 case OO_New: 00296 case OO_Delete: 00297 case OO_Array_New: 00298 case OO_Array_Delete: 00299 getSema().DeclareGlobalNewDelete(); 00300 break; 00301 00302 default: 00303 break; 00304 } 00305 00306 // Compiler builtins are always visible, regardless of where they end 00307 // up being declared. 00308 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { 00309 if (unsigned BuiltinID = Id->getBuiltinID()) { 00310 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 00311 AllowHidden = true; 00312 } 00313 } 00314 } 00315 00316 bool LookupResult::sanity() const { 00317 // This function is never called by NDEBUG builds. 00318 assert(ResultKind != NotFound || Decls.size() == 0); 00319 assert(ResultKind != Found || Decls.size() == 1); 00320 assert(ResultKind != FoundOverloaded || Decls.size() > 1 || 00321 (Decls.size() == 1 && 00322 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))); 00323 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved()); 00324 assert(ResultKind != Ambiguous || Decls.size() > 1 || 00325 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || 00326 Ambiguity == AmbiguousBaseSubobjectTypes))); 00327 assert((Paths != nullptr) == (ResultKind == Ambiguous && 00328 (Ambiguity == AmbiguousBaseSubobjectTypes || 00329 Ambiguity == AmbiguousBaseSubobjects))); 00330 return true; 00331 } 00332 00333 // Necessary because CXXBasePaths is not complete in Sema.h 00334 void LookupResult::deletePaths(CXXBasePaths *Paths) { 00335 delete Paths; 00336 } 00337 00338 /// Get a representative context for a declaration such that two declarations 00339 /// will have the same context if they were found within the same scope. 00340 static DeclContext *getContextForScopeMatching(Decl *D) { 00341 // For function-local declarations, use that function as the context. This 00342 // doesn't account for scopes within the function; the caller must deal with 00343 // those. 00344 DeclContext *DC = D->getLexicalDeclContext(); 00345 if (DC->isFunctionOrMethod()) 00346 return DC; 00347 00348 // Otherwise, look at the semantic context of the declaration. The 00349 // declaration must have been found there. 00350 return D->getDeclContext()->getRedeclContext(); 00351 } 00352 00353 /// Resolves the result kind of this lookup. 00354 void LookupResult::resolveKind() { 00355 unsigned N = Decls.size(); 00356 00357 // Fast case: no possible ambiguity. 00358 if (N == 0) { 00359 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation); 00360 return; 00361 } 00362 00363 // If there's a single decl, we need to examine it to decide what 00364 // kind of lookup this is. 00365 if (N == 1) { 00366 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); 00367 if (isa<FunctionTemplateDecl>(D)) 00368 ResultKind = FoundOverloaded; 00369 else if (isa<UnresolvedUsingValueDecl>(D)) 00370 ResultKind = FoundUnresolvedValue; 00371 return; 00372 } 00373 00374 // Don't do any extra resolution if we've already resolved as ambiguous. 00375 if (ResultKind == Ambiguous) return; 00376 00377 llvm::SmallPtrSet<NamedDecl*, 16> Unique; 00378 llvm::SmallPtrSet<QualType, 16> UniqueTypes; 00379 00380 bool Ambiguous = false; 00381 bool HasTag = false, HasFunction = false, HasNonFunction = false; 00382 bool HasFunctionTemplate = false, HasUnresolved = false; 00383 00384 unsigned UniqueTagIndex = 0; 00385 00386 unsigned I = 0; 00387 while (I < N) { 00388 NamedDecl *D = Decls[I]->getUnderlyingDecl(); 00389 D = cast<NamedDecl>(D->getCanonicalDecl()); 00390 00391 // Ignore an invalid declaration unless it's the only one left. 00392 if (D->isInvalidDecl() && I < N-1) { 00393 Decls[I] = Decls[--N]; 00394 continue; 00395 } 00396 00397 // Redeclarations of types via typedef can occur both within a scope 00398 // and, through using declarations and directives, across scopes. There is 00399 // no ambiguity if they all refer to the same type, so unique based on the 00400 // canonical type. 00401 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) { 00402 if (!TD->getDeclContext()->isRecord()) { 00403 QualType T = getSema().Context.getTypeDeclType(TD); 00404 if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T))) { 00405 // The type is not unique; pull something off the back and continue 00406 // at this index. 00407 Decls[I] = Decls[--N]; 00408 continue; 00409 } 00410 } 00411 } 00412 00413 if (!Unique.insert(D)) { 00414 // If it's not unique, pull something off the back (and 00415 // continue at this index). 00416 Decls[I] = Decls[--N]; 00417 continue; 00418 } 00419 00420 // Otherwise, do some decl type analysis and then continue. 00421 00422 if (isa<UnresolvedUsingValueDecl>(D)) { 00423 HasUnresolved = true; 00424 } else if (isa<TagDecl>(D)) { 00425 if (HasTag) 00426 Ambiguous = true; 00427 UniqueTagIndex = I; 00428 HasTag = true; 00429 } else if (isa<FunctionTemplateDecl>(D)) { 00430 HasFunction = true; 00431 HasFunctionTemplate = true; 00432 } else if (isa<FunctionDecl>(D)) { 00433 HasFunction = true; 00434 } else { 00435 if (HasNonFunction) 00436 Ambiguous = true; 00437 HasNonFunction = true; 00438 } 00439 I++; 00440 } 00441 00442 // C++ [basic.scope.hiding]p2: 00443 // A class name or enumeration name can be hidden by the name of 00444 // an object, function, or enumerator declared in the same 00445 // scope. If a class or enumeration name and an object, function, 00446 // or enumerator are declared in the same scope (in any order) 00447 // with the same name, the class or enumeration name is hidden 00448 // wherever the object, function, or enumerator name is visible. 00449 // But it's still an error if there are distinct tag types found, 00450 // even if they're not visible. (ref?) 00451 if (HideTags && HasTag && !Ambiguous && 00452 (HasFunction || HasNonFunction || HasUnresolved)) { 00453 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals( 00454 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1]))) 00455 Decls[UniqueTagIndex] = Decls[--N]; 00456 else 00457 Ambiguous = true; 00458 } 00459 00460 Decls.set_size(N); 00461 00462 if (HasNonFunction && (HasFunction || HasUnresolved)) 00463 Ambiguous = true; 00464 00465 if (Ambiguous) 00466 setAmbiguous(LookupResult::AmbiguousReference); 00467 else if (HasUnresolved) 00468 ResultKind = LookupResult::FoundUnresolvedValue; 00469 else if (N > 1 || HasFunctionTemplate) 00470 ResultKind = LookupResult::FoundOverloaded; 00471 else 00472 ResultKind = LookupResult::Found; 00473 } 00474 00475 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { 00476 CXXBasePaths::const_paths_iterator I, E; 00477 for (I = P.begin(), E = P.end(); I != E; ++I) 00478 for (DeclContext::lookup_iterator DI = I->Decls.begin(), 00479 DE = I->Decls.end(); DI != DE; ++DI) 00480 addDecl(*DI); 00481 } 00482 00483 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 00484 Paths = new CXXBasePaths; 00485 Paths->swap(P); 00486 addDeclsFromBasePaths(*Paths); 00487 resolveKind(); 00488 setAmbiguous(AmbiguousBaseSubobjects); 00489 } 00490 00491 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 00492 Paths = new CXXBasePaths; 00493 Paths->swap(P); 00494 addDeclsFromBasePaths(*Paths); 00495 resolveKind(); 00496 setAmbiguous(AmbiguousBaseSubobjectTypes); 00497 } 00498 00499 void LookupResult::print(raw_ostream &Out) { 00500 Out << Decls.size() << " result(s)"; 00501 if (isAmbiguous()) Out << ", ambiguous"; 00502 if (Paths) Out << ", base paths present"; 00503 00504 for (iterator I = begin(), E = end(); I != E; ++I) { 00505 Out << "\n"; 00506 (*I)->print(Out, 2); 00507 } 00508 } 00509 00510 /// \brief Lookup a builtin function, when name lookup would otherwise 00511 /// fail. 00512 static bool LookupBuiltin(Sema &S, LookupResult &R) { 00513 Sema::LookupNameKind NameKind = R.getLookupKind(); 00514 00515 // If we didn't find a use of this identifier, and if the identifier 00516 // corresponds to a compiler builtin, create the decl object for the builtin 00517 // now, injecting it into translation unit scope, and return it. 00518 if (NameKind == Sema::LookupOrdinaryName || 00519 NameKind == Sema::LookupRedeclarationWithLinkage) { 00520 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); 00521 if (II) { 00522 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode && 00523 II == S.getFloat128Identifier()) { 00524 // libstdc++4.7's type_traits expects type __float128 to exist, so 00525 // insert a dummy type to make that header build in gnu++11 mode. 00526 R.addDecl(S.getASTContext().getFloat128StubType()); 00527 return true; 00528 } 00529 00530 // If this is a builtin on this (or all) targets, create the decl. 00531 if (unsigned BuiltinID = II->getBuiltinID()) { 00532 // In C++, we don't have any predefined library functions like 00533 // 'malloc'. Instead, we'll just error. 00534 if (S.getLangOpts().CPlusPlus && 00535 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 00536 return false; 00537 00538 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, 00539 BuiltinID, S.TUScope, 00540 R.isForRedeclaration(), 00541 R.getNameLoc())) { 00542 R.addDecl(D); 00543 return true; 00544 } 00545 } 00546 } 00547 } 00548 00549 return false; 00550 } 00551 00552 /// \brief Determine whether we can declare a special member function within 00553 /// the class at this point. 00554 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) { 00555 // We need to have a definition for the class. 00556 if (!Class->getDefinition() || Class->isDependentContext()) 00557 return false; 00558 00559 // We can't be in the middle of defining the class. 00560 return !Class->isBeingDefined(); 00561 } 00562 00563 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { 00564 if (!CanDeclareSpecialMemberFunction(Class)) 00565 return; 00566 00567 // If the default constructor has not yet been declared, do so now. 00568 if (Class->needsImplicitDefaultConstructor()) 00569 DeclareImplicitDefaultConstructor(Class); 00570 00571 // If the copy constructor has not yet been declared, do so now. 00572 if (Class->needsImplicitCopyConstructor()) 00573 DeclareImplicitCopyConstructor(Class); 00574 00575 // If the copy assignment operator has not yet been declared, do so now. 00576 if (Class->needsImplicitCopyAssignment()) 00577 DeclareImplicitCopyAssignment(Class); 00578 00579 if (getLangOpts().CPlusPlus11) { 00580 // If the move constructor has not yet been declared, do so now. 00581 if (Class->needsImplicitMoveConstructor()) 00582 DeclareImplicitMoveConstructor(Class); // might not actually do it 00583 00584 // If the move assignment operator has not yet been declared, do so now. 00585 if (Class->needsImplicitMoveAssignment()) 00586 DeclareImplicitMoveAssignment(Class); // might not actually do it 00587 } 00588 00589 // If the destructor has not yet been declared, do so now. 00590 if (Class->needsImplicitDestructor()) 00591 DeclareImplicitDestructor(Class); 00592 } 00593 00594 /// \brief Determine whether this is the name of an implicitly-declared 00595 /// special member function. 00596 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { 00597 switch (Name.getNameKind()) { 00598 case DeclarationName::CXXConstructorName: 00599 case DeclarationName::CXXDestructorName: 00600 return true; 00601 00602 case DeclarationName::CXXOperatorName: 00603 return Name.getCXXOverloadedOperator() == OO_Equal; 00604 00605 default: 00606 break; 00607 } 00608 00609 return false; 00610 } 00611 00612 /// \brief If there are any implicit member functions with the given name 00613 /// that need to be declared in the given declaration context, do so. 00614 static void DeclareImplicitMemberFunctionsWithName(Sema &S, 00615 DeclarationName Name, 00616 const DeclContext *DC) { 00617 if (!DC) 00618 return; 00619 00620 switch (Name.getNameKind()) { 00621 case DeclarationName::CXXConstructorName: 00622 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 00623 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 00624 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 00625 if (Record->needsImplicitDefaultConstructor()) 00626 S.DeclareImplicitDefaultConstructor(Class); 00627 if (Record->needsImplicitCopyConstructor()) 00628 S.DeclareImplicitCopyConstructor(Class); 00629 if (S.getLangOpts().CPlusPlus11 && 00630 Record->needsImplicitMoveConstructor()) 00631 S.DeclareImplicitMoveConstructor(Class); 00632 } 00633 break; 00634 00635 case DeclarationName::CXXDestructorName: 00636 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 00637 if (Record->getDefinition() && Record->needsImplicitDestructor() && 00638 CanDeclareSpecialMemberFunction(Record)) 00639 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); 00640 break; 00641 00642 case DeclarationName::CXXOperatorName: 00643 if (Name.getCXXOverloadedOperator() != OO_Equal) 00644 break; 00645 00646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) { 00647 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { 00648 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); 00649 if (Record->needsImplicitCopyAssignment()) 00650 S.DeclareImplicitCopyAssignment(Class); 00651 if (S.getLangOpts().CPlusPlus11 && 00652 Record->needsImplicitMoveAssignment()) 00653 S.DeclareImplicitMoveAssignment(Class); 00654 } 00655 } 00656 break; 00657 00658 default: 00659 break; 00660 } 00661 } 00662 00663 // Adds all qualifying matches for a name within a decl context to the 00664 // given lookup result. Returns true if any matches were found. 00665 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { 00666 bool Found = false; 00667 00668 // Lazily declare C++ special member functions. 00669 if (S.getLangOpts().CPlusPlus) 00670 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC); 00671 00672 // Perform lookup into this declaration context. 00673 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName()); 00674 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E; 00675 ++I) { 00676 NamedDecl *D = *I; 00677 if ((D = R.getAcceptableDecl(D))) { 00678 R.addDecl(D); 00679 Found = true; 00680 } 00681 } 00682 00683 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R)) 00684 return true; 00685 00686 if (R.getLookupName().getNameKind() 00687 != DeclarationName::CXXConversionFunctionName || 00688 R.getLookupName().getCXXNameType()->isDependentType() || 00689 !isa<CXXRecordDecl>(DC)) 00690 return Found; 00691 00692 // C++ [temp.mem]p6: 00693 // A specialization of a conversion function template is not found by 00694 // name lookup. Instead, any conversion function templates visible in the 00695 // context of the use are considered. [...] 00696 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 00697 if (!Record->isCompleteDefinition()) 00698 return Found; 00699 00700 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(), 00701 UEnd = Record->conversion_end(); U != UEnd; ++U) { 00702 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); 00703 if (!ConvTemplate) 00704 continue; 00705 00706 // When we're performing lookup for the purposes of redeclaration, just 00707 // add the conversion function template. When we deduce template 00708 // arguments for specializations, we'll end up unifying the return 00709 // type of the new declaration with the type of the function template. 00710 if (R.isForRedeclaration()) { 00711 R.addDecl(ConvTemplate); 00712 Found = true; 00713 continue; 00714 } 00715 00716 // C++ [temp.mem]p6: 00717 // [...] For each such operator, if argument deduction succeeds 00718 // (14.9.2.3), the resulting specialization is used as if found by 00719 // name lookup. 00720 // 00721 // When referencing a conversion function for any purpose other than 00722 // a redeclaration (such that we'll be building an expression with the 00723 // result), perform template argument deduction and place the 00724 // specialization into the result set. We do this to avoid forcing all 00725 // callers to perform special deduction for conversion functions. 00726 TemplateDeductionInfo Info(R.getNameLoc()); 00727 FunctionDecl *Specialization = nullptr; 00728 00729 const FunctionProtoType *ConvProto 00730 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); 00731 assert(ConvProto && "Nonsensical conversion function template type"); 00732 00733 // Compute the type of the function that we would expect the conversion 00734 // function to have, if it were to match the name given. 00735 // FIXME: Calling convention! 00736 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo(); 00737 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C); 00738 EPI.ExceptionSpec = EST_None; 00739 QualType ExpectedType 00740 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(), 00741 None, EPI); 00742 00743 // Perform template argument deduction against the type that we would 00744 // expect the function to have. 00745 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType, 00746 Specialization, Info) 00747 == Sema::TDK_Success) { 00748 R.addDecl(Specialization); 00749 Found = true; 00750 } 00751 } 00752 00753 return Found; 00754 } 00755 00756 // Performs C++ unqualified lookup into the given file context. 00757 static bool 00758 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 00759 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) { 00760 00761 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 00762 00763 // Perform direct name lookup into the LookupCtx. 00764 bool Found = LookupDirect(S, R, NS); 00765 00766 // Perform direct name lookup into the namespaces nominated by the 00767 // using directives whose common ancestor is this namespace. 00768 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 00769 std::tie(UI, UEnd) = UDirs.getNamespacesFor(NS); 00770 00771 for (; UI != UEnd; ++UI) 00772 if (LookupDirect(S, R, UI->getNominatedNamespace())) 00773 Found = true; 00774 00775 R.resolveKind(); 00776 00777 return Found; 00778 } 00779 00780 static bool isNamespaceOrTranslationUnitScope(Scope *S) { 00781 if (DeclContext *Ctx = S->getEntity()) 00782 return Ctx->isFileContext(); 00783 return false; 00784 } 00785 00786 // Find the next outer declaration context from this scope. This 00787 // routine actually returns the semantic outer context, which may 00788 // differ from the lexical context (encoded directly in the Scope 00789 // stack) when we are parsing a member of a class template. In this 00790 // case, the second element of the pair will be true, to indicate that 00791 // name lookup should continue searching in this semantic context when 00792 // it leaves the current template parameter scope. 00793 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) { 00794 DeclContext *DC = S->getEntity(); 00795 DeclContext *Lexical = nullptr; 00796 for (Scope *OuterS = S->getParent(); OuterS; 00797 OuterS = OuterS->getParent()) { 00798 if (OuterS->getEntity()) { 00799 Lexical = OuterS->getEntity(); 00800 break; 00801 } 00802 } 00803 00804 // C++ [temp.local]p8: 00805 // In the definition of a member of a class template that appears 00806 // outside of the namespace containing the class template 00807 // definition, the name of a template-parameter hides the name of 00808 // a member of this namespace. 00809 // 00810 // Example: 00811 // 00812 // namespace N { 00813 // class C { }; 00814 // 00815 // template<class T> class B { 00816 // void f(T); 00817 // }; 00818 // } 00819 // 00820 // template<class C> void N::B<C>::f(C) { 00821 // C b; // C is the template parameter, not N::C 00822 // } 00823 // 00824 // In this example, the lexical context we return is the 00825 // TranslationUnit, while the semantic context is the namespace N. 00826 if (!Lexical || !DC || !S->getParent() || 00827 !S->getParent()->isTemplateParamScope()) 00828 return std::make_pair(Lexical, false); 00829 00830 // Find the outermost template parameter scope. 00831 // For the example, this is the scope for the template parameters of 00832 // template<class C>. 00833 Scope *OutermostTemplateScope = S->getParent(); 00834 while (OutermostTemplateScope->getParent() && 00835 OutermostTemplateScope->getParent()->isTemplateParamScope()) 00836 OutermostTemplateScope = OutermostTemplateScope->getParent(); 00837 00838 // Find the namespace context in which the original scope occurs. In 00839 // the example, this is namespace N. 00840 DeclContext *Semantic = DC; 00841 while (!Semantic->isFileContext()) 00842 Semantic = Semantic->getParent(); 00843 00844 // Find the declaration context just outside of the template 00845 // parameter scope. This is the context in which the template is 00846 // being lexically declaration (a namespace context). In the 00847 // example, this is the global scope. 00848 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) && 00849 Lexical->Encloses(Semantic)) 00850 return std::make_pair(Semantic, true); 00851 00852 return std::make_pair(Lexical, false); 00853 } 00854 00855 namespace { 00856 /// An RAII object to specify that we want to find block scope extern 00857 /// declarations. 00858 struct FindLocalExternScope { 00859 FindLocalExternScope(LookupResult &R) 00860 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() & 00861 Decl::IDNS_LocalExtern) { 00862 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary); 00863 } 00864 void restore() { 00865 R.setFindLocalExtern(OldFindLocalExtern); 00866 } 00867 ~FindLocalExternScope() { 00868 restore(); 00869 } 00870 LookupResult &R; 00871 bool OldFindLocalExtern; 00872 }; 00873 } 00874 00875 bool Sema::CppLookupName(LookupResult &R, Scope *S) { 00876 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup"); 00877 00878 DeclarationName Name = R.getLookupName(); 00879 Sema::LookupNameKind NameKind = R.getLookupKind(); 00880 00881 // If this is the name of an implicitly-declared special member function, 00882 // go through the scope stack to implicitly declare 00883 if (isImplicitlyDeclaredMemberFunctionName(Name)) { 00884 for (Scope *PreS = S; PreS; PreS = PreS->getParent()) 00885 if (DeclContext *DC = PreS->getEntity()) 00886 DeclareImplicitMemberFunctionsWithName(*this, Name, DC); 00887 } 00888 00889 // Implicitly declare member functions with the name we're looking for, if in 00890 // fact we are in a scope where it matters. 00891 00892 Scope *Initial = S; 00893 IdentifierResolver::iterator 00894 I = IdResolver.begin(Name), 00895 IEnd = IdResolver.end(); 00896 00897 // First we lookup local scope. 00898 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 00899 // ...During unqualified name lookup (3.4.1), the names appear as if 00900 // they were declared in the nearest enclosing namespace which contains 00901 // both the using-directive and the nominated namespace. 00902 // [Note: in this context, "contains" means "contains directly or 00903 // indirectly". 00904 // 00905 // For example: 00906 // namespace A { int i; } 00907 // void foo() { 00908 // int i; 00909 // { 00910 // using namespace A; 00911 // ++i; // finds local 'i', A::i appears at global scope 00912 // } 00913 // } 00914 // 00915 UnqualUsingDirectiveSet UDirs; 00916 bool VisitedUsingDirectives = false; 00917 bool LeftStartingScope = false; 00918 DeclContext *OutsideOfTemplateParamDC = nullptr; 00919 00920 // When performing a scope lookup, we want to find local extern decls. 00921 FindLocalExternScope FindLocals(R); 00922 00923 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 00924 DeclContext *Ctx = S->getEntity(); 00925 00926 // Check whether the IdResolver has anything in this scope. 00927 bool Found = false; 00928 for (; I != IEnd && S->isDeclScope(*I); ++I) { 00929 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 00930 if (NameKind == LookupRedeclarationWithLinkage) { 00931 // Determine whether this (or a previous) declaration is 00932 // out-of-scope. 00933 if (!LeftStartingScope && !Initial->isDeclScope(*I)) 00934 LeftStartingScope = true; 00935 00936 // If we found something outside of our starting scope that 00937 // does not have linkage, skip it. If it's a template parameter, 00938 // we still find it, so we can diagnose the invalid redeclaration. 00939 if (LeftStartingScope && !((*I)->hasLinkage()) && 00940 !(*I)->isTemplateParameter()) { 00941 R.setShadowed(); 00942 continue; 00943 } 00944 } 00945 00946 Found = true; 00947 R.addDecl(ND); 00948 } 00949 } 00950 if (Found) { 00951 R.resolveKind(); 00952 if (S->isClassScope()) 00953 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 00954 R.setNamingClass(Record); 00955 return true; 00956 } 00957 00958 if (NameKind == LookupLocalFriendName && !S->isClassScope()) { 00959 // C++11 [class.friend]p11: 00960 // If a friend declaration appears in a local class and the name 00961 // specified is an unqualified name, a prior declaration is 00962 // looked up without considering scopes that are outside the 00963 // innermost enclosing non-class scope. 00964 return false; 00965 } 00966 00967 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 00968 S->getParent() && !S->getParent()->isTemplateParamScope()) { 00969 // We've just searched the last template parameter scope and 00970 // found nothing, so look into the contexts between the 00971 // lexical and semantic declaration contexts returned by 00972 // findOuterContext(). This implements the name lookup behavior 00973 // of C++ [temp.local]p8. 00974 Ctx = OutsideOfTemplateParamDC; 00975 OutsideOfTemplateParamDC = nullptr; 00976 } 00977 00978 if (Ctx) { 00979 DeclContext *OuterCtx; 00980 bool SearchAfterTemplateScope; 00981 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 00982 if (SearchAfterTemplateScope) 00983 OutsideOfTemplateParamDC = OuterCtx; 00984 00985 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 00986 // We do not directly look into transparent contexts, since 00987 // those entities will be found in the nearest enclosing 00988 // non-transparent context. 00989 if (Ctx->isTransparentContext()) 00990 continue; 00991 00992 // We do not look directly into function or method contexts, 00993 // since all of the local variables and parameters of the 00994 // function/method are present within the Scope. 00995 if (Ctx->isFunctionOrMethod()) { 00996 // If we have an Objective-C instance method, look for ivars 00997 // in the corresponding interface. 00998 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 00999 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) 01000 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { 01001 ObjCInterfaceDecl *ClassDeclared; 01002 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( 01003 Name.getAsIdentifierInfo(), 01004 ClassDeclared)) { 01005 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) { 01006 R.addDecl(ND); 01007 R.resolveKind(); 01008 return true; 01009 } 01010 } 01011 } 01012 } 01013 01014 continue; 01015 } 01016 01017 // If this is a file context, we need to perform unqualified name 01018 // lookup considering using directives. 01019 if (Ctx->isFileContext()) { 01020 // If we haven't handled using directives yet, do so now. 01021 if (!VisitedUsingDirectives) { 01022 // Add using directives from this context up to the top level. 01023 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) { 01024 if (UCtx->isTransparentContext()) 01025 continue; 01026 01027 UDirs.visit(UCtx, UCtx); 01028 } 01029 01030 // Find the innermost file scope, so we can add using directives 01031 // from local scopes. 01032 Scope *InnermostFileScope = S; 01033 while (InnermostFileScope && 01034 !isNamespaceOrTranslationUnitScope(InnermostFileScope)) 01035 InnermostFileScope = InnermostFileScope->getParent(); 01036 UDirs.visitScopeChain(Initial, InnermostFileScope); 01037 01038 UDirs.done(); 01039 01040 VisitedUsingDirectives = true; 01041 } 01042 01043 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) { 01044 R.resolveKind(); 01045 return true; 01046 } 01047 01048 continue; 01049 } 01050 01051 // Perform qualified name lookup into this context. 01052 // FIXME: In some cases, we know that every name that could be found by 01053 // this qualified name lookup will also be on the identifier chain. For 01054 // example, inside a class without any base classes, we never need to 01055 // perform qualified lookup because all of the members are on top of the 01056 // identifier chain. 01057 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) 01058 return true; 01059 } 01060 } 01061 } 01062 01063 // Stop if we ran out of scopes. 01064 // FIXME: This really, really shouldn't be happening. 01065 if (!S) return false; 01066 01067 // If we are looking for members, no need to look into global/namespace scope. 01068 if (NameKind == LookupMemberName) 01069 return false; 01070 01071 // Collect UsingDirectiveDecls in all scopes, and recursively all 01072 // nominated namespaces by those using-directives. 01073 // 01074 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 01075 // don't build it for each lookup! 01076 if (!VisitedUsingDirectives) { 01077 UDirs.visitScopeChain(Initial, S); 01078 UDirs.done(); 01079 } 01080 01081 // If we're not performing redeclaration lookup, do not look for local 01082 // extern declarations outside of a function scope. 01083 if (!R.isForRedeclaration()) 01084 FindLocals.restore(); 01085 01086 // Lookup namespace scope, and global scope. 01087 // Unqualified name lookup in C++ requires looking into scopes 01088 // that aren't strictly lexical, and therefore we walk through the 01089 // context as well as walking through the scopes. 01090 for (; S; S = S->getParent()) { 01091 // Check whether the IdResolver has anything in this scope. 01092 bool Found = false; 01093 for (; I != IEnd && S->isDeclScope(*I); ++I) { 01094 if (NamedDecl *ND = R.getAcceptableDecl(*I)) { 01095 // We found something. Look for anything else in our scope 01096 // with this same name and in an acceptable identifier 01097 // namespace, so that we can construct an overload set if we 01098 // need to. 01099 Found = true; 01100 R.addDecl(ND); 01101 } 01102 } 01103 01104 if (Found && S->isTemplateParamScope()) { 01105 R.resolveKind(); 01106 return true; 01107 } 01108 01109 DeclContext *Ctx = S->getEntity(); 01110 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 01111 S->getParent() && !S->getParent()->isTemplateParamScope()) { 01112 // We've just searched the last template parameter scope and 01113 // found nothing, so look into the contexts between the 01114 // lexical and semantic declaration contexts returned by 01115 // findOuterContext(). This implements the name lookup behavior 01116 // of C++ [temp.local]p8. 01117 Ctx = OutsideOfTemplateParamDC; 01118 OutsideOfTemplateParamDC = nullptr; 01119 } 01120 01121 if (Ctx) { 01122 DeclContext *OuterCtx; 01123 bool SearchAfterTemplateScope; 01124 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 01125 if (SearchAfterTemplateScope) 01126 OutsideOfTemplateParamDC = OuterCtx; 01127 01128 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 01129 // We do not directly look into transparent contexts, since 01130 // those entities will be found in the nearest enclosing 01131 // non-transparent context. 01132 if (Ctx->isTransparentContext()) 01133 continue; 01134 01135 // If we have a context, and it's not a context stashed in the 01136 // template parameter scope for an out-of-line definition, also 01137 // look into that context. 01138 if (!(Found && S && S->isTemplateParamScope())) { 01139 assert(Ctx->isFileContext() && 01140 "We should have been looking only at file context here already."); 01141 01142 // Look into context considering using-directives. 01143 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) 01144 Found = true; 01145 } 01146 01147 if (Found) { 01148 R.resolveKind(); 01149 return true; 01150 } 01151 01152 if (R.isForRedeclaration() && !Ctx->isTransparentContext()) 01153 return false; 01154 } 01155 } 01156 01157 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) 01158 return false; 01159 } 01160 01161 return !R.empty(); 01162 } 01163 01164 /// \brief Find the declaration that a class temploid member specialization was 01165 /// instantiated from, or the member itself if it is an explicit specialization. 01166 static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) { 01167 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom(); 01168 } 01169 01170 /// \brief Find the module in which the given declaration was defined. 01171 static Module *getDefiningModule(Decl *Entity) { 01172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) { 01173 // If this function was instantiated from a template, the defining module is 01174 // the module containing the pattern. 01175 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 01176 Entity = Pattern; 01177 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) { 01178 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern()) 01179 Entity = Pattern; 01180 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) { 01181 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo()) 01182 Entity = getInstantiatedFrom(ED, MSInfo); 01183 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) { 01184 // FIXME: Map from variable template specializations back to the template. 01185 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) 01186 Entity = getInstantiatedFrom(VD, MSInfo); 01187 } 01188 01189 // Walk up to the containing context. That might also have been instantiated 01190 // from a template. 01191 DeclContext *Context = Entity->getDeclContext(); 01192 if (Context->isFileContext()) 01193 return Entity->getOwningModule(); 01194 return getDefiningModule(cast<Decl>(Context)); 01195 } 01196 01197 llvm::DenseSet<Module*> &Sema::getLookupModules() { 01198 unsigned N = ActiveTemplateInstantiations.size(); 01199 for (unsigned I = ActiveTemplateInstantiationLookupModules.size(); 01200 I != N; ++I) { 01201 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity); 01202 if (M && !LookupModulesCache.insert(M).second) 01203 M = nullptr; 01204 ActiveTemplateInstantiationLookupModules.push_back(M); 01205 } 01206 return LookupModulesCache; 01207 } 01208 01209 /// \brief Determine whether a declaration is visible to name lookup. 01210 /// 01211 /// This routine determines whether the declaration D is visible in the current 01212 /// lookup context, taking into account the current template instantiation 01213 /// stack. During template instantiation, a declaration is visible if it is 01214 /// visible from a module containing any entity on the template instantiation 01215 /// path (by instantiating a template, you allow it to see the declarations that 01216 /// your module can see, including those later on in your module). 01217 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) { 01218 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() && 01219 "should not call this: not in slow case"); 01220 Module *DeclModule = D->getOwningModule(); 01221 assert(DeclModule && "hidden decl not from a module"); 01222 01223 // Find the extra places where we need to look. 01224 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules(); 01225 if (LookupModules.empty()) 01226 return false; 01227 01228 // If our lookup set contains the decl's module, it's visible. 01229 if (LookupModules.count(DeclModule)) 01230 return true; 01231 01232 // If the declaration isn't exported, it's not visible in any other module. 01233 if (D->isModulePrivate()) 01234 return false; 01235 01236 // Check whether DeclModule is transitively exported to an import of 01237 // the lookup set. 01238 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(), 01239 E = LookupModules.end(); 01240 I != E; ++I) 01241 if ((*I)->isModuleVisible(DeclModule)) 01242 return true; 01243 return false; 01244 } 01245 01246 /// \brief Retrieve the visible declaration corresponding to D, if any. 01247 /// 01248 /// This routine determines whether the declaration D is visible in the current 01249 /// module, with the current imports. If not, it checks whether any 01250 /// redeclaration of D is visible, and if so, returns that declaration. 01251 /// 01252 /// \returns D, or a visible previous declaration of D, whichever is more recent 01253 /// and visible. If no declaration of D is visible, returns null. 01254 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 01255 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 01256 01257 for (auto RD : D->redecls()) { 01258 if (auto ND = dyn_cast<NamedDecl>(RD)) { 01259 if (LookupResult::isVisible(SemaRef, ND)) 01260 return ND; 01261 } 01262 } 01263 01264 return nullptr; 01265 } 01266 01267 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const { 01268 return findAcceptableDecl(getSema(), D); 01269 } 01270 01271 /// @brief Perform unqualified name lookup starting from a given 01272 /// scope. 01273 /// 01274 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 01275 /// used to find names within the current scope. For example, 'x' in 01276 /// @code 01277 /// int x; 01278 /// int f() { 01279 /// return x; // unqualified name look finds 'x' in the global scope 01280 /// } 01281 /// @endcode 01282 /// 01283 /// Different lookup criteria can find different names. For example, a 01284 /// particular scope can have both a struct and a function of the same 01285 /// name, and each can be found by certain lookup criteria. For more 01286 /// information about lookup criteria, see the documentation for the 01287 /// class LookupCriteria. 01288 /// 01289 /// @param S The scope from which unqualified name lookup will 01290 /// begin. If the lookup criteria permits, name lookup may also search 01291 /// in the parent scopes. 01292 /// 01293 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to 01294 /// look up and the lookup kind), and is updated with the results of lookup 01295 /// including zero or more declarations and possibly additional information 01296 /// used to diagnose ambiguities. 01297 /// 01298 /// @returns \c true if lookup succeeded and false otherwise. 01299 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { 01300 DeclarationName Name = R.getLookupName(); 01301 if (!Name) return false; 01302 01303 LookupNameKind NameKind = R.getLookupKind(); 01304 01305 if (!getLangOpts().CPlusPlus) { 01306 // Unqualified name lookup in C/Objective-C is purely lexical, so 01307 // search in the declarations attached to the name. 01308 if (NameKind == Sema::LookupRedeclarationWithLinkage) { 01309 // Find the nearest non-transparent declaration scope. 01310 while (!(S->getFlags() & Scope::DeclScope) || 01311 (S->getEntity() && S->getEntity()->isTransparentContext())) 01312 S = S->getParent(); 01313 } 01314 01315 // When performing a scope lookup, we want to find local extern decls. 01316 FindLocalExternScope FindLocals(R); 01317 01318 // Scan up the scope chain looking for a decl that matches this 01319 // identifier that is in the appropriate namespace. This search 01320 // should not take long, as shadowing of names is uncommon, and 01321 // deep shadowing is extremely uncommon. 01322 bool LeftStartingScope = false; 01323 01324 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 01325 IEnd = IdResolver.end(); 01326 I != IEnd; ++I) 01327 if (NamedDecl *D = R.getAcceptableDecl(*I)) { 01328 if (NameKind == LookupRedeclarationWithLinkage) { 01329 // Determine whether this (or a previous) declaration is 01330 // out-of-scope. 01331 if (!LeftStartingScope && !S->isDeclScope(*I)) 01332 LeftStartingScope = true; 01333 01334 // If we found something outside of our starting scope that 01335 // does not have linkage, skip it. 01336 if (LeftStartingScope && !((*I)->hasLinkage())) { 01337 R.setShadowed(); 01338 continue; 01339 } 01340 } 01341 else if (NameKind == LookupObjCImplicitSelfParam && 01342 !isa<ImplicitParamDecl>(*I)) 01343 continue; 01344 01345 R.addDecl(D); 01346 01347 // Check whether there are any other declarations with the same name 01348 // and in the same scope. 01349 if (I != IEnd) { 01350 // Find the scope in which this declaration was declared (if it 01351 // actually exists in a Scope). 01352 while (S && !S->isDeclScope(D)) 01353 S = S->getParent(); 01354 01355 // If the scope containing the declaration is the translation unit, 01356 // then we'll need to perform our checks based on the matching 01357 // DeclContexts rather than matching scopes. 01358 if (S && isNamespaceOrTranslationUnitScope(S)) 01359 S = nullptr; 01360 01361 // Compute the DeclContext, if we need it. 01362 DeclContext *DC = nullptr; 01363 if (!S) 01364 DC = (*I)->getDeclContext()->getRedeclContext(); 01365 01366 IdentifierResolver::iterator LastI = I; 01367 for (++LastI; LastI != IEnd; ++LastI) { 01368 if (S) { 01369 // Match based on scope. 01370 if (!S->isDeclScope(*LastI)) 01371 break; 01372 } else { 01373 // Match based on DeclContext. 01374 DeclContext *LastDC 01375 = (*LastI)->getDeclContext()->getRedeclContext(); 01376 if (!LastDC->Equals(DC)) 01377 break; 01378 } 01379 01380 // If the declaration is in the right namespace and visible, add it. 01381 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI)) 01382 R.addDecl(LastD); 01383 } 01384 01385 R.resolveKind(); 01386 } 01387 01388 return true; 01389 } 01390 } else { 01391 // Perform C++ unqualified name lookup. 01392 if (CppLookupName(R, S)) 01393 return true; 01394 } 01395 01396 // If we didn't find a use of this identifier, and if the identifier 01397 // corresponds to a compiler builtin, create the decl object for the builtin 01398 // now, injecting it into translation unit scope, and return it. 01399 if (AllowBuiltinCreation && LookupBuiltin(*this, R)) 01400 return true; 01401 01402 // If we didn't find a use of this identifier, the ExternalSource 01403 // may be able to handle the situation. 01404 // Note: some lookup failures are expected! 01405 // See e.g. R.isForRedeclaration(). 01406 return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); 01407 } 01408 01409 /// @brief Perform qualified name lookup in the namespaces nominated by 01410 /// using directives by the given context. 01411 /// 01412 /// C++98 [namespace.qual]p2: 01413 /// Given X::m (where X is a user-declared namespace), or given \::m 01414 /// (where X is the global namespace), let S be the set of all 01415 /// declarations of m in X and in the transitive closure of all 01416 /// namespaces nominated by using-directives in X and its used 01417 /// namespaces, except that using-directives are ignored in any 01418 /// namespace, including X, directly containing one or more 01419 /// declarations of m. No namespace is searched more than once in 01420 /// the lookup of a name. If S is the empty set, the program is 01421 /// ill-formed. Otherwise, if S has exactly one member, or if the 01422 /// context of the reference is a using-declaration 01423 /// (namespace.udecl), S is the required set of declarations of 01424 /// m. Otherwise if the use of m is not one that allows a unique 01425 /// declaration to be chosen from S, the program is ill-formed. 01426 /// 01427 /// C++98 [namespace.qual]p5: 01428 /// During the lookup of a qualified namespace member name, if the 01429 /// lookup finds more than one declaration of the member, and if one 01430 /// declaration introduces a class name or enumeration name and the 01431 /// other declarations either introduce the same object, the same 01432 /// enumerator or a set of functions, the non-type name hides the 01433 /// class or enumeration name if and only if the declarations are 01434 /// from the same namespace; otherwise (the declarations are from 01435 /// different namespaces), the program is ill-formed. 01436 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, 01437 DeclContext *StartDC) { 01438 assert(StartDC->isFileContext() && "start context is not a file context"); 01439 01440 DeclContext::udir_range UsingDirectives = StartDC->using_directives(); 01441 if (UsingDirectives.begin() == UsingDirectives.end()) return false; 01442 01443 // We have at least added all these contexts to the queue. 01444 llvm::SmallPtrSet<DeclContext*, 8> Visited; 01445 Visited.insert(StartDC); 01446 01447 // We have not yet looked into these namespaces, much less added 01448 // their "using-children" to the queue. 01449 SmallVector<NamespaceDecl*, 8> Queue; 01450 01451 // We have already looked into the initial namespace; seed the queue 01452 // with its using-children. 01453 for (auto *I : UsingDirectives) { 01454 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace(); 01455 if (Visited.insert(ND)) 01456 Queue.push_back(ND); 01457 } 01458 01459 // The easiest way to implement the restriction in [namespace.qual]p5 01460 // is to check whether any of the individual results found a tag 01461 // and, if so, to declare an ambiguity if the final result is not 01462 // a tag. 01463 bool FoundTag = false; 01464 bool FoundNonTag = false; 01465 01466 LookupResult LocalR(LookupResult::Temporary, R); 01467 01468 bool Found = false; 01469 while (!Queue.empty()) { 01470 NamespaceDecl *ND = Queue.pop_back_val(); 01471 01472 // We go through some convolutions here to avoid copying results 01473 // between LookupResults. 01474 bool UseLocal = !R.empty(); 01475 LookupResult &DirectR = UseLocal ? LocalR : R; 01476 bool FoundDirect = LookupDirect(S, DirectR, ND); 01477 01478 if (FoundDirect) { 01479 // First do any local hiding. 01480 DirectR.resolveKind(); 01481 01482 // If the local result is a tag, remember that. 01483 if (DirectR.isSingleTagDecl()) 01484 FoundTag = true; 01485 else 01486 FoundNonTag = true; 01487 01488 // Append the local results to the total results if necessary. 01489 if (UseLocal) { 01490 R.addAllDecls(LocalR); 01491 LocalR.clear(); 01492 } 01493 } 01494 01495 // If we find names in this namespace, ignore its using directives. 01496 if (FoundDirect) { 01497 Found = true; 01498 continue; 01499 } 01500 01501 for (auto I : ND->using_directives()) { 01502 NamespaceDecl *Nom = I->getNominatedNamespace(); 01503 if (Visited.insert(Nom)) 01504 Queue.push_back(Nom); 01505 } 01506 } 01507 01508 if (Found) { 01509 if (FoundTag && FoundNonTag) 01510 R.setAmbiguousQualifiedTagHiding(); 01511 else 01512 R.resolveKind(); 01513 } 01514 01515 return Found; 01516 } 01517 01518 /// \brief Callback that looks for any member of a class with the given name. 01519 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, 01520 CXXBasePath &Path, 01521 void *Name) { 01522 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 01523 01524 DeclarationName N = DeclarationName::getFromOpaquePtr(Name); 01525 Path.Decls = BaseRecord->lookup(N); 01526 return !Path.Decls.empty(); 01527 } 01528 01529 /// \brief Determine whether the given set of member declarations contains only 01530 /// static members, nested types, and enumerators. 01531 template<typename InputIterator> 01532 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) { 01533 Decl *D = (*First)->getUnderlyingDecl(); 01534 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D)) 01535 return true; 01536 01537 if (isa<CXXMethodDecl>(D)) { 01538 // Determine whether all of the methods are static. 01539 bool AllMethodsAreStatic = true; 01540 for(; First != Last; ++First) { 01541 D = (*First)->getUnderlyingDecl(); 01542 01543 if (!isa<CXXMethodDecl>(D)) { 01544 assert(isa<TagDecl>(D) && "Non-function must be a tag decl"); 01545 break; 01546 } 01547 01548 if (!cast<CXXMethodDecl>(D)->isStatic()) { 01549 AllMethodsAreStatic = false; 01550 break; 01551 } 01552 } 01553 01554 if (AllMethodsAreStatic) 01555 return true; 01556 } 01557 01558 return false; 01559 } 01560 01561 /// \brief Perform qualified name lookup into a given context. 01562 /// 01563 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 01564 /// names when the context of those names is explicit specified, e.g., 01565 /// "std::vector" or "x->member", or as part of unqualified name lookup. 01566 /// 01567 /// Different lookup criteria can find different names. For example, a 01568 /// particular scope can have both a struct and a function of the same 01569 /// name, and each can be found by certain lookup criteria. For more 01570 /// information about lookup criteria, see the documentation for the 01571 /// class LookupCriteria. 01572 /// 01573 /// \param R captures both the lookup criteria and any lookup results found. 01574 /// 01575 /// \param LookupCtx The context in which qualified name lookup will 01576 /// search. If the lookup criteria permits, name lookup may also search 01577 /// in the parent contexts or (for C++ classes) base classes. 01578 /// 01579 /// \param InUnqualifiedLookup true if this is qualified name lookup that 01580 /// occurs as part of unqualified name lookup. 01581 /// 01582 /// \returns true if lookup succeeded, false if it failed. 01583 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 01584 bool InUnqualifiedLookup) { 01585 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 01586 01587 if (!R.getLookupName()) 01588 return false; 01589 01590 // Make sure that the declaration context is complete. 01591 assert((!isa<TagDecl>(LookupCtx) || 01592 LookupCtx->isDependentContext() || 01593 cast<TagDecl>(LookupCtx)->isCompleteDefinition() || 01594 cast<TagDecl>(LookupCtx)->isBeingDefined()) && 01595 "Declaration context must already be complete!"); 01596 01597 // Perform qualified name lookup into the LookupCtx. 01598 if (LookupDirect(*this, R, LookupCtx)) { 01599 R.resolveKind(); 01600 if (isa<CXXRecordDecl>(LookupCtx)) 01601 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 01602 return true; 01603 } 01604 01605 // Don't descend into implied contexts for redeclarations. 01606 // C++98 [namespace.qual]p6: 01607 // In a declaration for a namespace member in which the 01608 // declarator-id is a qualified-id, given that the qualified-id 01609 // for the namespace member has the form 01610 // nested-name-specifier unqualified-id 01611 // the unqualified-id shall name a member of the namespace 01612 // designated by the nested-name-specifier. 01613 // See also [class.mfct]p5 and [class.static.data]p2. 01614 if (R.isForRedeclaration()) 01615 return false; 01616 01617 // If this is a namespace, look it up in the implied namespaces. 01618 if (LookupCtx->isFileContext()) 01619 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 01620 01621 // If this isn't a C++ class, we aren't allowed to look into base 01622 // classes, we're done. 01623 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 01624 if (!LookupRec || !LookupRec->getDefinition()) 01625 return false; 01626 01627 // If we're performing qualified name lookup into a dependent class, 01628 // then we are actually looking into a current instantiation. If we have any 01629 // dependent base classes, then we either have to delay lookup until 01630 // template instantiation time (at which point all bases will be available) 01631 // or we have to fail. 01632 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 01633 LookupRec->hasAnyDependentBases()) { 01634 R.setNotFoundInCurrentInstantiation(); 01635 return false; 01636 } 01637 01638 // Perform lookup into our base classes. 01639 CXXBasePaths Paths; 01640 Paths.setOrigin(LookupRec); 01641 01642 // Look for this member in our base classes 01643 CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr; 01644 switch (R.getLookupKind()) { 01645 case LookupObjCImplicitSelfParam: 01646 case LookupOrdinaryName: 01647 case LookupMemberName: 01648 case LookupRedeclarationWithLinkage: 01649 case LookupLocalFriendName: 01650 BaseCallback = &CXXRecordDecl::FindOrdinaryMember; 01651 break; 01652 01653 case LookupTagName: 01654 BaseCallback = &CXXRecordDecl::FindTagMember; 01655 break; 01656 01657 case LookupAnyName: 01658 BaseCallback = &LookupAnyMember; 01659 break; 01660 01661 case LookupUsingDeclName: 01662 // This lookup is for redeclarations only. 01663 01664 case LookupOperatorName: 01665 case LookupNamespaceName: 01666 case LookupObjCProtocolName: 01667 case LookupLabel: 01668 // These lookups will never find a member in a C++ class (or base class). 01669 return false; 01670 01671 case LookupNestedNameSpecifierName: 01672 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; 01673 break; 01674 } 01675 01676 if (!LookupRec->lookupInBases(BaseCallback, 01677 R.getLookupName().getAsOpaquePtr(), Paths)) 01678 return false; 01679 01680 R.setNamingClass(LookupRec); 01681 01682 // C++ [class.member.lookup]p2: 01683 // [...] If the resulting set of declarations are not all from 01684 // sub-objects of the same type, or the set has a nonstatic member 01685 // and includes members from distinct sub-objects, there is an 01686 // ambiguity and the program is ill-formed. Otherwise that set is 01687 // the result of the lookup. 01688 QualType SubobjectType; 01689 int SubobjectNumber = 0; 01690 AccessSpecifier SubobjectAccess = AS_none; 01691 01692 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 01693 Path != PathEnd; ++Path) { 01694 const CXXBasePathElement &PathElement = Path->back(); 01695 01696 // Pick the best (i.e. most permissive i.e. numerically lowest) access 01697 // across all paths. 01698 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 01699 01700 // Determine whether we're looking at a distinct sub-object or not. 01701 if (SubobjectType.isNull()) { 01702 // This is the first subobject we've looked at. Record its type. 01703 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 01704 SubobjectNumber = PathElement.SubobjectNumber; 01705 continue; 01706 } 01707 01708 if (SubobjectType 01709 != Context.getCanonicalType(PathElement.Base->getType())) { 01710 // We found members of the given name in two subobjects of 01711 // different types. If the declaration sets aren't the same, this 01712 // lookup is ambiguous. 01713 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) { 01714 CXXBasePaths::paths_iterator FirstPath = Paths.begin(); 01715 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin(); 01716 DeclContext::lookup_iterator CurrentD = Path->Decls.begin(); 01717 01718 while (FirstD != FirstPath->Decls.end() && 01719 CurrentD != Path->Decls.end()) { 01720 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() != 01721 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl()) 01722 break; 01723 01724 ++FirstD; 01725 ++CurrentD; 01726 } 01727 01728 if (FirstD == FirstPath->Decls.end() && 01729 CurrentD == Path->Decls.end()) 01730 continue; 01731 } 01732 01733 R.setAmbiguousBaseSubobjectTypes(Paths); 01734 return true; 01735 } 01736 01737 if (SubobjectNumber != PathElement.SubobjectNumber) { 01738 // We have a different subobject of the same type. 01739 01740 // C++ [class.member.lookup]p5: 01741 // A static member, a nested type or an enumerator defined in 01742 // a base class T can unambiguously be found even if an object 01743 // has more than one base class subobject of type T. 01744 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) 01745 continue; 01746 01747 // We have found a nonstatic member name in multiple, distinct 01748 // subobjects. Name lookup is ambiguous. 01749 R.setAmbiguousBaseSubobjects(Paths); 01750 return true; 01751 } 01752 } 01753 01754 // Lookup in a base class succeeded; return these results. 01755 01756 for (auto *D : Paths.front().Decls) { 01757 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 01758 D->getAccess()); 01759 R.addDecl(D, AS); 01760 } 01761 R.resolveKind(); 01762 return true; 01763 } 01764 01765 /// @brief Performs name lookup for a name that was parsed in the 01766 /// source code, and may contain a C++ scope specifier. 01767 /// 01768 /// This routine is a convenience routine meant to be called from 01769 /// contexts that receive a name and an optional C++ scope specifier 01770 /// (e.g., "N::M::x"). It will then perform either qualified or 01771 /// unqualified name lookup (with LookupQualifiedName or LookupName, 01772 /// respectively) on the given name and return those results. It will 01773 /// perform a special type of lookup for "__super::" scope specifier. 01774 /// 01775 /// @param S The scope from which unqualified name lookup will 01776 /// begin. 01777 /// 01778 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 01779 /// 01780 /// @param EnteringContext Indicates whether we are going to enter the 01781 /// context of the scope-specifier SS (if present). 01782 /// 01783 /// @returns True if any decls were found (but possibly ambiguous) 01784 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 01785 bool AllowBuiltinCreation, bool EnteringContext) { 01786 if (SS && SS->isInvalid()) { 01787 // When the scope specifier is invalid, don't even look for 01788 // anything. 01789 return false; 01790 } 01791 01792 if (SS && SS->isSet()) { 01793 NestedNameSpecifier *NNS = SS->getScopeRep(); 01794 if (NNS->getKind() == NestedNameSpecifier::Super) 01795 return LookupInSuper(R, NNS->getAsRecordDecl()); 01796 01797 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 01798 // We have resolved the scope specifier to a particular declaration 01799 // contex, and will perform name lookup in that context. 01800 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 01801 return false; 01802 01803 R.setContextRange(SS->getRange()); 01804 return LookupQualifiedName(R, DC); 01805 } 01806 01807 // We could not resolve the scope specified to a specific declaration 01808 // context, which means that SS refers to an unknown specialization. 01809 // Name lookup can't find anything in this case. 01810 R.setNotFoundInCurrentInstantiation(); 01811 R.setContextRange(SS->getRange()); 01812 return false; 01813 } 01814 01815 // Perform unqualified name lookup starting in the given scope. 01816 return LookupName(R, S, AllowBuiltinCreation); 01817 } 01818 01819 /// \brief Perform qualified name lookup into all base classes of the given 01820 /// class. 01821 /// 01822 /// \param R captures both the lookup criteria and any lookup results found. 01823 /// 01824 /// \param Class The context in which qualified name lookup will 01825 /// search. Name lookup will search in all base classes merging the results. 01826 /// 01827 /// @returns True if any decls were found (but possibly ambiguous) 01828 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) { 01829 for (const auto &BaseSpec : Class->bases()) { 01830 CXXRecordDecl *RD = cast<CXXRecordDecl>( 01831 BaseSpec.getType()->castAs<RecordType>()->getDecl()); 01832 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind()); 01833 Result.setBaseObjectType(Context.getRecordType(Class)); 01834 LookupQualifiedName(Result, RD); 01835 for (auto *Decl : Result) 01836 R.addDecl(Decl); 01837 } 01838 01839 R.resolveKind(); 01840 01841 return !R.empty(); 01842 } 01843 01844 /// \brief Produce a diagnostic describing the ambiguity that resulted 01845 /// from name lookup. 01846 /// 01847 /// \param Result The result of the ambiguous lookup to be diagnosed. 01848 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 01849 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 01850 01851 DeclarationName Name = Result.getLookupName(); 01852 SourceLocation NameLoc = Result.getNameLoc(); 01853 SourceRange LookupRange = Result.getContextRange(); 01854 01855 switch (Result.getAmbiguityKind()) { 01856 case LookupResult::AmbiguousBaseSubobjects: { 01857 CXXBasePaths *Paths = Result.getBasePaths(); 01858 QualType SubobjectType = Paths->front().back().Base->getType(); 01859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 01860 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 01861 << LookupRange; 01862 01863 DeclContext::lookup_iterator Found = Paths->front().Decls.begin(); 01864 while (isa<CXXMethodDecl>(*Found) && 01865 cast<CXXMethodDecl>(*Found)->isStatic()) 01866 ++Found; 01867 01868 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 01869 break; 01870 } 01871 01872 case LookupResult::AmbiguousBaseSubobjectTypes: { 01873 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 01874 << Name << LookupRange; 01875 01876 CXXBasePaths *Paths = Result.getBasePaths(); 01877 std::set<Decl *> DeclsPrinted; 01878 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 01879 PathEnd = Paths->end(); 01880 Path != PathEnd; ++Path) { 01881 Decl *D = Path->Decls.front(); 01882 if (DeclsPrinted.insert(D).second) 01883 Diag(D->getLocation(), diag::note_ambiguous_member_found); 01884 } 01885 break; 01886 } 01887 01888 case LookupResult::AmbiguousTagHiding: { 01889 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 01890 01891 llvm::SmallPtrSet<NamedDecl*,8> TagDecls; 01892 01893 for (auto *D : Result) 01894 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 01895 TagDecls.insert(TD); 01896 Diag(TD->getLocation(), diag::note_hidden_tag); 01897 } 01898 01899 for (auto *D : Result) 01900 if (!isa<TagDecl>(D)) 01901 Diag(D->getLocation(), diag::note_hiding_object); 01902 01903 // For recovery purposes, go ahead and implement the hiding. 01904 LookupResult::Filter F = Result.makeFilter(); 01905 while (F.hasNext()) { 01906 if (TagDecls.count(F.next())) 01907 F.erase(); 01908 } 01909 F.done(); 01910 break; 01911 } 01912 01913 case LookupResult::AmbiguousReference: { 01914 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 01915 01916 for (auto *D : Result) 01917 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D; 01918 break; 01919 } 01920 } 01921 } 01922 01923 namespace { 01924 struct AssociatedLookup { 01925 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, 01926 Sema::AssociatedNamespaceSet &Namespaces, 01927 Sema::AssociatedClassSet &Classes) 01928 : S(S), Namespaces(Namespaces), Classes(Classes), 01929 InstantiationLoc(InstantiationLoc) { 01930 } 01931 01932 Sema &S; 01933 Sema::AssociatedNamespaceSet &Namespaces; 01934 Sema::AssociatedClassSet &Classes; 01935 SourceLocation InstantiationLoc; 01936 }; 01937 } 01938 01939 static void 01940 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 01941 01942 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 01943 DeclContext *Ctx) { 01944 // Add the associated namespace for this class. 01945 01946 // We don't use DeclContext::getEnclosingNamespaceContext() as this may 01947 // be a locally scoped record. 01948 01949 // We skip out of inline namespaces. The innermost non-inline namespace 01950 // contains all names of all its nested inline namespaces anyway, so we can 01951 // replace the entire inline namespace tree with its root. 01952 while (Ctx->isRecord() || Ctx->isTransparentContext() || 01953 Ctx->isInlineNamespace()) 01954 Ctx = Ctx->getParent(); 01955 01956 if (Ctx->isFileContext()) 01957 Namespaces.insert(Ctx->getPrimaryContext()); 01958 } 01959 01960 // \brief Add the associated classes and namespaces for argument-dependent 01961 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 01962 static void 01963 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 01964 const TemplateArgument &Arg) { 01965 // C++ [basic.lookup.koenig]p2, last bullet: 01966 // -- [...] ; 01967 switch (Arg.getKind()) { 01968 case TemplateArgument::Null: 01969 break; 01970 01971 case TemplateArgument::Type: 01972 // [...] the namespaces and classes associated with the types of the 01973 // template arguments provided for template type parameters (excluding 01974 // template template parameters) 01975 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 01976 break; 01977 01978 case TemplateArgument::Template: 01979 case TemplateArgument::TemplateExpansion: { 01980 // [...] the namespaces in which any template template arguments are 01981 // defined; and the classes in which any member templates used as 01982 // template template arguments are defined. 01983 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 01984 if (ClassTemplateDecl *ClassTemplate 01985 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 01986 DeclContext *Ctx = ClassTemplate->getDeclContext(); 01987 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 01988 Result.Classes.insert(EnclosingClass); 01989 // Add the associated namespace for this class. 01990 CollectEnclosingNamespace(Result.Namespaces, Ctx); 01991 } 01992 break; 01993 } 01994 01995 case TemplateArgument::Declaration: 01996 case TemplateArgument::Integral: 01997 case TemplateArgument::Expression: 01998 case TemplateArgument::NullPtr: 01999 // [Note: non-type template arguments do not contribute to the set of 02000 // associated namespaces. ] 02001 break; 02002 02003 case TemplateArgument::Pack: 02004 for (const auto &P : Arg.pack_elements()) 02005 addAssociatedClassesAndNamespaces(Result, P); 02006 break; 02007 } 02008 } 02009 02010 // \brief Add the associated classes and namespaces for 02011 // argument-dependent lookup with an argument of class type 02012 // (C++ [basic.lookup.koenig]p2). 02013 static void 02014 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 02015 CXXRecordDecl *Class) { 02016 02017 // Just silently ignore anything whose name is __va_list_tag. 02018 if (Class->getDeclName() == Result.S.VAListTagName) 02019 return; 02020 02021 // C++ [basic.lookup.koenig]p2: 02022 // [...] 02023 // -- If T is a class type (including unions), its associated 02024 // classes are: the class itself; the class of which it is a 02025 // member, if any; and its direct and indirect base 02026 // classes. Its associated namespaces are the namespaces in 02027 // which its associated classes are defined. 02028 02029 // Add the class of which it is a member, if any. 02030 DeclContext *Ctx = Class->getDeclContext(); 02031 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 02032 Result.Classes.insert(EnclosingClass); 02033 // Add the associated namespace for this class. 02034 CollectEnclosingNamespace(Result.Namespaces, Ctx); 02035 02036 // Add the class itself. If we've already seen this class, we don't 02037 // need to visit base classes. 02038 // 02039 // FIXME: That's not correct, we may have added this class only because it 02040 // was the enclosing class of another class, and in that case we won't have 02041 // added its base classes yet. 02042 if (!Result.Classes.insert(Class)) 02043 return; 02044 02045 // -- If T is a template-id, its associated namespaces and classes are 02046 // the namespace in which the template is defined; for member 02047 // templates, the member template's class; the namespaces and classes 02048 // associated with the types of the template arguments provided for 02049 // template type parameters (excluding template template parameters); the 02050 // namespaces in which any template template arguments are defined; and 02051 // the classes in which any member templates used as template template 02052 // arguments are defined. [Note: non-type template arguments do not 02053 // contribute to the set of associated namespaces. ] 02054 if (ClassTemplateSpecializationDecl *Spec 02055 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 02056 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 02057 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 02058 Result.Classes.insert(EnclosingClass); 02059 // Add the associated namespace for this class. 02060 CollectEnclosingNamespace(Result.Namespaces, Ctx); 02061 02062 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 02063 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 02064 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 02065 } 02066 02067 // Only recurse into base classes for complete types. 02068 if (!Class->hasDefinition()) 02069 return; 02070 02071 // Add direct and indirect base classes along with their associated 02072 // namespaces. 02073 SmallVector<CXXRecordDecl *, 32> Bases; 02074 Bases.push_back(Class); 02075 while (!Bases.empty()) { 02076 // Pop this class off the stack. 02077 Class = Bases.pop_back_val(); 02078 02079 // Visit the base classes. 02080 for (const auto &Base : Class->bases()) { 02081 const RecordType *BaseType = Base.getType()->getAs<RecordType>(); 02082 // In dependent contexts, we do ADL twice, and the first time around, 02083 // the base type might be a dependent TemplateSpecializationType, or a 02084 // TemplateTypeParmType. If that happens, simply ignore it. 02085 // FIXME: If we want to support export, we probably need to add the 02086 // namespace of the template in a TemplateSpecializationType, or even 02087 // the classes and namespaces of known non-dependent arguments. 02088 if (!BaseType) 02089 continue; 02090 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 02091 if (Result.Classes.insert(BaseDecl)) { 02092 // Find the associated namespace for this base class. 02093 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 02094 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 02095 02096 // Make sure we visit the bases of this base class. 02097 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 02098 Bases.push_back(BaseDecl); 02099 } 02100 } 02101 } 02102 } 02103 02104 // \brief Add the associated classes and namespaces for 02105 // argument-dependent lookup with an argument of type T 02106 // (C++ [basic.lookup.koenig]p2). 02107 static void 02108 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 02109 // C++ [basic.lookup.koenig]p2: 02110 // 02111 // For each argument type T in the function call, there is a set 02112 // of zero or more associated namespaces and a set of zero or more 02113 // associated classes to be considered. The sets of namespaces and 02114 // classes is determined entirely by the types of the function 02115 // arguments (and the namespace of any template template 02116 // argument). Typedef names and using-declarations used to specify 02117 // the types do not contribute to this set. The sets of namespaces 02118 // and classes are determined in the following way: 02119 02120 SmallVector<const Type *, 16> Queue; 02121 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 02122 02123 while (true) { 02124 switch (T->getTypeClass()) { 02125 02126 #define TYPE(Class, Base) 02127 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 02128 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 02129 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 02130 #define ABSTRACT_TYPE(Class, Base) 02131 #include "clang/AST/TypeNodes.def" 02132 // T is canonical. We can also ignore dependent types because 02133 // we don't need to do ADL at the definition point, but if we 02134 // wanted to implement template export (or if we find some other 02135 // use for associated classes and namespaces...) this would be 02136 // wrong. 02137 break; 02138 02139 // -- If T is a pointer to U or an array of U, its associated 02140 // namespaces and classes are those associated with U. 02141 case Type::Pointer: 02142 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 02143 continue; 02144 case Type::ConstantArray: 02145 case Type::IncompleteArray: 02146 case Type::VariableArray: 02147 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 02148 continue; 02149 02150 // -- If T is a fundamental type, its associated sets of 02151 // namespaces and classes are both empty. 02152 case Type::Builtin: 02153 break; 02154 02155 // -- If T is a class type (including unions), its associated 02156 // classes are: the class itself; the class of which it is a 02157 // member, if any; and its direct and indirect base 02158 // classes. Its associated namespaces are the namespaces in 02159 // which its associated classes are defined. 02160 case Type::Record: { 02161 Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0), 02162 /*no diagnostic*/ 0); 02163 CXXRecordDecl *Class 02164 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 02165 addAssociatedClassesAndNamespaces(Result, Class); 02166 break; 02167 } 02168 02169 // -- If T is an enumeration type, its associated namespace is 02170 // the namespace in which it is defined. If it is class 02171 // member, its associated class is the member's class; else 02172 // it has no associated class. 02173 case Type::Enum: { 02174 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 02175 02176 DeclContext *Ctx = Enum->getDeclContext(); 02177 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 02178 Result.Classes.insert(EnclosingClass); 02179 02180 // Add the associated namespace for this class. 02181 CollectEnclosingNamespace(Result.Namespaces, Ctx); 02182 02183 break; 02184 } 02185 02186 // -- If T is a function type, its associated namespaces and 02187 // classes are those associated with the function parameter 02188 // types and those associated with the return type. 02189 case Type::FunctionProto: { 02190 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 02191 for (const auto &Arg : Proto->param_types()) 02192 Queue.push_back(Arg.getTypePtr()); 02193 // fallthrough 02194 } 02195 case Type::FunctionNoProto: { 02196 const FunctionType *FnType = cast<FunctionType>(T); 02197 T = FnType->getReturnType().getTypePtr(); 02198 continue; 02199 } 02200 02201 // -- If T is a pointer to a member function of a class X, its 02202 // associated namespaces and classes are those associated 02203 // with the function parameter types and return type, 02204 // together with those associated with X. 02205 // 02206 // -- If T is a pointer to a data member of class X, its 02207 // associated namespaces and classes are those associated 02208 // with the member type together with those associated with 02209 // X. 02210 case Type::MemberPointer: { 02211 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 02212 02213 // Queue up the class type into which this points. 02214 Queue.push_back(MemberPtr->getClass()); 02215 02216 // And directly continue with the pointee type. 02217 T = MemberPtr->getPointeeType().getTypePtr(); 02218 continue; 02219 } 02220 02221 // As an extension, treat this like a normal pointer. 02222 case Type::BlockPointer: 02223 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 02224 continue; 02225 02226 // References aren't covered by the standard, but that's such an 02227 // obvious defect that we cover them anyway. 02228 case Type::LValueReference: 02229 case Type::RValueReference: 02230 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 02231 continue; 02232 02233 // These are fundamental types. 02234 case Type::Vector: 02235 case Type::ExtVector: 02236 case Type::Complex: 02237 break; 02238 02239 // Non-deduced auto types only get here for error cases. 02240 case Type::Auto: 02241 break; 02242 02243 // If T is an Objective-C object or interface type, or a pointer to an 02244 // object or interface type, the associated namespace is the global 02245 // namespace. 02246 case Type::ObjCObject: 02247 case Type::ObjCInterface: 02248 case Type::ObjCObjectPointer: 02249 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); 02250 break; 02251 02252 // Atomic types are just wrappers; use the associations of the 02253 // contained type. 02254 case Type::Atomic: 02255 T = cast<AtomicType>(T)->getValueType().getTypePtr(); 02256 continue; 02257 } 02258 02259 if (Queue.empty()) 02260 break; 02261 T = Queue.pop_back_val(); 02262 } 02263 } 02264 02265 /// \brief Find the associated classes and namespaces for 02266 /// argument-dependent lookup for a call with the given set of 02267 /// arguments. 02268 /// 02269 /// This routine computes the sets of associated classes and associated 02270 /// namespaces searched by argument-dependent lookup 02271 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 02272 void Sema::FindAssociatedClassesAndNamespaces( 02273 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 02274 AssociatedNamespaceSet &AssociatedNamespaces, 02275 AssociatedClassSet &AssociatedClasses) { 02276 AssociatedNamespaces.clear(); 02277 AssociatedClasses.clear(); 02278 02279 AssociatedLookup Result(*this, InstantiationLoc, 02280 AssociatedNamespaces, AssociatedClasses); 02281 02282 // C++ [basic.lookup.koenig]p2: 02283 // For each argument type T in the function call, there is a set 02284 // of zero or more associated namespaces and a set of zero or more 02285 // associated classes to be considered. The sets of namespaces and 02286 // classes is determined entirely by the types of the function 02287 // arguments (and the namespace of any template template 02288 // argument). 02289 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 02290 Expr *Arg = Args[ArgIdx]; 02291 02292 if (Arg->getType() != Context.OverloadTy) { 02293 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 02294 continue; 02295 } 02296 02297 // [...] In addition, if the argument is the name or address of a 02298 // set of overloaded functions and/or function templates, its 02299 // associated classes and namespaces are the union of those 02300 // associated with each of the members of the set: the namespace 02301 // in which the function or function template is defined and the 02302 // classes and namespaces associated with its (non-dependent) 02303 // parameter types and return type. 02304 Arg = Arg->IgnoreParens(); 02305 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) 02306 if (unaryOp->getOpcode() == UO_AddrOf) 02307 Arg = unaryOp->getSubExpr(); 02308 02309 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); 02310 if (!ULE) continue; 02311 02312 for (const auto *D : ULE->decls()) { 02313 // Look through any using declarations to find the underlying function. 02314 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction(); 02315 02316 // Add the classes and namespaces associated with the parameter 02317 // types and return type of this function. 02318 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 02319 } 02320 } 02321 } 02322 02323 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 02324 SourceLocation Loc, 02325 LookupNameKind NameKind, 02326 RedeclarationKind Redecl) { 02327 LookupResult R(*this, Name, Loc, NameKind, Redecl); 02328 LookupName(R, S); 02329 return R.getAsSingle<NamedDecl>(); 02330 } 02331 02332 /// \brief Find the protocol with the given name, if any. 02333 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 02334 SourceLocation IdLoc, 02335 RedeclarationKind Redecl) { 02336 Decl *D = LookupSingleName(TUScope, II, IdLoc, 02337 LookupObjCProtocolName, Redecl); 02338 return cast_or_null<ObjCProtocolDecl>(D); 02339 } 02340 02341 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 02342 QualType T1, QualType T2, 02343 UnresolvedSetImpl &Functions) { 02344 // C++ [over.match.oper]p3: 02345 // -- The set of non-member candidates is the result of the 02346 // unqualified lookup of operator@ in the context of the 02347 // expression according to the usual rules for name lookup in 02348 // unqualified function calls (3.4.2) except that all member 02349 // functions are ignored. 02350 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 02351 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 02352 LookupName(Operators, S); 02353 02354 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 02355 Functions.append(Operators.begin(), Operators.end()); 02356 } 02357 02358 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD, 02359 CXXSpecialMember SM, 02360 bool ConstArg, 02361 bool VolatileArg, 02362 bool RValueThis, 02363 bool ConstThis, 02364 bool VolatileThis) { 02365 assert(CanDeclareSpecialMemberFunction(RD) && 02366 "doing special member lookup into record that isn't fully complete"); 02367 RD = RD->getDefinition(); 02368 if (RValueThis || ConstThis || VolatileThis) 02369 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && 02370 "constructors and destructors always have unqualified lvalue this"); 02371 if (ConstArg || VolatileArg) 02372 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && 02373 "parameter-less special members can't have qualified arguments"); 02374 02375 llvm::FoldingSetNodeID ID; 02376 ID.AddPointer(RD); 02377 ID.AddInteger(SM); 02378 ID.AddInteger(ConstArg); 02379 ID.AddInteger(VolatileArg); 02380 ID.AddInteger(RValueThis); 02381 ID.AddInteger(ConstThis); 02382 ID.AddInteger(VolatileThis); 02383 02384 void *InsertPoint; 02385 SpecialMemberOverloadResult *Result = 02386 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); 02387 02388 // This was already cached 02389 if (Result) 02390 return Result; 02391 02392 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>(); 02393 Result = new (Result) SpecialMemberOverloadResult(ID); 02394 SpecialMemberCache.InsertNode(Result, InsertPoint); 02395 02396 if (SM == CXXDestructor) { 02397 if (RD->needsImplicitDestructor()) 02398 DeclareImplicitDestructor(RD); 02399 CXXDestructorDecl *DD = RD->getDestructor(); 02400 assert(DD && "record without a destructor"); 02401 Result->setMethod(DD); 02402 Result->setKind(DD->isDeleted() ? 02403 SpecialMemberOverloadResult::NoMemberOrDeleted : 02404 SpecialMemberOverloadResult::Success); 02405 return Result; 02406 } 02407 02408 // Prepare for overload resolution. Here we construct a synthetic argument 02409 // if necessary and make sure that implicit functions are declared. 02410 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); 02411 DeclarationName Name; 02412 Expr *Arg = nullptr; 02413 unsigned NumArgs; 02414 02415 QualType ArgType = CanTy; 02416 ExprValueKind VK = VK_LValue; 02417 02418 if (SM == CXXDefaultConstructor) { 02419 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 02420 NumArgs = 0; 02421 if (RD->needsImplicitDefaultConstructor()) 02422 DeclareImplicitDefaultConstructor(RD); 02423 } else { 02424 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { 02425 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 02426 if (RD->needsImplicitCopyConstructor()) 02427 DeclareImplicitCopyConstructor(RD); 02428 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) 02429 DeclareImplicitMoveConstructor(RD); 02430 } else { 02431 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 02432 if (RD->needsImplicitCopyAssignment()) 02433 DeclareImplicitCopyAssignment(RD); 02434 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) 02435 DeclareImplicitMoveAssignment(RD); 02436 } 02437 02438 if (ConstArg) 02439 ArgType.addConst(); 02440 if (VolatileArg) 02441 ArgType.addVolatile(); 02442 02443 // This isn't /really/ specified by the standard, but it's implied 02444 // we should be working from an RValue in the case of move to ensure 02445 // that we prefer to bind to rvalue references, and an LValue in the 02446 // case of copy to ensure we don't bind to rvalue references. 02447 // Possibly an XValue is actually correct in the case of move, but 02448 // there is no semantic difference for class types in this restricted 02449 // case. 02450 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) 02451 VK = VK_LValue; 02452 else 02453 VK = VK_RValue; 02454 } 02455 02456 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK); 02457 02458 if (SM != CXXDefaultConstructor) { 02459 NumArgs = 1; 02460 Arg = &FakeArg; 02461 } 02462 02463 // Create the object argument 02464 QualType ThisTy = CanTy; 02465 if (ConstThis) 02466 ThisTy.addConst(); 02467 if (VolatileThis) 02468 ThisTy.addVolatile(); 02469 Expr::Classification Classification = 02470 OpaqueValueExpr(SourceLocation(), ThisTy, 02471 RValueThis ? VK_RValue : VK_LValue).Classify(Context); 02472 02473 // Now we perform lookup on the name we computed earlier and do overload 02474 // resolution. Lookup is only performed directly into the class since there 02475 // will always be a (possibly implicit) declaration to shadow any others. 02476 OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal); 02477 DeclContext::lookup_result R = RD->lookup(Name); 02478 assert(!R.empty() && 02479 "lookup for a constructor or assignment operator was empty"); 02480 02481 // Copy the candidates as our processing of them may load new declarations 02482 // from an external source and invalidate lookup_result. 02483 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); 02484 02485 for (auto *Cand : Candidates) { 02486 if (Cand->isInvalidDecl()) 02487 continue; 02488 02489 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) { 02490 // FIXME: [namespace.udecl]p15 says that we should only consider a 02491 // using declaration here if it does not match a declaration in the 02492 // derived class. We do not implement this correctly in other cases 02493 // either. 02494 Cand = U->getTargetDecl(); 02495 02496 if (Cand->isInvalidDecl()) 02497 continue; 02498 } 02499 02500 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) { 02501 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 02502 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy, 02503 Classification, llvm::makeArrayRef(&Arg, NumArgs), 02504 OCS, true); 02505 else 02506 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), 02507 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 02508 } else if (FunctionTemplateDecl *Tmpl = 02509 dyn_cast<FunctionTemplateDecl>(Cand)) { 02510 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 02511 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 02512 RD, nullptr, ThisTy, Classification, 02513 llvm::makeArrayRef(&Arg, NumArgs), 02514 OCS, true); 02515 else 02516 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public), 02517 nullptr, llvm::makeArrayRef(&Arg, NumArgs), 02518 OCS, true); 02519 } else { 02520 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl"); 02521 } 02522 } 02523 02524 OverloadCandidateSet::iterator Best; 02525 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) { 02526 case OR_Success: 02527 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 02528 Result->setKind(SpecialMemberOverloadResult::Success); 02529 break; 02530 02531 case OR_Deleted: 02532 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 02533 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 02534 break; 02535 02536 case OR_Ambiguous: 02537 Result->setMethod(nullptr); 02538 Result->setKind(SpecialMemberOverloadResult::Ambiguous); 02539 break; 02540 02541 case OR_No_Viable_Function: 02542 Result->setMethod(nullptr); 02543 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 02544 break; 02545 } 02546 02547 return Result; 02548 } 02549 02550 /// \brief Look up the default constructor for the given class. 02551 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { 02552 SpecialMemberOverloadResult *Result = 02553 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, 02554 false, false); 02555 02556 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 02557 } 02558 02559 /// \brief Look up the copying constructor for the given class. 02560 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, 02561 unsigned Quals) { 02562 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 02563 "non-const, non-volatile qualifiers for copy ctor arg"); 02564 SpecialMemberOverloadResult *Result = 02565 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, 02566 Quals & Qualifiers::Volatile, false, false, false); 02567 02568 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 02569 } 02570 02571 /// \brief Look up the moving constructor for the given class. 02572 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, 02573 unsigned Quals) { 02574 SpecialMemberOverloadResult *Result = 02575 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, 02576 Quals & Qualifiers::Volatile, false, false, false); 02577 02578 return cast_or_null<CXXConstructorDecl>(Result->getMethod()); 02579 } 02580 02581 /// \brief Look up the constructors for the given class. 02582 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 02583 // If the implicit constructors have not yet been declared, do so now. 02584 if (CanDeclareSpecialMemberFunction(Class)) { 02585 if (Class->needsImplicitDefaultConstructor()) 02586 DeclareImplicitDefaultConstructor(Class); 02587 if (Class->needsImplicitCopyConstructor()) 02588 DeclareImplicitCopyConstructor(Class); 02589 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) 02590 DeclareImplicitMoveConstructor(Class); 02591 } 02592 02593 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 02594 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 02595 return Class->lookup(Name); 02596 } 02597 02598 /// \brief Look up the copying assignment operator for the given class. 02599 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, 02600 unsigned Quals, bool RValueThis, 02601 unsigned ThisQuals) { 02602 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 02603 "non-const, non-volatile qualifiers for copy assignment arg"); 02604 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 02605 "non-const, non-volatile qualifiers for copy assignment this"); 02606 SpecialMemberOverloadResult *Result = 02607 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, 02608 Quals & Qualifiers::Volatile, RValueThis, 02609 ThisQuals & Qualifiers::Const, 02610 ThisQuals & Qualifiers::Volatile); 02611 02612 return Result->getMethod(); 02613 } 02614 02615 /// \brief Look up the moving assignment operator for the given class. 02616 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, 02617 unsigned Quals, 02618 bool RValueThis, 02619 unsigned ThisQuals) { 02620 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 02621 "non-const, non-volatile qualifiers for copy assignment this"); 02622 SpecialMemberOverloadResult *Result = 02623 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, 02624 Quals & Qualifiers::Volatile, RValueThis, 02625 ThisQuals & Qualifiers::Const, 02626 ThisQuals & Qualifiers::Volatile); 02627 02628 return Result->getMethod(); 02629 } 02630 02631 /// \brief Look for the destructor of the given class. 02632 /// 02633 /// During semantic analysis, this routine should be used in lieu of 02634 /// CXXRecordDecl::getDestructor(). 02635 /// 02636 /// \returns The destructor for this class. 02637 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 02638 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor, 02639 false, false, false, 02640 false, false)->getMethod()); 02641 } 02642 02643 /// LookupLiteralOperator - Determine which literal operator should be used for 02644 /// a user-defined literal, per C++11 [lex.ext]. 02645 /// 02646 /// Normal overload resolution is not used to select which literal operator to 02647 /// call for a user-defined literal. Look up the provided literal operator name, 02648 /// and filter the results to the appropriate set for the given argument types. 02649 Sema::LiteralOperatorLookupResult 02650 Sema::LookupLiteralOperator(Scope *S, LookupResult &R, 02651 ArrayRef<QualType> ArgTys, 02652 bool AllowRaw, bool AllowTemplate, 02653 bool AllowStringTemplate) { 02654 LookupName(R, S); 02655 assert(R.getResultKind() != LookupResult::Ambiguous && 02656 "literal operator lookup can't be ambiguous"); 02657 02658 // Filter the lookup results appropriately. 02659 LookupResult::Filter F = R.makeFilter(); 02660 02661 bool FoundRaw = false; 02662 bool FoundTemplate = false; 02663 bool FoundStringTemplate = false; 02664 bool FoundExactMatch = false; 02665 02666 while (F.hasNext()) { 02667 Decl *D = F.next(); 02668 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 02669 D = USD->getTargetDecl(); 02670 02671 // If the declaration we found is invalid, skip it. 02672 if (D->isInvalidDecl()) { 02673 F.erase(); 02674 continue; 02675 } 02676 02677 bool IsRaw = false; 02678 bool IsTemplate = false; 02679 bool IsStringTemplate = false; 02680 bool IsExactMatch = false; 02681 02682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 02683 if (FD->getNumParams() == 1 && 02684 FD->getParamDecl(0)->getType()->getAs<PointerType>()) 02685 IsRaw = true; 02686 else if (FD->getNumParams() == ArgTys.size()) { 02687 IsExactMatch = true; 02688 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { 02689 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); 02690 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { 02691 IsExactMatch = false; 02692 break; 02693 } 02694 } 02695 } 02696 } 02697 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) { 02698 TemplateParameterList *Params = FD->getTemplateParameters(); 02699 if (Params->size() == 1) 02700 IsTemplate = true; 02701 else 02702 IsStringTemplate = true; 02703 } 02704 02705 if (IsExactMatch) { 02706 FoundExactMatch = true; 02707 AllowRaw = false; 02708 AllowTemplate = false; 02709 AllowStringTemplate = false; 02710 if (FoundRaw || FoundTemplate || FoundStringTemplate) { 02711 // Go through again and remove the raw and template decls we've 02712 // already found. 02713 F.restart(); 02714 FoundRaw = FoundTemplate = FoundStringTemplate = false; 02715 } 02716 } else if (AllowRaw && IsRaw) { 02717 FoundRaw = true; 02718 } else if (AllowTemplate && IsTemplate) { 02719 FoundTemplate = true; 02720 } else if (AllowStringTemplate && IsStringTemplate) { 02721 FoundStringTemplate = true; 02722 } else { 02723 F.erase(); 02724 } 02725 } 02726 02727 F.done(); 02728 02729 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching 02730 // parameter type, that is used in preference to a raw literal operator 02731 // or literal operator template. 02732 if (FoundExactMatch) 02733 return LOLR_Cooked; 02734 02735 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal 02736 // operator template, but not both. 02737 if (FoundRaw && FoundTemplate) { 02738 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 02739 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 02740 NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction()); 02741 return LOLR_Error; 02742 } 02743 02744 if (FoundRaw) 02745 return LOLR_Raw; 02746 02747 if (FoundTemplate) 02748 return LOLR_Template; 02749 02750 if (FoundStringTemplate) 02751 return LOLR_StringTemplate; 02752 02753 // Didn't find anything we could use. 02754 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) 02755 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] 02756 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw 02757 << (AllowTemplate || AllowStringTemplate); 02758 return LOLR_Error; 02759 } 02760 02761 void ADLResult::insert(NamedDecl *New) { 02762 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 02763 02764 // If we haven't yet seen a decl for this key, or the last decl 02765 // was exactly this one, we're done. 02766 if (Old == nullptr || Old == New) { 02767 Old = New; 02768 return; 02769 } 02770 02771 // Otherwise, decide which is a more recent redeclaration. 02772 FunctionDecl *OldFD = Old->getAsFunction(); 02773 FunctionDecl *NewFD = New->getAsFunction(); 02774 02775 FunctionDecl *Cursor = NewFD; 02776 while (true) { 02777 Cursor = Cursor->getPreviousDecl(); 02778 02779 // If we got to the end without finding OldFD, OldFD is the newer 02780 // declaration; leave things as they are. 02781 if (!Cursor) return; 02782 02783 // If we do find OldFD, then NewFD is newer. 02784 if (Cursor == OldFD) break; 02785 02786 // Otherwise, keep looking. 02787 } 02788 02789 Old = New; 02790 } 02791 02792 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 02793 ArrayRef<Expr *> Args, ADLResult &Result) { 02794 // Find all of the associated namespaces and classes based on the 02795 // arguments we have. 02796 AssociatedNamespaceSet AssociatedNamespaces; 02797 AssociatedClassSet AssociatedClasses; 02798 FindAssociatedClassesAndNamespaces(Loc, Args, 02799 AssociatedNamespaces, 02800 AssociatedClasses); 02801 02802 // C++ [basic.lookup.argdep]p3: 02803 // Let X be the lookup set produced by unqualified lookup (3.4.1) 02804 // and let Y be the lookup set produced by argument dependent 02805 // lookup (defined as follows). If X contains [...] then Y is 02806 // empty. Otherwise Y is the set of declarations found in the 02807 // namespaces associated with the argument types as described 02808 // below. The set of declarations found by the lookup of the name 02809 // is the union of X and Y. 02810 // 02811 // Here, we compute Y and add its members to the overloaded 02812 // candidate set. 02813 for (auto *NS : AssociatedNamespaces) { 02814 // When considering an associated namespace, the lookup is the 02815 // same as the lookup performed when the associated namespace is 02816 // used as a qualifier (3.4.3.2) except that: 02817 // 02818 // -- Any using-directives in the associated namespace are 02819 // ignored. 02820 // 02821 // -- Any namespace-scope friend functions declared in 02822 // associated classes are visible within their respective 02823 // namespaces even if they are not visible during an ordinary 02824 // lookup (11.4). 02825 DeclContext::lookup_result R = NS->lookup(Name); 02826 for (auto *D : R) { 02827 // If the only declaration here is an ordinary friend, consider 02828 // it only if it was declared in an associated classes. 02829 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) { 02830 // If it's neither ordinarily visible nor a friend, we can't find it. 02831 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0) 02832 continue; 02833 02834 bool DeclaredInAssociatedClass = false; 02835 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) { 02836 DeclContext *LexDC = DI->getLexicalDeclContext(); 02837 if (isa<CXXRecordDecl>(LexDC) && 02838 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) { 02839 DeclaredInAssociatedClass = true; 02840 break; 02841 } 02842 } 02843 if (!DeclaredInAssociatedClass) 02844 continue; 02845 } 02846 02847 if (isa<UsingShadowDecl>(D)) 02848 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 02849 02850 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) 02851 continue; 02852 02853 Result.insert(D); 02854 } 02855 } 02856 } 02857 02858 //---------------------------------------------------------------------------- 02859 // Search for all visible declarations. 02860 //---------------------------------------------------------------------------- 02861 VisibleDeclConsumer::~VisibleDeclConsumer() { } 02862 02863 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } 02864 02865 namespace { 02866 02867 class ShadowContextRAII; 02868 02869 class VisibleDeclsRecord { 02870 public: 02871 /// \brief An entry in the shadow map, which is optimized to store a 02872 /// single declaration (the common case) but can also store a list 02873 /// of declarations. 02874 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; 02875 02876 private: 02877 /// \brief A mapping from declaration names to the declarations that have 02878 /// this name within a particular scope. 02879 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 02880 02881 /// \brief A list of shadow maps, which is used to model name hiding. 02882 std::list<ShadowMap> ShadowMaps; 02883 02884 /// \brief The declaration contexts we have already visited. 02885 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 02886 02887 friend class ShadowContextRAII; 02888 02889 public: 02890 /// \brief Determine whether we have already visited this context 02891 /// (and, if not, note that we are going to visit that context now). 02892 bool visitedContext(DeclContext *Ctx) { 02893 return !VisitedContexts.insert(Ctx); 02894 } 02895 02896 bool alreadyVisitedContext(DeclContext *Ctx) { 02897 return VisitedContexts.count(Ctx); 02898 } 02899 02900 /// \brief Determine whether the given declaration is hidden in the 02901 /// current scope. 02902 /// 02903 /// \returns the declaration that hides the given declaration, or 02904 /// NULL if no such declaration exists. 02905 NamedDecl *checkHidden(NamedDecl *ND); 02906 02907 /// \brief Add a declaration to the current shadow map. 02908 void add(NamedDecl *ND) { 02909 ShadowMaps.back()[ND->getDeclName()].push_back(ND); 02910 } 02911 }; 02912 02913 /// \brief RAII object that records when we've entered a shadow context. 02914 class ShadowContextRAII { 02915 VisibleDeclsRecord &Visible; 02916 02917 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 02918 02919 public: 02920 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 02921 Visible.ShadowMaps.push_back(ShadowMap()); 02922 } 02923 02924 ~ShadowContextRAII() { 02925 Visible.ShadowMaps.pop_back(); 02926 } 02927 }; 02928 02929 } // end anonymous namespace 02930 02931 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 02932 // Look through using declarations. 02933 ND = ND->getUnderlyingDecl(); 02934 02935 unsigned IDNS = ND->getIdentifierNamespace(); 02936 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 02937 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 02938 SM != SMEnd; ++SM) { 02939 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 02940 if (Pos == SM->end()) 02941 continue; 02942 02943 for (auto *D : Pos->second) { 02944 // A tag declaration does not hide a non-tag declaration. 02945 if (D->hasTagIdentifierNamespace() && 02946 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 02947 Decl::IDNS_ObjCProtocol))) 02948 continue; 02949 02950 // Protocols are in distinct namespaces from everything else. 02951 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 02952 || (IDNS & Decl::IDNS_ObjCProtocol)) && 02953 D->getIdentifierNamespace() != IDNS) 02954 continue; 02955 02956 // Functions and function templates in the same scope overload 02957 // rather than hide. FIXME: Look for hiding based on function 02958 // signatures! 02959 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 02960 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 02961 SM == ShadowMaps.rbegin()) 02962 continue; 02963 02964 // We've found a declaration that hides this one. 02965 return D; 02966 } 02967 } 02968 02969 return nullptr; 02970 } 02971 02972 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, 02973 bool QualifiedNameLookup, 02974 bool InBaseClass, 02975 VisibleDeclConsumer &Consumer, 02976 VisibleDeclsRecord &Visited) { 02977 if (!Ctx) 02978 return; 02979 02980 // Make sure we don't visit the same context twice. 02981 if (Visited.visitedContext(Ctx->getPrimaryContext())) 02982 return; 02983 02984 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 02985 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 02986 02987 // Enumerate all of the results in this context. 02988 for (const auto &R : Ctx->lookups()) { 02989 for (auto *I : R) { 02990 if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) { 02991 if ((ND = Result.getAcceptableDecl(ND))) { 02992 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 02993 Visited.add(ND); 02994 } 02995 } 02996 } 02997 } 02998 02999 // Traverse using directives for qualified name lookup. 03000 if (QualifiedNameLookup) { 03001 ShadowContextRAII Shadow(Visited); 03002 for (auto I : Ctx->using_directives()) { 03003 LookupVisibleDecls(I->getNominatedNamespace(), Result, 03004 QualifiedNameLookup, InBaseClass, Consumer, Visited); 03005 } 03006 } 03007 03008 // Traverse the contexts of inherited C++ classes. 03009 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 03010 if (!Record->hasDefinition()) 03011 return; 03012 03013 for (const auto &B : Record->bases()) { 03014 QualType BaseType = B.getType(); 03015 03016 // Don't look into dependent bases, because name lookup can't look 03017 // there anyway. 03018 if (BaseType->isDependentType()) 03019 continue; 03020 03021 const RecordType *Record = BaseType->getAs<RecordType>(); 03022 if (!Record) 03023 continue; 03024 03025 // FIXME: It would be nice to be able to determine whether referencing 03026 // a particular member would be ambiguous. For example, given 03027 // 03028 // struct A { int member; }; 03029 // struct B { int member; }; 03030 // struct C : A, B { }; 03031 // 03032 // void f(C *c) { c->### } 03033 // 03034 // accessing 'member' would result in an ambiguity. However, we 03035 // could be smart enough to qualify the member with the base 03036 // class, e.g., 03037 // 03038 // c->B::member 03039 // 03040 // or 03041 // 03042 // c->A::member 03043 03044 // Find results in this base class (and its bases). 03045 ShadowContextRAII Shadow(Visited); 03046 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, 03047 true, Consumer, Visited); 03048 } 03049 } 03050 03051 // Traverse the contexts of Objective-C classes. 03052 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 03053 // Traverse categories. 03054 for (auto *Cat : IFace->visible_categories()) { 03055 ShadowContextRAII Shadow(Visited); 03056 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, 03057 Consumer, Visited); 03058 } 03059 03060 // Traverse protocols. 03061 for (auto *I : IFace->all_referenced_protocols()) { 03062 ShadowContextRAII Shadow(Visited); 03063 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 03064 Visited); 03065 } 03066 03067 // Traverse the superclass. 03068 if (IFace->getSuperClass()) { 03069 ShadowContextRAII Shadow(Visited); 03070 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, 03071 true, Consumer, Visited); 03072 } 03073 03074 // If there is an implementation, traverse it. We do this to find 03075 // synthesized ivars. 03076 if (IFace->getImplementation()) { 03077 ShadowContextRAII Shadow(Visited); 03078 LookupVisibleDecls(IFace->getImplementation(), Result, 03079 QualifiedNameLookup, InBaseClass, Consumer, Visited); 03080 } 03081 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 03082 for (auto *I : Protocol->protocols()) { 03083 ShadowContextRAII Shadow(Visited); 03084 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 03085 Visited); 03086 } 03087 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 03088 for (auto *I : Category->protocols()) { 03089 ShadowContextRAII Shadow(Visited); 03090 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, 03091 Visited); 03092 } 03093 03094 // If there is an implementation, traverse it. 03095 if (Category->getImplementation()) { 03096 ShadowContextRAII Shadow(Visited); 03097 LookupVisibleDecls(Category->getImplementation(), Result, 03098 QualifiedNameLookup, true, Consumer, Visited); 03099 } 03100 } 03101 } 03102 03103 static void LookupVisibleDecls(Scope *S, LookupResult &Result, 03104 UnqualUsingDirectiveSet &UDirs, 03105 VisibleDeclConsumer &Consumer, 03106 VisibleDeclsRecord &Visited) { 03107 if (!S) 03108 return; 03109 03110 if (!S->getEntity() || 03111 (!S->getParent() && 03112 !Visited.alreadyVisitedContext(S->getEntity())) || 03113 (S->getEntity())->isFunctionOrMethod()) { 03114 FindLocalExternScope FindLocals(Result); 03115 // Walk through the declarations in this Scope. 03116 for (auto *D : S->decls()) { 03117 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 03118 if ((ND = Result.getAcceptableDecl(ND))) { 03119 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false); 03120 Visited.add(ND); 03121 } 03122 } 03123 } 03124 03125 // FIXME: C++ [temp.local]p8 03126 DeclContext *Entity = nullptr; 03127 if (S->getEntity()) { 03128 // Look into this scope's declaration context, along with any of its 03129 // parent lookup contexts (e.g., enclosing classes), up to the point 03130 // where we hit the context stored in the next outer scope. 03131 Entity = S->getEntity(); 03132 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME 03133 03134 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 03135 Ctx = Ctx->getLookupParent()) { 03136 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 03137 if (Method->isInstanceMethod()) { 03138 // For instance methods, look for ivars in the method's interface. 03139 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 03140 Result.getNameLoc(), Sema::LookupMemberName); 03141 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { 03142 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 03143 /*InBaseClass=*/false, Consumer, Visited); 03144 } 03145 } 03146 03147 // We've already performed all of the name lookup that we need 03148 // to for Objective-C methods; the next context will be the 03149 // outer scope. 03150 break; 03151 } 03152 03153 if (Ctx->isFunctionOrMethod()) 03154 continue; 03155 03156 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 03157 /*InBaseClass=*/false, Consumer, Visited); 03158 } 03159 } else if (!S->getParent()) { 03160 // Look into the translation unit scope. We walk through the translation 03161 // unit's declaration context, because the Scope itself won't have all of 03162 // the declarations if we loaded a precompiled header. 03163 // FIXME: We would like the translation unit's Scope object to point to the 03164 // translation unit, so we don't need this special "if" branch. However, 03165 // doing so would force the normal C++ name-lookup code to look into the 03166 // translation unit decl when the IdentifierInfo chains would suffice. 03167 // Once we fix that problem (which is part of a more general "don't look 03168 // in DeclContexts unless we have to" optimization), we can eliminate this. 03169 Entity = Result.getSema().Context.getTranslationUnitDecl(); 03170 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 03171 /*InBaseClass=*/false, Consumer, Visited); 03172 } 03173 03174 if (Entity) { 03175 // Lookup visible declarations in any namespaces found by using 03176 // directives. 03177 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 03178 std::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity); 03179 for (; UI != UEnd; ++UI) 03180 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()), 03181 Result, /*QualifiedNameLookup=*/false, 03182 /*InBaseClass=*/false, Consumer, Visited); 03183 } 03184 03185 // Lookup names in the parent scope. 03186 ShadowContextRAII Shadow(Visited); 03187 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited); 03188 } 03189 03190 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 03191 VisibleDeclConsumer &Consumer, 03192 bool IncludeGlobalScope) { 03193 // Determine the set of using directives available during 03194 // unqualified name lookup. 03195 Scope *Initial = S; 03196 UnqualUsingDirectiveSet UDirs; 03197 if (getLangOpts().CPlusPlus) { 03198 // Find the first namespace or translation-unit scope. 03199 while (S && !isNamespaceOrTranslationUnitScope(S)) 03200 S = S->getParent(); 03201 03202 UDirs.visitScopeChain(Initial, S); 03203 } 03204 UDirs.done(); 03205 03206 // Look for visible declarations. 03207 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 03208 Result.setAllowHidden(Consumer.includeHiddenDecls()); 03209 VisibleDeclsRecord Visited; 03210 if (!IncludeGlobalScope) 03211 Visited.visitedContext(Context.getTranslationUnitDecl()); 03212 ShadowContextRAII Shadow(Visited); 03213 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited); 03214 } 03215 03216 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 03217 VisibleDeclConsumer &Consumer, 03218 bool IncludeGlobalScope) { 03219 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 03220 Result.setAllowHidden(Consumer.includeHiddenDecls()); 03221 VisibleDeclsRecord Visited; 03222 if (!IncludeGlobalScope) 03223 Visited.visitedContext(Context.getTranslationUnitDecl()); 03224 ShadowContextRAII Shadow(Visited); 03225 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 03226 /*InBaseClass=*/false, Consumer, Visited); 03227 } 03228 03229 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 03230 /// If GnuLabelLoc is a valid source location, then this is a definition 03231 /// of an __label__ label name, otherwise it is a normal label definition 03232 /// or use. 03233 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, 03234 SourceLocation GnuLabelLoc) { 03235 // Do a lookup to see if we have a label with this name already. 03236 NamedDecl *Res = nullptr; 03237 03238 if (GnuLabelLoc.isValid()) { 03239 // Local label definitions always shadow existing labels. 03240 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); 03241 Scope *S = CurScope; 03242 PushOnScopeChains(Res, S, true); 03243 return cast<LabelDecl>(Res); 03244 } 03245 03246 // Not a GNU local label. 03247 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); 03248 // If we found a label, check to see if it is in the same context as us. 03249 // When in a Block, we don't want to reuse a label in an enclosing function. 03250 if (Res && Res->getDeclContext() != CurContext) 03251 Res = nullptr; 03252 if (!Res) { 03253 // If not forward referenced or defined already, create the backing decl. 03254 Res = LabelDecl::Create(Context, CurContext, Loc, II); 03255 Scope *S = CurScope->getFnParent(); 03256 assert(S && "Not in a function?"); 03257 PushOnScopeChains(Res, S, true); 03258 } 03259 return cast<LabelDecl>(Res); 03260 } 03261 03262 //===----------------------------------------------------------------------===// 03263 // Typo correction 03264 //===----------------------------------------------------------------------===// 03265 03266 static bool isCandidateViable(CorrectionCandidateCallback &CCC, 03267 TypoCorrection &Candidate) { 03268 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); 03269 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; 03270 } 03271 03272 static void LookupPotentialTypoResult(Sema &SemaRef, 03273 LookupResult &Res, 03274 IdentifierInfo *Name, 03275 Scope *S, CXXScopeSpec *SS, 03276 DeclContext *MemberContext, 03277 bool EnteringContext, 03278 bool isObjCIvarLookup, 03279 bool FindHidden); 03280 03281 /// \brief Check whether the declarations found for a typo correction are 03282 /// visible, and if none of them are, convert the correction to an 'import 03283 /// a module' correction. 03284 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) { 03285 if (TC.begin() == TC.end()) 03286 return; 03287 03288 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); 03289 03290 for (/**/; DI != DE; ++DI) 03291 if (!LookupResult::isVisible(SemaRef, *DI)) 03292 break; 03293 // Nothing to do if all decls are visible. 03294 if (DI == DE) 03295 return; 03296 03297 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); 03298 bool AnyVisibleDecls = !NewDecls.empty(); 03299 03300 for (/**/; DI != DE; ++DI) { 03301 NamedDecl *VisibleDecl = *DI; 03302 if (!LookupResult::isVisible(SemaRef, *DI)) 03303 VisibleDecl = findAcceptableDecl(SemaRef, *DI); 03304 03305 if (VisibleDecl) { 03306 if (!AnyVisibleDecls) { 03307 // Found a visible decl, discard all hidden ones. 03308 AnyVisibleDecls = true; 03309 NewDecls.clear(); 03310 } 03311 NewDecls.push_back(VisibleDecl); 03312 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) 03313 NewDecls.push_back(*DI); 03314 } 03315 03316 if (NewDecls.empty()) 03317 TC = TypoCorrection(); 03318 else { 03319 TC.setCorrectionDecls(NewDecls); 03320 TC.setRequiresImport(!AnyVisibleDecls); 03321 } 03322 } 03323 03324 // Fill the supplied vector with the IdentifierInfo pointers for each piece of 03325 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", 03326 // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). 03327 static void getNestedNameSpecifierIdentifiers( 03328 NestedNameSpecifier *NNS, 03329 SmallVectorImpl<const IdentifierInfo*> &Identifiers) { 03330 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) 03331 getNestedNameSpecifierIdentifiers(Prefix, Identifiers); 03332 else 03333 Identifiers.clear(); 03334 03335 const IdentifierInfo *II = nullptr; 03336 03337 switch (NNS->getKind()) { 03338 case NestedNameSpecifier::Identifier: 03339 II = NNS->getAsIdentifier(); 03340 break; 03341 03342 case NestedNameSpecifier::Namespace: 03343 if (NNS->getAsNamespace()->isAnonymousNamespace()) 03344 return; 03345 II = NNS->getAsNamespace()->getIdentifier(); 03346 break; 03347 03348 case NestedNameSpecifier::NamespaceAlias: 03349 II = NNS->getAsNamespaceAlias()->getIdentifier(); 03350 break; 03351 03352 case NestedNameSpecifier::TypeSpecWithTemplate: 03353 case NestedNameSpecifier::TypeSpec: 03354 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); 03355 break; 03356 03357 case NestedNameSpecifier::Global: 03358 case NestedNameSpecifier::Super: 03359 return; 03360 } 03361 03362 if (II) 03363 Identifiers.push_back(II); 03364 } 03365 03366 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 03367 DeclContext *Ctx, bool InBaseClass) { 03368 // Don't consider hidden names for typo correction. 03369 if (Hiding) 03370 return; 03371 03372 // Only consider entities with identifiers for names, ignoring 03373 // special names (constructors, overloaded operators, selectors, 03374 // etc.). 03375 IdentifierInfo *Name = ND->getIdentifier(); 03376 if (!Name) 03377 return; 03378 03379 // Only consider visible declarations and declarations from modules with 03380 // names that exactly match. 03381 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo && 03382 !findAcceptableDecl(SemaRef, ND)) 03383 return; 03384 03385 FoundName(Name->getName()); 03386 } 03387 03388 void TypoCorrectionConsumer::FoundName(StringRef Name) { 03389 // Compute the edit distance between the typo and the name of this 03390 // entity, and add the identifier to the list of results. 03391 addName(Name, nullptr); 03392 } 03393 03394 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { 03395 // Compute the edit distance between the typo and this keyword, 03396 // and add the keyword to the list of results. 03397 addName(Keyword, nullptr, nullptr, true); 03398 } 03399 03400 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, 03401 NestedNameSpecifier *NNS, bool isKeyword) { 03402 // Use a simple length-based heuristic to determine the minimum possible 03403 // edit distance. If the minimum isn't good enough, bail out early. 03404 StringRef TypoStr = Typo->getName(); 03405 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size()); 03406 if (MinED && TypoStr.size() / MinED < 3) 03407 return; 03408 03409 // Compute an upper bound on the allowable edit distance, so that the 03410 // edit-distance algorithm can short-circuit. 03411 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1; 03412 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound); 03413 if (ED >= UpperBound) return; 03414 03415 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); 03416 if (isKeyword) TC.makeKeyword(); 03417 addCorrection(TC); 03418 } 03419 03420 static const unsigned MaxTypoDistanceResultSets = 5; 03421 03422 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { 03423 StringRef TypoStr = Typo->getName(); 03424 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); 03425 03426 // For very short typos, ignore potential corrections that have a different 03427 // base identifier from the typo or which have a normalized edit distance 03428 // longer than the typo itself. 03429 if (TypoStr.size() < 3 && 03430 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size())) 03431 return; 03432 03433 // If the correction is resolved but is not viable, ignore it. 03434 if (Correction.isResolved()) { 03435 checkCorrectionVisibility(SemaRef, Correction); 03436 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction)) 03437 return; 03438 } 03439 03440 TypoResultList &CList = 03441 CorrectionResults[Correction.getEditDistance(false)][Name]; 03442 03443 if (!CList.empty() && !CList.back().isResolved()) 03444 CList.pop_back(); 03445 if (NamedDecl *NewND = Correction.getCorrectionDecl()) { 03446 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts()); 03447 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end(); 03448 RI != RIEnd; ++RI) { 03449 // If the Correction refers to a decl already in the result list, 03450 // replace the existing result if the string representation of Correction 03451 // comes before the current result alphabetically, then stop as there is 03452 // nothing more to be done to add Correction to the candidate set. 03453 if (RI->getCorrectionDecl() == NewND) { 03454 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts())) 03455 *RI = Correction; 03456 return; 03457 } 03458 } 03459 } 03460 if (CList.empty() || Correction.isResolved()) 03461 CList.push_back(Correction); 03462 03463 while (CorrectionResults.size() > MaxTypoDistanceResultSets) 03464 CorrectionResults.erase(std::prev(CorrectionResults.end())); 03465 } 03466 03467 void TypoCorrectionConsumer::addNamespaces( 03468 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) { 03469 SearchNamespaces = true; 03470 03471 for (auto KNPair : KnownNamespaces) 03472 Namespaces.addNameSpecifier(KNPair.first); 03473 03474 bool SSIsTemplate = false; 03475 if (NestedNameSpecifier *NNS = 03476 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) { 03477 if (const Type *T = NNS->getAsType()) 03478 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; 03479 } 03480 for (const auto *TI : SemaRef.getASTContext().types()) { 03481 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { 03482 CD = CD->getCanonicalDecl(); 03483 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && 03484 !CD->isUnion() && CD->getIdentifier() && 03485 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) && 03486 (CD->isBeingDefined() || CD->isCompleteDefinition())) 03487 Namespaces.addNameSpecifier(CD); 03488 } 03489 } 03490 } 03491 03492 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() { 03493 if (++CurrentTCIndex < ValidatedCorrections.size()) 03494 return ValidatedCorrections[CurrentTCIndex]; 03495 03496 CurrentTCIndex = ValidatedCorrections.size(); 03497 while (!CorrectionResults.empty()) { 03498 auto DI = CorrectionResults.begin(); 03499 if (DI->second.empty()) { 03500 CorrectionResults.erase(DI); 03501 continue; 03502 } 03503 03504 auto RI = DI->second.begin(); 03505 if (RI->second.empty()) { 03506 DI->second.erase(RI); 03507 performQualifiedLookups(); 03508 continue; 03509 } 03510 03511 TypoCorrection TC = RI->second.pop_back_val(); 03512 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) { 03513 ValidatedCorrections.push_back(TC); 03514 return ValidatedCorrections[CurrentTCIndex]; 03515 } 03516 } 03517 return ValidatedCorrections[0]; // The empty correction. 03518 } 03519 03520 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) { 03521 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); 03522 DeclContext *TempMemberContext = MemberContext; 03523 CXXScopeSpec *TempSS = SS.get(); 03524 if (Candidate.getCorrectionRange().isInvalid()) 03525 Candidate.setCorrectionRange(TempSS, Result.getLookupNameInfo()); 03526 retry_lookup: 03527 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext, 03528 EnteringContext, 03529 CorrectionValidator->IsObjCIvarLookup, 03530 Name == Typo && !Candidate.WillReplaceSpecifier()); 03531 switch (Result.getResultKind()) { 03532 case LookupResult::NotFound: 03533 case LookupResult::NotFoundInCurrentInstantiation: 03534 case LookupResult::FoundUnresolvedValue: 03535 if (TempSS) { 03536 // Immediately retry the lookup without the given CXXScopeSpec 03537 TempSS = nullptr; 03538 Candidate.WillReplaceSpecifier(true); 03539 goto retry_lookup; 03540 } 03541 if (TempMemberContext) { 03542 if (SS && !TempSS) 03543 TempSS = SS.get(); 03544 TempMemberContext = nullptr; 03545 goto retry_lookup; 03546 } 03547 if (SearchNamespaces) 03548 QualifiedResults.push_back(Candidate); 03549 break; 03550 03551 case LookupResult::Ambiguous: 03552 // We don't deal with ambiguities. 03553 break; 03554 03555 case LookupResult::Found: 03556 case LookupResult::FoundOverloaded: 03557 // Store all of the Decls for overloaded symbols 03558 for (auto *TRD : Result) 03559 Candidate.addCorrectionDecl(TRD); 03560 checkCorrectionVisibility(SemaRef, Candidate); 03561 if (!isCandidateViable(*CorrectionValidator, Candidate)) { 03562 if (SearchNamespaces) 03563 QualifiedResults.push_back(Candidate); 03564 break; 03565 } 03566 return true; 03567 } 03568 return false; 03569 } 03570 03571 void TypoCorrectionConsumer::performQualifiedLookups() { 03572 unsigned TypoLen = Typo->getName().size(); 03573 for (auto QR : QualifiedResults) { 03574 for (auto NSI : Namespaces) { 03575 DeclContext *Ctx = NSI.DeclCtx; 03576 const Type *NSType = NSI.NameSpecifier->getAsType(); 03577 03578 // If the current NestedNameSpecifier refers to a class and the 03579 // current correction candidate is the name of that class, then skip 03580 // it as it is unlikely a qualified version of the class' constructor 03581 // is an appropriate correction. 03582 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) { 03583 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) 03584 continue; 03585 } 03586 03587 TypoCorrection TC(QR); 03588 TC.ClearCorrectionDecls(); 03589 TC.setCorrectionSpecifier(NSI.NameSpecifier); 03590 TC.setQualifierDistance(NSI.EditDistance); 03591 TC.setCallbackDistance(0); // Reset the callback distance 03592 03593 // If the current correction candidate and namespace combination are 03594 // too far away from the original typo based on the normalized edit 03595 // distance, then skip performing a qualified name lookup. 03596 unsigned TmpED = TC.getEditDistance(true); 03597 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED && 03598 TypoLen / TmpED < 3) 03599 continue; 03600 03601 Result.clear(); 03602 Result.setLookupName(QR.getCorrectionAsIdentifierInfo()); 03603 if (!SemaRef.LookupQualifiedName(Result, Ctx)) 03604 continue; 03605 03606 // Any corrections added below will be validated in subsequent 03607 // iterations of the main while() loop over the Consumer's contents. 03608 switch (Result.getResultKind()) { 03609 case LookupResult::Found: 03610 case LookupResult::FoundOverloaded: { 03611 if (SS && SS->isValid()) { 03612 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts()); 03613 std::string OldQualified; 03614 llvm::raw_string_ostream OldOStream(OldQualified); 03615 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy()); 03616 OldOStream << Typo->getName(); 03617 // If correction candidate would be an identical written qualified 03618 // identifer, then the existing CXXScopeSpec probably included a 03619 // typedef that didn't get accounted for properly. 03620 if (OldOStream.str() == NewQualified) 03621 break; 03622 } 03623 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end(); 03624 TRD != TRDEnd; ++TRD) { 03625 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(), 03626 NSType ? NSType->getAsCXXRecordDecl() 03627 : nullptr, 03628 TRD.getPair()) == Sema::AR_accessible) 03629 TC.addCorrectionDecl(*TRD); 03630 } 03631 if (TC.isResolved()) 03632 addCorrection(TC); 03633 break; 03634 } 03635 case LookupResult::NotFound: 03636 case LookupResult::NotFoundInCurrentInstantiation: 03637 case LookupResult::Ambiguous: 03638 case LookupResult::FoundUnresolvedValue: 03639 break; 03640 } 03641 } 03642 } 03643 QualifiedResults.clear(); 03644 } 03645 03646 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet( 03647 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec) 03648 : Context(Context), CurContextChain(buildContextChain(CurContext)), 03649 isSorted(false) { 03650 if (NestedNameSpecifier *NNS = 03651 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) { 03652 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); 03653 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 03654 03655 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers); 03656 } 03657 // Build the list of identifiers that would be used for an absolute 03658 // (from the global context) NestedNameSpecifier referring to the current 03659 // context. 03660 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 03661 CEnd = CurContextChain.rend(); 03662 C != CEnd; ++C) { 03663 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) 03664 CurContextIdentifiers.push_back(ND->getIdentifier()); 03665 } 03666 03667 // Add the global context as a NestedNameSpecifier 03668 Distances.insert(1); 03669 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()), 03670 NestedNameSpecifier::GlobalSpecifier(Context), 1}; 03671 DistanceMap[1].push_back(SI); 03672 } 03673 03674 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain( 03675 DeclContext *Start) -> DeclContextList { 03676 assert(Start && "Building a context chain from a null context"); 03677 DeclContextList Chain; 03678 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr; 03679 DC = DC->getLookupParent()) { 03680 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); 03681 if (!DC->isInlineNamespace() && !DC->isTransparentContext() && 03682 !(ND && ND->isAnonymousNamespace())) 03683 Chain.push_back(DC->getPrimaryContext()); 03684 } 03685 return Chain; 03686 } 03687 03688 void TypoCorrectionConsumer::NamespaceSpecifierSet::sortNamespaces() { 03689 SmallVector<unsigned, 4> sortedDistances; 03690 sortedDistances.append(Distances.begin(), Distances.end()); 03691 03692 if (sortedDistances.size() > 1) 03693 std::sort(sortedDistances.begin(), sortedDistances.end()); 03694 03695 Specifiers.clear(); 03696 for (auto D : sortedDistances) { 03697 SpecifierInfoList &SpecList = DistanceMap[D]; 03698 Specifiers.append(SpecList.begin(), SpecList.end()); 03699 } 03700 03701 isSorted = true; 03702 } 03703 03704 unsigned 03705 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier( 03706 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) { 03707 unsigned NumSpecifiers = 0; 03708 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(), 03709 CEnd = DeclChain.rend(); 03710 C != CEnd; ++C) { 03711 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) { 03712 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 03713 ++NumSpecifiers; 03714 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) { 03715 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), 03716 RD->getTypeForDecl()); 03717 ++NumSpecifiers; 03718 } 03719 } 03720 return NumSpecifiers; 03721 } 03722 03723 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier( 03724 DeclContext *Ctx) { 03725 NestedNameSpecifier *NNS = nullptr; 03726 unsigned NumSpecifiers = 0; 03727 DeclContextList NamespaceDeclChain(buildContextChain(Ctx)); 03728 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 03729 03730 // Eliminate common elements from the two DeclContext chains. 03731 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(), 03732 CEnd = CurContextChain.rend(); 03733 C != CEnd && !NamespaceDeclChain.empty() && 03734 NamespaceDeclChain.back() == *C; ++C) { 03735 NamespaceDeclChain.pop_back(); 03736 } 03737 03738 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 03739 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS); 03740 03741 // Add an explicit leading '::' specifier if needed. 03742 if (NamespaceDeclChain.empty()) { 03743 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 03744 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 03745 NumSpecifiers = 03746 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 03747 } else if (NamedDecl *ND = 03748 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) { 03749 IdentifierInfo *Name = ND->getIdentifier(); 03750 bool SameNameSpecifier = false; 03751 if (std::find(CurNameSpecifierIdentifiers.begin(), 03752 CurNameSpecifierIdentifiers.end(), 03753 Name) != CurNameSpecifierIdentifiers.end()) { 03754 std::string NewNameSpecifier; 03755 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); 03756 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; 03757 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 03758 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 03759 SpecifierOStream.flush(); 03760 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; 03761 } 03762 if (SameNameSpecifier || 03763 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(), 03764 Name) != CurContextIdentifiers.end()) { 03765 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 03766 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 03767 NumSpecifiers = 03768 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 03769 } 03770 } 03771 03772 // If the built NestedNameSpecifier would be replacing an existing 03773 // NestedNameSpecifier, use the number of component identifiers that 03774 // would need to be changed as the edit distance instead of the number 03775 // of components in the built NestedNameSpecifier. 03776 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 03777 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 03778 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 03779 NumSpecifiers = llvm::ComputeEditDistance( 03780 llvm::makeArrayRef(CurNameSpecifierIdentifiers), 03781 llvm::makeArrayRef(NewNameSpecifierIdentifiers)); 03782 } 03783 03784 isSorted = false; 03785 Distances.insert(NumSpecifiers); 03786 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers}; 03787 DistanceMap[NumSpecifiers].push_back(SI); 03788 } 03789 03790 /// \brief Perform name lookup for a possible result for typo correction. 03791 static void LookupPotentialTypoResult(Sema &SemaRef, 03792 LookupResult &Res, 03793 IdentifierInfo *Name, 03794 Scope *S, CXXScopeSpec *SS, 03795 DeclContext *MemberContext, 03796 bool EnteringContext, 03797 bool isObjCIvarLookup, 03798 bool FindHidden) { 03799 Res.suppressDiagnostics(); 03800 Res.clear(); 03801 Res.setLookupName(Name); 03802 Res.setAllowHidden(FindHidden); 03803 if (MemberContext) { 03804 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { 03805 if (isObjCIvarLookup) { 03806 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { 03807 Res.addDecl(Ivar); 03808 Res.resolveKind(); 03809 return; 03810 } 03811 } 03812 03813 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) { 03814 Res.addDecl(Prop); 03815 Res.resolveKind(); 03816 return; 03817 } 03818 } 03819 03820 SemaRef.LookupQualifiedName(Res, MemberContext); 03821 return; 03822 } 03823 03824 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 03825 EnteringContext); 03826 03827 // Fake ivar lookup; this should really be part of 03828 // LookupParsedName. 03829 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 03830 if (Method->isInstanceMethod() && Method->getClassInterface() && 03831 (Res.empty() || 03832 (Res.isSingleResult() && 03833 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { 03834 if (ObjCIvarDecl *IV 03835 = Method->getClassInterface()->lookupInstanceVariable(Name)) { 03836 Res.addDecl(IV); 03837 Res.resolveKind(); 03838 } 03839 } 03840 } 03841 } 03842 03843 /// \brief Add keywords to the consumer as possible typo corrections. 03844 static void AddKeywordsToConsumer(Sema &SemaRef, 03845 TypoCorrectionConsumer &Consumer, 03846 Scope *S, CorrectionCandidateCallback &CCC, 03847 bool AfterNestedNameSpecifier) { 03848 if (AfterNestedNameSpecifier) { 03849 // For 'X::', we know exactly which keywords can appear next. 03850 Consumer.addKeywordResult("template"); 03851 if (CCC.WantExpressionKeywords) 03852 Consumer.addKeywordResult("operator"); 03853 return; 03854 } 03855 03856 if (CCC.WantObjCSuper) 03857 Consumer.addKeywordResult("super"); 03858 03859 if (CCC.WantTypeSpecifiers) { 03860 // Add type-specifier keywords to the set of results. 03861 static const char *const CTypeSpecs[] = { 03862 "char", "const", "double", "enum", "float", "int", "long", "short", 03863 "signed", "struct", "union", "unsigned", "void", "volatile", 03864 "_Complex", "_Imaginary", 03865 // storage-specifiers as well 03866 "extern", "inline", "static", "typedef" 03867 }; 03868 03869 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); 03870 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 03871 Consumer.addKeywordResult(CTypeSpecs[I]); 03872 03873 if (SemaRef.getLangOpts().C99) 03874 Consumer.addKeywordResult("restrict"); 03875 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) 03876 Consumer.addKeywordResult("bool"); 03877 else if (SemaRef.getLangOpts().C99) 03878 Consumer.addKeywordResult("_Bool"); 03879 03880 if (SemaRef.getLangOpts().CPlusPlus) { 03881 Consumer.addKeywordResult("class"); 03882 Consumer.addKeywordResult("typename"); 03883 Consumer.addKeywordResult("wchar_t"); 03884 03885 if (SemaRef.getLangOpts().CPlusPlus11) { 03886 Consumer.addKeywordResult("char16_t"); 03887 Consumer.addKeywordResult("char32_t"); 03888 Consumer.addKeywordResult("constexpr"); 03889 Consumer.addKeywordResult("decltype"); 03890 Consumer.addKeywordResult("thread_local"); 03891 } 03892 } 03893 03894 if (SemaRef.getLangOpts().GNUMode) 03895 Consumer.addKeywordResult("typeof"); 03896 } else if (CCC.WantFunctionLikeCasts) { 03897 static const char *const CastableTypeSpecs[] = { 03898 "char", "double", "float", "int", "long", "short", 03899 "signed", "unsigned", "void" 03900 }; 03901 for (auto *kw : CastableTypeSpecs) 03902 Consumer.addKeywordResult(kw); 03903 } 03904 03905 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { 03906 Consumer.addKeywordResult("const_cast"); 03907 Consumer.addKeywordResult("dynamic_cast"); 03908 Consumer.addKeywordResult("reinterpret_cast"); 03909 Consumer.addKeywordResult("static_cast"); 03910 } 03911 03912 if (CCC.WantExpressionKeywords) { 03913 Consumer.addKeywordResult("sizeof"); 03914 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { 03915 Consumer.addKeywordResult("false"); 03916 Consumer.addKeywordResult("true"); 03917 } 03918 03919 if (SemaRef.getLangOpts().CPlusPlus) { 03920 static const char *const CXXExprs[] = { 03921 "delete", "new", "operator", "throw", "typeid" 03922 }; 03923 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); 03924 for (unsigned I = 0; I != NumCXXExprs; ++I) 03925 Consumer.addKeywordResult(CXXExprs[I]); 03926 03927 if (isa<CXXMethodDecl>(SemaRef.CurContext) && 03928 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) 03929 Consumer.addKeywordResult("this"); 03930 03931 if (SemaRef.getLangOpts().CPlusPlus11) { 03932 Consumer.addKeywordResult("alignof"); 03933 Consumer.addKeywordResult("nullptr"); 03934 } 03935 } 03936 03937 if (SemaRef.getLangOpts().C11) { 03938 // FIXME: We should not suggest _Alignof if the alignof macro 03939 // is present. 03940 Consumer.addKeywordResult("_Alignof"); 03941 } 03942 } 03943 03944 if (CCC.WantRemainingKeywords) { 03945 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { 03946 // Statements. 03947 static const char *const CStmts[] = { 03948 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 03949 const unsigned NumCStmts = llvm::array_lengthof(CStmts); 03950 for (unsigned I = 0; I != NumCStmts; ++I) 03951 Consumer.addKeywordResult(CStmts[I]); 03952 03953 if (SemaRef.getLangOpts().CPlusPlus) { 03954 Consumer.addKeywordResult("catch"); 03955 Consumer.addKeywordResult("try"); 03956 } 03957 03958 if (S && S->getBreakParent()) 03959 Consumer.addKeywordResult("break"); 03960 03961 if (S && S->getContinueParent()) 03962 Consumer.addKeywordResult("continue"); 03963 03964 if (!SemaRef.getCurFunction()->SwitchStack.empty()) { 03965 Consumer.addKeywordResult("case"); 03966 Consumer.addKeywordResult("default"); 03967 } 03968 } else { 03969 if (SemaRef.getLangOpts().CPlusPlus) { 03970 Consumer.addKeywordResult("namespace"); 03971 Consumer.addKeywordResult("template"); 03972 } 03973 03974 if (S && S->isClassScope()) { 03975 Consumer.addKeywordResult("explicit"); 03976 Consumer.addKeywordResult("friend"); 03977 Consumer.addKeywordResult("mutable"); 03978 Consumer.addKeywordResult("private"); 03979 Consumer.addKeywordResult("protected"); 03980 Consumer.addKeywordResult("public"); 03981 Consumer.addKeywordResult("virtual"); 03982 } 03983 } 03984 03985 if (SemaRef.getLangOpts().CPlusPlus) { 03986 Consumer.addKeywordResult("using"); 03987 03988 if (SemaRef.getLangOpts().CPlusPlus11) 03989 Consumer.addKeywordResult("static_assert"); 03990 } 03991 } 03992 } 03993 03994 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer( 03995 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, 03996 Scope *S, CXXScopeSpec *SS, 03997 std::unique_ptr<CorrectionCandidateCallback> CCC, 03998 DeclContext *MemberContext, bool EnteringContext, 03999 const ObjCObjectPointerType *OPT, bool ErrorRecovery, 04000 bool &IsUnqualifiedLookup) { 04001 04002 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || 04003 DisableTypoCorrection) 04004 return nullptr; 04005 04006 // In Microsoft mode, don't perform typo correction in a template member 04007 // function dependent context because it interferes with the "lookup into 04008 // dependent bases of class templates" feature. 04009 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 04010 isa<CXXMethodDecl>(CurContext)) 04011 return nullptr; 04012 04013 // We only attempt to correct typos for identifiers. 04014 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 04015 if (!Typo) 04016 return nullptr; 04017 04018 // If the scope specifier itself was invalid, don't try to correct 04019 // typos. 04020 if (SS && SS->isInvalid()) 04021 return nullptr; 04022 04023 // Never try to correct typos during template deduction or 04024 // instantiation. 04025 if (!ActiveTemplateInstantiations.empty()) 04026 return nullptr; 04027 04028 // Don't try to correct 'super'. 04029 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) 04030 return nullptr; 04031 04032 // Abort if typo correction already failed for this specific typo. 04033 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo); 04034 if (locs != TypoCorrectionFailures.end() && 04035 locs->second.count(TypoName.getLoc())) 04036 return nullptr; 04037 04038 // Don't try to correct the identifier "vector" when in AltiVec mode. 04039 // TODO: Figure out why typo correction misbehaves in this case, fix it, and 04040 // remove this workaround. 04041 if (getLangOpts().AltiVec && Typo->isStr("vector")) 04042 return nullptr; 04043 04044 // If we're handling a missing symbol error, using modules, and the 04045 // special search all modules option is used, look for a missing import. 04046 if (ErrorRecovery && getLangOpts().Modules && 04047 getLangOpts().ModulesSearchAll) { 04048 // The following has the side effect of loading the missing module. 04049 getModuleLoader().lookupMissingImports(Typo->getName(), 04050 TypoName.getLocStart()); 04051 } 04052 04053 CorrectionCandidateCallback &CCCRef = *CCC; 04054 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>( 04055 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext, 04056 EnteringContext); 04057 04058 // If a callback object considers an empty typo correction candidate to be 04059 // viable, assume it does not do any actual validation of the candidates. 04060 TypoCorrection EmptyCorrection; 04061 bool ValidatingCallback = !isCandidateViable(CCCRef, EmptyCorrection); 04062 04063 // Perform name lookup to find visible, similarly-named entities. 04064 IsUnqualifiedLookup = false; 04065 DeclContext *QualifiedDC = MemberContext; 04066 if (MemberContext) { 04067 LookupVisibleDecls(MemberContext, LookupKind, *Consumer); 04068 04069 // Look in qualified interfaces. 04070 if (OPT) { 04071 for (auto *I : OPT->quals()) 04072 LookupVisibleDecls(I, LookupKind, *Consumer); 04073 } 04074 } else if (SS && SS->isSet()) { 04075 QualifiedDC = computeDeclContext(*SS, EnteringContext); 04076 if (!QualifiedDC) 04077 return nullptr; 04078 04079 // Provide a stop gap for files that are just seriously broken. Trying 04080 // to correct all typos can turn into a HUGE performance penalty, causing 04081 // some files to take minutes to get rejected by the parser. 04082 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 04083 return nullptr; 04084 ++TyposCorrected; 04085 04086 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer); 04087 } else { 04088 IsUnqualifiedLookup = true; 04089 UnqualifiedTyposCorrectedMap::iterator Cached 04090 = UnqualifiedTyposCorrected.find(Typo); 04091 if (Cached != UnqualifiedTyposCorrected.end()) { 04092 // Add the cached value, unless it's a keyword or fails validation. In the 04093 // keyword case, we'll end up adding the keyword below. 04094 if (Cached->second) { 04095 if (!Cached->second.isKeyword() && 04096 isCandidateViable(CCCRef, Cached->second)) { 04097 // Do not use correction that is unaccessible in the given scope. 04098 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl(); 04099 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(), 04100 CorrectionDecl->getLocation()); 04101 LookupResult R(*this, NameInfo, LookupOrdinaryName); 04102 if (LookupName(R, S)) 04103 Consumer->addCorrection(Cached->second); 04104 } 04105 } else { 04106 // Only honor no-correction cache hits when a callback that will validate 04107 // correction candidates is not being used. 04108 if (!ValidatingCallback) 04109 return nullptr; 04110 } 04111 } 04112 if (Cached == UnqualifiedTyposCorrected.end()) { 04113 // Provide a stop gap for files that are just seriously broken. Trying 04114 // to correct all typos can turn into a HUGE performance penalty, causing 04115 // some files to take minutes to get rejected by the parser. 04116 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20) 04117 return nullptr; 04118 } 04119 } 04120 04121 // Determine whether we are going to search in the various namespaces for 04122 // corrections. 04123 bool SearchNamespaces 04124 = getLangOpts().CPlusPlus && 04125 (IsUnqualifiedLookup || (SS && SS->isSet())); 04126 04127 if (IsUnqualifiedLookup || SearchNamespaces) { 04128 // For unqualified lookup, look through all of the names that we have 04129 // seen in this translation unit. 04130 // FIXME: Re-add the ability to skip very unlikely potential corrections. 04131 for (const auto &I : Context.Idents) 04132 Consumer->FoundName(I.getKey()); 04133 04134 // Walk through identifiers in external identifier sources. 04135 // FIXME: Re-add the ability to skip very unlikely potential corrections. 04136 if (IdentifierInfoLookup *External 04137 = Context.Idents.getExternalIdentifierLookup()) { 04138 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 04139 do { 04140 StringRef Name = Iter->Next(); 04141 if (Name.empty()) 04142 break; 04143 04144 Consumer->FoundName(Name); 04145 } while (true); 04146 } 04147 } 04148 04149 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty()); 04150 04151 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going 04152 // to search those namespaces. 04153 if (SearchNamespaces) { 04154 // Load any externally-known namespaces. 04155 if (ExternalSource && !LoadedExternalKnownNamespaces) { 04156 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; 04157 LoadedExternalKnownNamespaces = true; 04158 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); 04159 for (auto *N : ExternalKnownNamespaces) 04160 KnownNamespaces[N] = true; 04161 } 04162 04163 Consumer->addNamespaces(KnownNamespaces); 04164 } 04165 04166 return Consumer; 04167 } 04168 04169 /// \brief Try to "correct" a typo in the source code by finding 04170 /// visible declarations whose names are similar to the name that was 04171 /// present in the source code. 04172 /// 04173 /// \param TypoName the \c DeclarationNameInfo structure that contains 04174 /// the name that was present in the source code along with its location. 04175 /// 04176 /// \param LookupKind the name-lookup criteria used to search for the name. 04177 /// 04178 /// \param S the scope in which name lookup occurs. 04179 /// 04180 /// \param SS the nested-name-specifier that precedes the name we're 04181 /// looking for, if present. 04182 /// 04183 /// \param CCC A CorrectionCandidateCallback object that provides further 04184 /// validation of typo correction candidates. It also provides flags for 04185 /// determining the set of keywords permitted. 04186 /// 04187 /// \param MemberContext if non-NULL, the context in which to look for 04188 /// a member access expression. 04189 /// 04190 /// \param EnteringContext whether we're entering the context described by 04191 /// the nested-name-specifier SS. 04192 /// 04193 /// \param OPT when non-NULL, the search for visible declarations will 04194 /// also walk the protocols in the qualified interfaces of \p OPT. 04195 /// 04196 /// \returns a \c TypoCorrection containing the corrected name if the typo 04197 /// along with information such as the \c NamedDecl where the corrected name 04198 /// was declared, and any additional \c NestedNameSpecifier needed to access 04199 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 04200 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, 04201 Sema::LookupNameKind LookupKind, 04202 Scope *S, CXXScopeSpec *SS, 04203 std::unique_ptr<CorrectionCandidateCallback> CCC, 04204 CorrectTypoKind Mode, 04205 DeclContext *MemberContext, 04206 bool EnteringContext, 04207 const ObjCObjectPointerType *OPT, 04208 bool RecordFailure) { 04209 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback"); 04210 04211 // Always let the ExternalSource have the first chance at correction, even 04212 // if we would otherwise have given up. 04213 if (ExternalSource) { 04214 if (TypoCorrection Correction = ExternalSource->CorrectTypo( 04215 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT)) 04216 return Correction; 04217 } 04218 04219 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; 04220 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for 04221 // some instances of CTC_Unknown, while WantRemainingKeywords is true 04222 // for CTC_Unknown but not for CTC_ObjCMessageReceiver. 04223 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords; 04224 04225 TypoCorrection EmptyCorrection; 04226 bool ValidatingCallback = !isCandidateViable(*CCC, EmptyCorrection); 04227 04228 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 04229 bool IsUnqualifiedLookup = false; 04230 auto Consumer = makeTypoCorrectionConsumer( 04231 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext, 04232 EnteringContext, OPT, Mode == CTK_ErrorRecovery, IsUnqualifiedLookup); 04233 04234 if (!Consumer) 04235 return TypoCorrection(); 04236 04237 // If we haven't found anything, we're done. 04238 if (Consumer->empty()) 04239 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 04240 IsUnqualifiedLookup); 04241 04242 // Make sure the best edit distance (prior to adding any namespace qualifiers) 04243 // is not more that about a third of the length of the typo's identifier. 04244 unsigned ED = Consumer->getBestEditDistance(true); 04245 unsigned TypoLen = Typo->getName().size(); 04246 if (ED > 0 && TypoLen / ED < 3) 04247 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 04248 IsUnqualifiedLookup); 04249 04250 TypoCorrection BestTC = Consumer->getNextCorrection(); 04251 TypoCorrection SecondBestTC = Consumer->getNextCorrection(); 04252 if (!BestTC) 04253 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 04254 04255 ED = BestTC.getEditDistance(); 04256 04257 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) { 04258 // If this was an unqualified lookup and we believe the callback 04259 // object wouldn't have filtered out possible corrections, note 04260 // that no correction was found. 04261 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 04262 IsUnqualifiedLookup && !ValidatingCallback); 04263 } 04264 04265 // If only a single name remains, return that result. 04266 if (!SecondBestTC || 04267 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) { 04268 const TypoCorrection &Result = BestTC; 04269 04270 // Don't correct to a keyword that's the same as the typo; the keyword 04271 // wasn't actually in scope. 04272 if (ED == 0 && Result.isKeyword()) 04273 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 04274 04275 // Record the correction for unqualified lookup. 04276 if (IsUnqualifiedLookup) 04277 UnqualifiedTyposCorrected[Typo] = Result; 04278 04279 TypoCorrection TC = Result; 04280 TC.setCorrectionRange(SS, TypoName); 04281 checkCorrectionVisibility(*this, TC); 04282 return TC; 04283 } else if (SecondBestTC && ObjCMessageReceiver) { 04284 // Prefer 'super' when we're completing in a message-receiver 04285 // context. 04286 04287 if (BestTC.getCorrection().getAsString() != "super") { 04288 if (SecondBestTC.getCorrection().getAsString() == "super") 04289 BestTC = SecondBestTC; 04290 else if ((*Consumer)["super"].front().isKeyword()) 04291 BestTC = (*Consumer)["super"].front(); 04292 } 04293 // Don't correct to a keyword that's the same as the typo; the keyword 04294 // wasn't actually in scope. 04295 if (BestTC.getEditDistance() == 0 || 04296 BestTC.getCorrection().getAsString() != "super") 04297 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 04298 04299 // Record the correction for unqualified lookup. 04300 if (IsUnqualifiedLookup) 04301 UnqualifiedTyposCorrected[Typo] = BestTC; 04302 04303 BestTC.setCorrectionRange(SS, TypoName); 04304 return BestTC; 04305 } 04306 04307 // Record the failure's location if needed and return an empty correction. If 04308 // this was an unqualified lookup and we believe the callback object did not 04309 // filter out possible corrections, also cache the failure for the typo. 04310 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure, 04311 IsUnqualifiedLookup && !ValidatingCallback); 04312 } 04313 04314 /// \brief Try to "correct" a typo in the source code by finding 04315 /// visible declarations whose names are similar to the name that was 04316 /// present in the source code. 04317 /// 04318 /// \param TypoName the \c DeclarationNameInfo structure that contains 04319 /// the name that was present in the source code along with its location. 04320 /// 04321 /// \param LookupKind the name-lookup criteria used to search for the name. 04322 /// 04323 /// \param S the scope in which name lookup occurs. 04324 /// 04325 /// \param SS the nested-name-specifier that precedes the name we're 04326 /// looking for, if present. 04327 /// 04328 /// \param CCC A CorrectionCandidateCallback object that provides further 04329 /// validation of typo correction candidates. It also provides flags for 04330 /// determining the set of keywords permitted. 04331 /// 04332 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print 04333 /// diagnostics when the actual typo correction is attempted. 04334 /// 04335 /// \param TRC A TypoRecoveryCallback functor that will be used to build an 04336 /// Expr from a typo correction candidate. 04337 /// 04338 /// \param MemberContext if non-NULL, the context in which to look for 04339 /// a member access expression. 04340 /// 04341 /// \param EnteringContext whether we're entering the context described by 04342 /// the nested-name-specifier SS. 04343 /// 04344 /// \param OPT when non-NULL, the search for visible declarations will 04345 /// also walk the protocols in the qualified interfaces of \p OPT. 04346 /// 04347 /// \returns a new \c TypoExpr that will later be replaced in the AST with an 04348 /// Expr representing the result of performing typo correction, or nullptr if 04349 /// typo correction is not possible. If nullptr is returned, no diagnostics will 04350 /// be emitted and it is the responsibility of the caller to emit any that are 04351 /// needed. 04352 TypoExpr *Sema::CorrectTypoDelayed( 04353 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, 04354 Scope *S, CXXScopeSpec *SS, 04355 std::unique_ptr<CorrectionCandidateCallback> CCC, 04356 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, 04357 DeclContext *MemberContext, bool EnteringContext, 04358 const ObjCObjectPointerType *OPT) { 04359 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback"); 04360 04361 TypoCorrection Empty; 04362 bool IsUnqualifiedLookup = false; 04363 auto Consumer = makeTypoCorrectionConsumer( 04364 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext, 04365 EnteringContext, OPT, 04366 /*SearchModules=*/(Mode == CTK_ErrorRecovery) && getLangOpts().Modules && 04367 getLangOpts().ModulesSearchAll, 04368 IsUnqualifiedLookup); 04369 04370 if (!Consumer || Consumer->empty()) 04371 return nullptr; 04372 04373 // Make sure the best edit distance (prior to adding any namespace qualifiers) 04374 // is not more that about a third of the length of the typo's identifier. 04375 unsigned ED = Consumer->getBestEditDistance(true); 04376 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 04377 if (ED > 0 && Typo->getName().size() / ED < 3) 04378 return nullptr; 04379 04380 ExprEvalContexts.back().NumTypos++; 04381 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC)); 04382 } 04383 04384 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { 04385 if (!CDecl) return; 04386 04387 if (isKeyword()) 04388 CorrectionDecls.clear(); 04389 04390 CorrectionDecls.push_back(CDecl->getUnderlyingDecl()); 04391 04392 if (!CorrectionName) 04393 CorrectionName = CDecl->getDeclName(); 04394 } 04395 04396 std::string TypoCorrection::getAsString(const LangOptions &LO) const { 04397 if (CorrectionNameSpec) { 04398 std::string tmpBuffer; 04399 llvm::raw_string_ostream PrefixOStream(tmpBuffer); 04400 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); 04401 PrefixOStream << CorrectionName; 04402 return PrefixOStream.str(); 04403 } 04404 04405 return CorrectionName.getAsString(); 04406 } 04407 04408 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) { 04409 if (!candidate.isResolved()) 04410 return true; 04411 04412 if (candidate.isKeyword()) 04413 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || 04414 WantRemainingKeywords || WantObjCSuper; 04415 04416 bool HasNonType = false; 04417 bool HasStaticMethod = false; 04418 bool HasNonStaticMethod = false; 04419 for (Decl *D : candidate) { 04420 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 04421 D = FTD->getTemplatedDecl(); 04422 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 04423 if (Method->isStatic()) 04424 HasStaticMethod = true; 04425 else 04426 HasNonStaticMethod = true; 04427 } 04428 if (!isa<TypeDecl>(D)) 04429 HasNonType = true; 04430 } 04431 04432 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod && 04433 !candidate.getCorrectionSpecifier()) 04434 return false; 04435 04436 return WantTypeSpecifiers || HasNonType; 04437 } 04438 04439 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, 04440 bool HasExplicitTemplateArgs, 04441 MemberExpr *ME) 04442 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), 04443 CurContext(SemaRef.CurContext), MemberFn(ME) { 04444 WantTypeSpecifiers = false; 04445 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1; 04446 WantRemainingKeywords = false; 04447 } 04448 04449 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { 04450 if (!candidate.getCorrectionDecl()) 04451 return candidate.isKeyword(); 04452 04453 for (auto *C : candidate) { 04454 FunctionDecl *FD = nullptr; 04455 NamedDecl *ND = C->getUnderlyingDecl(); 04456 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 04457 FD = FTD->getTemplatedDecl(); 04458 if (!HasExplicitTemplateArgs && !FD) { 04459 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 04460 // If the Decl is neither a function nor a template function, 04461 // determine if it is a pointer or reference to a function. If so, 04462 // check against the number of arguments expected for the pointee. 04463 QualType ValType = cast<ValueDecl>(ND)->getType(); 04464 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 04465 ValType = ValType->getPointeeType(); 04466 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 04467 if (FPT->getNumParams() == NumArgs) 04468 return true; 04469 } 04470 } 04471 04472 // Skip the current candidate if it is not a FunctionDecl or does not accept 04473 // the current number of arguments. 04474 if (!FD || !(FD->getNumParams() >= NumArgs && 04475 FD->getMinRequiredArguments() <= NumArgs)) 04476 continue; 04477 04478 // If the current candidate is a non-static C++ method, skip the candidate 04479 // unless the method being corrected--or the current DeclContext, if the 04480 // function being corrected is not a method--is a method in the same class 04481 // or a descendent class of the candidate's parent class. 04482 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 04483 if (MemberFn || !MD->isStatic()) { 04484 CXXMethodDecl *CurMD = 04485 MemberFn 04486 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl()) 04487 : dyn_cast_or_null<CXXMethodDecl>(CurContext); 04488 CXXRecordDecl *CurRD = 04489 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr; 04490 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); 04491 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD))) 04492 continue; 04493 } 04494 } 04495 return true; 04496 } 04497 return false; 04498 } 04499 04500 void Sema::diagnoseTypo(const TypoCorrection &Correction, 04501 const PartialDiagnostic &TypoDiag, 04502 bool ErrorRecovery) { 04503 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), 04504 ErrorRecovery); 04505 } 04506 04507 /// Find which declaration we should import to provide the definition of 04508 /// the given declaration. 04509 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) { 04510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 04511 return VD->getDefinition(); 04512 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 04513 return FD->isDefined(FD) ? FD : nullptr; 04514 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 04515 return TD->getDefinition(); 04516 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) 04517 return ID->getDefinition(); 04518 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) 04519 return PD->getDefinition(); 04520 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 04521 return getDefinitionToImport(TD->getTemplatedDecl()); 04522 return nullptr; 04523 } 04524 04525 /// \brief Diagnose a successfully-corrected typo. Separated from the correction 04526 /// itself to allow external validation of the result, etc. 04527 /// 04528 /// \param Correction The result of performing typo correction. 04529 /// \param TypoDiag The diagnostic to produce. This will have the corrected 04530 /// string added to it (and usually also a fixit). 04531 /// \param PrevNote A note to use when indicating the location of the entity to 04532 /// which we are correcting. Will have the correction string added to it. 04533 /// \param ErrorRecovery If \c true (the default), the caller is going to 04534 /// recover from the typo as if the corrected string had been typed. 04535 /// In this case, \c PDiag must be an error, and we will attach a fixit 04536 /// to it. 04537 void Sema::diagnoseTypo(const TypoCorrection &Correction, 04538 const PartialDiagnostic &TypoDiag, 04539 const PartialDiagnostic &PrevNote, 04540 bool ErrorRecovery) { 04541 std::string CorrectedStr = Correction.getAsString(getLangOpts()); 04542 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); 04543 FixItHint FixTypo = FixItHint::CreateReplacement( 04544 Correction.getCorrectionRange(), CorrectedStr); 04545 04546 // Maybe we're just missing a module import. 04547 if (Correction.requiresImport()) { 04548 NamedDecl *Decl = Correction.getCorrectionDecl(); 04549 assert(Decl && "import required but no declaration to import"); 04550 04551 // Suggest importing a module providing the definition of this entity, if 04552 // possible. 04553 const NamedDecl *Def = getDefinitionToImport(Decl); 04554 if (!Def) 04555 Def = Decl; 04556 Module *Owner = Def->getOwningModule(); 04557 assert(Owner && "definition of hidden declaration is not in a module"); 04558 04559 Diag(Correction.getCorrectionRange().getBegin(), 04560 diag::err_module_private_declaration) 04561 << Def << Owner->getFullModuleName(); 04562 Diag(Def->getLocation(), diag::note_previous_declaration); 04563 04564 // Recover by implicitly importing this module. 04565 if (ErrorRecovery) 04566 createImplicitModuleImportForErrorRecovery( 04567 Correction.getCorrectionRange().getBegin(), Owner); 04568 return; 04569 } 04570 04571 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) 04572 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); 04573 04574 NamedDecl *ChosenDecl = 04575 Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl(); 04576 if (PrevNote.getDiagID() && ChosenDecl) 04577 Diag(ChosenDecl->getLocation(), PrevNote) 04578 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); 04579 } 04580 04581 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 04582 TypoDiagnosticGenerator TDG, 04583 TypoRecoveryCallback TRC) { 04584 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer"); 04585 auto TE = new (Context) TypoExpr(Context.DependentTy); 04586 auto &State = DelayedTypos[TE]; 04587 State.Consumer = std::move(TCC); 04588 State.DiagHandler = std::move(TDG); 04589 State.RecoveryHandler = std::move(TRC); 04590 return TE; 04591 } 04592 04593 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const { 04594 auto Entry = DelayedTypos.find(TE); 04595 assert(Entry != DelayedTypos.end() && 04596 "Failed to get the state for a TypoExpr!"); 04597 return Entry->second; 04598 } 04599 04600 void Sema::clearDelayedTypo(TypoExpr *TE) { 04601 DelayedTypos.erase(TE); 04602 }