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