1 //===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements C++ semantic analysis for scope specifiers.
12 //===----------------------------------------------------------------------===//
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"
26 using namespace clang;
28 /// \brief Find the current instantiation that associated with the given type.
29 static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
30 DeclContext *CurContext) {
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))
42 } else if (isa<InjectedClassNameType>(Ty))
43 return cast<InjectedClassNameType>(Ty)->getDecl();
48 /// \brief Compute the DeclContext that is associated with the given type.
50 /// \param T the type for which we are attempting to find a DeclContext.
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).
55 DeclContext *Sema::computeDeclContext(QualType T) {
56 if (!T->isDependentType())
57 if (const TagType *Tag = T->getAs<TagType>())
58 return Tag->getDecl();
60 return ::getCurrentInstantiationOf(T, CurContext);
63 /// \brief Compute the DeclContext that is associated with the given
66 /// \param SS the C++ scope specifier as it appears in the source
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.
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).
76 DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
77 bool EnteringContext) {
78 if (!SS.isSet() || SS.isInvalid())
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))
88 if (EnteringContext) {
89 const Type *NNSType = NNS->getAsType();
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())) {
105 = Context.getCanonicalType(QualType(SpecType, 0));
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.
111 = ClassTemplate->getInjectedClassNameSpecialization();
112 if (Context.hasSameType(Injected, ContextType))
113 return ClassTemplate->getTemplatedDecl();
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))
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();
132 switch (NNS->getKind()) {
133 case NestedNameSpecifier::Identifier:
134 llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
136 case NestedNameSpecifier::Namespace:
137 return NNS->getAsNamespace();
139 case NestedNameSpecifier::NamespaceAlias:
140 return NNS->getAsNamespaceAlias()->getNamespace();
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();
149 case NestedNameSpecifier::Global:
150 return Context.getTranslationUnitDecl();
153 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
156 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
157 if (!SS.isSet() || SS.isInvalid())
160 return SS.getScopeRep()->isDependent();
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.
166 bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
167 if (!isDependentScopeSpecifier(SS))
170 return getCurrentInstantiationOf(SS.getScopeRep()) == 0;
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).
177 /// \param NNS a dependent nested name specifier.
178 CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
179 assert(getLangOpts().CPlusPlus && "Only callable in C++");
180 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
182 if (!NNS->getAsType())
185 QualType T = QualType(NNS->getAsType(), 0);
186 return ::getCurrentInstantiationOf(T, CurContext);
189 /// \brief Require that the context specified by SS be complete.
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.
198 bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
200 assert(DC != 0 && "given null context");
202 TagDecl *tag = dyn_cast<TagDecl>(DC);
204 // If this is a dependent type, then we consider it complete.
205 if (!tag || tag->isDependentContext())
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())
215 SourceLocation loc = SS.getLastQualifierNameLoc();
216 if (loc.isInvalid()) loc = SS.getRange().getBegin();
218 // The type must be complete.
219 if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
221 SS.SetInvalid(SS.getRange());
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
228 const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType);
229 if (!enumType || enumType->getDecl()->isCompleteDefinition())
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());
247 Diag(loc, diag::err_incomplete_nested_name_spec)
248 << type << SS.getRange();
249 SS.SetInvalid(SS.getRange());
253 bool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
255 SS.MakeGlobal(Context, CCLoc);
259 /// \brief Determines whether the given declaration is an valid acceptable
260 /// result for name lookup of a nested-name-specifier.
261 bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD) {
265 // Namespace and namespace aliases are fine.
266 if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
269 if (!isa<TypeDecl>(SD))
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())
277 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
278 if (TD->getUnderlyingType()->isRecordType() ||
279 (Context.getLangOpts().CPlusPlus11 &&
280 TD->getUnderlyingType()->isEnumeralType()))
282 } else if (isa<RecordDecl>(SD) ||
283 (Context.getLangOpts().CPlusPlus11 && isa<EnumDecl>(SD)))
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
293 NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
297 while (NNS->getPrefix())
298 NNS = NNS->getPrefix();
300 if (NNS->getKind() != NestedNameSpecifier::Identifier)
303 LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
304 LookupNestedNameSpecifierName);
305 LookupName(Found, S);
306 assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
308 if (!Found.isSingleResult())
311 NamedDecl *Result = Found.getFoundDecl();
312 if (isAcceptableNestedNameSpecifier(Result))
318 bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
319 SourceLocation IdLoc,
321 ParsedType ObjectTypePtr) {
322 QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
323 LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
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());
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.
348 // The declaration context must be complete.
349 if (!LookupCtx->isDependentContext() &&
350 RequireCompleteDeclContext(SS, LookupCtx))
353 LookupQualifiedName(Found, LookupCtx);
354 } else if (isDependent) {
357 LookupName(Found, S);
359 Found.suppressDiagnostics();
361 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
362 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
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.
371 class NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback {
373 explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
376 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
377 return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
386 /// \brief Build a new nested-name-specifier for "identifier::", as described
387 /// by ActOnCXXNestedNameSpecifier.
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.
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
400 bool Sema::BuildCXXNestedNameSpecifier(Scope *S,
401 IdentifierInfo &Identifier,
402 SourceLocation IdentifierLoc,
403 SourceLocation CCLoc,
405 bool EnteringContext,
407 NamedDecl *ScopeLookupResult,
408 bool ErrorRecoveryLookup) {
409 LookupResult Found(*this, &Identifier, IdentifierLoc,
410 LookupNestedNameSpecifierName);
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());
430 bool ObjectTypeSearchedInScope = false;
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.
437 // The declaration context must be complete.
438 if (!LookupCtx->isDependentContext() &&
439 RequireCompleteDeclContext(SS, LookupCtx))
442 LookupQualifiedName(Found, LookupCtx);
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
449 // class-name-or-namespace-name::...
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. [...]
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
466 LookupName(Found, S);
467 else if (ScopeLookupResult)
468 Found.addDecl(ScopeLookupResult);
470 ObjectTypeSearchedInScope = true;
472 } else if (!isDependent) {
473 // Perform unqualified name lookup in the current scope.
474 LookupName(Found, S);
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)
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);
495 // FIXME: Deal with ambiguities cleanly.
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;
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()));
510 Diag(Found.getNameLoc(), diag::err_no_member_suggest)
511 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
512 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
515 Diag(Found.getNameLoc(), diag::err_undeclared_var_use_suggest)
516 << Name << CorrectedQuotedStr
517 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
519 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
520 Diag(ND->getLocation(), diag::note_previous_decl) << CorrectedQuotedStr;
523 Found.setLookupName(Corrected.getCorrection());
525 Found.setLookupName(&Identifier);
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.
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.
542 // Note that C++11 does *not* perform this redundant lookup.
543 NamedDecl *OuterDecl;
545 LookupResult FoundOuter(*this, &Identifier, IdentifierLoc,
546 LookupNestedNameSpecifierName);
547 LookupName(FoundOuter, S);
548 OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
550 OuterDecl = ScopeLookupResult;
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)
562 diag::err_nested_name_member_ref_lookup_ambiguous)
564 Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
566 Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
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.
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)
578 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
579 SS.Extend(Context, Namespace, IdentifierLoc, CCLoc);
583 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
584 SS.Extend(Context, Alias, IdentifierLoc, CCLoc);
588 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
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);
620 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
623 if (T->isEnumeralType())
624 Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
626 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
631 // Otherwise, we have an error case. If we don't want diagnostics, just
632 // return an error now.
633 if (ErrorRecoveryLookup)
636 // If we didn't find anything during our lookup, try again with
637 // ordinary name lookup, which can help us produce better error
640 Found.clear(LookupOrdinaryName);
641 LookupName(Found, S);
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.
653 // static void foo2() { }
655 // template <class T> class A { public: typedef C D; };
657 // template <class T> class B : public A<T> {
659 // void foo() { D::foo2(); }
661 if (getLangOpts().MicrosoftExt) {
662 DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
663 if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
664 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
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();
677 DiagID = diag::err_undeclared_var_use;
680 Diag(IdentifierLoc, DiagID) << &Identifier << SS.getRange();
682 Diag(IdentifierLoc, DiagID) << &Identifier;
687 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
688 IdentifierInfo &Identifier,
689 SourceLocation IdentifierLoc,
690 SourceLocation CCLoc,
691 ParsedType ObjectType,
692 bool EnteringContext,
697 return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc,
698 GetTypeFromParser(ObjectType),
700 /*ScopeLookupResult=*/0, false);
703 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
705 SourceLocation ColonColonLoc) {
706 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
709 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
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;
719 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
720 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
721 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
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.
731 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
732 bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
733 IdentifierInfo &Identifier,
734 SourceLocation IdentifierLoc,
735 SourceLocation ColonLoc,
736 ParsedType ObjectType,
737 bool EnteringContext) {
741 return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc,
742 GetTypeFromParser(ObjectType),
744 /*ScopeLookupResult=*/0, true);
747 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
749 SourceLocation TemplateKWLoc,
751 SourceLocation TemplateNameLoc,
752 SourceLocation LAngleLoc,
753 ASTTemplateArgsPtr TemplateArgsIn,
754 SourceLocation RAngleLoc,
755 SourceLocation CCLoc,
756 bool EnteringContext) {
760 // Translate the parser's template argument list in our AST format.
761 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
762 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
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,
770 DTN->getIdentifier(),
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());
786 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
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());
798 Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
799 << Template.get() << R;
800 NoteAllFoundTemplates(Template.get());
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,
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());
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());
831 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
837 /// \brief A structure that stores a nested-name-specifier annotation,
838 /// including both the nested-name-specifier
839 struct NestedNameSpecifierAnnotation {
840 NestedNameSpecifier *NNS;
844 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
845 if (SS.isEmpty() || SS.isInvalid())
848 void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) +
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());
858 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
859 SourceRange AnnotationRange,
861 if (!AnnotationPtr) {
862 SS.SetInvalid(AnnotationRange);
866 NestedNameSpecifierAnnotation *Annotation
867 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
868 SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
871 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
872 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
874 NestedNameSpecifier *Qualifier = SS.getScopeRep();
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.
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();
898 case NestedNameSpecifier::Identifier:
899 case NestedNameSpecifier::TypeSpec:
900 case NestedNameSpecifier::TypeSpecWithTemplate:
901 // These are never namespace scopes.
905 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
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.
914 bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
915 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
917 if (SS.isInvalid()) return true;
919 DeclContext *DC = computeDeclContext(SS, true);
920 if (!DC) return true;
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))
927 EnterDeclaratorContext(S, DC);
929 // Rebuild the nested name specifier for the new scope.
930 if (DC->isDependentContext())
931 RebuildNestedNameSpecifierInCurrentInstantiation(SS);
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
941 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
942 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
945 assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
946 "exiting declarator scope we never really entered");
947 ExitDeclaratorContext(S);