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/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/NestedNameSpecifier.h"
20 #include "clang/Basic/PartialDiagnostic.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "TypeLocBuilder.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
27 /// \brief Find the current instantiation that associated with the given type.
28 static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
29 DeclContext *CurContext) {
33 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
34 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
35 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
36 if (!T->isDependentType())
39 // This may be a member of a class template or class template partial
40 // specialization. If it's part of the current semantic context, then it's
41 // an injected-class-name;
42 for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
43 if (CurContext->Equals(Record))
47 } else if (isa<InjectedClassNameType>(Ty))
48 return cast<InjectedClassNameType>(Ty)->getDecl();
53 /// \brief Compute the DeclContext that is associated with the given type.
55 /// \param T the type for which we are attempting to find a DeclContext.
57 /// \returns the declaration context represented by the type T,
58 /// or NULL if the declaration context cannot be computed (e.g., because it is
59 /// dependent and not the current instantiation).
60 DeclContext *Sema::computeDeclContext(QualType T) {
61 if (!T->isDependentType())
62 if (const TagType *Tag = T->getAs<TagType>())
63 return Tag->getDecl();
65 return ::getCurrentInstantiationOf(T, CurContext);
68 /// \brief Compute the DeclContext that is associated with the given
71 /// \param SS the C++ scope specifier as it appears in the source
73 /// \param EnteringContext when true, we will be entering the context of
74 /// this scope specifier, so we can retrieve the declaration context of a
75 /// class template or class template partial specialization even if it is
76 /// not the current instantiation.
78 /// \returns the declaration context represented by the scope specifier @p SS,
79 /// or NULL if the declaration context cannot be computed (e.g., because it is
80 /// dependent and not the current instantiation).
81 DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
82 bool EnteringContext) {
83 if (!SS.isSet() || SS.isInvalid())
86 NestedNameSpecifier *NNS
87 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
88 if (NNS->isDependent()) {
89 // If this nested-name-specifier refers to the current
90 // instantiation, return its DeclContext.
91 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
94 if (EnteringContext) {
95 const Type *NNSType = NNS->getAsType();
100 // Look through type alias templates, per C++0x [temp.dep.type]p1.
101 NNSType = Context.getCanonicalType(NNSType);
102 if (const TemplateSpecializationType *SpecType
103 = NNSType->getAs<TemplateSpecializationType>()) {
104 // We are entering the context of the nested name specifier, so try to
105 // match the nested name specifier to either a primary class template
106 // or a class template partial specialization.
107 if (ClassTemplateDecl *ClassTemplate
108 = dyn_cast_or_null<ClassTemplateDecl>(
109 SpecType->getTemplateName().getAsTemplateDecl())) {
111 = Context.getCanonicalType(QualType(SpecType, 0));
113 // If the type of the nested name specifier is the same as the
114 // injected class name of the named class template, we're entering
115 // into that class template definition.
117 = ClassTemplate->getInjectedClassNameSpecialization();
118 if (Context.hasSameType(Injected, ContextType))
119 return ClassTemplate->getTemplatedDecl();
121 // If the type of the nested name specifier is the same as the
122 // type of one of the class template's class template partial
123 // specializations, we're entering into the definition of that
124 // class template partial specialization.
125 if (ClassTemplatePartialSpecializationDecl *PartialSpec
126 = ClassTemplate->findPartialSpecialization(ContextType))
129 } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
130 // The nested name specifier refers to a member of a class template.
131 return RecordT->getDecl();
138 switch (NNS->getKind()) {
139 case NestedNameSpecifier::Identifier:
140 llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
142 case NestedNameSpecifier::Namespace:
143 return NNS->getAsNamespace();
145 case NestedNameSpecifier::NamespaceAlias:
146 return NNS->getAsNamespaceAlias()->getNamespace();
148 case NestedNameSpecifier::TypeSpec:
149 case NestedNameSpecifier::TypeSpecWithTemplate: {
150 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
151 assert(Tag && "Non-tag type in nested-name-specifier");
152 return Tag->getDecl();
155 case NestedNameSpecifier::Global:
156 return Context.getTranslationUnitDecl();
159 // Required to silence a GCC warning.
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(getLangOptions().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 if (TagDecl *tag = dyn_cast<TagDecl>(DC)) {
214 // If this is a dependent type, then we consider it complete.
215 if (tag->isDependentContext())
218 // If we're currently defining this type, then lookup into the
219 // type is okay: don't complain that it isn't complete yet.
220 QualType type = Context.getTypeDeclType(tag);
221 const TagType *tagType = type->getAs<TagType>();
222 if (tagType && tagType->isBeingDefined())
225 SourceLocation loc = SS.getLastQualifierNameLoc();
226 if (loc.isInvalid()) loc = SS.getRange().getBegin();
228 // The type must be complete.
229 if (RequireCompleteType(loc, type,
230 PDiag(diag::err_incomplete_nested_name_spec)
232 SS.SetInvalid(SS.getRange());
236 // Fixed enum types are complete, but they aren't valid as scopes
237 // until we see a definition, so awkwardly pull out this special
239 if (const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType)) {
240 if (!enumType->getDecl()->isCompleteDefinition()) {
241 Diag(loc, diag::err_incomplete_nested_name_spec)
242 << type << SS.getRange();
243 SS.SetInvalid(SS.getRange());
252 bool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
254 SS.MakeGlobal(Context, CCLoc);
258 /// \brief Determines whether the given declaration is an valid acceptable
259 /// result for name lookup of a nested-name-specifier.
260 bool Sema::isAcceptableNestedNameSpecifier(NamedDecl *SD) {
264 // Namespace and namespace aliases are fine.
265 if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
268 if (!isa<TypeDecl>(SD))
271 // Determine whether we have a class (or, in C++0x, an enum) or
272 // a typedef thereof. If so, build the nested-name-specifier.
273 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
274 if (T->isDependentType())
276 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
277 if (TD->getUnderlyingType()->isRecordType() ||
278 (Context.getLangOptions().CPlusPlus0x &&
279 TD->getUnderlyingType()->isEnumeralType()))
281 } else if (isa<RecordDecl>(SD) ||
282 (Context.getLangOptions().CPlusPlus0x && isa<EnumDecl>(SD)))
288 /// \brief If the given nested-name-specifier begins with a bare identifier
289 /// (e.g., Base::), perform name lookup for that identifier as a
290 /// nested-name-specifier within the given scope, and return the result of that
292 NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
296 while (NNS->getPrefix())
297 NNS = NNS->getPrefix();
299 if (NNS->getKind() != NestedNameSpecifier::Identifier)
302 LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
303 LookupNestedNameSpecifierName);
304 LookupName(Found, S);
305 assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
307 if (!Found.isSingleResult())
310 NamedDecl *Result = Found.getFoundDecl();
311 if (isAcceptableNestedNameSpecifier(Result))
317 bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
318 SourceLocation IdLoc,
320 ParsedType ObjectTypePtr) {
321 QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
322 LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
324 // Determine where to perform name lookup
325 DeclContext *LookupCtx = 0;
326 bool isDependent = false;
327 if (!ObjectType.isNull()) {
328 // This nested-name-specifier occurs in a member access expression, e.g.,
329 // x->B::f, and we are looking into the type of the object.
330 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
331 LookupCtx = computeDeclContext(ObjectType);
332 isDependent = ObjectType->isDependentType();
333 } else if (SS.isSet()) {
334 // This nested-name-specifier occurs after another nested-name-specifier,
335 // so long into the context associated with the prior nested-name-specifier.
336 LookupCtx = computeDeclContext(SS, false);
337 isDependent = isDependentScopeSpecifier(SS);
338 Found.setContextRange(SS.getRange());
342 // Perform "qualified" name lookup into the declaration context we
343 // computed, which is either the type of the base of a member access
344 // expression or the declaration context associated with a prior
345 // nested-name-specifier.
347 // The declaration context must be complete.
348 if (!LookupCtx->isDependentContext() &&
349 RequireCompleteDeclContext(SS, LookupCtx))
352 LookupQualifiedName(Found, LookupCtx);
353 } else if (isDependent) {
356 LookupName(Found, S);
358 Found.suppressDiagnostics();
360 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
361 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
366 /// \brief Build a new nested-name-specifier for "identifier::", as described
367 /// by ActOnCXXNestedNameSpecifier.
369 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
370 /// that it contains an extra parameter \p ScopeLookupResult, which provides
371 /// the result of name lookup within the scope of the nested-name-specifier
372 /// that was computed at template definition time.
374 /// If ErrorRecoveryLookup is true, then this call is used to improve error
375 /// recovery. This means that it should not emit diagnostics, it should
376 /// just return true on failure. It also means it should only return a valid
377 /// scope if it *knows* that the result is correct. It should not return in a
378 /// dependent context, for example. Nor will it extend \p SS with the scope
380 bool Sema::BuildCXXNestedNameSpecifier(Scope *S,
381 IdentifierInfo &Identifier,
382 SourceLocation IdentifierLoc,
383 SourceLocation CCLoc,
385 bool EnteringContext,
387 NamedDecl *ScopeLookupResult,
388 bool ErrorRecoveryLookup) {
389 LookupResult Found(*this, &Identifier, IdentifierLoc,
390 LookupNestedNameSpecifierName);
392 // Determine where to perform name lookup
393 DeclContext *LookupCtx = 0;
394 bool isDependent = false;
395 if (!ObjectType.isNull()) {
396 // This nested-name-specifier occurs in a member access expression, e.g.,
397 // x->B::f, and we are looking into the type of the object.
398 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
399 LookupCtx = computeDeclContext(ObjectType);
400 isDependent = ObjectType->isDependentType();
401 } else if (SS.isSet()) {
402 // This nested-name-specifier occurs after another nested-name-specifier,
403 // so look into the context associated with the prior nested-name-specifier.
404 LookupCtx = computeDeclContext(SS, EnteringContext);
405 isDependent = isDependentScopeSpecifier(SS);
406 Found.setContextRange(SS.getRange());
410 bool ObjectTypeSearchedInScope = false;
412 // Perform "qualified" name lookup into the declaration context we
413 // computed, which is either the type of the base of a member access
414 // expression or the declaration context associated with a prior
415 // nested-name-specifier.
417 // The declaration context must be complete.
418 if (!LookupCtx->isDependentContext() &&
419 RequireCompleteDeclContext(SS, LookupCtx))
422 LookupQualifiedName(Found, LookupCtx);
424 if (!ObjectType.isNull() && Found.empty()) {
425 // C++ [basic.lookup.classref]p4:
426 // If the id-expression in a class member access is a qualified-id of
429 // class-name-or-namespace-name::...
431 // the class-name-or-namespace-name following the . or -> operator is
432 // looked up both in the context of the entire postfix-expression and in
433 // the scope of the class of the object expression. If the name is found
434 // only in the scope of the class of the object expression, the name
435 // shall refer to a class-name. If the name is found only in the
436 // context of the entire postfix-expression, the name shall refer to a
437 // class-name or namespace-name. [...]
439 // Qualified name lookup into a class will not find a namespace-name,
440 // so we do not need to diagnose that case specifically. However,
441 // this qualified name lookup may find nothing. In that case, perform
442 // unqualified name lookup in the given scope (if available) or
443 // reconstruct the result from when name lookup was performed at template
446 LookupName(Found, S);
447 else if (ScopeLookupResult)
448 Found.addDecl(ScopeLookupResult);
450 ObjectTypeSearchedInScope = true;
452 } else if (!isDependent) {
453 // Perform unqualified name lookup in the current scope.
454 LookupName(Found, S);
457 // If we performed lookup into a dependent context and did not find anything,
458 // that's fine: just build a dependent nested-name-specifier.
459 if (Found.empty() && isDependent &&
460 !(LookupCtx && LookupCtx->isRecord() &&
461 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
462 !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {
463 // Don't speculate if we're just trying to improve error recovery.
464 if (ErrorRecoveryLookup)
467 // We were not able to compute the declaration context for a dependent
468 // base object type or prior nested-name-specifier, so this
469 // nested-name-specifier refers to an unknown specialization. Just build
470 // a dependent nested-name-specifier.
471 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
475 // FIXME: Deal with ambiguities cleanly.
477 if (Found.empty() && !ErrorRecoveryLookup) {
478 // We haven't found anything, and we're not recovering from a
479 // different kind of error, so look for typos.
480 DeclarationName Name = Found.getLookupName();
481 TypoCorrection Corrected;
483 if ((Corrected = CorrectTypo(Found.getLookupNameInfo(),
484 Found.getLookupKind(), S, &SS, LookupCtx,
485 EnteringContext, CTC_NoKeywords)) &&
486 isAcceptableNestedNameSpecifier(Corrected.getCorrectionDecl())) {
487 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
488 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
490 Diag(Found.getNameLoc(), diag::err_no_member_suggest)
491 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
492 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
494 Diag(Found.getNameLoc(), diag::err_undeclared_var_use_suggest)
495 << Name << CorrectedQuotedStr
496 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
498 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
499 Diag(ND->getLocation(), diag::note_previous_decl) << CorrectedQuotedStr;
502 Found.setLookupName(Corrected.getCorrection());
504 Found.setLookupName(&Identifier);
508 NamedDecl *SD = Found.getAsSingle<NamedDecl>();
509 if (isAcceptableNestedNameSpecifier(SD)) {
510 if (!ObjectType.isNull() && !ObjectTypeSearchedInScope) {
511 // C++ [basic.lookup.classref]p4:
512 // [...] If the name is found in both contexts, the
513 // class-name-or-namespace-name shall refer to the same entity.
515 // We already found the name in the scope of the object. Now, look
516 // into the current scope (the scope of the postfix-expression) to
517 // see if we can find the same name there. As above, if there is no
518 // scope, reconstruct the result from the template instantiation itself.
519 NamedDecl *OuterDecl;
521 LookupResult FoundOuter(*this, &Identifier, IdentifierLoc,
522 LookupNestedNameSpecifierName);
523 LookupName(FoundOuter, S);
524 OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
526 OuterDecl = ScopeLookupResult;
528 if (isAcceptableNestedNameSpecifier(OuterDecl) &&
529 OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
530 (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
531 !Context.hasSameType(
532 Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
533 Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
534 if (ErrorRecoveryLookup)
538 diag::err_nested_name_member_ref_lookup_ambiguous)
540 Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
542 Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
544 // Fall through so that we'll pick the name we found in the object
545 // type, since that's probably what the user wanted anyway.
549 // If we're just performing this lookup for error-recovery purposes,
550 // don't extend the nested-name-specifier. Just return now.
551 if (ErrorRecoveryLookup)
554 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
555 SS.Extend(Context, Namespace, IdentifierLoc, CCLoc);
559 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
560 SS.Extend(Context, Alias, IdentifierLoc, CCLoc);
564 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
566 if (isa<InjectedClassNameType>(T)) {
567 InjectedClassNameTypeLoc InjectedTL
568 = TLB.push<InjectedClassNameTypeLoc>(T);
569 InjectedTL.setNameLoc(IdentifierLoc);
570 } else if (isa<RecordType>(T)) {
571 RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
572 RecordTL.setNameLoc(IdentifierLoc);
573 } else if (isa<TypedefType>(T)) {
574 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
575 TypedefTL.setNameLoc(IdentifierLoc);
576 } else if (isa<EnumType>(T)) {
577 EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
578 EnumTL.setNameLoc(IdentifierLoc);
579 } else if (isa<TemplateTypeParmType>(T)) {
580 TemplateTypeParmTypeLoc TemplateTypeTL
581 = TLB.push<TemplateTypeParmTypeLoc>(T);
582 TemplateTypeTL.setNameLoc(IdentifierLoc);
583 } else if (isa<UnresolvedUsingType>(T)) {
584 UnresolvedUsingTypeLoc UnresolvedTL
585 = TLB.push<UnresolvedUsingTypeLoc>(T);
586 UnresolvedTL.setNameLoc(IdentifierLoc);
587 } else if (isa<SubstTemplateTypeParmType>(T)) {
588 SubstTemplateTypeParmTypeLoc TL
589 = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
590 TL.setNameLoc(IdentifierLoc);
591 } else if (isa<SubstTemplateTypeParmPackType>(T)) {
592 SubstTemplateTypeParmPackTypeLoc TL
593 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
594 TL.setNameLoc(IdentifierLoc);
596 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
599 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
604 // Otherwise, we have an error case. If we don't want diagnostics, just
605 // return an error now.
606 if (ErrorRecoveryLookup)
609 // If we didn't find anything during our lookup, try again with
610 // ordinary name lookup, which can help us produce better error
613 Found.clear(LookupOrdinaryName);
614 LookupName(Found, S);
617 // In Microsoft mode, if we are within a templated function and we can't
618 // resolve Identifier, then extend the SS with Identifier. This will have
619 // the effect of resolving Identifier during template instantiation.
620 // The goal is to be able to resolve a function call whose
621 // nested-name-specifier is located inside a dependent base class.
626 // static void foo2() { }
628 // template <class T> class A { public: typedef C D; };
630 // template <class T> class B : public A<T> {
632 // void foo() { D::foo2(); }
634 if (getLangOptions().MicrosoftExt) {
635 DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
636 if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
637 SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
644 DiagID = diag::err_expected_class_or_namespace;
645 else if (SS.isSet()) {
646 Diag(IdentifierLoc, diag::err_no_member)
647 << &Identifier << LookupCtx << SS.getRange();
650 DiagID = diag::err_undeclared_var_use;
653 Diag(IdentifierLoc, DiagID) << &Identifier << SS.getRange();
655 Diag(IdentifierLoc, DiagID) << &Identifier;
660 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
661 IdentifierInfo &Identifier,
662 SourceLocation IdentifierLoc,
663 SourceLocation CCLoc,
664 ParsedType ObjectType,
665 bool EnteringContext,
670 return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc,
671 GetTypeFromParser(ObjectType),
673 /*ScopeLookupResult=*/0, false);
676 /// IsInvalidUnlessNestedName - This method is used for error recovery
677 /// purposes to determine whether the specified identifier is only valid as
678 /// a nested name specifier, for example a namespace name. It is
679 /// conservatively correct to always return false from this method.
681 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
682 bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
683 IdentifierInfo &Identifier,
684 SourceLocation IdentifierLoc,
685 SourceLocation ColonLoc,
686 ParsedType ObjectType,
687 bool EnteringContext) {
691 return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc,
692 GetTypeFromParser(ObjectType),
694 /*ScopeLookupResult=*/0, true);
697 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
698 SourceLocation TemplateLoc,
701 SourceLocation TemplateNameLoc,
702 SourceLocation LAngleLoc,
703 ASTTemplateArgsPtr TemplateArgsIn,
704 SourceLocation RAngleLoc,
705 SourceLocation CCLoc,
706 bool EnteringContext) {
710 // Translate the parser's template argument list in our AST format.
711 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
712 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
714 if (DependentTemplateName *DTN = Template.get().getAsDependentTemplateName()){
715 // Handle a dependent template specialization for which we cannot resolve
716 // the template name.
717 assert(DTN->getQualifier()
718 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
719 QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
721 DTN->getIdentifier(),
724 // Create source-location information for this type.
725 TypeLocBuilder Builder;
726 DependentTemplateSpecializationTypeLoc SpecTL
727 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
728 SpecTL.setLAngleLoc(LAngleLoc);
729 SpecTL.setRAngleLoc(RAngleLoc);
730 SpecTL.setKeywordLoc(SourceLocation());
731 SpecTL.setNameLoc(TemplateNameLoc);
732 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
733 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
734 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
736 SS.Extend(Context, TemplateLoc, Builder.getTypeLocInContext(Context, T),
742 if (Template.get().getAsOverloadedTemplate() ||
743 isa<FunctionTemplateDecl>(Template.get().getAsTemplateDecl())) {
744 SourceRange R(TemplateNameLoc, RAngleLoc);
745 if (SS.getRange().isValid())
746 R.setBegin(SS.getRange().getBegin());
748 Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
749 << Template.get() << R;
750 NoteAllFoundTemplates(Template.get());
754 // We were able to resolve the template name to an actual template.
755 // Build an appropriate nested-name-specifier.
756 QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc,
761 // Alias template specializations can produce types which are not valid
762 // nested name specifiers.
763 if (!T->isDependentType() && !T->getAs<TagType>()) {
764 Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
765 NoteAllFoundTemplates(Template.get());
769 // Provide source-location information for the template specialization
771 TypeLocBuilder Builder;
772 TemplateSpecializationTypeLoc SpecTL
773 = Builder.push<TemplateSpecializationTypeLoc>(T);
775 SpecTL.setLAngleLoc(LAngleLoc);
776 SpecTL.setRAngleLoc(RAngleLoc);
777 SpecTL.setTemplateNameLoc(TemplateNameLoc);
778 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
779 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
782 SS.Extend(Context, TemplateLoc, Builder.getTypeLocInContext(Context, T),
788 /// \brief A structure that stores a nested-name-specifier annotation,
789 /// including both the nested-name-specifier
790 struct NestedNameSpecifierAnnotation {
791 NestedNameSpecifier *NNS;
795 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
796 if (SS.isEmpty() || SS.isInvalid())
799 void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) +
801 llvm::alignOf<NestedNameSpecifierAnnotation>());
802 NestedNameSpecifierAnnotation *Annotation
803 = new (Mem) NestedNameSpecifierAnnotation;
804 Annotation->NNS = SS.getScopeRep();
805 memcpy(Annotation + 1, SS.location_data(), SS.location_size());
809 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
810 SourceRange AnnotationRange,
812 if (!AnnotationPtr) {
813 SS.SetInvalid(AnnotationRange);
817 NestedNameSpecifierAnnotation *Annotation
818 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
819 SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
822 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
823 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
825 NestedNameSpecifier *Qualifier =
826 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
828 // There are only two places a well-formed program may qualify a
829 // declarator: first, when defining a namespace or class member
830 // out-of-line, and second, when naming an explicitly-qualified
831 // friend function. The latter case is governed by
832 // C++03 [basic.lookup.unqual]p10:
833 // In a friend declaration naming a member function, a name used
834 // in the function declarator and not part of a template-argument
835 // in a template-id is first looked up in the scope of the member
836 // function's class. If it is not found, or if the name is part of
837 // a template-argument in a template-id, the look up is as
838 // described for unqualified names in the definition of the class
839 // granting friendship.
840 // i.e. we don't push a scope unless it's a class member.
842 switch (Qualifier->getKind()) {
843 case NestedNameSpecifier::Global:
844 case NestedNameSpecifier::Namespace:
845 case NestedNameSpecifier::NamespaceAlias:
846 // These are always namespace scopes. We never want to enter a
847 // namespace scope from anything but a file context.
848 return CurContext->getRedeclContext()->isFileContext();
850 case NestedNameSpecifier::Identifier:
851 case NestedNameSpecifier::TypeSpec:
852 case NestedNameSpecifier::TypeSpecWithTemplate:
853 // These are never namespace scopes.
857 // Silence bogus warning.
861 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
862 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
863 /// After this method is called, according to [C++ 3.4.3p3], names should be
864 /// looked up in the declarator-id's scope, until the declarator is parsed and
865 /// ActOnCXXExitDeclaratorScope is called.
866 /// The 'SS' should be a non-empty valid CXXScopeSpec.
867 bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
868 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
870 if (SS.isInvalid()) return true;
872 DeclContext *DC = computeDeclContext(SS, true);
873 if (!DC) return true;
875 // Before we enter a declarator's context, we need to make sure that
876 // it is a complete declaration context.
877 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
880 EnterDeclaratorContext(S, DC);
882 // Rebuild the nested name specifier for the new scope.
883 if (DC->isDependentContext())
884 RebuildNestedNameSpecifierInCurrentInstantiation(SS);
889 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
890 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
891 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
892 /// Used to indicate that names should revert to being looked up in the
894 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
895 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
898 assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
899 "exiting declarator scope we never really entered");
900 ExitDeclaratorContext(S);