1 //===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements C++ semantic analysis for scope specifiers.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/NestedNameSpecifier.h"
18 #include "clang/Basic/PartialDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/SemaInternal.h"
22 #include "clang/Sema/Template.h"
23 #include "llvm/ADT/STLExtras.h"
24 using namespace clang
;
26 /// Find the current instantiation that associated with the given type.
27 static CXXRecordDecl
*getCurrentInstantiationOf(QualType T
,
28 DeclContext
*CurContext
) {
32 const Type
*Ty
= T
->getCanonicalTypeInternal().getTypePtr();
33 if (const RecordType
*RecordTy
= dyn_cast
<RecordType
>(Ty
)) {
34 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
35 if (!Record
->isDependentContext() ||
36 Record
->isCurrentInstantiation(CurContext
))
40 } else if (isa
<InjectedClassNameType
>(Ty
))
41 return cast
<InjectedClassNameType
>(Ty
)->getDecl();
46 /// Compute the DeclContext that is associated with the given type.
48 /// \param T the type for which we are attempting to find a DeclContext.
50 /// \returns the declaration context represented by the type T,
51 /// or NULL if the declaration context cannot be computed (e.g., because it is
52 /// dependent and not the current instantiation).
53 DeclContext
*Sema::computeDeclContext(QualType T
) {
54 if (!T
->isDependentType())
55 if (const TagType
*Tag
= T
->getAs
<TagType
>())
56 return Tag
->getDecl();
58 return ::getCurrentInstantiationOf(T
, CurContext
);
61 /// Compute the DeclContext that is associated with the given
64 /// \param SS the C++ scope specifier as it appears in the source
66 /// \param EnteringContext when true, we will be entering the context of
67 /// this scope specifier, so we can retrieve the declaration context of a
68 /// class template or class template partial specialization even if it is
69 /// not the current instantiation.
71 /// \returns the declaration context represented by the scope specifier @p SS,
72 /// or NULL if the declaration context cannot be computed (e.g., because it is
73 /// dependent and not the current instantiation).
74 DeclContext
*Sema::computeDeclContext(const CXXScopeSpec
&SS
,
75 bool EnteringContext
) {
76 if (!SS
.isSet() || SS
.isInvalid())
79 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
80 if (NNS
->isDependent()) {
81 // If this nested-name-specifier refers to the current
82 // instantiation, return its DeclContext.
83 if (CXXRecordDecl
*Record
= getCurrentInstantiationOf(NNS
))
86 if (EnteringContext
) {
87 const Type
*NNSType
= NNS
->getAsType();
92 // Look through type alias templates, per C++0x [temp.dep.type]p1.
93 NNSType
= Context
.getCanonicalType(NNSType
);
94 if (const TemplateSpecializationType
*SpecType
95 = NNSType
->getAs
<TemplateSpecializationType
>()) {
96 // We are entering the context of the nested name specifier, so try to
97 // match the nested name specifier to either a primary class template
98 // or a class template partial specialization.
99 if (ClassTemplateDecl
*ClassTemplate
100 = dyn_cast_or_null
<ClassTemplateDecl
>(
101 SpecType
->getTemplateName().getAsTemplateDecl())) {
102 QualType ContextType
=
103 Context
.getCanonicalType(QualType(SpecType
, 0));
105 // FIXME: The fallback on the search of partial
106 // specialization using ContextType should be eventually removed since
107 // it doesn't handle the case of constrained template parameters
108 // correctly. Currently removing this fallback would change the
109 // diagnostic output for invalid code in a number of tests.
110 ClassTemplatePartialSpecializationDecl
*PartialSpec
= nullptr;
111 ArrayRef
<TemplateParameterList
*> TemplateParamLists
=
112 SS
.getTemplateParamLists();
113 if (!TemplateParamLists
.empty()) {
114 unsigned Depth
= ClassTemplate
->getTemplateParameters()->getDepth();
115 auto L
= find_if(TemplateParamLists
,
116 [Depth
](TemplateParameterList
*TPL
) {
117 return TPL
->getDepth() == Depth
;
119 if (L
!= TemplateParamLists
.end()) {
121 PartialSpec
= ClassTemplate
->findPartialSpecialization(
122 SpecType
->template_arguments(), *L
, Pos
);
125 PartialSpec
= ClassTemplate
->findPartialSpecialization(ContextType
);
129 // A declaration of the partial specialization must be visible.
130 // We can always recover here, because this only happens when we're
131 // entering the context, and that can't happen in a SFINAE context.
132 assert(!isSFINAEContext() && "partial specialization scope "
133 "specifier in SFINAE context?");
134 if (PartialSpec
->hasDefinition() &&
135 !hasReachableDefinition(PartialSpec
))
136 diagnoseMissingImport(SS
.getLastQualifierNameLoc(), PartialSpec
,
137 MissingImportKind::PartialSpecialization
,
142 // If the type of the nested name specifier is the same as the
143 // injected class name of the named class template, we're entering
144 // into that class template definition.
146 ClassTemplate
->getInjectedClassNameSpecialization();
147 if (Context
.hasSameType(Injected
, ContextType
))
148 return ClassTemplate
->getTemplatedDecl();
150 } else if (const RecordType
*RecordT
= NNSType
->getAs
<RecordType
>()) {
151 // The nested name specifier refers to a member of a class template.
152 return RecordT
->getDecl();
159 switch (NNS
->getKind()) {
160 case NestedNameSpecifier::Identifier
:
161 llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
163 case NestedNameSpecifier::Namespace
:
164 return NNS
->getAsNamespace();
166 case NestedNameSpecifier::NamespaceAlias
:
167 return NNS
->getAsNamespaceAlias()->getNamespace();
169 case NestedNameSpecifier::TypeSpec
:
170 case NestedNameSpecifier::TypeSpecWithTemplate
: {
171 const TagType
*Tag
= NNS
->getAsType()->getAs
<TagType
>();
172 assert(Tag
&& "Non-tag type in nested-name-specifier");
173 return Tag
->getDecl();
176 case NestedNameSpecifier::Global
:
177 return Context
.getTranslationUnitDecl();
179 case NestedNameSpecifier::Super
:
180 return NNS
->getAsRecordDecl();
183 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
186 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec
&SS
) {
187 if (!SS
.isSet() || SS
.isInvalid())
190 return SS
.getScopeRep()->isDependent();
193 /// If the given nested name specifier refers to the current
194 /// instantiation, return the declaration that corresponds to that
195 /// current instantiation (C++0x [temp.dep.type]p1).
197 /// \param NNS a dependent nested name specifier.
198 CXXRecordDecl
*Sema::getCurrentInstantiationOf(NestedNameSpecifier
*NNS
) {
199 assert(getLangOpts().CPlusPlus
&& "Only callable in C++");
200 assert(NNS
->isDependent() && "Only dependent nested-name-specifier allowed");
202 if (!NNS
->getAsType())
205 QualType T
= QualType(NNS
->getAsType(), 0);
206 return ::getCurrentInstantiationOf(T
, CurContext
);
209 /// Require that the context specified by SS be complete.
211 /// If SS refers to a type, this routine checks whether the type is
212 /// complete enough (or can be made complete enough) for name lookup
213 /// into the DeclContext. A type that is not yet completed can be
214 /// considered "complete enough" if it is a class/struct/union/enum
215 /// that is currently being defined. Or, if we have a type that names
216 /// a class template specialization that is not a complete type, we
217 /// will attempt to instantiate that class template.
218 bool Sema::RequireCompleteDeclContext(CXXScopeSpec
&SS
,
220 assert(DC
&& "given null context");
222 TagDecl
*tag
= dyn_cast
<TagDecl
>(DC
);
224 // If this is a dependent type, then we consider it complete.
225 // FIXME: This is wrong; we should require a (visible) definition to
226 // exist in this case too.
227 if (!tag
|| tag
->isDependentContext())
230 // Grab the tag definition, if there is one.
231 QualType type
= Context
.getTypeDeclType(tag
);
232 tag
= type
->getAsTagDecl();
234 // If we're currently defining this type, then lookup into the
235 // type is okay: don't complain that it isn't complete yet.
236 if (tag
->isBeingDefined())
239 SourceLocation loc
= SS
.getLastQualifierNameLoc();
240 if (loc
.isInvalid()) loc
= SS
.getRange().getBegin();
242 // The type must be complete.
243 if (RequireCompleteType(loc
, type
, diag::err_incomplete_nested_name_spec
,
245 SS
.SetInvalid(SS
.getRange());
249 if (auto *EnumD
= dyn_cast
<EnumDecl
>(tag
))
250 // Fixed enum types and scoped enum instantiations are complete, but they
251 // aren't valid as scopes until we see or instantiate their definition.
252 return RequireCompleteEnumDecl(EnumD
, loc
, &SS
);
257 /// Require that the EnumDecl is completed with its enumerators defined or
258 /// instantiated. SS, if provided, is the ScopeRef parsed.
260 bool Sema::RequireCompleteEnumDecl(EnumDecl
*EnumD
, SourceLocation L
,
262 if (EnumD
->isCompleteDefinition()) {
263 // If we know about the definition but it is not visible, complain.
264 NamedDecl
*SuggestedDef
= nullptr;
265 if (!hasReachableDefinition(EnumD
, &SuggestedDef
,
266 /*OnlyNeedComplete*/ false)) {
267 // If the user is going to see an error here, recover by making the
268 // definition visible.
269 bool TreatAsComplete
= !isSFINAEContext();
270 diagnoseMissingImport(L
, SuggestedDef
, MissingImportKind::Definition
,
271 /*Recover*/ TreatAsComplete
);
272 return !TreatAsComplete
;
277 // Try to instantiate the definition, if this is a specialization of an
278 // enumeration temploid.
279 if (EnumDecl
*Pattern
= EnumD
->getInstantiatedFromMemberEnum()) {
280 MemberSpecializationInfo
*MSI
= EnumD
->getMemberSpecializationInfo();
281 if (MSI
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
) {
282 if (InstantiateEnum(L
, EnumD
, Pattern
,
283 getTemplateInstantiationArgs(EnumD
),
284 TSK_ImplicitInstantiation
)) {
286 SS
->SetInvalid(SS
->getRange());
294 Diag(L
, diag::err_incomplete_nested_name_spec
)
295 << QualType(EnumD
->getTypeForDecl(), 0) << SS
->getRange();
296 SS
->SetInvalid(SS
->getRange());
298 Diag(L
, diag::err_incomplete_enum
) << QualType(EnumD
->getTypeForDecl(), 0);
299 Diag(EnumD
->getLocation(), diag::note_declared_at
);
305 bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc
,
307 SS
.MakeGlobal(Context
, CCLoc
);
311 bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc
,
312 SourceLocation ColonColonLoc
,
314 if (getCurLambda()) {
315 Diag(SuperLoc
, diag::err_super_in_lambda_unsupported
);
319 CXXRecordDecl
*RD
= nullptr;
320 for (Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
321 if (S
->isFunctionScope()) {
322 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(S
->getEntity()))
323 RD
= MD
->getParent();
326 if (S
->isClassScope()) {
327 RD
= cast
<CXXRecordDecl
>(S
->getEntity());
333 Diag(SuperLoc
, diag::err_invalid_super_scope
);
335 } else if (RD
->getNumBases() == 0) {
336 Diag(SuperLoc
, diag::err_no_base_classes
) << RD
->getName();
340 SS
.MakeSuper(Context
, RD
, SuperLoc
, ColonColonLoc
);
344 /// Determines whether the given declaration is an valid acceptable
345 /// result for name lookup of a nested-name-specifier.
346 /// \param SD Declaration checked for nested-name-specifier.
347 /// \param IsExtension If not null and the declaration is accepted as an
348 /// extension, the pointed variable is assigned true.
349 bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl
*SD
,
354 SD
= SD
->getUnderlyingDecl();
356 // Namespace and namespace aliases are fine.
357 if (isa
<NamespaceDecl
>(SD
))
360 if (!isa
<TypeDecl
>(SD
))
363 // Determine whether we have a class (or, in C++11, an enum) or
364 // a typedef thereof. If so, build the nested-name-specifier.
365 QualType T
= Context
.getTypeDeclType(cast
<TypeDecl
>(SD
));
366 if (T
->isDependentType())
368 if (const TypedefNameDecl
*TD
= dyn_cast
<TypedefNameDecl
>(SD
)) {
369 if (TD
->getUnderlyingType()->isRecordType())
371 if (TD
->getUnderlyingType()->isEnumeralType()) {
372 if (Context
.getLangOpts().CPlusPlus11
)
377 } else if (isa
<RecordDecl
>(SD
)) {
379 } else if (isa
<EnumDecl
>(SD
)) {
380 if (Context
.getLangOpts().CPlusPlus11
)
389 /// If the given nested-name-specifier begins with a bare identifier
390 /// (e.g., Base::), perform name lookup for that identifier as a
391 /// nested-name-specifier within the given scope, and return the result of that
393 NamedDecl
*Sema::FindFirstQualifierInScope(Scope
*S
, NestedNameSpecifier
*NNS
) {
397 while (NNS
->getPrefix())
398 NNS
= NNS
->getPrefix();
400 if (NNS
->getKind() != NestedNameSpecifier::Identifier
)
403 LookupResult
Found(*this, NNS
->getAsIdentifier(), SourceLocation(),
404 LookupNestedNameSpecifierName
);
405 LookupName(Found
, S
);
406 assert(!Found
.isAmbiguous() && "Cannot handle ambiguities here yet");
408 if (!Found
.isSingleResult())
411 NamedDecl
*Result
= Found
.getFoundDecl();
412 if (isAcceptableNestedNameSpecifier(Result
))
420 // Callback to only accept typo corrections that can be a valid C++ member
421 // initializer: either a non-static field member or a base class.
422 class NestedNameSpecifierValidatorCCC final
423 : public CorrectionCandidateCallback
{
425 explicit NestedNameSpecifierValidatorCCC(Sema
&SRef
)
428 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
429 return SRef
.isAcceptableNestedNameSpecifier(candidate
.getCorrectionDecl());
432 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
433 return std::make_unique
<NestedNameSpecifierValidatorCCC
>(*this);
442 /// Build a new nested-name-specifier for "identifier::", as described
443 /// by ActOnCXXNestedNameSpecifier.
445 /// \param S Scope in which the nested-name-specifier occurs.
446 /// \param IdInfo Parser information about an identifier in the
447 /// nested-name-spec.
448 /// \param EnteringContext If true, enter the context specified by the
449 /// nested-name-specifier.
450 /// \param SS Optional nested name specifier preceding the identifier.
451 /// \param ScopeLookupResult Provides the result of name lookup within the
452 /// scope of the nested-name-specifier that was computed at template
454 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
455 /// error recovery and what kind of recovery is performed.
456 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
457 /// are allowed. The bool value pointed by this parameter is set to
458 /// 'true' if the identifier is treated as if it was followed by ':',
460 /// \param OnlyNamespace If true, only considers namespaces in lookup.
462 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
463 /// that it contains an extra parameter \p ScopeLookupResult, which provides
464 /// the result of name lookup within the scope of the nested-name-specifier
465 /// that was computed at template definition time.
467 /// If ErrorRecoveryLookup is true, then this call is used to improve error
468 /// recovery. This means that it should not emit diagnostics, it should
469 /// just return true on failure. It also means it should only return a valid
470 /// scope if it *knows* that the result is correct. It should not return in a
471 /// dependent context, for example. Nor will it extend \p SS with the scope
473 bool Sema::BuildCXXNestedNameSpecifier(Scope
*S
, NestedNameSpecInfo
&IdInfo
,
474 bool EnteringContext
, CXXScopeSpec
&SS
,
475 NamedDecl
*ScopeLookupResult
,
476 bool ErrorRecoveryLookup
,
477 bool *IsCorrectedToColon
,
478 bool OnlyNamespace
) {
479 if (IdInfo
.Identifier
->isEditorPlaceholder())
481 LookupResult
Found(*this, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
482 OnlyNamespace
? LookupNamespaceName
483 : LookupNestedNameSpecifierName
);
484 QualType ObjectType
= GetTypeFromParser(IdInfo
.ObjectType
);
486 // Determine where to perform name lookup
487 DeclContext
*LookupCtx
= nullptr;
488 bool isDependent
= false;
489 if (IsCorrectedToColon
)
490 *IsCorrectedToColon
= false;
491 if (!ObjectType
.isNull()) {
492 // This nested-name-specifier occurs in a member access expression, e.g.,
493 // x->B::f, and we are looking into the type of the object.
494 assert(!SS
.isSet() && "ObjectType and scope specifier cannot coexist");
495 LookupCtx
= computeDeclContext(ObjectType
);
496 isDependent
= ObjectType
->isDependentType();
497 } else if (SS
.isSet()) {
498 // This nested-name-specifier occurs after another nested-name-specifier,
499 // so look into the context associated with the prior nested-name-specifier.
500 LookupCtx
= computeDeclContext(SS
, EnteringContext
);
501 isDependent
= isDependentScopeSpecifier(SS
);
502 Found
.setContextRange(SS
.getRange());
505 bool ObjectTypeSearchedInScope
= false;
507 // Perform "qualified" name lookup into the declaration context we
508 // computed, which is either the type of the base of a member access
509 // expression or the declaration context associated with a prior
510 // nested-name-specifier.
512 // The declaration context must be complete.
513 if (!LookupCtx
->isDependentContext() &&
514 RequireCompleteDeclContext(SS
, LookupCtx
))
517 LookupQualifiedName(Found
, LookupCtx
);
519 if (!ObjectType
.isNull() && Found
.empty()) {
520 // C++ [basic.lookup.classref]p4:
521 // If the id-expression in a class member access is a qualified-id of
524 // class-name-or-namespace-name::...
526 // the class-name-or-namespace-name following the . or -> operator is
527 // looked up both in the context of the entire postfix-expression and in
528 // the scope of the class of the object expression. If the name is found
529 // only in the scope of the class of the object expression, the name
530 // shall refer to a class-name. If the name is found only in the
531 // context of the entire postfix-expression, the name shall refer to a
532 // class-name or namespace-name. [...]
534 // Qualified name lookup into a class will not find a namespace-name,
535 // so we do not need to diagnose that case specifically. However,
536 // this qualified name lookup may find nothing. In that case, perform
537 // unqualified name lookup in the given scope (if available) or
538 // reconstruct the result from when name lookup was performed at template
541 LookupName(Found
, S
);
542 else if (ScopeLookupResult
)
543 Found
.addDecl(ScopeLookupResult
);
545 ObjectTypeSearchedInScope
= true;
547 } else if (!isDependent
) {
548 // Perform unqualified name lookup in the current scope.
549 LookupName(Found
, S
);
552 if (Found
.isAmbiguous())
555 // If we performed lookup into a dependent context and did not find anything,
556 // that's fine: just build a dependent nested-name-specifier.
557 if (Found
.empty() && isDependent
&&
558 !(LookupCtx
&& LookupCtx
->isRecord() &&
559 (!cast
<CXXRecordDecl
>(LookupCtx
)->hasDefinition() ||
560 !cast
<CXXRecordDecl
>(LookupCtx
)->hasAnyDependentBases()))) {
561 // Don't speculate if we're just trying to improve error recovery.
562 if (ErrorRecoveryLookup
)
565 // We were not able to compute the declaration context for a dependent
566 // base object type or prior nested-name-specifier, so this
567 // nested-name-specifier refers to an unknown specialization. Just build
568 // a dependent nested-name-specifier.
569 SS
.Extend(Context
, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
, IdInfo
.CCLoc
);
573 if (Found
.empty() && !ErrorRecoveryLookup
) {
574 // If identifier is not found as class-name-or-namespace-name, but is found
575 // as other entity, don't look for typos.
576 LookupResult
R(*this, Found
.getLookupNameInfo(), LookupOrdinaryName
);
578 LookupQualifiedName(R
, LookupCtx
);
579 else if (S
&& !isDependent
)
582 // Don't diagnose problems with this speculative lookup.
583 R
.suppressDiagnostics();
584 // The identifier is found in ordinary lookup. If correction to colon is
585 // allowed, suggest replacement to ':'.
586 if (IsCorrectedToColon
) {
587 *IsCorrectedToColon
= true;
588 Diag(IdInfo
.CCLoc
, diag::err_nested_name_spec_is_not_class
)
589 << IdInfo
.Identifier
<< getLangOpts().CPlusPlus
590 << FixItHint::CreateReplacement(IdInfo
.CCLoc
, ":");
591 if (NamedDecl
*ND
= R
.getAsSingle
<NamedDecl
>())
592 Diag(ND
->getLocation(), diag::note_declared_at
);
595 // Replacement '::' -> ':' is not allowed, just issue respective error.
596 Diag(R
.getNameLoc(), OnlyNamespace
597 ? unsigned(diag::err_expected_namespace_name
)
598 : unsigned(diag::err_expected_class_or_namespace
))
599 << IdInfo
.Identifier
<< getLangOpts().CPlusPlus
;
600 if (NamedDecl
*ND
= R
.getAsSingle
<NamedDecl
>())
601 Diag(ND
->getLocation(), diag::note_entity_declared_at
)
602 << IdInfo
.Identifier
;
607 if (Found
.empty() && !ErrorRecoveryLookup
&& !getLangOpts().MSVCCompat
) {
608 // We haven't found anything, and we're not recovering from a
609 // different kind of error, so look for typos.
610 DeclarationName Name
= Found
.getLookupName();
612 NestedNameSpecifierValidatorCCC
CCC(*this);
613 if (TypoCorrection Corrected
= CorrectTypo(
614 Found
.getLookupNameInfo(), Found
.getLookupKind(), S
, &SS
, CCC
,
615 CTK_ErrorRecovery
, LookupCtx
, EnteringContext
)) {
617 bool DroppedSpecifier
=
618 Corrected
.WillReplaceSpecifier() &&
619 Name
.getAsString() == Corrected
.getAsString(getLangOpts());
620 if (DroppedSpecifier
)
622 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
623 << Name
<< LookupCtx
<< DroppedSpecifier
626 diagnoseTypo(Corrected
, PDiag(diag::err_undeclared_var_use_suggest
)
629 if (Corrected
.getCorrectionSpecifier())
630 SS
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
631 SourceRange(Found
.getNameLoc()));
633 if (NamedDecl
*ND
= Corrected
.getFoundDecl())
635 Found
.setLookupName(Corrected
.getCorrection());
637 Found
.setLookupName(IdInfo
.Identifier
);
642 Found
.isSingleResult() ? Found
.getRepresentativeDecl() : nullptr;
643 bool IsExtension
= false;
644 bool AcceptSpec
= isAcceptableNestedNameSpecifier(SD
, &IsExtension
);
645 if (!AcceptSpec
&& IsExtension
) {
647 Diag(IdInfo
.IdentifierLoc
, diag::ext_nested_name_spec_is_enum
);
650 if (!ObjectType
.isNull() && !ObjectTypeSearchedInScope
&&
651 !getLangOpts().CPlusPlus11
) {
652 // C++03 [basic.lookup.classref]p4:
653 // [...] If the name is found in both contexts, the
654 // class-name-or-namespace-name shall refer to the same entity.
656 // We already found the name in the scope of the object. Now, look
657 // into the current scope (the scope of the postfix-expression) to
658 // see if we can find the same name there. As above, if there is no
659 // scope, reconstruct the result from the template instantiation itself.
661 // Note that C++11 does *not* perform this redundant lookup.
662 NamedDecl
*OuterDecl
;
664 LookupResult
FoundOuter(*this, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
665 LookupNestedNameSpecifierName
);
666 LookupName(FoundOuter
, S
);
667 OuterDecl
= FoundOuter
.getAsSingle
<NamedDecl
>();
669 OuterDecl
= ScopeLookupResult
;
671 if (isAcceptableNestedNameSpecifier(OuterDecl
) &&
672 OuterDecl
->getCanonicalDecl() != SD
->getCanonicalDecl() &&
673 (!isa
<TypeDecl
>(OuterDecl
) || !isa
<TypeDecl
>(SD
) ||
674 !Context
.hasSameType(
675 Context
.getTypeDeclType(cast
<TypeDecl
>(OuterDecl
)),
676 Context
.getTypeDeclType(cast
<TypeDecl
>(SD
))))) {
677 if (ErrorRecoveryLookup
)
680 Diag(IdInfo
.IdentifierLoc
,
681 diag::err_nested_name_member_ref_lookup_ambiguous
)
682 << IdInfo
.Identifier
;
683 Diag(SD
->getLocation(), diag::note_ambig_member_ref_object_type
)
685 Diag(OuterDecl
->getLocation(), diag::note_ambig_member_ref_scope
);
687 // Fall through so that we'll pick the name we found in the object
688 // type, since that's probably what the user wanted anyway.
692 if (auto *TD
= dyn_cast_or_null
<TypedefNameDecl
>(SD
))
693 MarkAnyDeclReferenced(TD
->getLocation(), TD
, /*OdrUse=*/false);
695 // If we're just performing this lookup for error-recovery purposes,
696 // don't extend the nested-name-specifier. Just return now.
697 if (ErrorRecoveryLookup
)
700 // The use of a nested name specifier may trigger deprecation warnings.
701 DiagnoseUseOfDecl(SD
, IdInfo
.CCLoc
);
703 if (NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(SD
)) {
704 SS
.Extend(Context
, Namespace
, IdInfo
.IdentifierLoc
, IdInfo
.CCLoc
);
708 if (NamespaceAliasDecl
*Alias
= dyn_cast
<NamespaceAliasDecl
>(SD
)) {
709 SS
.Extend(Context
, Alias
, IdInfo
.IdentifierLoc
, IdInfo
.CCLoc
);
714 Context
.getTypeDeclType(cast
<TypeDecl
>(SD
->getUnderlyingDecl()));
716 if (T
->isEnumeralType())
717 Diag(IdInfo
.IdentifierLoc
, diag::warn_cxx98_compat_enum_nested_name_spec
);
720 if (const auto *USD
= dyn_cast
<UsingShadowDecl
>(SD
)) {
721 T
= Context
.getUsingType(USD
, T
);
722 TLB
.pushTypeSpec(T
).setNameLoc(IdInfo
.IdentifierLoc
);
723 } else if (isa
<InjectedClassNameType
>(T
)) {
724 InjectedClassNameTypeLoc InjectedTL
725 = TLB
.push
<InjectedClassNameTypeLoc
>(T
);
726 InjectedTL
.setNameLoc(IdInfo
.IdentifierLoc
);
727 } else if (isa
<RecordType
>(T
)) {
728 RecordTypeLoc RecordTL
= TLB
.push
<RecordTypeLoc
>(T
);
729 RecordTL
.setNameLoc(IdInfo
.IdentifierLoc
);
730 } else if (isa
<TypedefType
>(T
)) {
731 TypedefTypeLoc TypedefTL
= TLB
.push
<TypedefTypeLoc
>(T
);
732 TypedefTL
.setNameLoc(IdInfo
.IdentifierLoc
);
733 } else if (isa
<EnumType
>(T
)) {
734 EnumTypeLoc EnumTL
= TLB
.push
<EnumTypeLoc
>(T
);
735 EnumTL
.setNameLoc(IdInfo
.IdentifierLoc
);
736 } else if (isa
<TemplateTypeParmType
>(T
)) {
737 TemplateTypeParmTypeLoc TemplateTypeTL
738 = TLB
.push
<TemplateTypeParmTypeLoc
>(T
);
739 TemplateTypeTL
.setNameLoc(IdInfo
.IdentifierLoc
);
740 } else if (isa
<UnresolvedUsingType
>(T
)) {
741 UnresolvedUsingTypeLoc UnresolvedTL
742 = TLB
.push
<UnresolvedUsingTypeLoc
>(T
);
743 UnresolvedTL
.setNameLoc(IdInfo
.IdentifierLoc
);
744 } else if (isa
<SubstTemplateTypeParmType
>(T
)) {
745 SubstTemplateTypeParmTypeLoc TL
746 = TLB
.push
<SubstTemplateTypeParmTypeLoc
>(T
);
747 TL
.setNameLoc(IdInfo
.IdentifierLoc
);
748 } else if (isa
<SubstTemplateTypeParmPackType
>(T
)) {
749 SubstTemplateTypeParmPackTypeLoc TL
750 = TLB
.push
<SubstTemplateTypeParmPackTypeLoc
>(T
);
751 TL
.setNameLoc(IdInfo
.IdentifierLoc
);
753 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
756 SS
.Extend(Context
, SourceLocation(), TLB
.getTypeLocInContext(Context
, T
),
761 // Otherwise, we have an error case. If we don't want diagnostics, just
762 // return an error now.
763 if (ErrorRecoveryLookup
)
766 // If we didn't find anything during our lookup, try again with
767 // ordinary name lookup, which can help us produce better error
770 Found
.clear(LookupOrdinaryName
);
771 LookupName(Found
, S
);
774 // In Microsoft mode, if we are within a templated function and we can't
775 // resolve Identifier, then extend the SS with Identifier. This will have
776 // the effect of resolving Identifier during template instantiation.
777 // The goal is to be able to resolve a function call whose
778 // nested-name-specifier is located inside a dependent base class.
783 // static void foo2() { }
785 // template <class T> class A { public: typedef C D; };
787 // template <class T> class B : public A<T> {
789 // void foo() { D::foo2(); }
791 if (getLangOpts().MSVCCompat
) {
792 DeclContext
*DC
= LookupCtx
? LookupCtx
: CurContext
;
793 if (DC
->isDependentContext() && DC
->isFunctionOrMethod()) {
794 CXXRecordDecl
*ContainingClass
= dyn_cast
<CXXRecordDecl
>(DC
->getParent());
795 if (ContainingClass
&& ContainingClass
->hasAnyDependentBases()) {
796 Diag(IdInfo
.IdentifierLoc
,
797 diag::ext_undeclared_unqual_id_with_dependent_base
)
798 << IdInfo
.Identifier
<< ContainingClass
;
799 SS
.Extend(Context
, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
806 if (!Found
.empty()) {
807 if (TypeDecl
*TD
= Found
.getAsSingle
<TypeDecl
>()) {
808 Diag(IdInfo
.IdentifierLoc
, diag::err_expected_class_or_namespace
)
809 << Context
.getTypeDeclType(TD
) << getLangOpts().CPlusPlus
;
810 } else if (Found
.getAsSingle
<TemplateDecl
>()) {
811 ParsedType SuggestedType
;
812 DiagnoseUnknownTypeName(IdInfo
.Identifier
, IdInfo
.IdentifierLoc
, S
, &SS
,
815 Diag(IdInfo
.IdentifierLoc
, diag::err_expected_class_or_namespace
)
816 << IdInfo
.Identifier
<< getLangOpts().CPlusPlus
;
817 if (NamedDecl
*ND
= Found
.getAsSingle
<NamedDecl
>())
818 Diag(ND
->getLocation(), diag::note_entity_declared_at
)
819 << IdInfo
.Identifier
;
821 } else if (SS
.isSet())
822 Diag(IdInfo
.IdentifierLoc
, diag::err_no_member
) << IdInfo
.Identifier
823 << LookupCtx
<< SS
.getRange();
825 Diag(IdInfo
.IdentifierLoc
, diag::err_undeclared_var_use
)
826 << IdInfo
.Identifier
;
831 bool Sema::ActOnCXXNestedNameSpecifier(Scope
*S
, NestedNameSpecInfo
&IdInfo
,
832 bool EnteringContext
, CXXScopeSpec
&SS
,
833 bool *IsCorrectedToColon
,
834 bool OnlyNamespace
) {
838 return BuildCXXNestedNameSpecifier(S
, IdInfo
, EnteringContext
, SS
,
839 /*ScopeLookupResult=*/nullptr, false,
840 IsCorrectedToColon
, OnlyNamespace
);
843 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec
&SS
,
845 SourceLocation ColonColonLoc
) {
846 if (SS
.isInvalid() || DS
.getTypeSpecType() == DeclSpec::TST_error
)
849 assert(DS
.getTypeSpecType() == DeclSpec::TST_decltype
);
851 QualType T
= BuildDecltypeType(DS
.getRepAsExpr());
855 if (!T
->isDependentType() && !T
->getAs
<TagType
>()) {
856 Diag(DS
.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace
)
857 << T
<< getLangOpts().CPlusPlus
;
862 DecltypeTypeLoc DecltypeTL
= TLB
.push
<DecltypeTypeLoc
>(T
);
863 DecltypeTL
.setDecltypeLoc(DS
.getTypeSpecTypeLoc());
864 DecltypeTL
.setRParenLoc(DS
.getTypeofParensRange().getEnd());
865 SS
.Extend(Context
, SourceLocation(), TLB
.getTypeLocInContext(Context
, T
),
870 /// IsInvalidUnlessNestedName - This method is used for error recovery
871 /// purposes to determine whether the specified identifier is only valid as
872 /// a nested name specifier, for example a namespace name. It is
873 /// conservatively correct to always return false from this method.
875 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
876 bool Sema::IsInvalidUnlessNestedName(Scope
*S
, CXXScopeSpec
&SS
,
877 NestedNameSpecInfo
&IdInfo
,
878 bool EnteringContext
) {
882 return !BuildCXXNestedNameSpecifier(S
, IdInfo
, EnteringContext
, SS
,
883 /*ScopeLookupResult=*/nullptr, true);
886 bool Sema::ActOnCXXNestedNameSpecifier(Scope
*S
,
888 SourceLocation TemplateKWLoc
,
889 TemplateTy OpaqueTemplate
,
890 SourceLocation TemplateNameLoc
,
891 SourceLocation LAngleLoc
,
892 ASTTemplateArgsPtr TemplateArgsIn
,
893 SourceLocation RAngleLoc
,
894 SourceLocation CCLoc
,
895 bool EnteringContext
) {
899 TemplateName Template
= OpaqueTemplate
.get();
901 // Translate the parser's template argument list in our AST format.
902 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
903 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
905 DependentTemplateName
*DTN
= Template
.getAsDependentTemplateName();
906 if (DTN
&& DTN
->isIdentifier()) {
907 // Handle a dependent template specialization for which we cannot resolve
908 // the template name.
909 assert(DTN
->getQualifier() == SS
.getScopeRep());
910 QualType T
= Context
.getDependentTemplateSpecializationType(
911 ElaboratedTypeKeyword::None
, DTN
->getQualifier(), DTN
->getIdentifier(),
912 TemplateArgs
.arguments());
914 // Create source-location information for this type.
915 TypeLocBuilder Builder
;
916 DependentTemplateSpecializationTypeLoc SpecTL
917 = Builder
.push
<DependentTemplateSpecializationTypeLoc
>(T
);
918 SpecTL
.setElaboratedKeywordLoc(SourceLocation());
919 SpecTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
920 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
921 SpecTL
.setTemplateNameLoc(TemplateNameLoc
);
922 SpecTL
.setLAngleLoc(LAngleLoc
);
923 SpecTL
.setRAngleLoc(RAngleLoc
);
924 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
925 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
927 SS
.Extend(Context
, TemplateKWLoc
, Builder
.getTypeLocInContext(Context
, T
),
932 // If we assumed an undeclared identifier was a template name, try to
933 // typo-correct it now.
934 if (Template
.getAsAssumedTemplateName() &&
935 resolveAssumedTemplateNameAsType(S
, Template
, TemplateNameLoc
))
938 TemplateDecl
*TD
= Template
.getAsTemplateDecl();
939 if (Template
.getAsOverloadedTemplate() || DTN
||
940 isa
<FunctionTemplateDecl
>(TD
) || isa
<VarTemplateDecl
>(TD
)) {
941 SourceRange
R(TemplateNameLoc
, RAngleLoc
);
942 if (SS
.getRange().isValid())
943 R
.setBegin(SS
.getRange().getBegin());
945 Diag(CCLoc
, diag::err_non_type_template_in_nested_name_specifier
)
946 << (TD
&& isa
<VarTemplateDecl
>(TD
)) << Template
<< R
;
947 NoteAllFoundTemplates(Template
);
951 // We were able to resolve the template name to an actual template.
952 // Build an appropriate nested-name-specifier.
953 QualType T
= CheckTemplateIdType(Template
, TemplateNameLoc
, TemplateArgs
);
957 // Alias template specializations can produce types which are not valid
958 // nested name specifiers.
959 if (!T
->isDependentType() && !T
->getAs
<TagType
>()) {
960 Diag(TemplateNameLoc
, diag::err_nested_name_spec_non_tag
) << T
;
961 NoteAllFoundTemplates(Template
);
965 // Provide source-location information for the template specialization type.
966 TypeLocBuilder Builder
;
967 TemplateSpecializationTypeLoc SpecTL
968 = Builder
.push
<TemplateSpecializationTypeLoc
>(T
);
969 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
970 SpecTL
.setTemplateNameLoc(TemplateNameLoc
);
971 SpecTL
.setLAngleLoc(LAngleLoc
);
972 SpecTL
.setRAngleLoc(RAngleLoc
);
973 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
974 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
977 SS
.Extend(Context
, TemplateKWLoc
, Builder
.getTypeLocInContext(Context
, T
),
983 /// A structure that stores a nested-name-specifier annotation,
984 /// including both the nested-name-specifier
985 struct NestedNameSpecifierAnnotation
{
986 NestedNameSpecifier
*NNS
;
990 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec
&SS
) {
991 if (SS
.isEmpty() || SS
.isInvalid())
994 void *Mem
= Context
.Allocate(
995 (sizeof(NestedNameSpecifierAnnotation
) + SS
.location_size()),
996 alignof(NestedNameSpecifierAnnotation
));
997 NestedNameSpecifierAnnotation
*Annotation
998 = new (Mem
) NestedNameSpecifierAnnotation
;
999 Annotation
->NNS
= SS
.getScopeRep();
1000 memcpy(Annotation
+ 1, SS
.location_data(), SS
.location_size());
1004 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr
,
1005 SourceRange AnnotationRange
,
1007 if (!AnnotationPtr
) {
1008 SS
.SetInvalid(AnnotationRange
);
1012 NestedNameSpecifierAnnotation
*Annotation
1013 = static_cast<NestedNameSpecifierAnnotation
*>(AnnotationPtr
);
1014 SS
.Adopt(NestedNameSpecifierLoc(Annotation
->NNS
, Annotation
+ 1));
1017 bool Sema::ShouldEnterDeclaratorScope(Scope
*S
, const CXXScopeSpec
&SS
) {
1018 assert(SS
.isSet() && "Parser passed invalid CXXScopeSpec.");
1020 // Don't enter a declarator context when the current context is an Objective-C
1022 if (isa
<ObjCContainerDecl
>(CurContext
) || isa
<ObjCMethodDecl
>(CurContext
))
1025 NestedNameSpecifier
*Qualifier
= SS
.getScopeRep();
1027 // There are only two places a well-formed program may qualify a
1028 // declarator: first, when defining a namespace or class member
1029 // out-of-line, and second, when naming an explicitly-qualified
1030 // friend function. The latter case is governed by
1031 // C++03 [basic.lookup.unqual]p10:
1032 // In a friend declaration naming a member function, a name used
1033 // in the function declarator and not part of a template-argument
1034 // in a template-id is first looked up in the scope of the member
1035 // function's class. If it is not found, or if the name is part of
1036 // a template-argument in a template-id, the look up is as
1037 // described for unqualified names in the definition of the class
1038 // granting friendship.
1039 // i.e. we don't push a scope unless it's a class member.
1041 switch (Qualifier
->getKind()) {
1042 case NestedNameSpecifier::Global
:
1043 case NestedNameSpecifier::Namespace
:
1044 case NestedNameSpecifier::NamespaceAlias
:
1045 // These are always namespace scopes. We never want to enter a
1046 // namespace scope from anything but a file context.
1047 return CurContext
->getRedeclContext()->isFileContext();
1049 case NestedNameSpecifier::Identifier
:
1050 case NestedNameSpecifier::TypeSpec
:
1051 case NestedNameSpecifier::TypeSpecWithTemplate
:
1052 case NestedNameSpecifier::Super
:
1053 // These are never namespace scopes.
1057 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1060 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
1061 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
1062 /// After this method is called, according to [C++ 3.4.3p3], names should be
1063 /// looked up in the declarator-id's scope, until the declarator is parsed and
1064 /// ActOnCXXExitDeclaratorScope is called.
1065 /// The 'SS' should be a non-empty valid CXXScopeSpec.
1066 bool Sema::ActOnCXXEnterDeclaratorScope(Scope
*S
, CXXScopeSpec
&SS
) {
1067 assert(SS
.isSet() && "Parser passed invalid CXXScopeSpec.");
1069 if (SS
.isInvalid()) return true;
1071 DeclContext
*DC
= computeDeclContext(SS
, true);
1072 if (!DC
) return true;
1074 // Before we enter a declarator's context, we need to make sure that
1075 // it is a complete declaration context.
1076 if (!DC
->isDependentContext() && RequireCompleteDeclContext(SS
, DC
))
1079 EnterDeclaratorContext(S
, DC
);
1081 // Rebuild the nested name specifier for the new scope.
1082 if (DC
->isDependentContext())
1083 RebuildNestedNameSpecifierInCurrentInstantiation(SS
);
1088 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
1089 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
1090 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
1091 /// Used to indicate that names should revert to being looked up in the
1093 void Sema::ActOnCXXExitDeclaratorScope(Scope
*S
, const CXXScopeSpec
&SS
) {
1094 assert(SS
.isSet() && "Parser passed invalid CXXScopeSpec.");
1097 assert(!SS
.isInvalid() && computeDeclContext(SS
, true) &&
1098 "exiting declarator scope we never really entered");
1099 ExitDeclaratorContext(S
);