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