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