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 "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;
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 (!T->isDependentType())
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))
48 } else if (isa<InjectedClassNameType>(Ty))
49 return cast<InjectedClassNameType>(Ty)->getDecl();
54 /// \brief Compute the DeclContext that is associated with the given type.
56 /// \param T the type for which we are attempting to find a DeclContext.
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();
66 return ::getCurrentInstantiationOf(T, CurContext);
69 /// \brief Compute the DeclContext that is associated with the given
72 /// \param SS the C++ scope specifier as it appears in the source
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.
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())
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))
95 if (EnteringContext) {
96 const Type *NNSType = NNS->getAsType();
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())) {
112 = Context.getCanonicalType(QualType(SpecType, 0));
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.
118 = ClassTemplate->getInjectedClassNameSpecialization();
119 if (Context.hasSameType(Injected, ContextType))
120 return ClassTemplate->getTemplatedDecl();
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))
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();
139 switch (NNS->getKind()) {
140 case NestedNameSpecifier::Identifier:
141 llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
143 case NestedNameSpecifier::Namespace:
144 return NNS->getAsNamespace();
146 case NestedNameSpecifier::NamespaceAlias:
147 return NNS->getAsNamespaceAlias()->getNamespace();
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();
156 case NestedNameSpecifier::Global:
157 return Context.getTranslationUnitDecl();
160 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
163 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
164 if (!SS.isSet() || SS.isInvalid())
167 NestedNameSpecifier *NNS
168 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
169 return NNS->isDependent();
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))
179 NestedNameSpecifier *NNS
180 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
181 return getCurrentInstantiationOf(NNS) == 0;
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).
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");
193 if (!NNS->getAsType())
196 QualType T = QualType(NNS->getAsType(), 0);
197 return ::getCurrentInstantiationOf(T, CurContext);
200 /// \brief Require that the context specified by SS be complete.
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,
211 assert(DC != 0 && "given null context");
213 TagDecl *tag = dyn_cast<TagDecl>(DC);
215 // If this is a dependent type, then we consider it complete.
216 if (!tag || tag->isDependentContext())
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())
226 SourceLocation loc = SS.getLastQualifierNameLoc();
227 if (loc.isInvalid()) loc = SS.getRange().getBegin();
229 // The type must be complete.
230 if (RequireCompleteType(loc, type,
231 PDiag(diag::err_incomplete_nested_name_spec)
233 SS.SetInvalid(SS.getRange());
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
240 const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType);
241 if (!enumType || enumType->getDecl()->isCompleteDefinition())
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());
259 Diag(loc, diag::err_incomplete_nested_name_spec)
260 << type << SS.getRange();
261 SS.SetInvalid(SS.getRange());
265 bool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
267 SS.MakeGlobal(Context, CCLoc);
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) {
277 // Namespace and namespace aliases are fine.
278 if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
281 if (!isa<TypeDecl>(SD))
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())
289 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
290 if (TD->getUnderlyingType()->isRecordType() ||
291 (Context.getLangOpts().CPlusPlus0x &&
292 TD->getUnderlyingType()->isEnumeralType()))
294 } else if (isa<RecordDecl>(SD) ||
295 (Context.getLangOpts().CPlusPlus0x && isa<EnumDecl>(SD)))
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
305 NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
309 while (NNS->getPrefix())
310 NNS = NNS->getPrefix();
312 if (NNS->getKind() != NestedNameSpecifier::Identifier)
315 LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
316 LookupNestedNameSpecifierName);
317 LookupName(Found, S);
318 assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
320 if (!Found.isSingleResult())
323 NamedDecl *Result = Found.getFoundDecl();
324 if (isAcceptableNestedNameSpecifier(Result))
330 bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
331 SourceLocation IdLoc,
333 ParsedType ObjectTypePtr) {
334 QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
335 LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
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());
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.
360 // The declaration context must be complete.
361 if (!LookupCtx->isDependentContext() &&
362 RequireCompleteDeclContext(SS, LookupCtx))
365 LookupQualifiedName(Found, LookupCtx);
366 } else if (isDependent) {
369 LookupName(Found, S);
371 Found.suppressDiagnostics();
373 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
374 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
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 {
385 explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
388 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
389 return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
398 /// \brief Build a new nested-name-specifier for "identifier::", as described
399 /// by ActOnCXXNestedNameSpecifier.
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.
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
412 bool Sema::BuildCXXNestedNameSpecifier(Scope *S,
413 IdentifierInfo &Identifier,
414 SourceLocation IdentifierLoc,
415 SourceLocation CCLoc,
417 bool EnteringContext,
419 NamedDecl *ScopeLookupResult,
420 bool ErrorRecoveryLookup) {
421 LookupResult Found(*this, &Identifier, IdentifierLoc,
422 LookupNestedNameSpecifierName);
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());
442 bool ObjectTypeSearchedInScope = false;
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.
449 // The declaration context must be complete.
450 if (!LookupCtx->isDependentContext() &&
451 RequireCompleteDeclContext(SS, LookupCtx))
454 LookupQualifiedName(Found, LookupCtx);
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
461 // class-name-or-namespace-name::...
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. [...]
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
478 LookupName(Found, S);
479 else if (ScopeLookupResult)
480 Found.addDecl(ScopeLookupResult);
482 ObjectTypeSearchedInScope = true;
484 } else if (!isDependent) {
485 // Perform unqualified name lookup in the current scope.
486 LookupName(Found, S);
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)
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);
507 // FIXME: Deal with ambiguities cleanly.
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;
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()));
522 Diag(Found.getNameLoc(), diag::err_no_member_suggest)
523 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
524 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
526 Diag(Found.getNameLoc(), diag::err_undeclared_var_use_suggest)
527 << Name << CorrectedQuotedStr
528 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
530 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
531 Diag(ND->getLocation(), diag::note_previous_decl) << CorrectedQuotedStr;
534 Found.setLookupName(Corrected.getCorrection());
536 Found.setLookupName(&Identifier);
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.
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;
553 LookupResult FoundOuter(*this, &Identifier, IdentifierLoc,
554 LookupNestedNameSpecifierName);
555 LookupName(FoundOuter, S);
556 OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
558 OuterDecl = ScopeLookupResult;
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)
570 diag::err_nested_name_member_ref_lookup_ambiguous)
572 Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
574 Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
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.
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)
586 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
587 SS.Extend(Context, Namespace, IdentifierLoc, CCLoc);
591 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
592 SS.Extend(Context, Alias, IdentifierLoc, CCLoc);
596 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
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);
628 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
631 if (T->isEnumeralType())
632 Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
634 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
639 // Otherwise, we have an error case. If we don't want diagnostics, just
640 // return an error now.
641 if (ErrorRecoveryLookup)
644 // If we didn't find anything during our lookup, try again with
645 // ordinary name lookup, which can help us produce better error
648 Found.clear(LookupOrdinaryName);
649 LookupName(Found, S);
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.
661 // static void foo2() { }
663 // template <class T> class A { public: typedef C D; };
665 // template <class T> class B : public A<T> {
667 // void foo() { D::foo2(); }
669 if (getLangOpts().MicrosoftExt) {
670 DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
671 if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
672 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
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();
685 DiagID = diag::err_undeclared_var_use;
688 Diag(IdentifierLoc, DiagID) << &Identifier << SS.getRange();
690 Diag(IdentifierLoc, DiagID) << &Identifier;
695 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
696 IdentifierInfo &Identifier,
697 SourceLocation IdentifierLoc,
698 SourceLocation CCLoc,
699 ParsedType ObjectType,
700 bool EnteringContext,
705 return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc,
706 GetTypeFromParser(ObjectType),
708 /*ScopeLookupResult=*/0, false);
711 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
713 SourceLocation ColonColonLoc) {
714 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
717 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
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;
727 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
728 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
729 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
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.
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) {
749 return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc,
750 GetTypeFromParser(ObjectType),
752 /*ScopeLookupResult=*/0, true);
755 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
757 SourceLocation TemplateKWLoc,
759 SourceLocation TemplateNameLoc,
760 SourceLocation LAngleLoc,
761 ASTTemplateArgsPtr TemplateArgsIn,
762 SourceLocation RAngleLoc,
763 SourceLocation CCLoc,
764 bool EnteringContext) {
768 // Translate the parser's template argument list in our AST format.
769 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
770 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
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,
779 DTN->getIdentifier(),
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());
795 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
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());
807 Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
808 << Template.get() << R;
809 NoteAllFoundTemplates(Template.get());
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,
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());
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());
840 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
846 /// \brief A structure that stores a nested-name-specifier annotation,
847 /// including both the nested-name-specifier
848 struct NestedNameSpecifierAnnotation {
849 NestedNameSpecifier *NNS;
853 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
854 if (SS.isEmpty() || SS.isInvalid())
857 void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) +
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());
867 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
868 SourceRange AnnotationRange,
870 if (!AnnotationPtr) {
871 SS.SetInvalid(AnnotationRange);
875 NestedNameSpecifierAnnotation *Annotation
876 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
877 SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
880 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
881 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
883 NestedNameSpecifier *Qualifier =
884 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
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.
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();
908 case NestedNameSpecifier::Identifier:
909 case NestedNameSpecifier::TypeSpec:
910 case NestedNameSpecifier::TypeSpecWithTemplate:
911 // These are never namespace scopes.
915 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
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.");
927 if (SS.isInvalid()) return true;
929 DeclContext *DC = computeDeclContext(SS, true);
930 if (!DC) return true;
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))
937 EnterDeclaratorContext(S, DC);
939 // Rebuild the nested name specifier for the new scope.
940 if (DC->isDependentContext())
941 RebuildNestedNameSpecifierInCurrentInstantiation(SS);
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
951 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
952 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
955 assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
956 "exiting declarator scope we never really entered");
957 ExitDeclaratorContext(S);