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())) {
103 = Context
.getCanonicalType(QualType(SpecType
, 0));
105 // If the type of the nested name specifier is the same as the
106 // injected class name of the named class template, we're entering
107 // into that class template definition.
109 = ClassTemplate
->getInjectedClassNameSpecialization();
110 if (Context
.hasSameType(Injected
, ContextType
))
111 return ClassTemplate
->getTemplatedDecl();
113 // If the type of the nested name specifier is the same as the
114 // type of one of the class template's class template partial
115 // specializations, we're entering into the definition of that
116 // class template partial specialization.
117 if (ClassTemplatePartialSpecializationDecl
*PartialSpec
118 = ClassTemplate
->findPartialSpecialization(ContextType
)) {
119 // A declaration of the partial specialization must be visible.
120 // We can always recover here, because this only happens when we're
121 // entering the context, and that can't happen in a SFINAE context.
122 assert(!isSFINAEContext() &&
123 "partial specialization scope specifier in SFINAE context?");
124 if (!hasReachableDefinition(PartialSpec
))
125 diagnoseMissingImport(SS
.getLastQualifierNameLoc(), PartialSpec
,
126 MissingImportKind::PartialSpecialization
,
131 } else if (const RecordType
*RecordT
= NNSType
->getAs
<RecordType
>()) {
132 // The nested name specifier refers to a member of a class template.
133 return RecordT
->getDecl();
140 switch (NNS
->getKind()) {
141 case NestedNameSpecifier::Identifier
:
142 llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
144 case NestedNameSpecifier::Namespace
:
145 return NNS
->getAsNamespace();
147 case NestedNameSpecifier::NamespaceAlias
:
148 return NNS
->getAsNamespaceAlias()->getNamespace();
150 case NestedNameSpecifier::TypeSpec
:
151 case NestedNameSpecifier::TypeSpecWithTemplate
: {
152 const TagType
*Tag
= NNS
->getAsType()->getAs
<TagType
>();
153 assert(Tag
&& "Non-tag type in nested-name-specifier");
154 return Tag
->getDecl();
157 case NestedNameSpecifier::Global
:
158 return Context
.getTranslationUnitDecl();
160 case NestedNameSpecifier::Super
:
161 return NNS
->getAsRecordDecl();
164 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
167 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec
&SS
) {
168 if (!SS
.isSet() || SS
.isInvalid())
171 return SS
.getScopeRep()->isDependent();
174 /// If the given nested name specifier refers to the current
175 /// instantiation, return the declaration that corresponds to that
176 /// current instantiation (C++0x [temp.dep.type]p1).
178 /// \param NNS a dependent nested name specifier.
179 CXXRecordDecl
*Sema::getCurrentInstantiationOf(NestedNameSpecifier
*NNS
) {
180 assert(getLangOpts().CPlusPlus
&& "Only callable in C++");
181 assert(NNS
->isDependent() && "Only dependent nested-name-specifier allowed");
183 if (!NNS
->getAsType())
186 QualType T
= QualType(NNS
->getAsType(), 0);
187 return ::getCurrentInstantiationOf(T
, CurContext
);
190 /// Require that the context specified by SS be complete.
192 /// If SS refers to a type, this routine checks whether the type is
193 /// complete enough (or can be made complete enough) for name lookup
194 /// into the DeclContext. A type that is not yet completed can be
195 /// considered "complete enough" if it is a class/struct/union/enum
196 /// that is currently being defined. Or, if we have a type that names
197 /// a class template specialization that is not a complete type, we
198 /// will attempt to instantiate that class template.
199 bool Sema::RequireCompleteDeclContext(CXXScopeSpec
&SS
,
201 assert(DC
&& "given null context");
203 TagDecl
*tag
= dyn_cast
<TagDecl
>(DC
);
205 // If this is a dependent type, then we consider it complete.
206 // FIXME: This is wrong; we should require a (visible) definition to
207 // exist in this case too.
208 if (!tag
|| tag
->isDependentContext())
211 // Grab the tag definition, if there is one.
212 QualType type
= Context
.getTypeDeclType(tag
);
213 tag
= type
->getAsTagDecl();
215 // If we're currently defining this type, then lookup into the
216 // type is okay: don't complain that it isn't complete yet.
217 if (tag
->isBeingDefined())
220 SourceLocation loc
= SS
.getLastQualifierNameLoc();
221 if (loc
.isInvalid()) loc
= SS
.getRange().getBegin();
223 // The type must be complete.
224 if (RequireCompleteType(loc
, type
, diag::err_incomplete_nested_name_spec
,
226 SS
.SetInvalid(SS
.getRange());
230 if (auto *EnumD
= dyn_cast
<EnumDecl
>(tag
))
231 // Fixed enum types and scoped enum instantiations are complete, but they
232 // aren't valid as scopes until we see or instantiate their definition.
233 return RequireCompleteEnumDecl(EnumD
, loc
, &SS
);
238 /// Require that the EnumDecl is completed with its enumerators defined or
239 /// instantiated. SS, if provided, is the ScopeRef parsed.
241 bool Sema::RequireCompleteEnumDecl(EnumDecl
*EnumD
, SourceLocation L
,
243 if (EnumD
->isCompleteDefinition()) {
244 // If we know about the definition but it is not visible, complain.
245 NamedDecl
*SuggestedDef
= nullptr;
246 if (!hasReachableDefinition(EnumD
, &SuggestedDef
,
247 /*OnlyNeedComplete*/ false)) {
248 // If the user is going to see an error here, recover by making the
249 // definition visible.
250 bool TreatAsComplete
= !isSFINAEContext();
251 diagnoseMissingImport(L
, SuggestedDef
, MissingImportKind::Definition
,
252 /*Recover*/ TreatAsComplete
);
253 return !TreatAsComplete
;
258 // Try to instantiate the definition, if this is a specialization of an
259 // enumeration temploid.
260 if (EnumDecl
*Pattern
= EnumD
->getInstantiatedFromMemberEnum()) {
261 MemberSpecializationInfo
*MSI
= EnumD
->getMemberSpecializationInfo();
262 if (MSI
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
) {
263 if (InstantiateEnum(L
, EnumD
, Pattern
,
264 getTemplateInstantiationArgs(EnumD
),
265 TSK_ImplicitInstantiation
)) {
267 SS
->SetInvalid(SS
->getRange());
275 Diag(L
, diag::err_incomplete_nested_name_spec
)
276 << QualType(EnumD
->getTypeForDecl(), 0) << SS
->getRange();
277 SS
->SetInvalid(SS
->getRange());
279 Diag(L
, diag::err_incomplete_enum
) << QualType(EnumD
->getTypeForDecl(), 0);
280 Diag(EnumD
->getLocation(), diag::note_declared_at
);
286 bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc
,
288 SS
.MakeGlobal(Context
, CCLoc
);
292 bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc
,
293 SourceLocation ColonColonLoc
,
295 CXXRecordDecl
*RD
= nullptr;
296 for (Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
297 if (S
->isFunctionScope()) {
298 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(S
->getEntity()))
299 RD
= MD
->getParent();
302 if (S
->isClassScope()) {
303 RD
= cast
<CXXRecordDecl
>(S
->getEntity());
309 Diag(SuperLoc
, diag::err_invalid_super_scope
);
311 } else if (RD
->isLambda()) {
312 Diag(SuperLoc
, diag::err_super_in_lambda_unsupported
);
314 } else if (RD
->getNumBases() == 0) {
315 Diag(SuperLoc
, diag::err_no_base_classes
) << RD
->getName();
319 SS
.MakeSuper(Context
, RD
, SuperLoc
, ColonColonLoc
);
323 /// Determines whether the given declaration is an valid acceptable
324 /// result for name lookup of a nested-name-specifier.
325 /// \param SD Declaration checked for nested-name-specifier.
326 /// \param IsExtension If not null and the declaration is accepted as an
327 /// extension, the pointed variable is assigned true.
328 bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl
*SD
,
333 SD
= SD
->getUnderlyingDecl();
335 // Namespace and namespace aliases are fine.
336 if (isa
<NamespaceDecl
>(SD
))
339 if (!isa
<TypeDecl
>(SD
))
342 // Determine whether we have a class (or, in C++11, an enum) or
343 // a typedef thereof. If so, build the nested-name-specifier.
344 QualType T
= Context
.getTypeDeclType(cast
<TypeDecl
>(SD
));
345 if (T
->isDependentType())
347 if (const TypedefNameDecl
*TD
= dyn_cast
<TypedefNameDecl
>(SD
)) {
348 if (TD
->getUnderlyingType()->isRecordType())
350 if (TD
->getUnderlyingType()->isEnumeralType()) {
351 if (Context
.getLangOpts().CPlusPlus11
)
356 } else if (isa
<RecordDecl
>(SD
)) {
358 } else if (isa
<EnumDecl
>(SD
)) {
359 if (Context
.getLangOpts().CPlusPlus11
)
368 /// If the given nested-name-specifier begins with a bare identifier
369 /// (e.g., Base::), perform name lookup for that identifier as a
370 /// nested-name-specifier within the given scope, and return the result of that
372 NamedDecl
*Sema::FindFirstQualifierInScope(Scope
*S
, NestedNameSpecifier
*NNS
) {
376 while (NNS
->getPrefix())
377 NNS
= NNS
->getPrefix();
379 if (NNS
->getKind() != NestedNameSpecifier::Identifier
)
382 LookupResult
Found(*this, NNS
->getAsIdentifier(), SourceLocation(),
383 LookupNestedNameSpecifierName
);
384 LookupName(Found
, S
);
385 assert(!Found
.isAmbiguous() && "Cannot handle ambiguities here yet");
387 if (!Found
.isSingleResult())
390 NamedDecl
*Result
= Found
.getFoundDecl();
391 if (isAcceptableNestedNameSpecifier(Result
))
397 bool Sema::isNonTypeNestedNameSpecifier(Scope
*S
, CXXScopeSpec
&SS
,
398 NestedNameSpecInfo
&IdInfo
) {
399 QualType ObjectType
= GetTypeFromParser(IdInfo
.ObjectType
);
400 LookupResult
Found(*this, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
401 LookupNestedNameSpecifierName
);
403 // Determine where to perform name lookup
404 DeclContext
*LookupCtx
= nullptr;
405 bool isDependent
= false;
406 if (!ObjectType
.isNull()) {
407 // This nested-name-specifier occurs in a member access expression, e.g.,
408 // x->B::f, and we are looking into the type of the object.
409 assert(!SS
.isSet() && "ObjectType and scope specifier cannot coexist");
410 LookupCtx
= computeDeclContext(ObjectType
);
411 isDependent
= ObjectType
->isDependentType();
412 } else if (SS
.isSet()) {
413 // This nested-name-specifier occurs after another nested-name-specifier,
414 // so long into the context associated with the prior nested-name-specifier.
415 LookupCtx
= computeDeclContext(SS
, false);
416 isDependent
= isDependentScopeSpecifier(SS
);
417 Found
.setContextRange(SS
.getRange());
421 // Perform "qualified" name lookup into the declaration context we
422 // computed, which is either the type of the base of a member access
423 // expression or the declaration context associated with a prior
424 // nested-name-specifier.
426 // The declaration context must be complete.
427 if (!LookupCtx
->isDependentContext() &&
428 RequireCompleteDeclContext(SS
, LookupCtx
))
431 LookupQualifiedName(Found
, LookupCtx
);
432 } else if (isDependent
) {
435 LookupName(Found
, S
);
437 Found
.suppressDiagnostics();
439 return Found
.getAsSingle
<NamespaceDecl
>();
444 // Callback to only accept typo corrections that can be a valid C++ member
445 // initializer: either a non-static field member or a base class.
446 class NestedNameSpecifierValidatorCCC final
447 : public CorrectionCandidateCallback
{
449 explicit NestedNameSpecifierValidatorCCC(Sema
&SRef
)
452 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
453 return SRef
.isAcceptableNestedNameSpecifier(candidate
.getCorrectionDecl());
456 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
457 return std::make_unique
<NestedNameSpecifierValidatorCCC
>(*this);
466 /// Build a new nested-name-specifier for "identifier::", as described
467 /// by ActOnCXXNestedNameSpecifier.
469 /// \param S Scope in which the nested-name-specifier occurs.
470 /// \param IdInfo Parser information about an identifier in the
471 /// nested-name-spec.
472 /// \param EnteringContext If true, enter the context specified by the
473 /// nested-name-specifier.
474 /// \param SS Optional nested name specifier preceding the identifier.
475 /// \param ScopeLookupResult Provides the result of name lookup within the
476 /// scope of the nested-name-specifier that was computed at template
478 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
479 /// error recovery and what kind of recovery is performed.
480 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
481 /// are allowed. The bool value pointed by this parameter is set to
482 /// 'true' if the identifier is treated as if it was followed by ':',
484 /// \param OnlyNamespace If true, only considers namespaces in lookup.
486 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
487 /// that it contains an extra parameter \p ScopeLookupResult, which provides
488 /// the result of name lookup within the scope of the nested-name-specifier
489 /// that was computed at template definition time.
491 /// If ErrorRecoveryLookup is true, then this call is used to improve error
492 /// recovery. This means that it should not emit diagnostics, it should
493 /// just return true on failure. It also means it should only return a valid
494 /// scope if it *knows* that the result is correct. It should not return in a
495 /// dependent context, for example. Nor will it extend \p SS with the scope
497 bool Sema::BuildCXXNestedNameSpecifier(Scope
*S
, NestedNameSpecInfo
&IdInfo
,
498 bool EnteringContext
, CXXScopeSpec
&SS
,
499 NamedDecl
*ScopeLookupResult
,
500 bool ErrorRecoveryLookup
,
501 bool *IsCorrectedToColon
,
502 bool OnlyNamespace
) {
503 if (IdInfo
.Identifier
->isEditorPlaceholder())
505 LookupResult
Found(*this, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
506 OnlyNamespace
? LookupNamespaceName
507 : LookupNestedNameSpecifierName
);
508 QualType ObjectType
= GetTypeFromParser(IdInfo
.ObjectType
);
510 // Determine where to perform name lookup
511 DeclContext
*LookupCtx
= nullptr;
512 bool isDependent
= false;
513 if (IsCorrectedToColon
)
514 *IsCorrectedToColon
= false;
515 if (!ObjectType
.isNull()) {
516 // This nested-name-specifier occurs in a member access expression, e.g.,
517 // x->B::f, and we are looking into the type of the object.
518 assert(!SS
.isSet() && "ObjectType and scope specifier cannot coexist");
519 LookupCtx
= computeDeclContext(ObjectType
);
520 isDependent
= ObjectType
->isDependentType();
521 } else if (SS
.isSet()) {
522 // This nested-name-specifier occurs after another nested-name-specifier,
523 // so look into the context associated with the prior nested-name-specifier.
524 LookupCtx
= computeDeclContext(SS
, EnteringContext
);
525 isDependent
= isDependentScopeSpecifier(SS
);
526 Found
.setContextRange(SS
.getRange());
529 bool ObjectTypeSearchedInScope
= false;
531 // Perform "qualified" name lookup into the declaration context we
532 // computed, which is either the type of the base of a member access
533 // expression or the declaration context associated with a prior
534 // nested-name-specifier.
536 // The declaration context must be complete.
537 if (!LookupCtx
->isDependentContext() &&
538 RequireCompleteDeclContext(SS
, LookupCtx
))
541 LookupQualifiedName(Found
, LookupCtx
);
543 if (!ObjectType
.isNull() && Found
.empty()) {
544 // C++ [basic.lookup.classref]p4:
545 // If the id-expression in a class member access is a qualified-id of
548 // class-name-or-namespace-name::...
550 // the class-name-or-namespace-name following the . or -> operator is
551 // looked up both in the context of the entire postfix-expression and in
552 // the scope of the class of the object expression. If the name is found
553 // only in the scope of the class of the object expression, the name
554 // shall refer to a class-name. If the name is found only in the
555 // context of the entire postfix-expression, the name shall refer to a
556 // class-name or namespace-name. [...]
558 // Qualified name lookup into a class will not find a namespace-name,
559 // so we do not need to diagnose that case specifically. However,
560 // this qualified name lookup may find nothing. In that case, perform
561 // unqualified name lookup in the given scope (if available) or
562 // reconstruct the result from when name lookup was performed at template
565 LookupName(Found
, S
);
566 else if (ScopeLookupResult
)
567 Found
.addDecl(ScopeLookupResult
);
569 ObjectTypeSearchedInScope
= true;
571 } else if (!isDependent
) {
572 // Perform unqualified name lookup in the current scope.
573 LookupName(Found
, S
);
576 if (Found
.isAmbiguous())
579 // If we performed lookup into a dependent context and did not find anything,
580 // that's fine: just build a dependent nested-name-specifier.
581 if (Found
.empty() && isDependent
&&
582 !(LookupCtx
&& LookupCtx
->isRecord() &&
583 (!cast
<CXXRecordDecl
>(LookupCtx
)->hasDefinition() ||
584 !cast
<CXXRecordDecl
>(LookupCtx
)->hasAnyDependentBases()))) {
585 // Don't speculate if we're just trying to improve error recovery.
586 if (ErrorRecoveryLookup
)
589 // We were not able to compute the declaration context for a dependent
590 // base object type or prior nested-name-specifier, so this
591 // nested-name-specifier refers to an unknown specialization. Just build
592 // a dependent nested-name-specifier.
593 SS
.Extend(Context
, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
, IdInfo
.CCLoc
);
597 if (Found
.empty() && !ErrorRecoveryLookup
) {
598 // If identifier is not found as class-name-or-namespace-name, but is found
599 // as other entity, don't look for typos.
600 LookupResult
R(*this, Found
.getLookupNameInfo(), LookupOrdinaryName
);
602 LookupQualifiedName(R
, LookupCtx
);
603 else if (S
&& !isDependent
)
606 // Don't diagnose problems with this speculative lookup.
607 R
.suppressDiagnostics();
608 // The identifier is found in ordinary lookup. If correction to colon is
609 // allowed, suggest replacement to ':'.
610 if (IsCorrectedToColon
) {
611 *IsCorrectedToColon
= true;
612 Diag(IdInfo
.CCLoc
, diag::err_nested_name_spec_is_not_class
)
613 << IdInfo
.Identifier
<< getLangOpts().CPlusPlus
614 << FixItHint::CreateReplacement(IdInfo
.CCLoc
, ":");
615 if (NamedDecl
*ND
= R
.getAsSingle
<NamedDecl
>())
616 Diag(ND
->getLocation(), diag::note_declared_at
);
619 // Replacement '::' -> ':' is not allowed, just issue respective error.
620 Diag(R
.getNameLoc(), OnlyNamespace
621 ? unsigned(diag::err_expected_namespace_name
)
622 : unsigned(diag::err_expected_class_or_namespace
))
623 << IdInfo
.Identifier
<< getLangOpts().CPlusPlus
;
624 if (NamedDecl
*ND
= R
.getAsSingle
<NamedDecl
>())
625 Diag(ND
->getLocation(), diag::note_entity_declared_at
)
626 << IdInfo
.Identifier
;
631 if (Found
.empty() && !ErrorRecoveryLookup
&& !getLangOpts().MSVCCompat
) {
632 // We haven't found anything, and we're not recovering from a
633 // different kind of error, so look for typos.
634 DeclarationName Name
= Found
.getLookupName();
636 NestedNameSpecifierValidatorCCC
CCC(*this);
637 if (TypoCorrection Corrected
= CorrectTypo(
638 Found
.getLookupNameInfo(), Found
.getLookupKind(), S
, &SS
, CCC
,
639 CTK_ErrorRecovery
, LookupCtx
, EnteringContext
)) {
641 bool DroppedSpecifier
=
642 Corrected
.WillReplaceSpecifier() &&
643 Name
.getAsString() == Corrected
.getAsString(getLangOpts());
644 if (DroppedSpecifier
)
646 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
647 << Name
<< LookupCtx
<< DroppedSpecifier
650 diagnoseTypo(Corrected
, PDiag(diag::err_undeclared_var_use_suggest
)
653 if (Corrected
.getCorrectionSpecifier())
654 SS
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
655 SourceRange(Found
.getNameLoc()));
657 if (NamedDecl
*ND
= Corrected
.getFoundDecl())
659 Found
.setLookupName(Corrected
.getCorrection());
661 Found
.setLookupName(IdInfo
.Identifier
);
666 Found
.isSingleResult() ? Found
.getRepresentativeDecl() : nullptr;
667 bool IsExtension
= false;
668 bool AcceptSpec
= isAcceptableNestedNameSpecifier(SD
, &IsExtension
);
669 if (!AcceptSpec
&& IsExtension
) {
671 Diag(IdInfo
.IdentifierLoc
, diag::ext_nested_name_spec_is_enum
);
674 if (!ObjectType
.isNull() && !ObjectTypeSearchedInScope
&&
675 !getLangOpts().CPlusPlus11
) {
676 // C++03 [basic.lookup.classref]p4:
677 // [...] If the name is found in both contexts, the
678 // class-name-or-namespace-name shall refer to the same entity.
680 // We already found the name in the scope of the object. Now, look
681 // into the current scope (the scope of the postfix-expression) to
682 // see if we can find the same name there. As above, if there is no
683 // scope, reconstruct the result from the template instantiation itself.
685 // Note that C++11 does *not* perform this redundant lookup.
686 NamedDecl
*OuterDecl
;
688 LookupResult
FoundOuter(*this, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
689 LookupNestedNameSpecifierName
);
690 LookupName(FoundOuter
, S
);
691 OuterDecl
= FoundOuter
.getAsSingle
<NamedDecl
>();
693 OuterDecl
= ScopeLookupResult
;
695 if (isAcceptableNestedNameSpecifier(OuterDecl
) &&
696 OuterDecl
->getCanonicalDecl() != SD
->getCanonicalDecl() &&
697 (!isa
<TypeDecl
>(OuterDecl
) || !isa
<TypeDecl
>(SD
) ||
698 !Context
.hasSameType(
699 Context
.getTypeDeclType(cast
<TypeDecl
>(OuterDecl
)),
700 Context
.getTypeDeclType(cast
<TypeDecl
>(SD
))))) {
701 if (ErrorRecoveryLookup
)
704 Diag(IdInfo
.IdentifierLoc
,
705 diag::err_nested_name_member_ref_lookup_ambiguous
)
706 << IdInfo
.Identifier
;
707 Diag(SD
->getLocation(), diag::note_ambig_member_ref_object_type
)
709 Diag(OuterDecl
->getLocation(), diag::note_ambig_member_ref_scope
);
711 // Fall through so that we'll pick the name we found in the object
712 // type, since that's probably what the user wanted anyway.
716 if (auto *TD
= dyn_cast_or_null
<TypedefNameDecl
>(SD
))
717 MarkAnyDeclReferenced(TD
->getLocation(), TD
, /*OdrUse=*/false);
719 // If we're just performing this lookup for error-recovery purposes,
720 // don't extend the nested-name-specifier. Just return now.
721 if (ErrorRecoveryLookup
)
724 // The use of a nested name specifier may trigger deprecation warnings.
725 DiagnoseUseOfDecl(SD
, IdInfo
.CCLoc
);
727 if (NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(SD
)) {
728 SS
.Extend(Context
, Namespace
, IdInfo
.IdentifierLoc
, IdInfo
.CCLoc
);
732 if (NamespaceAliasDecl
*Alias
= dyn_cast
<NamespaceAliasDecl
>(SD
)) {
733 SS
.Extend(Context
, Alias
, IdInfo
.IdentifierLoc
, IdInfo
.CCLoc
);
738 Context
.getTypeDeclType(cast
<TypeDecl
>(SD
->getUnderlyingDecl()));
740 if (T
->isEnumeralType())
741 Diag(IdInfo
.IdentifierLoc
, diag::warn_cxx98_compat_enum_nested_name_spec
);
744 if (const auto *USD
= dyn_cast
<UsingShadowDecl
>(SD
)) {
745 T
= Context
.getUsingType(USD
, T
);
746 TLB
.pushTypeSpec(T
).setNameLoc(IdInfo
.IdentifierLoc
);
747 } else if (isa
<InjectedClassNameType
>(T
)) {
748 InjectedClassNameTypeLoc InjectedTL
749 = TLB
.push
<InjectedClassNameTypeLoc
>(T
);
750 InjectedTL
.setNameLoc(IdInfo
.IdentifierLoc
);
751 } else if (isa
<RecordType
>(T
)) {
752 RecordTypeLoc RecordTL
= TLB
.push
<RecordTypeLoc
>(T
);
753 RecordTL
.setNameLoc(IdInfo
.IdentifierLoc
);
754 } else if (isa
<TypedefType
>(T
)) {
755 TypedefTypeLoc TypedefTL
= TLB
.push
<TypedefTypeLoc
>(T
);
756 TypedefTL
.setNameLoc(IdInfo
.IdentifierLoc
);
757 } else if (isa
<EnumType
>(T
)) {
758 EnumTypeLoc EnumTL
= TLB
.push
<EnumTypeLoc
>(T
);
759 EnumTL
.setNameLoc(IdInfo
.IdentifierLoc
);
760 } else if (isa
<TemplateTypeParmType
>(T
)) {
761 TemplateTypeParmTypeLoc TemplateTypeTL
762 = TLB
.push
<TemplateTypeParmTypeLoc
>(T
);
763 TemplateTypeTL
.setNameLoc(IdInfo
.IdentifierLoc
);
764 } else if (isa
<UnresolvedUsingType
>(T
)) {
765 UnresolvedUsingTypeLoc UnresolvedTL
766 = TLB
.push
<UnresolvedUsingTypeLoc
>(T
);
767 UnresolvedTL
.setNameLoc(IdInfo
.IdentifierLoc
);
768 } else if (isa
<SubstTemplateTypeParmType
>(T
)) {
769 SubstTemplateTypeParmTypeLoc TL
770 = TLB
.push
<SubstTemplateTypeParmTypeLoc
>(T
);
771 TL
.setNameLoc(IdInfo
.IdentifierLoc
);
772 } else if (isa
<SubstTemplateTypeParmPackType
>(T
)) {
773 SubstTemplateTypeParmPackTypeLoc TL
774 = TLB
.push
<SubstTemplateTypeParmPackTypeLoc
>(T
);
775 TL
.setNameLoc(IdInfo
.IdentifierLoc
);
777 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
780 SS
.Extend(Context
, SourceLocation(), TLB
.getTypeLocInContext(Context
, T
),
785 // Otherwise, we have an error case. If we don't want diagnostics, just
786 // return an error now.
787 if (ErrorRecoveryLookup
)
790 // If we didn't find anything during our lookup, try again with
791 // ordinary name lookup, which can help us produce better error
794 Found
.clear(LookupOrdinaryName
);
795 LookupName(Found
, S
);
798 // In Microsoft mode, if we are within a templated function and we can't
799 // resolve Identifier, then extend the SS with Identifier. This will have
800 // the effect of resolving Identifier during template instantiation.
801 // The goal is to be able to resolve a function call whose
802 // nested-name-specifier is located inside a dependent base class.
807 // static void foo2() { }
809 // template <class T> class A { public: typedef C D; };
811 // template <class T> class B : public A<T> {
813 // void foo() { D::foo2(); }
815 if (getLangOpts().MSVCCompat
) {
816 DeclContext
*DC
= LookupCtx
? LookupCtx
: CurContext
;
817 if (DC
->isDependentContext() && DC
->isFunctionOrMethod()) {
818 CXXRecordDecl
*ContainingClass
= dyn_cast
<CXXRecordDecl
>(DC
->getParent());
819 if (ContainingClass
&& ContainingClass
->hasAnyDependentBases()) {
820 Diag(IdInfo
.IdentifierLoc
,
821 diag::ext_undeclared_unqual_id_with_dependent_base
)
822 << IdInfo
.Identifier
<< ContainingClass
;
823 SS
.Extend(Context
, IdInfo
.Identifier
, IdInfo
.IdentifierLoc
,
830 if (!Found
.empty()) {
831 if (TypeDecl
*TD
= Found
.getAsSingle
<TypeDecl
>()) {
832 Diag(IdInfo
.IdentifierLoc
, diag::err_expected_class_or_namespace
)
833 << Context
.getTypeDeclType(TD
) << getLangOpts().CPlusPlus
;
834 } else if (Found
.getAsSingle
<TemplateDecl
>()) {
835 ParsedType SuggestedType
;
836 DiagnoseUnknownTypeName(IdInfo
.Identifier
, IdInfo
.IdentifierLoc
, S
, &SS
,
839 Diag(IdInfo
.IdentifierLoc
, diag::err_expected_class_or_namespace
)
840 << IdInfo
.Identifier
<< getLangOpts().CPlusPlus
;
841 if (NamedDecl
*ND
= Found
.getAsSingle
<NamedDecl
>())
842 Diag(ND
->getLocation(), diag::note_entity_declared_at
)
843 << IdInfo
.Identifier
;
845 } else if (SS
.isSet())
846 Diag(IdInfo
.IdentifierLoc
, diag::err_no_member
) << IdInfo
.Identifier
847 << LookupCtx
<< SS
.getRange();
849 Diag(IdInfo
.IdentifierLoc
, diag::err_undeclared_var_use
)
850 << IdInfo
.Identifier
;
855 bool Sema::ActOnCXXNestedNameSpecifier(Scope
*S
, NestedNameSpecInfo
&IdInfo
,
856 bool EnteringContext
, CXXScopeSpec
&SS
,
857 bool *IsCorrectedToColon
,
858 bool OnlyNamespace
) {
862 return BuildCXXNestedNameSpecifier(S
, IdInfo
, EnteringContext
, SS
,
863 /*ScopeLookupResult=*/nullptr, false,
864 IsCorrectedToColon
, OnlyNamespace
);
867 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec
&SS
,
869 SourceLocation ColonColonLoc
) {
870 if (SS
.isInvalid() || DS
.getTypeSpecType() == DeclSpec::TST_error
)
873 assert(DS
.getTypeSpecType() == DeclSpec::TST_decltype
);
875 QualType T
= BuildDecltypeType(DS
.getRepAsExpr());
879 if (!T
->isDependentType() && !T
->getAs
<TagType
>()) {
880 Diag(DS
.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace
)
881 << T
<< getLangOpts().CPlusPlus
;
886 DecltypeTypeLoc DecltypeTL
= TLB
.push
<DecltypeTypeLoc
>(T
);
887 DecltypeTL
.setDecltypeLoc(DS
.getTypeSpecTypeLoc());
888 DecltypeTL
.setRParenLoc(DS
.getTypeofParensRange().getEnd());
889 SS
.Extend(Context
, SourceLocation(), TLB
.getTypeLocInContext(Context
, T
),
894 /// IsInvalidUnlessNestedName - This method is used for error recovery
895 /// purposes to determine whether the specified identifier is only valid as
896 /// a nested name specifier, for example a namespace name. It is
897 /// conservatively correct to always return false from this method.
899 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
900 bool Sema::IsInvalidUnlessNestedName(Scope
*S
, CXXScopeSpec
&SS
,
901 NestedNameSpecInfo
&IdInfo
,
902 bool EnteringContext
) {
906 return !BuildCXXNestedNameSpecifier(S
, IdInfo
, EnteringContext
, SS
,
907 /*ScopeLookupResult=*/nullptr, true);
910 bool Sema::ActOnCXXNestedNameSpecifier(Scope
*S
,
912 SourceLocation TemplateKWLoc
,
913 TemplateTy OpaqueTemplate
,
914 SourceLocation TemplateNameLoc
,
915 SourceLocation LAngleLoc
,
916 ASTTemplateArgsPtr TemplateArgsIn
,
917 SourceLocation RAngleLoc
,
918 SourceLocation CCLoc
,
919 bool EnteringContext
) {
923 TemplateName Template
= OpaqueTemplate
.get();
925 // Translate the parser's template argument list in our AST format.
926 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
927 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
929 DependentTemplateName
*DTN
= Template
.getAsDependentTemplateName();
930 if (DTN
&& DTN
->isIdentifier()) {
931 // Handle a dependent template specialization for which we cannot resolve
932 // the template name.
933 assert(DTN
->getQualifier() == SS
.getScopeRep());
934 QualType T
= Context
.getDependentTemplateSpecializationType(ETK_None
,
936 DTN
->getIdentifier(),
939 // Create source-location information for this type.
940 TypeLocBuilder Builder
;
941 DependentTemplateSpecializationTypeLoc SpecTL
942 = Builder
.push
<DependentTemplateSpecializationTypeLoc
>(T
);
943 SpecTL
.setElaboratedKeywordLoc(SourceLocation());
944 SpecTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
945 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
946 SpecTL
.setTemplateNameLoc(TemplateNameLoc
);
947 SpecTL
.setLAngleLoc(LAngleLoc
);
948 SpecTL
.setRAngleLoc(RAngleLoc
);
949 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
950 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
952 SS
.Extend(Context
, TemplateKWLoc
, Builder
.getTypeLocInContext(Context
, T
),
957 // If we assumed an undeclared identifier was a template name, try to
958 // typo-correct it now.
959 if (Template
.getAsAssumedTemplateName() &&
960 resolveAssumedTemplateNameAsType(S
, Template
, TemplateNameLoc
))
963 TemplateDecl
*TD
= Template
.getAsTemplateDecl();
964 if (Template
.getAsOverloadedTemplate() || DTN
||
965 isa
<FunctionTemplateDecl
>(TD
) || isa
<VarTemplateDecl
>(TD
)) {
966 SourceRange
R(TemplateNameLoc
, RAngleLoc
);
967 if (SS
.getRange().isValid())
968 R
.setBegin(SS
.getRange().getBegin());
970 Diag(CCLoc
, diag::err_non_type_template_in_nested_name_specifier
)
971 << (TD
&& isa
<VarTemplateDecl
>(TD
)) << Template
<< R
;
972 NoteAllFoundTemplates(Template
);
976 // We were able to resolve the template name to an actual template.
977 // Build an appropriate nested-name-specifier.
978 QualType T
= CheckTemplateIdType(Template
, TemplateNameLoc
, TemplateArgs
);
982 // Alias template specializations can produce types which are not valid
983 // nested name specifiers.
984 if (!T
->isDependentType() && !T
->getAs
<TagType
>()) {
985 Diag(TemplateNameLoc
, diag::err_nested_name_spec_non_tag
) << T
;
986 NoteAllFoundTemplates(Template
);
990 // Provide source-location information for the template specialization type.
991 TypeLocBuilder Builder
;
992 TemplateSpecializationTypeLoc SpecTL
993 = Builder
.push
<TemplateSpecializationTypeLoc
>(T
);
994 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
995 SpecTL
.setTemplateNameLoc(TemplateNameLoc
);
996 SpecTL
.setLAngleLoc(LAngleLoc
);
997 SpecTL
.setRAngleLoc(RAngleLoc
);
998 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
999 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
1002 SS
.Extend(Context
, TemplateKWLoc
, Builder
.getTypeLocInContext(Context
, T
),
1008 /// A structure that stores a nested-name-specifier annotation,
1009 /// including both the nested-name-specifier
1010 struct NestedNameSpecifierAnnotation
{
1011 NestedNameSpecifier
*NNS
;
1015 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec
&SS
) {
1016 if (SS
.isEmpty() || SS
.isInvalid())
1019 void *Mem
= Context
.Allocate(
1020 (sizeof(NestedNameSpecifierAnnotation
) + SS
.location_size()),
1021 alignof(NestedNameSpecifierAnnotation
));
1022 NestedNameSpecifierAnnotation
*Annotation
1023 = new (Mem
) NestedNameSpecifierAnnotation
;
1024 Annotation
->NNS
= SS
.getScopeRep();
1025 memcpy(Annotation
+ 1, SS
.location_data(), SS
.location_size());
1029 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr
,
1030 SourceRange AnnotationRange
,
1032 if (!AnnotationPtr
) {
1033 SS
.SetInvalid(AnnotationRange
);
1037 NestedNameSpecifierAnnotation
*Annotation
1038 = static_cast<NestedNameSpecifierAnnotation
*>(AnnotationPtr
);
1039 SS
.Adopt(NestedNameSpecifierLoc(Annotation
->NNS
, Annotation
+ 1));
1042 bool Sema::ShouldEnterDeclaratorScope(Scope
*S
, const CXXScopeSpec
&SS
) {
1043 assert(SS
.isSet() && "Parser passed invalid CXXScopeSpec.");
1045 // Don't enter a declarator context when the current context is an Objective-C
1047 if (isa
<ObjCContainerDecl
>(CurContext
) || isa
<ObjCMethodDecl
>(CurContext
))
1050 NestedNameSpecifier
*Qualifier
= SS
.getScopeRep();
1052 // There are only two places a well-formed program may qualify a
1053 // declarator: first, when defining a namespace or class member
1054 // out-of-line, and second, when naming an explicitly-qualified
1055 // friend function. The latter case is governed by
1056 // C++03 [basic.lookup.unqual]p10:
1057 // In a friend declaration naming a member function, a name used
1058 // in the function declarator and not part of a template-argument
1059 // in a template-id is first looked up in the scope of the member
1060 // function's class. If it is not found, or if the name is part of
1061 // a template-argument in a template-id, the look up is as
1062 // described for unqualified names in the definition of the class
1063 // granting friendship.
1064 // i.e. we don't push a scope unless it's a class member.
1066 switch (Qualifier
->getKind()) {
1067 case NestedNameSpecifier::Global
:
1068 case NestedNameSpecifier::Namespace
:
1069 case NestedNameSpecifier::NamespaceAlias
:
1070 // These are always namespace scopes. We never want to enter a
1071 // namespace scope from anything but a file context.
1072 return CurContext
->getRedeclContext()->isFileContext();
1074 case NestedNameSpecifier::Identifier
:
1075 case NestedNameSpecifier::TypeSpec
:
1076 case NestedNameSpecifier::TypeSpecWithTemplate
:
1077 case NestedNameSpecifier::Super
:
1078 // These are never namespace scopes.
1082 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1085 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
1086 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
1087 /// After this method is called, according to [C++ 3.4.3p3], names should be
1088 /// looked up in the declarator-id's scope, until the declarator is parsed and
1089 /// ActOnCXXExitDeclaratorScope is called.
1090 /// The 'SS' should be a non-empty valid CXXScopeSpec.
1091 bool Sema::ActOnCXXEnterDeclaratorScope(Scope
*S
, CXXScopeSpec
&SS
) {
1092 assert(SS
.isSet() && "Parser passed invalid CXXScopeSpec.");
1094 if (SS
.isInvalid()) return true;
1096 DeclContext
*DC
= computeDeclContext(SS
, true);
1097 if (!DC
) return true;
1099 // Before we enter a declarator's context, we need to make sure that
1100 // it is a complete declaration context.
1101 if (!DC
->isDependentContext() && RequireCompleteDeclContext(SS
, DC
))
1104 EnterDeclaratorContext(S
, DC
);
1106 // Rebuild the nested name specifier for the new scope.
1107 if (DC
->isDependentContext())
1108 RebuildNestedNameSpecifierInCurrentInstantiation(SS
);
1113 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
1114 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
1115 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
1116 /// Used to indicate that names should revert to being looked up in the
1118 void Sema::ActOnCXXExitDeclaratorScope(Scope
*S
, const CXXScopeSpec
&SS
) {
1119 assert(SS
.isSet() && "Parser passed invalid CXXScopeSpec.");
1122 assert(!SS
.isInvalid() && computeDeclContext(SS
, true) &&
1123 "exiting declarator scope we never really entered");
1124 ExitDeclaratorContext(S
);