Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaCXXScopeSpec.cpp
35233 views
//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements C++ semantic analysis for scope specifiers.9//10//===----------------------------------------------------------------------===//1112#include "TypeLocBuilder.h"13#include "clang/AST/ASTContext.h"14#include "clang/AST/DeclTemplate.h"15#include "clang/AST/ExprCXX.h"16#include "clang/AST/NestedNameSpecifier.h"17#include "clang/Basic/PartialDiagnostic.h"18#include "clang/Sema/DeclSpec.h"19#include "clang/Sema/Lookup.h"20#include "clang/Sema/SemaInternal.h"21#include "clang/Sema/Template.h"22#include "llvm/ADT/STLExtras.h"23using namespace clang;2425/// Find the current instantiation that associated with the given type.26static CXXRecordDecl *getCurrentInstantiationOf(QualType T,27DeclContext *CurContext) {28if (T.isNull())29return nullptr;3031const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();32if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {33CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());34if (!Record->isDependentContext() ||35Record->isCurrentInstantiation(CurContext))36return Record;3738return nullptr;39} else if (isa<InjectedClassNameType>(Ty))40return cast<InjectedClassNameType>(Ty)->getDecl();41else42return nullptr;43}4445DeclContext *Sema::computeDeclContext(QualType T) {46if (!T->isDependentType())47if (const TagType *Tag = T->getAs<TagType>())48return Tag->getDecl();4950return ::getCurrentInstantiationOf(T, CurContext);51}5253DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,54bool EnteringContext) {55if (!SS.isSet() || SS.isInvalid())56return nullptr;5758NestedNameSpecifier *NNS = SS.getScopeRep();59if (NNS->isDependent()) {60// If this nested-name-specifier refers to the current61// instantiation, return its DeclContext.62if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))63return Record;6465if (EnteringContext) {66const Type *NNSType = NNS->getAsType();67if (!NNSType) {68return nullptr;69}7071// Look through type alias templates, per C++0x [temp.dep.type]p1.72NNSType = Context.getCanonicalType(NNSType);73if (const TemplateSpecializationType *SpecType74= NNSType->getAs<TemplateSpecializationType>()) {75// We are entering the context of the nested name specifier, so try to76// match the nested name specifier to either a primary class template77// or a class template partial specialization.78if (ClassTemplateDecl *ClassTemplate79= dyn_cast_or_null<ClassTemplateDecl>(80SpecType->getTemplateName().getAsTemplateDecl())) {81QualType ContextType =82Context.getCanonicalType(QualType(SpecType, 0));8384// FIXME: The fallback on the search of partial85// specialization using ContextType should be eventually removed since86// it doesn't handle the case of constrained template parameters87// correctly. Currently removing this fallback would change the88// diagnostic output for invalid code in a number of tests.89ClassTemplatePartialSpecializationDecl *PartialSpec = nullptr;90ArrayRef<TemplateParameterList *> TemplateParamLists =91SS.getTemplateParamLists();92if (!TemplateParamLists.empty()) {93unsigned Depth = ClassTemplate->getTemplateParameters()->getDepth();94auto L = find_if(TemplateParamLists,95[Depth](TemplateParameterList *TPL) {96return TPL->getDepth() == Depth;97});98if (L != TemplateParamLists.end()) {99void *Pos = nullptr;100PartialSpec = ClassTemplate->findPartialSpecialization(101SpecType->template_arguments(), *L, Pos);102}103} else {104PartialSpec = ClassTemplate->findPartialSpecialization(ContextType);105}106107if (PartialSpec) {108// A declaration of the partial specialization must be visible.109// We can always recover here, because this only happens when we're110// entering the context, and that can't happen in a SFINAE context.111assert(!isSFINAEContext() && "partial specialization scope "112"specifier in SFINAE context?");113if (PartialSpec->hasDefinition() &&114!hasReachableDefinition(PartialSpec))115diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,116MissingImportKind::PartialSpecialization,117true);118return PartialSpec;119}120121// If the type of the nested name specifier is the same as the122// injected class name of the named class template, we're entering123// into that class template definition.124QualType Injected =125ClassTemplate->getInjectedClassNameSpecialization();126if (Context.hasSameType(Injected, ContextType))127return ClassTemplate->getTemplatedDecl();128}129} else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {130// The nested name specifier refers to a member of a class template.131return RecordT->getDecl();132}133}134135return nullptr;136}137138switch (NNS->getKind()) {139case NestedNameSpecifier::Identifier:140llvm_unreachable("Dependent nested-name-specifier has no DeclContext");141142case NestedNameSpecifier::Namespace:143return NNS->getAsNamespace();144145case NestedNameSpecifier::NamespaceAlias:146return NNS->getAsNamespaceAlias()->getNamespace();147148case NestedNameSpecifier::TypeSpec:149case NestedNameSpecifier::TypeSpecWithTemplate: {150const TagType *Tag = NNS->getAsType()->getAs<TagType>();151assert(Tag && "Non-tag type in nested-name-specifier");152return Tag->getDecl();153}154155case NestedNameSpecifier::Global:156return Context.getTranslationUnitDecl();157158case NestedNameSpecifier::Super:159return NNS->getAsRecordDecl();160}161162llvm_unreachable("Invalid NestedNameSpecifier::Kind!");163}164165bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {166if (!SS.isSet() || SS.isInvalid())167return false;168169return SS.getScopeRep()->isDependent();170}171172CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {173assert(getLangOpts().CPlusPlus && "Only callable in C++");174assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");175176if (!NNS->getAsType())177return nullptr;178179QualType T = QualType(NNS->getAsType(), 0);180return ::getCurrentInstantiationOf(T, CurContext);181}182183/// Require that the context specified by SS be complete.184///185/// If SS refers to a type, this routine checks whether the type is186/// complete enough (or can be made complete enough) for name lookup187/// into the DeclContext. A type that is not yet completed can be188/// considered "complete enough" if it is a class/struct/union/enum189/// that is currently being defined. Or, if we have a type that names190/// a class template specialization that is not a complete type, we191/// will attempt to instantiate that class template.192bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,193DeclContext *DC) {194assert(DC && "given null context");195196TagDecl *tag = dyn_cast<TagDecl>(DC);197198// If this is a dependent type, then we consider it complete.199// FIXME: This is wrong; we should require a (visible) definition to200// exist in this case too.201if (!tag || tag->isDependentContext())202return false;203204// Grab the tag definition, if there is one.205QualType type = Context.getTypeDeclType(tag);206tag = type->getAsTagDecl();207208// If we're currently defining this type, then lookup into the209// type is okay: don't complain that it isn't complete yet.210if (tag->isBeingDefined())211return false;212213SourceLocation loc = SS.getLastQualifierNameLoc();214if (loc.isInvalid()) loc = SS.getRange().getBegin();215216// The type must be complete.217if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,218SS.getRange())) {219SS.SetInvalid(SS.getRange());220return true;221}222223if (auto *EnumD = dyn_cast<EnumDecl>(tag))224// Fixed enum types and scoped enum instantiations are complete, but they225// aren't valid as scopes until we see or instantiate their definition.226return RequireCompleteEnumDecl(EnumD, loc, &SS);227228return false;229}230231/// Require that the EnumDecl is completed with its enumerators defined or232/// instantiated. SS, if provided, is the ScopeRef parsed.233///234bool Sema::RequireCompleteEnumDecl(EnumDecl *EnumD, SourceLocation L,235CXXScopeSpec *SS) {236if (EnumD->isCompleteDefinition()) {237// If we know about the definition but it is not visible, complain.238NamedDecl *SuggestedDef = nullptr;239if (!hasReachableDefinition(EnumD, &SuggestedDef,240/*OnlyNeedComplete*/ false)) {241// If the user is going to see an error here, recover by making the242// definition visible.243bool TreatAsComplete = !isSFINAEContext();244diagnoseMissingImport(L, SuggestedDef, MissingImportKind::Definition,245/*Recover*/ TreatAsComplete);246return !TreatAsComplete;247}248return false;249}250251// Try to instantiate the definition, if this is a specialization of an252// enumeration temploid.253if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {254MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();255if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {256if (InstantiateEnum(L, EnumD, Pattern,257getTemplateInstantiationArgs(EnumD),258TSK_ImplicitInstantiation)) {259if (SS)260SS->SetInvalid(SS->getRange());261return true;262}263return false;264}265}266267if (SS) {268Diag(L, diag::err_incomplete_nested_name_spec)269<< QualType(EnumD->getTypeForDecl(), 0) << SS->getRange();270SS->SetInvalid(SS->getRange());271} else {272Diag(L, diag::err_incomplete_enum) << QualType(EnumD->getTypeForDecl(), 0);273Diag(EnumD->getLocation(), diag::note_declared_at);274}275276return true;277}278279bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,280CXXScopeSpec &SS) {281SS.MakeGlobal(Context, CCLoc);282return false;283}284285bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,286SourceLocation ColonColonLoc,287CXXScopeSpec &SS) {288if (getCurLambda()) {289Diag(SuperLoc, diag::err_super_in_lambda_unsupported);290return true;291}292293CXXRecordDecl *RD = nullptr;294for (Scope *S = getCurScope(); S; S = S->getParent()) {295if (S->isFunctionScope()) {296if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))297RD = MD->getParent();298break;299}300if (S->isClassScope()) {301RD = cast<CXXRecordDecl>(S->getEntity());302break;303}304}305306if (!RD) {307Diag(SuperLoc, diag::err_invalid_super_scope);308return true;309} else if (RD->getNumBases() == 0) {310Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();311return true;312}313314SS.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);315return false;316}317318bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,319bool *IsExtension) {320if (!SD)321return false;322323SD = SD->getUnderlyingDecl();324325// Namespace and namespace aliases are fine.326if (isa<NamespaceDecl>(SD))327return true;328329if (!isa<TypeDecl>(SD))330return false;331332// Determine whether we have a class (or, in C++11, an enum) or333// a typedef thereof. If so, build the nested-name-specifier.334QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));335if (T->isDependentType())336return true;337if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {338if (TD->getUnderlyingType()->isRecordType())339return true;340if (TD->getUnderlyingType()->isEnumeralType()) {341if (Context.getLangOpts().CPlusPlus11)342return true;343if (IsExtension)344*IsExtension = true;345}346} else if (isa<RecordDecl>(SD)) {347return true;348} else if (isa<EnumDecl>(SD)) {349if (Context.getLangOpts().CPlusPlus11)350return true;351if (IsExtension)352*IsExtension = true;353}354355return false;356}357358NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {359if (!S || !NNS)360return nullptr;361362while (NNS->getPrefix())363NNS = NNS->getPrefix();364365if (NNS->getKind() != NestedNameSpecifier::Identifier)366return nullptr;367368LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),369LookupNestedNameSpecifierName);370LookupName(Found, S);371assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");372373if (!Found.isSingleResult())374return nullptr;375376NamedDecl *Result = Found.getFoundDecl();377if (isAcceptableNestedNameSpecifier(Result))378return Result;379380return nullptr;381}382383namespace {384385// Callback to only accept typo corrections that can be a valid C++ member386// initializer: either a non-static field member or a base class.387class NestedNameSpecifierValidatorCCC final388: public CorrectionCandidateCallback {389public:390explicit NestedNameSpecifierValidatorCCC(Sema &SRef)391: SRef(SRef) {}392393bool ValidateCandidate(const TypoCorrection &candidate) override {394return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());395}396397std::unique_ptr<CorrectionCandidateCallback> clone() override {398return std::make_unique<NestedNameSpecifierValidatorCCC>(*this);399}400401private:402Sema &SRef;403};404405}406407bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,408bool EnteringContext, CXXScopeSpec &SS,409NamedDecl *ScopeLookupResult,410bool ErrorRecoveryLookup,411bool *IsCorrectedToColon,412bool OnlyNamespace) {413if (IdInfo.Identifier->isEditorPlaceholder())414return true;415LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,416OnlyNamespace ? LookupNamespaceName417: LookupNestedNameSpecifierName);418QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);419420// Determine where to perform name lookup421DeclContext *LookupCtx = nullptr;422bool isDependent = false;423if (IsCorrectedToColon)424*IsCorrectedToColon = false;425if (!ObjectType.isNull()) {426// This nested-name-specifier occurs in a member access expression, e.g.,427// x->B::f, and we are looking into the type of the object.428assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");429LookupCtx = computeDeclContext(ObjectType);430isDependent = ObjectType->isDependentType();431} else if (SS.isSet()) {432// This nested-name-specifier occurs after another nested-name-specifier,433// so look into the context associated with the prior nested-name-specifier.434LookupCtx = computeDeclContext(SS, EnteringContext);435isDependent = isDependentScopeSpecifier(SS);436Found.setContextRange(SS.getRange());437}438439bool ObjectTypeSearchedInScope = false;440if (LookupCtx) {441// Perform "qualified" name lookup into the declaration context we442// computed, which is either the type of the base of a member access443// expression or the declaration context associated with a prior444// nested-name-specifier.445446// The declaration context must be complete.447if (!LookupCtx->isDependentContext() &&448RequireCompleteDeclContext(SS, LookupCtx))449return true;450451LookupQualifiedName(Found, LookupCtx);452453if (!ObjectType.isNull() && Found.empty()) {454// C++ [basic.lookup.classref]p4:455// If the id-expression in a class member access is a qualified-id of456// the form457//458// class-name-or-namespace-name::...459//460// the class-name-or-namespace-name following the . or -> operator is461// looked up both in the context of the entire postfix-expression and in462// the scope of the class of the object expression. If the name is found463// only in the scope of the class of the object expression, the name464// shall refer to a class-name. If the name is found only in the465// context of the entire postfix-expression, the name shall refer to a466// class-name or namespace-name. [...]467//468// Qualified name lookup into a class will not find a namespace-name,469// so we do not need to diagnose that case specifically. However,470// this qualified name lookup may find nothing. In that case, perform471// unqualified name lookup in the given scope (if available) or472// reconstruct the result from when name lookup was performed at template473// definition time.474if (S)475LookupName(Found, S);476else if (ScopeLookupResult)477Found.addDecl(ScopeLookupResult);478479ObjectTypeSearchedInScope = true;480}481} else if (!isDependent) {482// Perform unqualified name lookup in the current scope.483LookupName(Found, S);484}485486if (Found.isAmbiguous())487return true;488489// If we performed lookup into a dependent context and did not find anything,490// that's fine: just build a dependent nested-name-specifier.491if (Found.empty() && isDependent &&492!(LookupCtx && LookupCtx->isRecord() &&493(!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||494!cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {495// Don't speculate if we're just trying to improve error recovery.496if (ErrorRecoveryLookup)497return true;498499// We were not able to compute the declaration context for a dependent500// base object type or prior nested-name-specifier, so this501// nested-name-specifier refers to an unknown specialization. Just build502// a dependent nested-name-specifier.503SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc, IdInfo.CCLoc);504return false;505}506507if (Found.empty() && !ErrorRecoveryLookup) {508// If identifier is not found as class-name-or-namespace-name, but is found509// as other entity, don't look for typos.510LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);511if (LookupCtx)512LookupQualifiedName(R, LookupCtx);513else if (S && !isDependent)514LookupName(R, S);515if (!R.empty()) {516// Don't diagnose problems with this speculative lookup.517R.suppressDiagnostics();518// The identifier is found in ordinary lookup. If correction to colon is519// allowed, suggest replacement to ':'.520if (IsCorrectedToColon) {521*IsCorrectedToColon = true;522Diag(IdInfo.CCLoc, diag::err_nested_name_spec_is_not_class)523<< IdInfo.Identifier << getLangOpts().CPlusPlus524<< FixItHint::CreateReplacement(IdInfo.CCLoc, ":");525if (NamedDecl *ND = R.getAsSingle<NamedDecl>())526Diag(ND->getLocation(), diag::note_declared_at);527return true;528}529// Replacement '::' -> ':' is not allowed, just issue respective error.530Diag(R.getNameLoc(), OnlyNamespace531? unsigned(diag::err_expected_namespace_name)532: unsigned(diag::err_expected_class_or_namespace))533<< IdInfo.Identifier << getLangOpts().CPlusPlus;534if (NamedDecl *ND = R.getAsSingle<NamedDecl>())535Diag(ND->getLocation(), diag::note_entity_declared_at)536<< IdInfo.Identifier;537return true;538}539}540541if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) {542// We haven't found anything, and we're not recovering from a543// different kind of error, so look for typos.544DeclarationName Name = Found.getLookupName();545Found.clear();546NestedNameSpecifierValidatorCCC CCC(*this);547if (TypoCorrection Corrected = CorrectTypo(548Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, CCC,549CTK_ErrorRecovery, LookupCtx, EnteringContext)) {550if (LookupCtx) {551bool DroppedSpecifier =552Corrected.WillReplaceSpecifier() &&553Name.getAsString() == Corrected.getAsString(getLangOpts());554if (DroppedSpecifier)555SS.clear();556diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)557<< Name << LookupCtx << DroppedSpecifier558<< SS.getRange());559} else560diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)561<< Name);562563if (Corrected.getCorrectionSpecifier())564SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),565SourceRange(Found.getNameLoc()));566567if (NamedDecl *ND = Corrected.getFoundDecl())568Found.addDecl(ND);569Found.setLookupName(Corrected.getCorrection());570} else {571Found.setLookupName(IdInfo.Identifier);572}573}574575NamedDecl *SD =576Found.isSingleResult() ? Found.getRepresentativeDecl() : nullptr;577bool IsExtension = false;578bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);579if (!AcceptSpec && IsExtension) {580AcceptSpec = true;581Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);582}583if (AcceptSpec) {584if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&585!getLangOpts().CPlusPlus11) {586// C++03 [basic.lookup.classref]p4:587// [...] If the name is found in both contexts, the588// class-name-or-namespace-name shall refer to the same entity.589//590// We already found the name in the scope of the object. Now, look591// into the current scope (the scope of the postfix-expression) to592// see if we can find the same name there. As above, if there is no593// scope, reconstruct the result from the template instantiation itself.594//595// Note that C++11 does *not* perform this redundant lookup.596NamedDecl *OuterDecl;597if (S) {598LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,599LookupNestedNameSpecifierName);600LookupName(FoundOuter, S);601OuterDecl = FoundOuter.getAsSingle<NamedDecl>();602} else603OuterDecl = ScopeLookupResult;604605if (isAcceptableNestedNameSpecifier(OuterDecl) &&606OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&607(!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||608!Context.hasSameType(609Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),610Context.getTypeDeclType(cast<TypeDecl>(SD))))) {611if (ErrorRecoveryLookup)612return true;613614Diag(IdInfo.IdentifierLoc,615diag::err_nested_name_member_ref_lookup_ambiguous)616<< IdInfo.Identifier;617Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)618<< ObjectType;619Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);620621// Fall through so that we'll pick the name we found in the object622// type, since that's probably what the user wanted anyway.623}624}625626if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))627MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);628629// If we're just performing this lookup for error-recovery purposes,630// don't extend the nested-name-specifier. Just return now.631if (ErrorRecoveryLookup)632return false;633634// The use of a nested name specifier may trigger deprecation warnings.635DiagnoseUseOfDecl(SD, IdInfo.CCLoc);636637if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {638SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);639return false;640}641642if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {643SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);644return false;645}646647QualType T =648Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl()));649650if (T->isEnumeralType())651Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);652653TypeLocBuilder TLB;654if (const auto *USD = dyn_cast<UsingShadowDecl>(SD)) {655T = Context.getUsingType(USD, T);656TLB.pushTypeSpec(T).setNameLoc(IdInfo.IdentifierLoc);657} else if (isa<InjectedClassNameType>(T)) {658InjectedClassNameTypeLoc InjectedTL659= TLB.push<InjectedClassNameTypeLoc>(T);660InjectedTL.setNameLoc(IdInfo.IdentifierLoc);661} else if (isa<RecordType>(T)) {662RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);663RecordTL.setNameLoc(IdInfo.IdentifierLoc);664} else if (isa<TypedefType>(T)) {665TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);666TypedefTL.setNameLoc(IdInfo.IdentifierLoc);667} else if (isa<EnumType>(T)) {668EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);669EnumTL.setNameLoc(IdInfo.IdentifierLoc);670} else if (isa<TemplateTypeParmType>(T)) {671TemplateTypeParmTypeLoc TemplateTypeTL672= TLB.push<TemplateTypeParmTypeLoc>(T);673TemplateTypeTL.setNameLoc(IdInfo.IdentifierLoc);674} else if (isa<UnresolvedUsingType>(T)) {675UnresolvedUsingTypeLoc UnresolvedTL676= TLB.push<UnresolvedUsingTypeLoc>(T);677UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc);678} else if (isa<SubstTemplateTypeParmType>(T)) {679SubstTemplateTypeParmTypeLoc TL680= TLB.push<SubstTemplateTypeParmTypeLoc>(T);681TL.setNameLoc(IdInfo.IdentifierLoc);682} else if (isa<SubstTemplateTypeParmPackType>(T)) {683SubstTemplateTypeParmPackTypeLoc TL684= TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);685TL.setNameLoc(IdInfo.IdentifierLoc);686} else {687llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");688}689690SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),691IdInfo.CCLoc);692return false;693}694695// Otherwise, we have an error case. If we don't want diagnostics, just696// return an error now.697if (ErrorRecoveryLookup)698return true;699700// If we didn't find anything during our lookup, try again with701// ordinary name lookup, which can help us produce better error702// messages.703if (Found.empty()) {704Found.clear(LookupOrdinaryName);705LookupName(Found, S);706}707708// In Microsoft mode, if we are within a templated function and we can't709// resolve Identifier, then extend the SS with Identifier. This will have710// the effect of resolving Identifier during template instantiation.711// The goal is to be able to resolve a function call whose712// nested-name-specifier is located inside a dependent base class.713// Example:714//715// class C {716// public:717// static void foo2() { }718// };719// template <class T> class A { public: typedef C D; };720//721// template <class T> class B : public A<T> {722// public:723// void foo() { D::foo2(); }724// };725if (getLangOpts().MSVCCompat) {726DeclContext *DC = LookupCtx ? LookupCtx : CurContext;727if (DC->isDependentContext() && DC->isFunctionOrMethod()) {728CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());729if (ContainingClass && ContainingClass->hasAnyDependentBases()) {730Diag(IdInfo.IdentifierLoc,731diag::ext_undeclared_unqual_id_with_dependent_base)732<< IdInfo.Identifier << ContainingClass;733// Fake up a nested-name-specifier that starts with the734// injected-class-name of the enclosing class.735QualType T = Context.getTypeDeclType(ContainingClass);736TypeLocBuilder TLB;737TLB.pushTrivial(Context, T, IdInfo.IdentifierLoc);738SS.Extend(Context, /*TemplateKWLoc=*/SourceLocation(),739TLB.getTypeLocInContext(Context, T), IdInfo.IdentifierLoc);740// Add the identifier to form a dependent name.741SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc,742IdInfo.CCLoc);743return false;744}745}746}747748if (!Found.empty()) {749if (TypeDecl *TD = Found.getAsSingle<TypeDecl>()) {750Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)751<< Context.getTypeDeclType(TD) << getLangOpts().CPlusPlus;752} else if (Found.getAsSingle<TemplateDecl>()) {753ParsedType SuggestedType;754DiagnoseUnknownTypeName(IdInfo.Identifier, IdInfo.IdentifierLoc, S, &SS,755SuggestedType);756} else {757Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)758<< IdInfo.Identifier << getLangOpts().CPlusPlus;759if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())760Diag(ND->getLocation(), diag::note_entity_declared_at)761<< IdInfo.Identifier;762}763} else if (SS.isSet())764Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier765<< LookupCtx << SS.getRange();766else767Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)768<< IdInfo.Identifier;769770return true;771}772773bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,774bool EnteringContext, CXXScopeSpec &SS,775bool *IsCorrectedToColon,776bool OnlyNamespace) {777if (SS.isInvalid())778return true;779780return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,781/*ScopeLookupResult=*/nullptr, false,782IsCorrectedToColon, OnlyNamespace);783}784785bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,786const DeclSpec &DS,787SourceLocation ColonColonLoc) {788if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)789return true;790791assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);792793QualType T = BuildDecltypeType(DS.getRepAsExpr());794if (T.isNull())795return true;796797if (!T->isDependentType() && !T->getAs<TagType>()) {798Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)799<< T << getLangOpts().CPlusPlus;800return true;801}802803TypeLocBuilder TLB;804DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);805DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());806DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());807SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),808ColonColonLoc);809return false;810}811812bool Sema::ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,813const DeclSpec &DS,814SourceLocation ColonColonLoc,815QualType Type) {816if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)817return true;818819assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing);820821if (Type.isNull())822return true;823824TypeLocBuilder TLB;825TLB.pushTrivial(getASTContext(),826cast<PackIndexingType>(Type.getTypePtr())->getPattern(),827DS.getBeginLoc());828PackIndexingTypeLoc PIT = TLB.push<PackIndexingTypeLoc>(Type);829PIT.setEllipsisLoc(DS.getEllipsisLoc());830SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, Type),831ColonColonLoc);832return false;833}834835bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,836NestedNameSpecInfo &IdInfo,837bool EnteringContext) {838if (SS.isInvalid())839return false;840841return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,842/*ScopeLookupResult=*/nullptr, true);843}844845bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,846CXXScopeSpec &SS,847SourceLocation TemplateKWLoc,848TemplateTy OpaqueTemplate,849SourceLocation TemplateNameLoc,850SourceLocation LAngleLoc,851ASTTemplateArgsPtr TemplateArgsIn,852SourceLocation RAngleLoc,853SourceLocation CCLoc,854bool EnteringContext) {855if (SS.isInvalid())856return true;857858TemplateName Template = OpaqueTemplate.get();859860// Translate the parser's template argument list in our AST format.861TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);862translateTemplateArguments(TemplateArgsIn, TemplateArgs);863864DependentTemplateName *DTN = Template.getAsDependentTemplateName();865if (DTN && DTN->isIdentifier()) {866// Handle a dependent template specialization for which we cannot resolve867// the template name.868assert(DTN->getQualifier() == SS.getScopeRep());869QualType T = Context.getDependentTemplateSpecializationType(870ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),871TemplateArgs.arguments());872873// Create source-location information for this type.874TypeLocBuilder Builder;875DependentTemplateSpecializationTypeLoc SpecTL876= Builder.push<DependentTemplateSpecializationTypeLoc>(T);877SpecTL.setElaboratedKeywordLoc(SourceLocation());878SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));879SpecTL.setTemplateKeywordLoc(TemplateKWLoc);880SpecTL.setTemplateNameLoc(TemplateNameLoc);881SpecTL.setLAngleLoc(LAngleLoc);882SpecTL.setRAngleLoc(RAngleLoc);883for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)884SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());885886SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),887CCLoc);888return false;889}890891// If we assumed an undeclared identifier was a template name, try to892// typo-correct it now.893if (Template.getAsAssumedTemplateName() &&894resolveAssumedTemplateNameAsType(S, Template, TemplateNameLoc))895return true;896897TemplateDecl *TD = Template.getAsTemplateDecl();898if (Template.getAsOverloadedTemplate() || DTN ||899isa<FunctionTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)) {900SourceRange R(TemplateNameLoc, RAngleLoc);901if (SS.getRange().isValid())902R.setBegin(SS.getRange().getBegin());903904Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)905<< isa_and_nonnull<VarTemplateDecl>(TD) << Template << R;906NoteAllFoundTemplates(Template);907return true;908}909910// We were able to resolve the template name to an actual template.911// Build an appropriate nested-name-specifier.912QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);913if (T.isNull())914return true;915916// Alias template specializations can produce types which are not valid917// nested name specifiers.918if (!T->isDependentType() && !T->getAs<TagType>()) {919Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;920NoteAllFoundTemplates(Template);921return true;922}923924// Provide source-location information for the template specialization type.925TypeLocBuilder Builder;926TemplateSpecializationTypeLoc SpecTL927= Builder.push<TemplateSpecializationTypeLoc>(T);928SpecTL.setTemplateKeywordLoc(TemplateKWLoc);929SpecTL.setTemplateNameLoc(TemplateNameLoc);930SpecTL.setLAngleLoc(LAngleLoc);931SpecTL.setRAngleLoc(RAngleLoc);932for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)933SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());934935936SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),937CCLoc);938return false;939}940941namespace {942/// A structure that stores a nested-name-specifier annotation,943/// including both the nested-name-specifier944struct NestedNameSpecifierAnnotation {945NestedNameSpecifier *NNS;946};947}948949void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {950if (SS.isEmpty() || SS.isInvalid())951return nullptr;952953void *Mem = Context.Allocate(954(sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),955alignof(NestedNameSpecifierAnnotation));956NestedNameSpecifierAnnotation *Annotation957= new (Mem) NestedNameSpecifierAnnotation;958Annotation->NNS = SS.getScopeRep();959memcpy(Annotation + 1, SS.location_data(), SS.location_size());960return Annotation;961}962963void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,964SourceRange AnnotationRange,965CXXScopeSpec &SS) {966if (!AnnotationPtr) {967SS.SetInvalid(AnnotationRange);968return;969}970971NestedNameSpecifierAnnotation *Annotation972= static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);973SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));974}975976bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {977assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");978979// Don't enter a declarator context when the current context is an Objective-C980// declaration.981if (isa<ObjCContainerDecl>(CurContext) || isa<ObjCMethodDecl>(CurContext))982return false;983984NestedNameSpecifier *Qualifier = SS.getScopeRep();985986// There are only two places a well-formed program may qualify a987// declarator: first, when defining a namespace or class member988// out-of-line, and second, when naming an explicitly-qualified989// friend function. The latter case is governed by990// C++03 [basic.lookup.unqual]p10:991// In a friend declaration naming a member function, a name used992// in the function declarator and not part of a template-argument993// in a template-id is first looked up in the scope of the member994// function's class. If it is not found, or if the name is part of995// a template-argument in a template-id, the look up is as996// described for unqualified names in the definition of the class997// granting friendship.998// i.e. we don't push a scope unless it's a class member.9991000switch (Qualifier->getKind()) {1001case NestedNameSpecifier::Global:1002case NestedNameSpecifier::Namespace:1003case NestedNameSpecifier::NamespaceAlias:1004// These are always namespace scopes. We never want to enter a1005// namespace scope from anything but a file context.1006return CurContext->getRedeclContext()->isFileContext();10071008case NestedNameSpecifier::Identifier:1009case NestedNameSpecifier::TypeSpec:1010case NestedNameSpecifier::TypeSpecWithTemplate:1011case NestedNameSpecifier::Super:1012// These are never namespace scopes.1013return true;1014}10151016llvm_unreachable("Invalid NestedNameSpecifier::Kind!");1017}10181019bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {1020assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");10211022if (SS.isInvalid()) return true;10231024DeclContext *DC = computeDeclContext(SS, true);1025if (!DC) return true;10261027// Before we enter a declarator's context, we need to make sure that1028// it is a complete declaration context.1029if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))1030return true;10311032EnterDeclaratorContext(S, DC);10331034// Rebuild the nested name specifier for the new scope.1035if (DC->isDependentContext())1036RebuildNestedNameSpecifierInCurrentInstantiation(SS);10371038return false;1039}10401041void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {1042assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");1043if (SS.isInvalid())1044return;1045assert(!SS.isInvalid() && computeDeclContext(SS, true) &&1046"exiting declarator scope we never really entered");1047ExitDeclaratorContext(S);1048}104910501051