SemaCXXScopeSpec.cpp revision 95aafb2453e1fecec8dcfd9e125cd78277f45859
1//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements C++ semantic analysis for scope specifiers. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/NestedNameSpecifier.h" 20#include "clang/Basic/PartialDiagnostic.h" 21#include "clang/Sema/DeclSpec.h" 22#include "TypeLocBuilder.h" 23#include "llvm/ADT/STLExtras.h" 24#include "llvm/Support/raw_ostream.h" 25using namespace clang; 26 27/// \brief Find the current instantiation that associated with the given type. 28static CXXRecordDecl *getCurrentInstantiationOf(QualType T, 29 DeclContext *CurContext) { 30 if (T.isNull()) 31 return 0; 32 33 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr(); 34 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 35 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 36 if (!T->isDependentType()) 37 return Record; 38 39 // This may be a member of a class template or class template partial 40 // specialization. If it's part of the current semantic context, then it's 41 // an injected-class-name; 42 for (; !CurContext->isFileContext(); CurContext = CurContext->getParent()) 43 if (CurContext->Equals(Record)) 44 return Record; 45 46 return 0; 47 } else if (isa<InjectedClassNameType>(Ty)) 48 return cast<InjectedClassNameType>(Ty)->getDecl(); 49 else 50 return 0; 51} 52 53/// \brief Compute the DeclContext that is associated with the given type. 54/// 55/// \param T the type for which we are attempting to find a DeclContext. 56/// 57/// \returns the declaration context represented by the type T, 58/// or NULL if the declaration context cannot be computed (e.g., because it is 59/// dependent and not the current instantiation). 60DeclContext *Sema::computeDeclContext(QualType T) { 61 if (!T->isDependentType()) 62 if (const TagType *Tag = T->getAs<TagType>()) 63 return Tag->getDecl(); 64 65 return ::getCurrentInstantiationOf(T, CurContext); 66} 67 68/// \brief Compute the DeclContext that is associated with the given 69/// scope specifier. 70/// 71/// \param SS the C++ scope specifier as it appears in the source 72/// 73/// \param EnteringContext when true, we will be entering the context of 74/// this scope specifier, so we can retrieve the declaration context of a 75/// class template or class template partial specialization even if it is 76/// not the current instantiation. 77/// 78/// \returns the declaration context represented by the scope specifier @p SS, 79/// or NULL if the declaration context cannot be computed (e.g., because it is 80/// dependent and not the current instantiation). 81DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS, 82 bool EnteringContext) { 83 if (!SS.isSet() || SS.isInvalid()) 84 return 0; 85 86 NestedNameSpecifier *NNS 87 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 88 if (NNS->isDependent()) { 89 // If this nested-name-specifier refers to the current 90 // instantiation, return its DeclContext. 91 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS)) 92 return Record; 93 94 if (EnteringContext) { 95 const Type *NNSType = NNS->getAsType(); 96 if (!NNSType) { 97 return 0; 98 } 99 100 // Look through type alias templates, per C++0x [temp.dep.type]p1. 101 NNSType = Context.getCanonicalType(NNSType); 102 if (const TemplateSpecializationType *SpecType 103 = NNSType->getAs<TemplateSpecializationType>()) { 104 // We are entering the context of the nested name specifier, so try to 105 // match the nested name specifier to either a primary class template 106 // or a class template partial specialization. 107 if (ClassTemplateDecl *ClassTemplate 108 = dyn_cast_or_null<ClassTemplateDecl>( 109 SpecType->getTemplateName().getAsTemplateDecl())) { 110 QualType ContextType 111 = Context.getCanonicalType(QualType(SpecType, 0)); 112 113 // If the type of the nested name specifier is the same as the 114 // injected class name of the named class template, we're entering 115 // into that class template definition. 116 QualType Injected 117 = ClassTemplate->getInjectedClassNameSpecialization(); 118 if (Context.hasSameType(Injected, ContextType)) 119 return ClassTemplate->getTemplatedDecl(); 120 121 // If the type of the nested name specifier is the same as the 122 // type of one of the class template's class template partial 123 // specializations, we're entering into the definition of that 124 // class template partial specialization. 125 if (ClassTemplatePartialSpecializationDecl *PartialSpec 126 = ClassTemplate->findPartialSpecialization(ContextType)) 127 return PartialSpec; 128 } 129 } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) { 130 // The nested name specifier refers to a member of a class template. 131 return RecordT->getDecl(); 132 } 133 } 134 135 return 0; 136 } 137 138 switch (NNS->getKind()) { 139 case NestedNameSpecifier::Identifier: 140 llvm_unreachable("Dependent nested-name-specifier has no DeclContext"); 141 142 case NestedNameSpecifier::Namespace: 143 return NNS->getAsNamespace(); 144 145 case NestedNameSpecifier::NamespaceAlias: 146 return NNS->getAsNamespaceAlias()->getNamespace(); 147 148 case NestedNameSpecifier::TypeSpec: 149 case NestedNameSpecifier::TypeSpecWithTemplate: { 150 const TagType *Tag = NNS->getAsType()->getAs<TagType>(); 151 assert(Tag && "Non-tag type in nested-name-specifier"); 152 return Tag->getDecl(); 153 } break; 154 155 case NestedNameSpecifier::Global: 156 return Context.getTranslationUnitDecl(); 157 } 158 159 // Required to silence a GCC warning. 160 return 0; 161} 162 163bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) { 164 if (!SS.isSet() || SS.isInvalid()) 165 return false; 166 167 NestedNameSpecifier *NNS 168 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 169 return NNS->isDependent(); 170} 171 172// \brief Determine whether this C++ scope specifier refers to an 173// unknown specialization, i.e., a dependent type that is not the 174// current instantiation. 175bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) { 176 if (!isDependentScopeSpecifier(SS)) 177 return false; 178 179 NestedNameSpecifier *NNS 180 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 181 return getCurrentInstantiationOf(NNS) == 0; 182} 183 184/// \brief If the given nested name specifier refers to the current 185/// instantiation, return the declaration that corresponds to that 186/// current instantiation (C++0x [temp.dep.type]p1). 187/// 188/// \param NNS a dependent nested name specifier. 189CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) { 190 assert(getLangOptions().CPlusPlus && "Only callable in C++"); 191 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed"); 192 193 if (!NNS->getAsType()) 194 return 0; 195 196 QualType T = QualType(NNS->getAsType(), 0); 197 return ::getCurrentInstantiationOf(T, CurContext); 198} 199 200/// \brief Require that the context specified by SS be complete. 201/// 202/// If SS refers to a type, this routine checks whether the type is 203/// complete enough (or can be made complete enough) for name lookup 204/// into the DeclContext. A type that is not yet completed can be 205/// considered "complete enough" if it is a class/struct/union/enum 206/// that is currently being defined. Or, if we have a type that names 207/// a class template specialization that is not a complete type, we 208/// will attempt to instantiate that class template. 209bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS, 210 DeclContext *DC) { 211 assert(DC != 0 && "given null context"); 212 213 if (TagDecl *tag = dyn_cast<TagDecl>(DC)) { 214 // If this is a dependent type, then we consider it complete. 215 if (tag->isDependentContext()) 216 return false; 217 218 // If we're currently defining this type, then lookup into the 219 // type is okay: don't complain that it isn't complete yet. 220 QualType type = Context.getTypeDeclType(tag); 221 const TagType *tagType = type->getAs<TagType>(); 222 if (tagType && tagType->isBeingDefined()) 223 return false; 224 225 SourceLocation loc = SS.getLastQualifierNameLoc(); 226 if (loc.isInvalid()) loc = SS.getRange().getBegin(); 227 228 // The type must be complete. 229 if (RequireCompleteType(loc, type, 230 PDiag(diag::err_incomplete_nested_name_spec) 231 << SS.getRange())) { 232 SS.SetInvalid(SS.getRange()); 233 return true; 234 } 235 236 // Fixed enum types are complete, but they aren't valid as scopes 237 // until we see a definition, so awkwardly pull out this special 238 // case. 239 if (const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType)) { 240 if (!enumType->getDecl()->isCompleteDefinition()) { 241 Diag(loc, diag::err_incomplete_nested_name_spec) 242 << type << SS.getRange(); 243 SS.SetInvalid(SS.getRange()); 244 return true; 245 } 246 } 247 } 248 249 return false; 250} 251 252bool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 253 CXXScopeSpec &SS) { 254 SS.MakeGlobal(Context, CCLoc); 255 return false; 256} 257 258/// \brief Determines whether the given declaration is an valid acceptable 259/// result for name lookup of a nested-name-specifier. 260bool Sema::isAcceptableNestedNameSpecifier(NamedDecl *SD) { 261 if (!SD) 262 return false; 263 264 // Namespace and namespace aliases are fine. 265 if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD)) 266 return true; 267 268 if (!isa<TypeDecl>(SD)) 269 return false; 270 271 // Determine whether we have a class (or, in C++11, an enum) or 272 // a typedef thereof. If so, build the nested-name-specifier. 273 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD)); 274 if (T->isDependentType()) 275 return true; 276 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) { 277 if (TD->getUnderlyingType()->isRecordType() || 278 (Context.getLangOptions().CPlusPlus0x && 279 TD->getUnderlyingType()->isEnumeralType())) 280 return true; 281 } else if (isa<RecordDecl>(SD) || 282 (Context.getLangOptions().CPlusPlus0x && isa<EnumDecl>(SD))) 283 return true; 284 285 return false; 286} 287 288/// \brief If the given nested-name-specifier begins with a bare identifier 289/// (e.g., Base::), perform name lookup for that identifier as a 290/// nested-name-specifier within the given scope, and return the result of that 291/// name lookup. 292NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) { 293 if (!S || !NNS) 294 return 0; 295 296 while (NNS->getPrefix()) 297 NNS = NNS->getPrefix(); 298 299 if (NNS->getKind() != NestedNameSpecifier::Identifier) 300 return 0; 301 302 LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(), 303 LookupNestedNameSpecifierName); 304 LookupName(Found, S); 305 assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet"); 306 307 if (!Found.isSingleResult()) 308 return 0; 309 310 NamedDecl *Result = Found.getFoundDecl(); 311 if (isAcceptableNestedNameSpecifier(Result)) 312 return Result; 313 314 return 0; 315} 316 317bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 318 SourceLocation IdLoc, 319 IdentifierInfo &II, 320 ParsedType ObjectTypePtr) { 321 QualType ObjectType = GetTypeFromParser(ObjectTypePtr); 322 LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName); 323 324 // Determine where to perform name lookup 325 DeclContext *LookupCtx = 0; 326 bool isDependent = false; 327 if (!ObjectType.isNull()) { 328 // This nested-name-specifier occurs in a member access expression, e.g., 329 // x->B::f, and we are looking into the type of the object. 330 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 331 LookupCtx = computeDeclContext(ObjectType); 332 isDependent = ObjectType->isDependentType(); 333 } else if (SS.isSet()) { 334 // This nested-name-specifier occurs after another nested-name-specifier, 335 // so long into the context associated with the prior nested-name-specifier. 336 LookupCtx = computeDeclContext(SS, false); 337 isDependent = isDependentScopeSpecifier(SS); 338 Found.setContextRange(SS.getRange()); 339 } 340 341 if (LookupCtx) { 342 // Perform "qualified" name lookup into the declaration context we 343 // computed, which is either the type of the base of a member access 344 // expression or the declaration context associated with a prior 345 // nested-name-specifier. 346 347 // The declaration context must be complete. 348 if (!LookupCtx->isDependentContext() && 349 RequireCompleteDeclContext(SS, LookupCtx)) 350 return false; 351 352 LookupQualifiedName(Found, LookupCtx); 353 } else if (isDependent) { 354 return false; 355 } else { 356 LookupName(Found, S); 357 } 358 Found.suppressDiagnostics(); 359 360 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>()) 361 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 362 363 return false; 364} 365 366/// \brief Build a new nested-name-specifier for "identifier::", as described 367/// by ActOnCXXNestedNameSpecifier. 368/// 369/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in 370/// that it contains an extra parameter \p ScopeLookupResult, which provides 371/// the result of name lookup within the scope of the nested-name-specifier 372/// that was computed at template definition time. 373/// 374/// If ErrorRecoveryLookup is true, then this call is used to improve error 375/// recovery. This means that it should not emit diagnostics, it should 376/// just return true on failure. It also means it should only return a valid 377/// scope if it *knows* that the result is correct. It should not return in a 378/// dependent context, for example. Nor will it extend \p SS with the scope 379/// specifier. 380bool Sema::BuildCXXNestedNameSpecifier(Scope *S, 381 IdentifierInfo &Identifier, 382 SourceLocation IdentifierLoc, 383 SourceLocation CCLoc, 384 QualType ObjectType, 385 bool EnteringContext, 386 CXXScopeSpec &SS, 387 NamedDecl *ScopeLookupResult, 388 bool ErrorRecoveryLookup) { 389 LookupResult Found(*this, &Identifier, IdentifierLoc, 390 LookupNestedNameSpecifierName); 391 392 // Determine where to perform name lookup 393 DeclContext *LookupCtx = 0; 394 bool isDependent = false; 395 if (!ObjectType.isNull()) { 396 // This nested-name-specifier occurs in a member access expression, e.g., 397 // x->B::f, and we are looking into the type of the object. 398 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 399 LookupCtx = computeDeclContext(ObjectType); 400 isDependent = ObjectType->isDependentType(); 401 } else if (SS.isSet()) { 402 // This nested-name-specifier occurs after another nested-name-specifier, 403 // so look into the context associated with the prior nested-name-specifier. 404 LookupCtx = computeDeclContext(SS, EnteringContext); 405 isDependent = isDependentScopeSpecifier(SS); 406 Found.setContextRange(SS.getRange()); 407 } 408 409 410 bool ObjectTypeSearchedInScope = false; 411 if (LookupCtx) { 412 // Perform "qualified" name lookup into the declaration context we 413 // computed, which is either the type of the base of a member access 414 // expression or the declaration context associated with a prior 415 // nested-name-specifier. 416 417 // The declaration context must be complete. 418 if (!LookupCtx->isDependentContext() && 419 RequireCompleteDeclContext(SS, LookupCtx)) 420 return true; 421 422 LookupQualifiedName(Found, LookupCtx); 423 424 if (!ObjectType.isNull() && Found.empty()) { 425 // C++ [basic.lookup.classref]p4: 426 // If the id-expression in a class member access is a qualified-id of 427 // the form 428 // 429 // class-name-or-namespace-name::... 430 // 431 // the class-name-or-namespace-name following the . or -> operator is 432 // looked up both in the context of the entire postfix-expression and in 433 // the scope of the class of the object expression. If the name is found 434 // only in the scope of the class of the object expression, the name 435 // shall refer to a class-name. If the name is found only in the 436 // context of the entire postfix-expression, the name shall refer to a 437 // class-name or namespace-name. [...] 438 // 439 // Qualified name lookup into a class will not find a namespace-name, 440 // so we do not need to diagnose that case specifically. However, 441 // this qualified name lookup may find nothing. In that case, perform 442 // unqualified name lookup in the given scope (if available) or 443 // reconstruct the result from when name lookup was performed at template 444 // definition time. 445 if (S) 446 LookupName(Found, S); 447 else if (ScopeLookupResult) 448 Found.addDecl(ScopeLookupResult); 449 450 ObjectTypeSearchedInScope = true; 451 } 452 } else if (!isDependent) { 453 // Perform unqualified name lookup in the current scope. 454 LookupName(Found, S); 455 } 456 457 // If we performed lookup into a dependent context and did not find anything, 458 // that's fine: just build a dependent nested-name-specifier. 459 if (Found.empty() && isDependent && 460 !(LookupCtx && LookupCtx->isRecord() && 461 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() || 462 !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) { 463 // Don't speculate if we're just trying to improve error recovery. 464 if (ErrorRecoveryLookup) 465 return true; 466 467 // We were not able to compute the declaration context for a dependent 468 // base object type or prior nested-name-specifier, so this 469 // nested-name-specifier refers to an unknown specialization. Just build 470 // a dependent nested-name-specifier. 471 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc); 472 return false; 473 } 474 475 // FIXME: Deal with ambiguities cleanly. 476 477 if (Found.empty() && !ErrorRecoveryLookup) { 478 // We haven't found anything, and we're not recovering from a 479 // different kind of error, so look for typos. 480 DeclarationName Name = Found.getLookupName(); 481 TypoCorrection Corrected; 482 Found.clear(); 483 if ((Corrected = CorrectTypo(Found.getLookupNameInfo(), 484 Found.getLookupKind(), S, &SS, LookupCtx, 485 EnteringContext, CTC_NoKeywords)) && 486 isAcceptableNestedNameSpecifier(Corrected.getCorrectionDecl())) { 487 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 488 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 489 if (LookupCtx) 490 Diag(Found.getNameLoc(), diag::err_no_member_suggest) 491 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange() 492 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr); 493 else 494 Diag(Found.getNameLoc(), diag::err_undeclared_var_use_suggest) 495 << Name << CorrectedQuotedStr 496 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr); 497 498 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 499 Diag(ND->getLocation(), diag::note_previous_decl) << CorrectedQuotedStr; 500 Found.addDecl(ND); 501 } 502 Found.setLookupName(Corrected.getCorrection()); 503 } else { 504 Found.setLookupName(&Identifier); 505 } 506 } 507 508 NamedDecl *SD = Found.getAsSingle<NamedDecl>(); 509 if (isAcceptableNestedNameSpecifier(SD)) { 510 if (!ObjectType.isNull() && !ObjectTypeSearchedInScope) { 511 // C++ [basic.lookup.classref]p4: 512 // [...] If the name is found in both contexts, the 513 // class-name-or-namespace-name shall refer to the same entity. 514 // 515 // We already found the name in the scope of the object. Now, look 516 // into the current scope (the scope of the postfix-expression) to 517 // see if we can find the same name there. As above, if there is no 518 // scope, reconstruct the result from the template instantiation itself. 519 NamedDecl *OuterDecl; 520 if (S) { 521 LookupResult FoundOuter(*this, &Identifier, IdentifierLoc, 522 LookupNestedNameSpecifierName); 523 LookupName(FoundOuter, S); 524 OuterDecl = FoundOuter.getAsSingle<NamedDecl>(); 525 } else 526 OuterDecl = ScopeLookupResult; 527 528 if (isAcceptableNestedNameSpecifier(OuterDecl) && 529 OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() && 530 (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) || 531 !Context.hasSameType( 532 Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)), 533 Context.getTypeDeclType(cast<TypeDecl>(SD))))) { 534 if (ErrorRecoveryLookup) 535 return true; 536 537 Diag(IdentifierLoc, 538 diag::err_nested_name_member_ref_lookup_ambiguous) 539 << &Identifier; 540 Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type) 541 << ObjectType; 542 Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope); 543 544 // Fall through so that we'll pick the name we found in the object 545 // type, since that's probably what the user wanted anyway. 546 } 547 } 548 549 // If we're just performing this lookup for error-recovery purposes, 550 // don't extend the nested-name-specifier. Just return now. 551 if (ErrorRecoveryLookup) 552 return false; 553 554 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) { 555 SS.Extend(Context, Namespace, IdentifierLoc, CCLoc); 556 return false; 557 } 558 559 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) { 560 SS.Extend(Context, Alias, IdentifierLoc, CCLoc); 561 return false; 562 } 563 564 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD)); 565 TypeLocBuilder TLB; 566 if (isa<InjectedClassNameType>(T)) { 567 InjectedClassNameTypeLoc InjectedTL 568 = TLB.push<InjectedClassNameTypeLoc>(T); 569 InjectedTL.setNameLoc(IdentifierLoc); 570 } else if (isa<RecordType>(T)) { 571 RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T); 572 RecordTL.setNameLoc(IdentifierLoc); 573 } else if (isa<TypedefType>(T)) { 574 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T); 575 TypedefTL.setNameLoc(IdentifierLoc); 576 } else if (isa<EnumType>(T)) { 577 EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T); 578 EnumTL.setNameLoc(IdentifierLoc); 579 } else if (isa<TemplateTypeParmType>(T)) { 580 TemplateTypeParmTypeLoc TemplateTypeTL 581 = TLB.push<TemplateTypeParmTypeLoc>(T); 582 TemplateTypeTL.setNameLoc(IdentifierLoc); 583 } else if (isa<UnresolvedUsingType>(T)) { 584 UnresolvedUsingTypeLoc UnresolvedTL 585 = TLB.push<UnresolvedUsingTypeLoc>(T); 586 UnresolvedTL.setNameLoc(IdentifierLoc); 587 } else if (isa<SubstTemplateTypeParmType>(T)) { 588 SubstTemplateTypeParmTypeLoc TL 589 = TLB.push<SubstTemplateTypeParmTypeLoc>(T); 590 TL.setNameLoc(IdentifierLoc); 591 } else if (isa<SubstTemplateTypeParmPackType>(T)) { 592 SubstTemplateTypeParmPackTypeLoc TL 593 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T); 594 TL.setNameLoc(IdentifierLoc); 595 } else { 596 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier"); 597 } 598 599 if (T->isEnumeralType()) 600 Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec); 601 602 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T), 603 CCLoc); 604 return false; 605 } 606 607 // Otherwise, we have an error case. If we don't want diagnostics, just 608 // return an error now. 609 if (ErrorRecoveryLookup) 610 return true; 611 612 // If we didn't find anything during our lookup, try again with 613 // ordinary name lookup, which can help us produce better error 614 // messages. 615 if (Found.empty()) { 616 Found.clear(LookupOrdinaryName); 617 LookupName(Found, S); 618 } 619 620 // In Microsoft mode, if we are within a templated function and we can't 621 // resolve Identifier, then extend the SS with Identifier. This will have 622 // the effect of resolving Identifier during template instantiation. 623 // The goal is to be able to resolve a function call whose 624 // nested-name-specifier is located inside a dependent base class. 625 // Example: 626 // 627 // class C { 628 // public: 629 // static void foo2() { } 630 // }; 631 // template <class T> class A { public: typedef C D; }; 632 // 633 // template <class T> class B : public A<T> { 634 // public: 635 // void foo() { D::foo2(); } 636 // }; 637 if (getLangOptions().MicrosoftExt) { 638 DeclContext *DC = LookupCtx ? LookupCtx : CurContext; 639 if (DC->isDependentContext() && DC->isFunctionOrMethod()) { 640 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc); 641 return false; 642 } 643 } 644 645 unsigned DiagID; 646 if (!Found.empty()) 647 DiagID = diag::err_expected_class_or_namespace; 648 else if (SS.isSet()) { 649 Diag(IdentifierLoc, diag::err_no_member) 650 << &Identifier << LookupCtx << SS.getRange(); 651 return true; 652 } else 653 DiagID = diag::err_undeclared_var_use; 654 655 if (SS.isSet()) 656 Diag(IdentifierLoc, DiagID) << &Identifier << SS.getRange(); 657 else 658 Diag(IdentifierLoc, DiagID) << &Identifier; 659 660 return true; 661} 662 663bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, 664 IdentifierInfo &Identifier, 665 SourceLocation IdentifierLoc, 666 SourceLocation CCLoc, 667 ParsedType ObjectType, 668 bool EnteringContext, 669 CXXScopeSpec &SS) { 670 if (SS.isInvalid()) 671 return true; 672 673 return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc, 674 GetTypeFromParser(ObjectType), 675 EnteringContext, SS, 676 /*ScopeLookupResult=*/0, false); 677} 678 679/// IsInvalidUnlessNestedName - This method is used for error recovery 680/// purposes to determine whether the specified identifier is only valid as 681/// a nested name specifier, for example a namespace name. It is 682/// conservatively correct to always return false from this method. 683/// 684/// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier. 685bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 686 IdentifierInfo &Identifier, 687 SourceLocation IdentifierLoc, 688 SourceLocation ColonLoc, 689 ParsedType ObjectType, 690 bool EnteringContext) { 691 if (SS.isInvalid()) 692 return false; 693 694 return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc, 695 GetTypeFromParser(ObjectType), 696 EnteringContext, SS, 697 /*ScopeLookupResult=*/0, true); 698} 699 700bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, 701 SourceLocation TemplateLoc, 702 CXXScopeSpec &SS, 703 TemplateTy Template, 704 SourceLocation TemplateNameLoc, 705 SourceLocation LAngleLoc, 706 ASTTemplateArgsPtr TemplateArgsIn, 707 SourceLocation RAngleLoc, 708 SourceLocation CCLoc, 709 bool EnteringContext) { 710 if (SS.isInvalid()) 711 return true; 712 713 // Translate the parser's template argument list in our AST format. 714 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 715 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 716 717 if (DependentTemplateName *DTN = Template.get().getAsDependentTemplateName()){ 718 // Handle a dependent template specialization for which we cannot resolve 719 // the template name. 720 assert(DTN->getQualifier() 721 == static_cast<NestedNameSpecifier*>(SS.getScopeRep())); 722 QualType T = Context.getDependentTemplateSpecializationType(ETK_None, 723 DTN->getQualifier(), 724 DTN->getIdentifier(), 725 TemplateArgs); 726 727 // Create source-location information for this type. 728 TypeLocBuilder Builder; 729 DependentTemplateSpecializationTypeLoc SpecTL 730 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 731 SpecTL.setLAngleLoc(LAngleLoc); 732 SpecTL.setRAngleLoc(RAngleLoc); 733 SpecTL.setKeywordLoc(SourceLocation()); 734 SpecTL.setNameLoc(TemplateNameLoc); 735 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 736 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 737 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 738 739 SS.Extend(Context, TemplateLoc, Builder.getTypeLocInContext(Context, T), 740 CCLoc); 741 return false; 742 } 743 744 745 if (Template.get().getAsOverloadedTemplate() || 746 isa<FunctionTemplateDecl>(Template.get().getAsTemplateDecl())) { 747 SourceRange R(TemplateNameLoc, RAngleLoc); 748 if (SS.getRange().isValid()) 749 R.setBegin(SS.getRange().getBegin()); 750 751 Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier) 752 << Template.get() << R; 753 NoteAllFoundTemplates(Template.get()); 754 return true; 755 } 756 757 // We were able to resolve the template name to an actual template. 758 // Build an appropriate nested-name-specifier. 759 QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc, 760 TemplateArgs); 761 if (T.isNull()) 762 return true; 763 764 // Alias template specializations can produce types which are not valid 765 // nested name specifiers. 766 if (!T->isDependentType() && !T->getAs<TagType>()) { 767 Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T; 768 NoteAllFoundTemplates(Template.get()); 769 return true; 770 } 771 772 // Provide source-location information for the template specialization 773 // type. 774 TypeLocBuilder Builder; 775 TemplateSpecializationTypeLoc SpecTL 776 = Builder.push<TemplateSpecializationTypeLoc>(T); 777 778 SpecTL.setLAngleLoc(LAngleLoc); 779 SpecTL.setRAngleLoc(RAngleLoc); 780 SpecTL.setTemplateNameLoc(TemplateNameLoc); 781 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 782 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 783 784 785 SS.Extend(Context, TemplateLoc, Builder.getTypeLocInContext(Context, T), 786 CCLoc); 787 return false; 788} 789 790namespace { 791 /// \brief A structure that stores a nested-name-specifier annotation, 792 /// including both the nested-name-specifier 793 struct NestedNameSpecifierAnnotation { 794 NestedNameSpecifier *NNS; 795 }; 796} 797 798void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) { 799 if (SS.isEmpty() || SS.isInvalid()) 800 return 0; 801 802 void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) + 803 SS.location_size()), 804 llvm::alignOf<NestedNameSpecifierAnnotation>()); 805 NestedNameSpecifierAnnotation *Annotation 806 = new (Mem) NestedNameSpecifierAnnotation; 807 Annotation->NNS = SS.getScopeRep(); 808 memcpy(Annotation + 1, SS.location_data(), SS.location_size()); 809 return Annotation; 810} 811 812void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, 813 SourceRange AnnotationRange, 814 CXXScopeSpec &SS) { 815 if (!AnnotationPtr) { 816 SS.SetInvalid(AnnotationRange); 817 return; 818 } 819 820 NestedNameSpecifierAnnotation *Annotation 821 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr); 822 SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1)); 823} 824 825bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { 826 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); 827 828 NestedNameSpecifier *Qualifier = 829 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 830 831 // There are only two places a well-formed program may qualify a 832 // declarator: first, when defining a namespace or class member 833 // out-of-line, and second, when naming an explicitly-qualified 834 // friend function. The latter case is governed by 835 // C++03 [basic.lookup.unqual]p10: 836 // In a friend declaration naming a member function, a name used 837 // in the function declarator and not part of a template-argument 838 // in a template-id is first looked up in the scope of the member 839 // function's class. If it is not found, or if the name is part of 840 // a template-argument in a template-id, the look up is as 841 // described for unqualified names in the definition of the class 842 // granting friendship. 843 // i.e. we don't push a scope unless it's a class member. 844 845 switch (Qualifier->getKind()) { 846 case NestedNameSpecifier::Global: 847 case NestedNameSpecifier::Namespace: 848 case NestedNameSpecifier::NamespaceAlias: 849 // These are always namespace scopes. We never want to enter a 850 // namespace scope from anything but a file context. 851 return CurContext->getRedeclContext()->isFileContext(); 852 853 case NestedNameSpecifier::Identifier: 854 case NestedNameSpecifier::TypeSpec: 855 case NestedNameSpecifier::TypeSpecWithTemplate: 856 // These are never namespace scopes. 857 return true; 858 } 859 860 // Silence bogus warning. 861 return false; 862} 863 864/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 865/// scope or nested-name-specifier) is parsed, part of a declarator-id. 866/// After this method is called, according to [C++ 3.4.3p3], names should be 867/// looked up in the declarator-id's scope, until the declarator is parsed and 868/// ActOnCXXExitDeclaratorScope is called. 869/// The 'SS' should be a non-empty valid CXXScopeSpec. 870bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) { 871 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); 872 873 if (SS.isInvalid()) return true; 874 875 DeclContext *DC = computeDeclContext(SS, true); 876 if (!DC) return true; 877 878 // Before we enter a declarator's context, we need to make sure that 879 // it is a complete declaration context. 880 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC)) 881 return true; 882 883 EnterDeclaratorContext(S, DC); 884 885 // Rebuild the nested name specifier for the new scope. 886 if (DC->isDependentContext()) 887 RebuildNestedNameSpecifierInCurrentInstantiation(SS); 888 889 return false; 890} 891 892/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 893/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 894/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 895/// Used to indicate that names should revert to being looked up in the 896/// defining scope. 897void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) { 898 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec."); 899 if (SS.isInvalid()) 900 return; 901 assert(!SS.isInvalid() && computeDeclContext(SS, true) && 902 "exiting declarator scope we never really entered"); 903 ExitDeclaratorContext(S); 904} 905