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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/NestedNameSpecifier.h"
19 #include "clang/Basic/PartialDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/SemaInternal.h"
23 #include "clang/Sema/Template.h"
24 #include "llvm/ADT/STLExtras.h"
25 using namespace clang;
27 /// 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 (!Record->isDependentContext() ||
37 Record->isCurrentInstantiation(CurContext))
41 } else if (isa<InjectedClassNameType>(Ty))
42 return cast<InjectedClassNameType>(Ty)->getDecl();
47 /// Compute the DeclContext that is associated with the given type.
49 /// \param T the type for which we are attempting to find a DeclContext.
51 /// \returns the declaration context represented by the type T,
52 /// or NULL if the declaration context cannot be computed (e.g., because it is
53 /// dependent and not the current instantiation).
54 DeclContext *Sema::computeDeclContext(QualType T) {
55 if (!T->isDependentType())
56 if (const TagType *Tag = T->getAs<TagType>())
57 return Tag->getDecl();
59 return ::getCurrentInstantiationOf(T, CurContext);
62 /// Compute the DeclContext that is associated with the given
65 /// \param SS the C++ scope specifier as it appears in the source
67 /// \param EnteringContext when true, we will be entering the context of
68 /// this scope specifier, so we can retrieve the declaration context of a
69 /// class template or class template partial specialization even if it is
70 /// not the current instantiation.
72 /// \returns the declaration context represented by the scope specifier @p SS,
73 /// or NULL if the declaration context cannot be computed (e.g., because it is
74 /// dependent and not the current instantiation).
75 DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
76 bool EnteringContext) {
77 if (!SS.isSet() || SS.isInvalid())
80 NestedNameSpecifier *NNS = SS.getScopeRep();
81 if (NNS->isDependent()) {
82 // If this nested-name-specifier refers to the current
83 // instantiation, return its DeclContext.
84 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
87 if (EnteringContext) {
88 const Type *NNSType = NNS->getAsType();
93 // Look through type alias templates, per C++0x [temp.dep.type]p1.
94 NNSType = Context.getCanonicalType(NNSType);
95 if (const TemplateSpecializationType *SpecType
96 = NNSType->getAs<TemplateSpecializationType>()) {
97 // We are entering the context of the nested name specifier, so try to
98 // match the nested name specifier to either a primary class template
99 // or a class template partial specialization.
100 if (ClassTemplateDecl *ClassTemplate
101 = dyn_cast_or_null<ClassTemplateDecl>(
102 SpecType->getTemplateName().getAsTemplateDecl())) {
104 = Context.getCanonicalType(QualType(SpecType, 0));
106 // If the type of the nested name specifier is the same as the
107 // injected class name of the named class template, we're entering
108 // into that class template definition.
110 = ClassTemplate->getInjectedClassNameSpecialization();
111 if (Context.hasSameType(Injected, ContextType))
112 return ClassTemplate->getTemplatedDecl();
114 // If the type of the nested name specifier is the same as the
115 // type of one of the class template's class template partial
116 // specializations, we're entering into the definition of that
117 // class template partial specialization.
118 if (ClassTemplatePartialSpecializationDecl *PartialSpec
119 = ClassTemplate->findPartialSpecialization(ContextType)) {
120 // A declaration of the partial specialization must be visible.
121 // We can always recover here, because this only happens when we're
122 // entering the context, and that can't happen in a SFINAE context.
123 assert(!isSFINAEContext() &&
124 "partial specialization scope specifier in SFINAE context?");
125 if (!hasVisibleDeclaration(PartialSpec))
126 diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,
127 MissingImportKind::PartialSpecialization,
132 } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
133 // The nested name specifier refers to a member of a class template.
134 return RecordT->getDecl();
141 switch (NNS->getKind()) {
142 case NestedNameSpecifier::Identifier:
143 llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
145 case NestedNameSpecifier::Namespace:
146 return NNS->getAsNamespace();
148 case NestedNameSpecifier::NamespaceAlias:
149 return NNS->getAsNamespaceAlias()->getNamespace();
151 case NestedNameSpecifier::TypeSpec:
152 case NestedNameSpecifier::TypeSpecWithTemplate: {
153 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
154 assert(Tag && "Non-tag type in nested-name-specifier");
155 return Tag->getDecl();
158 case NestedNameSpecifier::Global:
159 return Context.getTranslationUnitDecl();
161 case NestedNameSpecifier::Super:
162 return NNS->getAsRecordDecl();
165 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
168 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
169 if (!SS.isSet() || SS.isInvalid())
172 return SS.getScopeRep()->isDependent();
175 /// If the given nested name specifier refers to the current
176 /// instantiation, return the declaration that corresponds to that
177 /// current instantiation (C++0x [temp.dep.type]p1).
179 /// \param NNS a dependent nested name specifier.
180 CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
181 assert(getLangOpts().CPlusPlus && "Only callable in C++");
182 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
184 if (!NNS->getAsType())
187 QualType T = QualType(NNS->getAsType(), 0);
188 return ::getCurrentInstantiationOf(T, CurContext);
191 /// Require that the context specified by SS be complete.
193 /// If SS refers to a type, this routine checks whether the type is
194 /// complete enough (or can be made complete enough) for name lookup
195 /// into the DeclContext. A type that is not yet completed can be
196 /// considered "complete enough" if it is a class/struct/union/enum
197 /// that is currently being defined. Or, if we have a type that names
198 /// a class template specialization that is not a complete type, we
199 /// will attempt to instantiate that class template.
200 bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
202 assert(DC && "given null context");
204 TagDecl *tag = dyn_cast<TagDecl>(DC);
206 // If this is a dependent type, then we consider it complete.
207 // FIXME: This is wrong; we should require a (visible) definition to
208 // exist in this case too.
209 if (!tag || tag->isDependentContext())
212 // Grab the tag definition, if there is one.
213 QualType type = Context.getTypeDeclType(tag);
214 tag = type->getAsTagDecl();
216 // If we're currently defining this type, then lookup into the
217 // type is okay: don't complain that it isn't complete yet.
218 if (tag->isBeingDefined())
221 SourceLocation loc = SS.getLastQualifierNameLoc();
222 if (loc.isInvalid()) loc = SS.getRange().getBegin();
224 // The type must be complete.
225 if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
227 SS.SetInvalid(SS.getRange());
231 // Fixed enum types are complete, but they aren't valid as scopes
232 // until we see a definition, so awkwardly pull out this special
234 auto *EnumD = dyn_cast<EnumDecl>(tag);
237 if (EnumD->isCompleteDefinition()) {
238 // If we know about the definition but it is not visible, complain.
239 NamedDecl *SuggestedDef = nullptr;
240 if (!hasVisibleDefinition(EnumD, &SuggestedDef,
241 /*OnlyNeedComplete*/false)) {
242 // If the user is going to see an error here, recover by making the
243 // definition visible.
244 bool TreatAsComplete = !isSFINAEContext();
245 diagnoseMissingImport(loc, SuggestedDef, MissingImportKind::Definition,
246 /*Recover*/TreatAsComplete);
247 return !TreatAsComplete;
252 // Try to instantiate the definition, if this is a specialization of an
253 // enumeration temploid.
254 if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {
255 MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();
256 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
257 if (InstantiateEnum(loc, EnumD, Pattern,
258 getTemplateInstantiationArgs(EnumD),
259 TSK_ImplicitInstantiation)) {
260 SS.SetInvalid(SS.getRange());
267 Diag(loc, diag::err_incomplete_nested_name_spec)
268 << type << SS.getRange();
269 SS.SetInvalid(SS.getRange());
273 bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,
275 SS.MakeGlobal(Context, CCLoc);
279 bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
280 SourceLocation ColonColonLoc,
282 CXXRecordDecl *RD = nullptr;
283 for (Scope *S = getCurScope(); S; S = S->getParent()) {
284 if (S->isFunctionScope()) {
285 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))
286 RD = MD->getParent();
289 if (S->isClassScope()) {
290 RD = cast<CXXRecordDecl>(S->getEntity());
296 Diag(SuperLoc, diag::err_invalid_super_scope);
298 } else if (RD->isLambda()) {
299 Diag(SuperLoc, diag::err_super_in_lambda_unsupported);
301 } else if (RD->getNumBases() == 0) {
302 Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();
306 SS.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
310 /// Determines whether the given declaration is an valid acceptable
311 /// result for name lookup of a nested-name-specifier.
312 /// \param SD Declaration checked for nested-name-specifier.
313 /// \param IsExtension If not null and the declaration is accepted as an
314 /// extension, the pointed variable is assigned true.
315 bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,
320 SD = SD->getUnderlyingDecl();
322 // Namespace and namespace aliases are fine.
323 if (isa<NamespaceDecl>(SD))
326 if (!isa<TypeDecl>(SD))
329 // Determine whether we have a class (or, in C++11, an enum) or
330 // a typedef thereof. If so, build the nested-name-specifier.
331 QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
332 if (T->isDependentType())
334 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
335 if (TD->getUnderlyingType()->isRecordType())
337 if (TD->getUnderlyingType()->isEnumeralType()) {
338 if (Context.getLangOpts().CPlusPlus11)
343 } else if (isa<RecordDecl>(SD)) {
345 } else if (isa<EnumDecl>(SD)) {
346 if (Context.getLangOpts().CPlusPlus11)
355 /// If the given nested-name-specifier begins with a bare identifier
356 /// (e.g., Base::), perform name lookup for that identifier as a
357 /// nested-name-specifier within the given scope, and return the result of that
359 NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
363 while (NNS->getPrefix())
364 NNS = NNS->getPrefix();
366 if (NNS->getKind() != NestedNameSpecifier::Identifier)
369 LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
370 LookupNestedNameSpecifierName);
371 LookupName(Found, S);
372 assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
374 if (!Found.isSingleResult())
377 NamedDecl *Result = Found.getFoundDecl();
378 if (isAcceptableNestedNameSpecifier(Result))
384 bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
385 NestedNameSpecInfo &IdInfo) {
386 QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
387 LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
388 LookupNestedNameSpecifierName);
390 // Determine where to perform name lookup
391 DeclContext *LookupCtx = nullptr;
392 bool isDependent = false;
393 if (!ObjectType.isNull()) {
394 // This nested-name-specifier occurs in a member access expression, e.g.,
395 // x->B::f, and we are looking into the type of the object.
396 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
397 LookupCtx = computeDeclContext(ObjectType);
398 isDependent = ObjectType->isDependentType();
399 } else if (SS.isSet()) {
400 // This nested-name-specifier occurs after another nested-name-specifier,
401 // so long into the context associated with the prior nested-name-specifier.
402 LookupCtx = computeDeclContext(SS, false);
403 isDependent = isDependentScopeSpecifier(SS);
404 Found.setContextRange(SS.getRange());
408 // Perform "qualified" name lookup into the declaration context we
409 // computed, which is either the type of the base of a member access
410 // expression or the declaration context associated with a prior
411 // nested-name-specifier.
413 // The declaration context must be complete.
414 if (!LookupCtx->isDependentContext() &&
415 RequireCompleteDeclContext(SS, LookupCtx))
418 LookupQualifiedName(Found, LookupCtx);
419 } else if (isDependent) {
422 LookupName(Found, S);
424 Found.suppressDiagnostics();
426 return Found.getAsSingle<NamespaceDecl>();
431 // Callback to only accept typo corrections that can be a valid C++ member
432 // intializer: either a non-static field member or a base class.
433 class NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback {
435 explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
438 bool ValidateCandidate(const TypoCorrection &candidate) override {
439 return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
448 /// Build a new nested-name-specifier for "identifier::", as described
449 /// by ActOnCXXNestedNameSpecifier.
451 /// \param S Scope in which the nested-name-specifier occurs.
452 /// \param IdInfo Parser information about an identifier in the
453 /// nested-name-spec.
454 /// \param EnteringContext If true, enter the context specified by the
455 /// nested-name-specifier.
456 /// \param SS Optional nested name specifier preceding the identifier.
457 /// \param ScopeLookupResult Provides the result of name lookup within the
458 /// scope of the nested-name-specifier that was computed at template
460 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
461 /// error recovery and what kind of recovery is performed.
462 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
463 /// are allowed. The bool value pointed by this parameter is set to
464 /// 'true' if the identifier is treated as if it was followed by ':',
466 /// \param OnlyNamespace If true, only considers namespaces in lookup.
468 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
469 /// that it contains an extra parameter \p ScopeLookupResult, which provides
470 /// the result of name lookup within the scope of the nested-name-specifier
471 /// that was computed at template definition time.
473 /// If ErrorRecoveryLookup is true, then this call is used to improve error
474 /// recovery. This means that it should not emit diagnostics, it should
475 /// just return true on failure. It also means it should only return a valid
476 /// scope if it *knows* that the result is correct. It should not return in a
477 /// dependent context, for example. Nor will it extend \p SS with the scope
479 bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
480 bool EnteringContext, CXXScopeSpec &SS,
481 NamedDecl *ScopeLookupResult,
482 bool ErrorRecoveryLookup,
483 bool *IsCorrectedToColon,
484 bool OnlyNamespace) {
485 if (IdInfo.Identifier->isEditorPlaceholder())
487 LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
488 OnlyNamespace ? LookupNamespaceName
489 : LookupNestedNameSpecifierName);
490 QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
492 // Determine where to perform name lookup
493 DeclContext *LookupCtx = nullptr;
494 bool isDependent = false;
495 if (IsCorrectedToColon)
496 *IsCorrectedToColon = false;
497 if (!ObjectType.isNull()) {
498 // This nested-name-specifier occurs in a member access expression, e.g.,
499 // x->B::f, and we are looking into the type of the object.
500 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
501 LookupCtx = computeDeclContext(ObjectType);
502 isDependent = ObjectType->isDependentType();
503 } else if (SS.isSet()) {
504 // This nested-name-specifier occurs after another nested-name-specifier,
505 // so look into the context associated with the prior nested-name-specifier.
506 LookupCtx = computeDeclContext(SS, EnteringContext);
507 isDependent = isDependentScopeSpecifier(SS);
508 Found.setContextRange(SS.getRange());
511 bool ObjectTypeSearchedInScope = false;
513 // Perform "qualified" name lookup into the declaration context we
514 // computed, which is either the type of the base of a member access
515 // expression or the declaration context associated with a prior
516 // nested-name-specifier.
518 // The declaration context must be complete.
519 if (!LookupCtx->isDependentContext() &&
520 RequireCompleteDeclContext(SS, LookupCtx))
523 LookupQualifiedName(Found, LookupCtx);
525 if (!ObjectType.isNull() && Found.empty()) {
526 // C++ [basic.lookup.classref]p4:
527 // If the id-expression in a class member access is a qualified-id of
530 // class-name-or-namespace-name::...
532 // the class-name-or-namespace-name following the . or -> operator is
533 // looked up both in the context of the entire postfix-expression and in
534 // the scope of the class of the object expression. If the name is found
535 // only in the scope of the class of the object expression, the name
536 // shall refer to a class-name. If the name is found only in the
537 // context of the entire postfix-expression, the name shall refer to a
538 // class-name or namespace-name. [...]
540 // Qualified name lookup into a class will not find a namespace-name,
541 // so we do not need to diagnose that case specifically. However,
542 // this qualified name lookup may find nothing. In that case, perform
543 // unqualified name lookup in the given scope (if available) or
544 // reconstruct the result from when name lookup was performed at template
547 LookupName(Found, S);
548 else if (ScopeLookupResult)
549 Found.addDecl(ScopeLookupResult);
551 ObjectTypeSearchedInScope = true;
553 } else if (!isDependent) {
554 // Perform unqualified name lookup in the current scope.
555 LookupName(Found, S);
558 if (Found.isAmbiguous())
561 // If we performed lookup into a dependent context and did not find anything,
562 // that's fine: just build a dependent nested-name-specifier.
563 if (Found.empty() && isDependent &&
564 !(LookupCtx && LookupCtx->isRecord() &&
565 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
566 !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {
567 // Don't speculate if we're just trying to improve error recovery.
568 if (ErrorRecoveryLookup)
571 // We were not able to compute the declaration context for a dependent
572 // base object type or prior nested-name-specifier, so this
573 // nested-name-specifier refers to an unknown specialization. Just build
574 // a dependent nested-name-specifier.
575 SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc, IdInfo.CCLoc);
579 if (Found.empty() && !ErrorRecoveryLookup) {
580 // If identifier is not found as class-name-or-namespace-name, but is found
581 // as other entity, don't look for typos.
582 LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
584 LookupQualifiedName(R, LookupCtx);
585 else if (S && !isDependent)
588 // Don't diagnose problems with this speculative lookup.
589 R.suppressDiagnostics();
590 // The identifier is found in ordinary lookup. If correction to colon is
591 // allowed, suggest replacement to ':'.
592 if (IsCorrectedToColon) {
593 *IsCorrectedToColon = true;
594 Diag(IdInfo.CCLoc, diag::err_nested_name_spec_is_not_class)
595 << IdInfo.Identifier << getLangOpts().CPlusPlus
596 << FixItHint::CreateReplacement(IdInfo.CCLoc, ":");
597 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
598 Diag(ND->getLocation(), diag::note_declared_at);
601 // Replacement '::' -> ':' is not allowed, just issue respective error.
602 Diag(R.getNameLoc(), OnlyNamespace
603 ? unsigned(diag::err_expected_namespace_name)
604 : unsigned(diag::err_expected_class_or_namespace))
605 << IdInfo.Identifier << getLangOpts().CPlusPlus;
606 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
607 Diag(ND->getLocation(), diag::note_entity_declared_at)
608 << IdInfo.Identifier;
613 if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) {
614 // We haven't found anything, and we're not recovering from a
615 // different kind of error, so look for typos.
616 DeclarationName Name = Found.getLookupName();
618 if (TypoCorrection Corrected = CorrectTypo(
619 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
620 llvm::make_unique<NestedNameSpecifierValidatorCCC>(*this),
621 CTK_ErrorRecovery, LookupCtx, EnteringContext)) {
623 bool DroppedSpecifier =
624 Corrected.WillReplaceSpecifier() &&
625 Name.getAsString() == Corrected.getAsString(getLangOpts());
626 if (DroppedSpecifier)
628 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
629 << Name << LookupCtx << DroppedSpecifier
632 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
635 if (Corrected.getCorrectionSpecifier())
636 SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
637 SourceRange(Found.getNameLoc()));
639 if (NamedDecl *ND = Corrected.getFoundDecl())
641 Found.setLookupName(Corrected.getCorrection());
643 Found.setLookupName(IdInfo.Identifier);
648 Found.isSingleResult() ? Found.getRepresentativeDecl() : nullptr;
649 bool IsExtension = false;
650 bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);
651 if (!AcceptSpec && IsExtension) {
653 Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);
656 if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
657 !getLangOpts().CPlusPlus11) {
658 // C++03 [basic.lookup.classref]p4:
659 // [...] If the name is found in both contexts, the
660 // class-name-or-namespace-name shall refer to the same entity.
662 // We already found the name in the scope of the object. Now, look
663 // into the current scope (the scope of the postfix-expression) to
664 // see if we can find the same name there. As above, if there is no
665 // scope, reconstruct the result from the template instantiation itself.
667 // Note that C++11 does *not* perform this redundant lookup.
668 NamedDecl *OuterDecl;
670 LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
671 LookupNestedNameSpecifierName);
672 LookupName(FoundOuter, S);
673 OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
675 OuterDecl = ScopeLookupResult;
677 if (isAcceptableNestedNameSpecifier(OuterDecl) &&
678 OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
679 (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
680 !Context.hasSameType(
681 Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
682 Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
683 if (ErrorRecoveryLookup)
686 Diag(IdInfo.IdentifierLoc,
687 diag::err_nested_name_member_ref_lookup_ambiguous)
688 << IdInfo.Identifier;
689 Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
691 Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
693 // Fall through so that we'll pick the name we found in the object
694 // type, since that's probably what the user wanted anyway.
698 if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))
699 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
701 // If we're just performing this lookup for error-recovery purposes,
702 // don't extend the nested-name-specifier. Just return now.
703 if (ErrorRecoveryLookup)
706 // The use of a nested name specifier may trigger deprecation warnings.
707 DiagnoseUseOfDecl(SD, IdInfo.CCLoc);
709 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
710 SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);
714 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
715 SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);
720 Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl()));
722 if (isa<InjectedClassNameType>(T)) {
723 InjectedClassNameTypeLoc InjectedTL
724 = TLB.push<InjectedClassNameTypeLoc>(T);
725 InjectedTL.setNameLoc(IdInfo.IdentifierLoc);
726 } else if (isa<RecordType>(T)) {
727 RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
728 RecordTL.setNameLoc(IdInfo.IdentifierLoc);
729 } else if (isa<TypedefType>(T)) {
730 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
731 TypedefTL.setNameLoc(IdInfo.IdentifierLoc);
732 } else if (isa<EnumType>(T)) {
733 EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
734 EnumTL.setNameLoc(IdInfo.IdentifierLoc);
735 } else if (isa<TemplateTypeParmType>(T)) {
736 TemplateTypeParmTypeLoc TemplateTypeTL
737 = TLB.push<TemplateTypeParmTypeLoc>(T);
738 TemplateTypeTL.setNameLoc(IdInfo.IdentifierLoc);
739 } else if (isa<UnresolvedUsingType>(T)) {
740 UnresolvedUsingTypeLoc UnresolvedTL
741 = TLB.push<UnresolvedUsingTypeLoc>(T);
742 UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc);
743 } else if (isa<SubstTemplateTypeParmType>(T)) {
744 SubstTemplateTypeParmTypeLoc TL
745 = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
746 TL.setNameLoc(IdInfo.IdentifierLoc);
747 } else if (isa<SubstTemplateTypeParmPackType>(T)) {
748 SubstTemplateTypeParmPackTypeLoc TL
749 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
750 TL.setNameLoc(IdInfo.IdentifierLoc);
752 llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
755 if (T->isEnumeralType())
756 Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
758 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
763 // Otherwise, we have an error case. If we don't want diagnostics, just
764 // return an error now.
765 if (ErrorRecoveryLookup)
768 // If we didn't find anything during our lookup, try again with
769 // ordinary name lookup, which can help us produce better error
772 Found.clear(LookupOrdinaryName);
773 LookupName(Found, S);
776 // In Microsoft mode, if we are within a templated function and we can't
777 // resolve Identifier, then extend the SS with Identifier. This will have
778 // the effect of resolving Identifier during template instantiation.
779 // The goal is to be able to resolve a function call whose
780 // nested-name-specifier is located inside a dependent base class.
785 // static void foo2() { }
787 // template <class T> class A { public: typedef C D; };
789 // template <class T> class B : public A<T> {
791 // void foo() { D::foo2(); }
793 if (getLangOpts().MSVCCompat) {
794 DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
795 if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
796 CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());
797 if (ContainingClass && ContainingClass->hasAnyDependentBases()) {
798 Diag(IdInfo.IdentifierLoc,
799 diag::ext_undeclared_unqual_id_with_dependent_base)
800 << IdInfo.Identifier << ContainingClass;
801 SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc,
808 if (!Found.empty()) {
809 if (TypeDecl *TD = Found.getAsSingle<TypeDecl>())
810 Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
811 << Context.getTypeDeclType(TD) << getLangOpts().CPlusPlus;
813 Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
814 << IdInfo.Identifier << getLangOpts().CPlusPlus;
815 if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
816 Diag(ND->getLocation(), diag::note_entity_declared_at)
817 << IdInfo.Identifier;
819 } else if (SS.isSet())
820 Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
821 << LookupCtx << SS.getRange();
823 Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
824 << IdInfo.Identifier;
829 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
830 bool EnteringContext, CXXScopeSpec &SS,
831 bool ErrorRecoveryLookup,
832 bool *IsCorrectedToColon,
833 bool OnlyNamespace) {
837 return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
838 /*ScopeLookupResult=*/nullptr, false,
839 IsCorrectedToColon, OnlyNamespace);
842 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
844 SourceLocation ColonColonLoc) {
845 if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
848 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
850 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
854 if (!T->isDependentType() && !T->getAs<TagType>()) {
855 Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)
856 << T << getLangOpts().CPlusPlus;
861 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
862 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
863 SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
868 /// IsInvalidUnlessNestedName - This method is used for error recovery
869 /// purposes to determine whether the specified identifier is only valid as
870 /// a nested name specifier, for example a namespace name. It is
871 /// conservatively correct to always return false from this method.
873 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
874 bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
875 NestedNameSpecInfo &IdInfo,
876 bool EnteringContext) {
880 return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
881 /*ScopeLookupResult=*/nullptr, true);
884 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
886 SourceLocation TemplateKWLoc,
888 SourceLocation TemplateNameLoc,
889 SourceLocation LAngleLoc,
890 ASTTemplateArgsPtr TemplateArgsIn,
891 SourceLocation RAngleLoc,
892 SourceLocation CCLoc,
893 bool EnteringContext) {
897 // Translate the parser's template argument list in our AST format.
898 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
899 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
901 DependentTemplateName *DTN = Template.get().getAsDependentTemplateName();
902 if (DTN && DTN->isIdentifier()) {
903 // Handle a dependent template specialization for which we cannot resolve
904 // the template name.
905 assert(DTN->getQualifier() == SS.getScopeRep());
906 QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
908 DTN->getIdentifier(),
911 // Create source-location information for this type.
912 TypeLocBuilder Builder;
913 DependentTemplateSpecializationTypeLoc SpecTL
914 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
915 SpecTL.setElaboratedKeywordLoc(SourceLocation());
916 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
917 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
918 SpecTL.setTemplateNameLoc(TemplateNameLoc);
919 SpecTL.setLAngleLoc(LAngleLoc);
920 SpecTL.setRAngleLoc(RAngleLoc);
921 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
922 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
924 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
929 TemplateDecl *TD = Template.get().getAsTemplateDecl();
930 if (Template.get().getAsOverloadedTemplate() || DTN ||
931 isa<FunctionTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)) {
932 SourceRange R(TemplateNameLoc, RAngleLoc);
933 if (SS.getRange().isValid())
934 R.setBegin(SS.getRange().getBegin());
936 Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
937 << (TD && isa<VarTemplateDecl>(TD)) << Template.get() << R;
938 NoteAllFoundTemplates(Template.get());
942 // We were able to resolve the template name to an actual template.
943 // Build an appropriate nested-name-specifier.
945 CheckTemplateIdType(Template.get(), TemplateNameLoc, TemplateArgs);
949 // Alias template specializations can produce types which are not valid
950 // nested name specifiers.
951 if (!T->isDependentType() && !T->getAs<TagType>()) {
952 Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
953 NoteAllFoundTemplates(Template.get());
957 // Provide source-location information for the template specialization type.
958 TypeLocBuilder Builder;
959 TemplateSpecializationTypeLoc SpecTL
960 = Builder.push<TemplateSpecializationTypeLoc>(T);
961 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
962 SpecTL.setTemplateNameLoc(TemplateNameLoc);
963 SpecTL.setLAngleLoc(LAngleLoc);
964 SpecTL.setRAngleLoc(RAngleLoc);
965 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
966 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
969 SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
975 /// A structure that stores a nested-name-specifier annotation,
976 /// including both the nested-name-specifier
977 struct NestedNameSpecifierAnnotation {
978 NestedNameSpecifier *NNS;
982 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
983 if (SS.isEmpty() || SS.isInvalid())
986 void *Mem = Context.Allocate(
987 (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
988 alignof(NestedNameSpecifierAnnotation));
989 NestedNameSpecifierAnnotation *Annotation
990 = new (Mem) NestedNameSpecifierAnnotation;
991 Annotation->NNS = SS.getScopeRep();
992 memcpy(Annotation + 1, SS.location_data(), SS.location_size());
996 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
997 SourceRange AnnotationRange,
999 if (!AnnotationPtr) {
1000 SS.SetInvalid(AnnotationRange);
1004 NestedNameSpecifierAnnotation *Annotation
1005 = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
1006 SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
1009 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1010 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1012 // Don't enter a declarator context when the current context is an Objective-C
1014 if (isa<ObjCContainerDecl>(CurContext) || isa<ObjCMethodDecl>(CurContext))
1017 NestedNameSpecifier *Qualifier = SS.getScopeRep();
1019 // There are only two places a well-formed program may qualify a
1020 // declarator: first, when defining a namespace or class member
1021 // out-of-line, and second, when naming an explicitly-qualified
1022 // friend function. The latter case is governed by
1023 // C++03 [basic.lookup.unqual]p10:
1024 // In a friend declaration naming a member function, a name used
1025 // in the function declarator and not part of a template-argument
1026 // in a template-id is first looked up in the scope of the member
1027 // function's class. If it is not found, or if the name is part of
1028 // a template-argument in a template-id, the look up is as
1029 // described for unqualified names in the definition of the class
1030 // granting friendship.
1031 // i.e. we don't push a scope unless it's a class member.
1033 switch (Qualifier->getKind()) {
1034 case NestedNameSpecifier::Global:
1035 case NestedNameSpecifier::Namespace:
1036 case NestedNameSpecifier::NamespaceAlias:
1037 // These are always namespace scopes. We never want to enter a
1038 // namespace scope from anything but a file context.
1039 return CurContext->getRedeclContext()->isFileContext();
1041 case NestedNameSpecifier::Identifier:
1042 case NestedNameSpecifier::TypeSpec:
1043 case NestedNameSpecifier::TypeSpecWithTemplate:
1044 case NestedNameSpecifier::Super:
1045 // These are never namespace scopes.
1049 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1052 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
1053 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
1054 /// After this method is called, according to [C++ 3.4.3p3], names should be
1055 /// looked up in the declarator-id's scope, until the declarator is parsed and
1056 /// ActOnCXXExitDeclaratorScope is called.
1057 /// The 'SS' should be a non-empty valid CXXScopeSpec.
1058 bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1059 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1061 if (SS.isInvalid()) return true;
1063 DeclContext *DC = computeDeclContext(SS, true);
1064 if (!DC) return true;
1066 // Before we enter a declarator's context, we need to make sure that
1067 // it is a complete declaration context.
1068 if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
1071 EnterDeclaratorContext(S, DC);
1073 // Rebuild the nested name specifier for the new scope.
1074 if (DC->isDependentContext())
1075 RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1080 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
1081 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
1082 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
1083 /// Used to indicate that names should revert to being looked up in the
1085 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1086 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1089 assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1090 "exiting declarator scope we never really entered");
1091 ExitDeclaratorContext(S);