brintos

brintos / llvm-project-archived public Read only

0
0
Text · 39.1 KiB · 17ae7ca Raw
1042 lines · cpp
1//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//2//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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements C++ semantic analysis for scope specifiers.10//11//===----------------------------------------------------------------------===//12 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/Template.h"22#include "llvm/ADT/STLExtras.h"23using namespace clang;24 25/// Find the current instantiation that associated with the given type.26static CXXRecordDecl *getCurrentInstantiationOf(QualType T,27                                                DeclContext *CurContext) {28  if (T.isNull())29    return nullptr;30 31  const TagType *TagTy = dyn_cast<TagType>(T->getCanonicalTypeInternal());32  if (!isa_and_present<RecordType, InjectedClassNameType>(TagTy))33    return nullptr;34  auto *RD = cast<CXXRecordDecl>(TagTy->getDecl())->getDefinitionOrSelf();35  if (isa<InjectedClassNameType>(TagTy) ||36      RD->isCurrentInstantiation(CurContext))37    return RD;38  return nullptr;39}40 41DeclContext *Sema::computeDeclContext(QualType T) {42  if (!T->isDependentType())43    if (auto *D = T->getAsTagDecl())44      return D;45  return ::getCurrentInstantiationOf(T, CurContext);46}47 48DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,49                                      bool EnteringContext) {50  if (!SS.isSet() || SS.isInvalid())51    return nullptr;52 53  NestedNameSpecifier NNS = SS.getScopeRep();54  if (NNS.isDependent()) {55    // If this nested-name-specifier refers to the current56    // instantiation, return its DeclContext.57    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))58      return Record;59 60    if (EnteringContext) {61      if (NNS.getKind() != NestedNameSpecifier::Kind::Type)62        return nullptr;63      const Type *NNSType = NNS.getAsType();64 65      // Look through type alias templates, per C++0x [temp.dep.type]p1.66      NNSType = Context.getCanonicalType(NNSType);67      if (const auto *SpecType =68              dyn_cast<TemplateSpecializationType>(NNSType)) {69        // We are entering the context of the nested name specifier, so try to70        // match the nested name specifier to either a primary class template71        // or a class template partial specialization.72        if (ClassTemplateDecl *ClassTemplate =73                dyn_cast_or_null<ClassTemplateDecl>(74                    SpecType->getTemplateName().getAsTemplateDecl())) {75          // FIXME: The fallback on the search of partial76          // specialization using ContextType should be eventually removed since77          // it doesn't handle the case of constrained template parameters78          // correctly. Currently removing this fallback would change the79          // diagnostic output for invalid code in a number of tests.80          ClassTemplatePartialSpecializationDecl *PartialSpec = nullptr;81          ArrayRef<TemplateParameterList *> TemplateParamLists =82              SS.getTemplateParamLists();83          if (!TemplateParamLists.empty()) {84            unsigned Depth = ClassTemplate->getTemplateParameters()->getDepth();85            auto L = find_if(TemplateParamLists,86                             [Depth](TemplateParameterList *TPL) {87                               return TPL->getDepth() == Depth;88                             });89            if (L != TemplateParamLists.end()) {90              void *Pos = nullptr;91              PartialSpec = ClassTemplate->findPartialSpecialization(92                  SpecType->template_arguments(), *L, Pos);93            }94          } else {95            PartialSpec =96                ClassTemplate->findPartialSpecialization(QualType(SpecType, 0));97          }98 99          if (PartialSpec) {100            // A declaration of the partial specialization must be visible.101            // We can always recover here, because this only happens when we're102            // entering the context, and that can't happen in a SFINAE context.103            assert(!isSFINAEContext() && "partial specialization scope "104                                         "specifier in SFINAE context?");105            if (PartialSpec->hasDefinition() &&106                !hasReachableDefinition(PartialSpec))107              diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,108                                    MissingImportKind::PartialSpecialization,109                                    true);110            return PartialSpec;111          }112 113          // If the type of the nested name specifier is the same as the114          // injected class name of the named class template, we're entering115          // into that class template definition.116          CanQualType Injected =117              ClassTemplate->getCanonicalInjectedSpecializationType(Context);118          if (Context.hasSameType(Injected, QualType(SpecType, 0)))119            return ClassTemplate->getTemplatedDecl();120        }121      } else if (const auto *RecordT = dyn_cast<RecordType>(NNSType)) {122        // The nested name specifier refers to a member of a class template.123        return RecordT->getDecl()->getDefinitionOrSelf();124      }125    }126 127    return nullptr;128  }129 130  switch (NNS.getKind()) {131  case NestedNameSpecifier::Kind::Namespace:132    return const_cast<NamespaceDecl *>(133        NNS.getAsNamespaceAndPrefix().Namespace->getNamespace());134 135  case NestedNameSpecifier::Kind::Type:136    return NNS.getAsType()->castAsTagDecl();137 138  case NestedNameSpecifier::Kind::Global:139    return Context.getTranslationUnitDecl();140 141  case NestedNameSpecifier::Kind::MicrosoftSuper:142    return NNS.getAsMicrosoftSuper();143 144  case NestedNameSpecifier::Kind::Null:145    llvm_unreachable("unexpected null nested name specifier");146  }147 148  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");149}150 151bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {152  if (!SS.isSet() || SS.isInvalid())153    return false;154 155  return SS.getScopeRep().isDependent();156}157 158CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier NNS) {159  assert(getLangOpts().CPlusPlus && "Only callable in C++");160  assert(NNS.isDependent() && "Only dependent nested-name-specifier allowed");161 162  if (NNS.getKind() != NestedNameSpecifier::Kind::Type)163    return nullptr;164 165  QualType T = QualType(NNS.getAsType(), 0);166  return ::getCurrentInstantiationOf(T, CurContext);167}168 169/// Require that the context specified by SS be complete.170///171/// If SS refers to a type, this routine checks whether the type is172/// complete enough (or can be made complete enough) for name lookup173/// into the DeclContext. A type that is not yet completed can be174/// considered "complete enough" if it is a class/struct/union/enum175/// that is currently being defined. Or, if we have a type that names176/// a class template specialization that is not a complete type, we177/// will attempt to instantiate that class template.178bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,179                                      DeclContext *DC) {180  assert(DC && "given null context");181 182  TagDecl *tag = dyn_cast<TagDecl>(DC);183 184  // If this is a dependent type, then we consider it complete.185  // FIXME: This is wrong; we should require a (visible) definition to186  // exist in this case too.187  if (!tag || tag->isDependentContext())188    return false;189 190  // Grab the tag definition, if there is one.191  tag = tag->getDefinitionOrSelf();192 193  // If we're currently defining this type, then lookup into the194  // type is okay: don't complain that it isn't complete yet.195  if (tag->isBeingDefined())196    return false;197 198  SourceLocation loc = SS.getLastQualifierNameLoc();199  if (loc.isInvalid()) loc = SS.getRange().getBegin();200 201  // The type must be complete.202  if (RequireCompleteType(loc, Context.getCanonicalTagType(tag),203                          diag::err_incomplete_nested_name_spec,204                          SS.getRange())) {205    SS.SetInvalid(SS.getRange());206    return true;207  }208 209  if (auto *EnumD = dyn_cast<EnumDecl>(tag))210    // Fixed enum types and scoped enum instantiations are complete, but they211    // aren't valid as scopes until we see or instantiate their definition.212    return RequireCompleteEnumDecl(EnumD, loc, &SS);213 214  return false;215}216 217/// Require that the EnumDecl is completed with its enumerators defined or218/// instantiated. SS, if provided, is the ScopeRef parsed.219///220bool Sema::RequireCompleteEnumDecl(EnumDecl *EnumD, SourceLocation L,221                                   CXXScopeSpec *SS) {222  if (EnumDecl *Def = EnumD->getDefinition();223      Def && Def->isCompleteDefinition()) {224    // If we know about the definition but it is not visible, complain.225    NamedDecl *SuggestedDef = nullptr;226    if (!hasReachableDefinition(Def, &SuggestedDef,227                                /*OnlyNeedComplete*/ false)) {228      // If the user is going to see an error here, recover by making the229      // definition visible.230      bool TreatAsComplete = !isSFINAEContext();231      diagnoseMissingImport(L, SuggestedDef, MissingImportKind::Definition,232                            /*Recover*/ TreatAsComplete);233      return !TreatAsComplete;234    }235    return false;236  }237 238  // Try to instantiate the definition, if this is a specialization of an239  // enumeration temploid.240  if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {241    MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();242    if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {243      if (InstantiateEnum(L, EnumD, Pattern,244                          getTemplateInstantiationArgs(EnumD),245                          TSK_ImplicitInstantiation)) {246        if (SS)247          SS->SetInvalid(SS->getRange());248        return true;249      }250      return false;251    }252  }253 254  if (SS) {255    Diag(L, diag::err_incomplete_nested_name_spec)256        << Context.getCanonicalTagType(EnumD) << SS->getRange();257    SS->SetInvalid(SS->getRange());258  } else {259    Diag(L, diag::err_incomplete_enum) << Context.getCanonicalTagType(EnumD);260    Diag(EnumD->getLocation(), diag::note_declared_at);261  }262 263  return true;264}265 266bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,267                                        CXXScopeSpec &SS) {268  SS.MakeGlobal(Context, CCLoc);269  return false;270}271 272bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,273                                    SourceLocation ColonColonLoc,274                                    CXXScopeSpec &SS) {275  if (getCurLambda()) {276    Diag(SuperLoc, diag::err_super_in_lambda_unsupported);277    return true;278  }279 280  CXXRecordDecl *RD = nullptr;281  for (Scope *S = getCurScope(); S; S = S->getParent()) {282    if (S->isFunctionScope()) {283      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))284        RD = MD->getParent();285      break;286    }287    if (S->isClassScope()) {288      RD = cast<CXXRecordDecl>(S->getEntity());289      break;290    }291  }292 293  if (!RD) {294    Diag(SuperLoc, diag::err_invalid_super_scope);295    return true;296  } else if (RD->getNumBases() == 0) {297    Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();298    return true;299  }300 301  SS.MakeMicrosoftSuper(Context, RD, SuperLoc, ColonColonLoc);302  return false;303}304 305bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,306                                           bool *IsExtension) {307  if (!SD)308    return false;309 310  SD = SD->getUnderlyingDecl();311 312  // Namespace and namespace aliases are fine.313  if (isa<NamespaceDecl>(SD))314    return true;315 316  if (!isa<TypeDecl>(SD))317    return false;318 319  // Determine whether we have a class (or, in C++11, an enum) or320  // a typedef thereof. If so, build the nested-name-specifier.321  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {322    if (TD->getUnderlyingType()->isRecordType())323      return true;324    if (TD->getUnderlyingType()->isEnumeralType()) {325      if (Context.getLangOpts().CPlusPlus11)326        return true;327      if (IsExtension)328        *IsExtension = true;329    }330  } else if (isa<RecordDecl>(SD)) {331    return true;332  } else if (isa<EnumDecl>(SD)) {333    if (Context.getLangOpts().CPlusPlus11)334      return true;335    if (IsExtension)336      *IsExtension = true;337  }338  if (auto *TD = dyn_cast<TagDecl>(SD)) {339    if (TD->isDependentType())340      return true;341  } else if (Context.getCanonicalTypeDeclType(cast<TypeDecl>(SD))342                 ->isDependentType()) {343    return true;344  }345 346  return false;347}348 349NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS) {350  if (!S)351    return nullptr;352 353  while (NNS.getKind() == NestedNameSpecifier::Kind::Type) {354    const Type *T = NNS.getAsType();355    if ((NNS = T->getPrefix()))356      continue;357 358    const auto *DNT = dyn_cast<DependentNameType>(T);359    if (!DNT)360      break;361 362    LookupResult Found(*this, DNT->getIdentifier(), SourceLocation(),363                       LookupNestedNameSpecifierName);364    LookupName(Found, S);365    assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");366 367    if (!Found.isSingleResult())368      return nullptr;369 370    NamedDecl *Result = Found.getFoundDecl();371    if (isAcceptableNestedNameSpecifier(Result))372      return Result;373  }374  return nullptr;375}376 377namespace {378 379// Callback to only accept typo corrections that can be a valid C++ member380// initializer: either a non-static field member or a base class.381class NestedNameSpecifierValidatorCCC final382    : public CorrectionCandidateCallback {383public:384  explicit NestedNameSpecifierValidatorCCC(Sema &SRef)385      : SRef(SRef) {}386 387  bool ValidateCandidate(const TypoCorrection &candidate) override {388    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());389  }390 391  std::unique_ptr<CorrectionCandidateCallback> clone() override {392    return std::make_unique<NestedNameSpecifierValidatorCCC>(*this);393  }394 395 private:396  Sema &SRef;397};398 399}400 401[[nodiscard]] static bool ExtendNestedNameSpecifier(Sema &S, CXXScopeSpec &SS,402                                                    const NamedDecl *ND,403                                                    SourceLocation NameLoc,404                                                    SourceLocation CCLoc) {405  TypeLocBuilder TLB;406  QualType T;407  if (const auto *USD = dyn_cast<UsingShadowDecl>(ND)) {408    T = S.Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),409                               USD);410    TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),411                                  SS.getWithLocInContext(S.Context), NameLoc);412  } else if (const auto *TD = dyn_cast<TypeDecl>(ND)) {413    T = S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),414                                  TD);415    switch (T->getTypeClass()) {416    case Type::Record:417    case Type::InjectedClassName:418    case Type::Enum: {419      auto TTL = TLB.push<TagTypeLoc>(T);420      TTL.setElaboratedKeywordLoc(SourceLocation());421      TTL.setQualifierLoc(SS.getWithLocInContext(S.Context));422      TTL.setNameLoc(NameLoc);423      break;424    }425    case Type::Typedef:426      TLB.push<TypedefTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),427                                      SS.getWithLocInContext(S.Context),428                                      NameLoc);429      break;430    case Type::UnresolvedUsing:431      TLB.push<UnresolvedUsingTypeLoc>(T).set(432          /*ElaboratedKeywordLoc=*/SourceLocation(),433          SS.getWithLocInContext(S.Context), NameLoc);434      break;435    default:436      assert(SS.isEmpty());437      T = S.Context.getTypeDeclType(TD);438      TLB.pushTypeSpec(T).setNameLoc(NameLoc);439      break;440    }441  } else {442    return false;443  }444  SS.clear();445  SS.Make(S.Context, TLB.getTypeLocInContext(S.Context, T), CCLoc);446  return true;447}448 449bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,450                                       bool EnteringContext, CXXScopeSpec &SS,451                                       NamedDecl *ScopeLookupResult,452                                       bool ErrorRecoveryLookup,453                                       bool *IsCorrectedToColon,454                                       bool OnlyNamespace) {455  if (IdInfo.Identifier->isEditorPlaceholder())456    return true;457  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,458                     OnlyNamespace ? LookupNamespaceName459                                   : LookupNestedNameSpecifierName);460  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);461 462  // Determine where to perform name lookup463  DeclContext *LookupCtx = nullptr;464  bool isDependent = false;465  if (IsCorrectedToColon)466    *IsCorrectedToColon = false;467  if (!ObjectType.isNull()) {468    // This nested-name-specifier occurs in a member access expression, e.g.,469    // x->B::f, and we are looking into the type of the object.470    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");471    LookupCtx = computeDeclContext(ObjectType);472    isDependent = ObjectType->isDependentType();473  } else if (SS.isSet()) {474    // This nested-name-specifier occurs after another nested-name-specifier,475    // so look into the context associated with the prior nested-name-specifier.476    LookupCtx = computeDeclContext(SS, EnteringContext);477    isDependent = isDependentScopeSpecifier(SS);478    Found.setContextRange(SS.getRange());479  }480 481  bool ObjectTypeSearchedInScope = false;482  if (LookupCtx) {483    // Perform "qualified" name lookup into the declaration context we484    // computed, which is either the type of the base of a member access485    // expression or the declaration context associated with a prior486    // nested-name-specifier.487 488    // The declaration context must be complete.489    if (!LookupCtx->isDependentContext() &&490        RequireCompleteDeclContext(SS, LookupCtx))491      return true;492 493    LookupQualifiedName(Found, LookupCtx);494 495    if (!ObjectType.isNull() && Found.empty()) {496      // C++ [basic.lookup.classref]p4:497      //   If the id-expression in a class member access is a qualified-id of498      //   the form499      //500      //        class-name-or-namespace-name::...501      //502      //   the class-name-or-namespace-name following the . or -> operator is503      //   looked up both in the context of the entire postfix-expression and in504      //   the scope of the class of the object expression. If the name is found505      //   only in the scope of the class of the object expression, the name506      //   shall refer to a class-name. If the name is found only in the507      //   context of the entire postfix-expression, the name shall refer to a508      //   class-name or namespace-name. [...]509      //510      // Qualified name lookup into a class will not find a namespace-name,511      // so we do not need to diagnose that case specifically. However,512      // this qualified name lookup may find nothing. In that case, perform513      // unqualified name lookup in the given scope (if available) or514      // reconstruct the result from when name lookup was performed at template515      // definition time.516      if (S)517        LookupName(Found, S);518      else if (ScopeLookupResult)519        Found.addDecl(ScopeLookupResult);520 521      ObjectTypeSearchedInScope = true;522    }523  } else if (!isDependent) {524    // Perform unqualified name lookup in the current scope.525    LookupName(Found, S);526  }527 528  if (Found.isAmbiguous())529    return true;530 531  // If we performed lookup into a dependent context and did not find anything,532  // that's fine: just build a dependent nested-name-specifier.533  if (Found.empty() && isDependent &&534      !(LookupCtx && LookupCtx->isRecord() &&535        (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||536         !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {537    // Don't speculate if we're just trying to improve error recovery.538    if (ErrorRecoveryLookup)539      return true;540 541    // We were not able to compute the declaration context for a dependent542    // base object type or prior nested-name-specifier, so this543    // nested-name-specifier refers to an unknown specialization. Just build544    // a dependent nested-name-specifier.545 546    TypeLocBuilder TLB;547 548    QualType DTN = Context.getDependentNameType(549        ElaboratedTypeKeyword::None, SS.getScopeRep(), IdInfo.Identifier);550    auto DTNL = TLB.push<DependentNameTypeLoc>(DTN);551    DTNL.setElaboratedKeywordLoc(SourceLocation());552    DTNL.setNameLoc(IdInfo.IdentifierLoc);553    DTNL.setQualifierLoc(SS.getWithLocInContext(Context));554 555    SS.clear();556    SS.Make(Context, TLB.getTypeLocInContext(Context, DTN), IdInfo.CCLoc);557    return false;558  }559 560  if (Found.empty() && !ErrorRecoveryLookup) {561    // If identifier is not found as class-name-or-namespace-name, but is found562    // as other entity, don't look for typos.563    LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);564    if (LookupCtx)565      LookupQualifiedName(R, LookupCtx);566    else if (S && !isDependent)567      LookupName(R, S);568    if (!R.empty()) {569      // Don't diagnose problems with this speculative lookup.570      R.suppressDiagnostics();571      // The identifier is found in ordinary lookup. If correction to colon is572      // allowed, suggest replacement to ':'.573      if (IsCorrectedToColon) {574        *IsCorrectedToColon = true;575        Diag(IdInfo.CCLoc, diag::err_nested_name_spec_is_not_class)576            << IdInfo.Identifier << getLangOpts().CPlusPlus577            << FixItHint::CreateReplacement(IdInfo.CCLoc, ":");578        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())579          Diag(ND->getLocation(), diag::note_declared_at);580        return true;581      }582      // Replacement '::' -> ':' is not allowed, just issue respective error.583      Diag(R.getNameLoc(), OnlyNamespace584                               ? unsigned(diag::err_expected_namespace_name)585                               : unsigned(diag::err_expected_class_or_namespace))586          << IdInfo.Identifier << getLangOpts().CPlusPlus;587      if (NamedDecl *ND = R.getAsSingle<NamedDecl>())588        Diag(ND->getLocation(), diag::note_entity_declared_at)589            << IdInfo.Identifier;590      return true;591    }592  }593 594  if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) {595    // We haven't found anything, and we're not recovering from a596    // different kind of error, so look for typos.597    DeclarationName Name = Found.getLookupName();598    Found.clear();599    NestedNameSpecifierValidatorCCC CCC(*this);600    if (TypoCorrection Corrected = CorrectTypo(601            Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, CCC,602            CorrectTypoKind::ErrorRecovery, LookupCtx, EnteringContext)) {603      if (LookupCtx) {604        bool DroppedSpecifier =605            Corrected.WillReplaceSpecifier() &&606            Name.getAsString() == Corrected.getAsString(getLangOpts());607        if (DroppedSpecifier)608          SS.clear();609        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)610                                  << Name << LookupCtx << DroppedSpecifier611                                  << SS.getRange());612      } else613        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)614                                  << Name);615 616      if (Corrected.getCorrectionSpecifier())617        SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),618                       SourceRange(Found.getNameLoc()));619 620      if (NamedDecl *ND = Corrected.getFoundDecl())621        Found.addDecl(ND);622      Found.setLookupName(Corrected.getCorrection());623    } else {624      Found.setLookupName(IdInfo.Identifier);625    }626  }627 628  NamedDecl *SD =629      Found.isSingleResult() ? Found.getRepresentativeDecl() : nullptr;630  bool IsExtension = false;631  bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);632  if (!AcceptSpec && IsExtension) {633    AcceptSpec = true;634    Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);635  }636  if (AcceptSpec) {637    if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&638        !getLangOpts().CPlusPlus11) {639      // C++03 [basic.lookup.classref]p4:640      //   [...] If the name is found in both contexts, the641      //   class-name-or-namespace-name shall refer to the same entity.642      //643      // We already found the name in the scope of the object. Now, look644      // into the current scope (the scope of the postfix-expression) to645      // see if we can find the same name there. As above, if there is no646      // scope, reconstruct the result from the template instantiation itself.647      //648      // Note that C++11 does *not* perform this redundant lookup.649      NamedDecl *OuterDecl;650      if (S) {651        LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,652                                LookupNestedNameSpecifierName);653        LookupName(FoundOuter, S);654        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();655      } else656        OuterDecl = ScopeLookupResult;657 658      if (isAcceptableNestedNameSpecifier(OuterDecl) &&659          OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&660          (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||661           !Context.hasSameType(662               Context.getCanonicalTypeDeclType(cast<TypeDecl>(OuterDecl)),663               Context.getCanonicalTypeDeclType(cast<TypeDecl>(SD))))) {664        if (ErrorRecoveryLookup)665          return true;666 667         Diag(IdInfo.IdentifierLoc,668              diag::err_nested_name_member_ref_lookup_ambiguous)669           << IdInfo.Identifier;670         Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)671           << ObjectType;672         Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);673 674         // Fall through so that we'll pick the name we found in the object675         // type, since that's probably what the user wanted anyway.676      }677    }678 679    if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))680      MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);681 682    // If we're just performing this lookup for error-recovery purposes,683    // don't extend the nested-name-specifier. Just return now.684    if (ErrorRecoveryLookup)685      return false;686 687    // The use of a nested name specifier may trigger deprecation warnings.688    DiagnoseUseOfDecl(SD, IdInfo.CCLoc);689 690    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {691      SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);692      return false;693    }694 695    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {696      SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);697      return false;698    }699 700    const auto *TD = cast<TypeDecl>(SD->getUnderlyingDecl());701    if (isa<EnumDecl>(TD))702      Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);703 704    [[maybe_unused]] bool IsType = ::ExtendNestedNameSpecifier(705        *this, SS, SD, IdInfo.IdentifierLoc, IdInfo.CCLoc);706    assert(IsType && "unhandled declaration kind");707    return false;708  }709 710  // Otherwise, we have an error case.  If we don't want diagnostics, just711  // return an error now.712  if (ErrorRecoveryLookup)713    return true;714 715  // If we didn't find anything during our lookup, try again with716  // ordinary name lookup, which can help us produce better error717  // messages.718  if (Found.empty()) {719    Found.clear(LookupOrdinaryName);720    LookupName(Found, S);721  }722 723  // In Microsoft mode, if we are within a templated function and we can't724  // resolve Identifier, then extend the SS with Identifier. This will have725  // the effect of resolving Identifier during template instantiation.726  // The goal is to be able to resolve a function call whose727  // nested-name-specifier is located inside a dependent base class.728  // Example:729  //730  // class C {731  // public:732  //    static void foo2() {  }733  // };734  // template <class T> class A { public: typedef C D; };735  //736  // template <class T> class B : public A<T> {737  // public:738  //   void foo() { D::foo2(); }739  // };740  if (getLangOpts().MSVCCompat) {741    DeclContext *DC = LookupCtx ? LookupCtx : CurContext;742    if (DC->isDependentContext() && DC->isFunctionOrMethod()) {743      CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());744      if (ContainingClass && ContainingClass->hasAnyDependentBases()) {745        Diag(IdInfo.IdentifierLoc,746             diag::ext_undeclared_unqual_id_with_dependent_base)747            << IdInfo.Identifier << ContainingClass;748 749        TypeLocBuilder TLB;750 751        // Fake up a nested-name-specifier that starts with the752        // injected-class-name of the enclosing class.753        // FIXME: This should be done as part of an adjustment, so that this754        // doesn't get confused with something written in source.755        QualType Result =756            Context.getTagType(ElaboratedTypeKeyword::None, SS.getScopeRep(),757                               ContainingClass, /*OwnsTag=*/false);758        auto TTL = TLB.push<TagTypeLoc>(Result);759        TTL.setElaboratedKeywordLoc(SourceLocation());760        TTL.setQualifierLoc(SS.getWithLocInContext(Context));761        TTL.setNameLoc(IdInfo.IdentifierLoc);762        SS.Make(Context, TLB.getTypeLocInContext(Context, Result),763                SourceLocation());764 765        TLB.clear();766 767        // Form a DependentNameType.768        QualType DTN = Context.getDependentNameType(769            ElaboratedTypeKeyword::None, SS.getScopeRep(), IdInfo.Identifier);770        auto DTNL = TLB.push<DependentNameTypeLoc>(DTN);771        DTNL.setElaboratedKeywordLoc(SourceLocation());772        DTNL.setNameLoc(IdInfo.IdentifierLoc);773        DTNL.setQualifierLoc(SS.getWithLocInContext(Context));774        SS.clear();775        SS.Make(Context, TLB.getTypeLocInContext(Context, DTN), IdInfo.CCLoc);776        return false;777      }778    }779  }780 781  if (!Found.empty()) {782    const auto *ND = Found.getAsSingle<NamedDecl>();783    if (!ND) {784      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)785          << IdInfo.Identifier << getLangOpts().CPlusPlus;786      return true;787    }788    if (::ExtendNestedNameSpecifier(*this, SS, ND, IdInfo.IdentifierLoc,789                                    IdInfo.CCLoc)) {790      const Type *T = SS.getScopeRep().getAsType();791      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)792          << QualType(T, 0) << getLangOpts().CPlusPlus;793      // Recover with this type if it would be a valid nested name specifier.794      return !T->getAsCanonical<TagType>();795    }796    if (isa<TemplateDecl>(ND)) {797      ParsedType SuggestedType;798      DiagnoseUnknownTypeName(IdInfo.Identifier, IdInfo.IdentifierLoc, S, &SS,799                              SuggestedType);800    } else {801      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)802          << IdInfo.Identifier << getLangOpts().CPlusPlus;803      if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())804        Diag(ND->getLocation(), diag::note_entity_declared_at)805            << IdInfo.Identifier;806    }807  } else if (SS.isSet())808    Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier809        << LookupCtx << SS.getRange();810  else811    Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)812        << IdInfo.Identifier;813 814  return true;815}816 817bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,818                                       bool EnteringContext, CXXScopeSpec &SS,819                                       bool *IsCorrectedToColon,820                                       bool OnlyNamespace) {821  if (SS.isInvalid())822    return true;823 824  return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,825                                     /*ScopeLookupResult=*/nullptr, false,826                                     IsCorrectedToColon, OnlyNamespace);827}828 829bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,830                                               const DeclSpec &DS,831                                               SourceLocation ColonColonLoc) {832  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)833    return true;834 835  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);836 837  QualType T = BuildDecltypeType(DS.getRepAsExpr());838  if (T.isNull())839    return true;840 841  if (!T->isDependentType() && !isa<TagType>(T.getCanonicalType())) {842    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)843      << T << getLangOpts().CPlusPlus;844    return true;845  }846 847  assert(SS.isEmpty());848 849  TypeLocBuilder TLB;850  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);851  DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());852  DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());853  SS.Make(Context, TLB.getTypeLocInContext(Context, T), ColonColonLoc);854  return false;855}856 857bool Sema::ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,858                                                  const DeclSpec &DS,859                                                  SourceLocation ColonColonLoc,860                                                  QualType Type) {861  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)862    return true;863 864  assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing);865 866  if (Type.isNull())867    return true;868 869  assert(SS.isEmpty());870 871  TypeLocBuilder TLB;872  TLB.pushTrivial(getASTContext(),873                  cast<PackIndexingType>(Type.getTypePtr())->getPattern(),874                  DS.getBeginLoc());875  PackIndexingTypeLoc PIT = TLB.push<PackIndexingTypeLoc>(Type);876  PIT.setEllipsisLoc(DS.getEllipsisLoc());877  SS.Make(Context, TLB.getTypeLocInContext(Context, Type), ColonColonLoc);878  return false;879}880 881bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,882                                     NestedNameSpecInfo &IdInfo,883                                     bool EnteringContext) {884  if (SS.isInvalid())885    return false;886 887  return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,888                                      /*ScopeLookupResult=*/nullptr, true);889}890 891bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,892                                       CXXScopeSpec &SS,893                                       SourceLocation TemplateKWLoc,894                                       TemplateTy OpaqueTemplate,895                                       SourceLocation TemplateNameLoc,896                                       SourceLocation LAngleLoc,897                                       ASTTemplateArgsPtr TemplateArgsIn,898                                       SourceLocation RAngleLoc,899                                       SourceLocation CCLoc,900                                       bool EnteringContext) {901  if (SS.isInvalid())902    return true;903 904  // Translate the parser's template argument list in our AST format.905  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);906  translateTemplateArguments(TemplateArgsIn, TemplateArgs);907 908  // We were able to resolve the template name to an actual template.909  // Build an appropriate nested-name-specifier.910  QualType T = CheckTemplateIdType(911      ElaboratedTypeKeyword::None, OpaqueTemplate.get(), TemplateNameLoc,912      TemplateArgs, /*Scope=*/S, /*ForNestedNameSpecifier=*/true);913  if (T.isNull())914    return true;915 916  // Alias template specializations can produce types which are not valid917  // nested name specifiers.918  if (!T->isDependentType() && !isa<TagType>(T.getCanonicalType())) {919    Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;920    NoteAllFoundTemplates(OpaqueTemplate.get());921    return true;922  }923 924  // Provide source-location information for the template specialization type.925  TypeLocBuilder TLB;926  TLB.push<TemplateSpecializationTypeLoc>(T).set(927      /*ElaboratedKeywordLoc=*/SourceLocation(),928      SS.getWithLocInContext(Context), TemplateKWLoc, TemplateNameLoc,929      TemplateArgs);930 931  SS.clear();932  SS.Make(Context, TLB.getTypeLocInContext(Context, T), CCLoc);933  return false;934}935 936namespace {937  /// A structure that stores a nested-name-specifier annotation,938  /// including both the nested-name-specifier939  struct NestedNameSpecifierAnnotation {940    NestedNameSpecifier NNS = std::nullopt;941  };942}943 944void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {945  if (SS.isEmpty() || SS.isInvalid())946    return nullptr;947 948  void *Mem = Context.Allocate(949      (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),950      alignof(NestedNameSpecifierAnnotation));951  NestedNameSpecifierAnnotation *Annotation952    = new (Mem) NestedNameSpecifierAnnotation;953  Annotation->NNS = SS.getScopeRep();954  memcpy(Annotation + 1, SS.location_data(), SS.location_size());955  return Annotation;956}957 958void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,959                                                SourceRange AnnotationRange,960                                                CXXScopeSpec &SS) {961  if (!AnnotationPtr) {962    SS.SetInvalid(AnnotationRange);963    return;964  }965 966  NestedNameSpecifierAnnotation *Annotation967    = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);968  SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));969}970 971bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {972  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");973 974  // Don't enter a declarator context when the current context is an Objective-C975  // declaration.976  if (isa<ObjCContainerDecl>(CurContext) || isa<ObjCMethodDecl>(CurContext))977    return false;978 979  // There are only two places a well-formed program may qualify a980  // declarator: first, when defining a namespace or class member981  // out-of-line, and second, when naming an explicitly-qualified982  // friend function.  The latter case is governed by983  // C++03 [basic.lookup.unqual]p10:984  //   In a friend declaration naming a member function, a name used985  //   in the function declarator and not part of a template-argument986  //   in a template-id is first looked up in the scope of the member987  //   function's class. If it is not found, or if the name is part of988  //   a template-argument in a template-id, the look up is as989  //   described for unqualified names in the definition of the class990  //   granting friendship.991  // i.e. we don't push a scope unless it's a class member.992 993  switch (SS.getScopeRep().getKind()) {994  case NestedNameSpecifier::Kind::Global:995  case NestedNameSpecifier::Kind::Namespace:996    // These are always namespace scopes.  We never want to enter a997    // namespace scope from anything but a file context.998    return CurContext->getRedeclContext()->isFileContext();999 1000  case NestedNameSpecifier::Kind::Type:1001  case NestedNameSpecifier::Kind::MicrosoftSuper:1002    // These are never namespace scopes.1003    return true;1004 1005  case NestedNameSpecifier::Kind::Null:1006    llvm_unreachable("unexpected null nested name specifier");1007  }1008 1009  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");1010}1011 1012bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {1013  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");1014 1015  if (SS.isInvalid()) return true;1016 1017  DeclContext *DC = computeDeclContext(SS, true);1018  if (!DC) return true;1019 1020  // Before we enter a declarator's context, we need to make sure that1021  // it is a complete declaration context.1022  if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))1023    return true;1024 1025  EnterDeclaratorContext(S, DC);1026 1027  // Rebuild the nested name specifier for the new scope.1028  if (DC->isDependentContext())1029    RebuildNestedNameSpecifierInCurrentInstantiation(SS);1030 1031  return false;1032}1033 1034void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {1035  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");1036  if (SS.isInvalid())1037    return;1038  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&1039         "exiting declarator scope we never really entered");1040  ExitDeclaratorContext(S);1041}1042