clang API Documentation

SemaCXXScopeSpec.cpp
Go to the documentation of this file.
00001 //===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements C++ semantic analysis for scope specifiers.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "TypeLocBuilder.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/DeclTemplate.h"
00018 #include "clang/AST/ExprCXX.h"
00019 #include "clang/AST/NestedNameSpecifier.h"
00020 #include "clang/Basic/PartialDiagnostic.h"
00021 #include "clang/Sema/DeclSpec.h"
00022 #include "clang/Sema/Lookup.h"
00023 #include "clang/Sema/Template.h"
00024 #include "llvm/ADT/STLExtras.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 using namespace clang;
00027 
00028 /// \brief Find the current instantiation that associated with the given type.
00029 static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
00030                                                 DeclContext *CurContext) {
00031   if (T.isNull())
00032     return nullptr;
00033 
00034   const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
00035   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
00036     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
00037     if (!Record->isDependentContext() ||
00038         Record->isCurrentInstantiation(CurContext))
00039       return Record;
00040 
00041     return nullptr;
00042   } else if (isa<InjectedClassNameType>(Ty))
00043     return cast<InjectedClassNameType>(Ty)->getDecl();
00044   else
00045     return nullptr;
00046 }
00047 
00048 /// \brief Compute the DeclContext that is associated with the given type.
00049 ///
00050 /// \param T the type for which we are attempting to find a DeclContext.
00051 ///
00052 /// \returns the declaration context represented by the type T,
00053 /// or NULL if the declaration context cannot be computed (e.g., because it is
00054 /// dependent and not the current instantiation).
00055 DeclContext *Sema::computeDeclContext(QualType T) {
00056   if (!T->isDependentType())
00057     if (const TagType *Tag = T->getAs<TagType>())
00058       return Tag->getDecl();
00059 
00060   return ::getCurrentInstantiationOf(T, CurContext);
00061 }
00062 
00063 /// \brief Compute the DeclContext that is associated with the given
00064 /// scope specifier.
00065 ///
00066 /// \param SS the C++ scope specifier as it appears in the source
00067 ///
00068 /// \param EnteringContext when true, we will be entering the context of
00069 /// this scope specifier, so we can retrieve the declaration context of a
00070 /// class template or class template partial specialization even if it is
00071 /// not the current instantiation.
00072 ///
00073 /// \returns the declaration context represented by the scope specifier @p SS,
00074 /// or NULL if the declaration context cannot be computed (e.g., because it is
00075 /// dependent and not the current instantiation).
00076 DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
00077                                       bool EnteringContext) {
00078   if (!SS.isSet() || SS.isInvalid())
00079     return nullptr;
00080 
00081   NestedNameSpecifier *NNS = SS.getScopeRep();
00082   if (NNS->isDependent()) {
00083     // If this nested-name-specifier refers to the current
00084     // instantiation, return its DeclContext.
00085     if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
00086       return Record;
00087 
00088     if (EnteringContext) {
00089       const Type *NNSType = NNS->getAsType();
00090       if (!NNSType) {
00091         return nullptr;
00092       }
00093 
00094       // Look through type alias templates, per C++0x [temp.dep.type]p1.
00095       NNSType = Context.getCanonicalType(NNSType);
00096       if (const TemplateSpecializationType *SpecType
00097             = NNSType->getAs<TemplateSpecializationType>()) {
00098         // We are entering the context of the nested name specifier, so try to
00099         // match the nested name specifier to either a primary class template
00100         // or a class template partial specialization.
00101         if (ClassTemplateDecl *ClassTemplate
00102               = dyn_cast_or_null<ClassTemplateDecl>(
00103                             SpecType->getTemplateName().getAsTemplateDecl())) {
00104           QualType ContextType
00105             = Context.getCanonicalType(QualType(SpecType, 0));
00106 
00107           // If the type of the nested name specifier is the same as the
00108           // injected class name of the named class template, we're entering
00109           // into that class template definition.
00110           QualType Injected
00111             = ClassTemplate->getInjectedClassNameSpecialization();
00112           if (Context.hasSameType(Injected, ContextType))
00113             return ClassTemplate->getTemplatedDecl();
00114 
00115           // If the type of the nested name specifier is the same as the
00116           // type of one of the class template's class template partial
00117           // specializations, we're entering into the definition of that
00118           // class template partial specialization.
00119           if (ClassTemplatePartialSpecializationDecl *PartialSpec
00120                 = ClassTemplate->findPartialSpecialization(ContextType))
00121             return PartialSpec;
00122         }
00123       } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
00124         // The nested name specifier refers to a member of a class template.
00125         return RecordT->getDecl();
00126       }
00127     }
00128 
00129     return nullptr;
00130   }
00131 
00132   switch (NNS->getKind()) {
00133   case NestedNameSpecifier::Identifier:
00134     llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
00135 
00136   case NestedNameSpecifier::Namespace:
00137     return NNS->getAsNamespace();
00138 
00139   case NestedNameSpecifier::NamespaceAlias:
00140     return NNS->getAsNamespaceAlias()->getNamespace();
00141 
00142   case NestedNameSpecifier::TypeSpec:
00143   case NestedNameSpecifier::TypeSpecWithTemplate: {
00144     const TagType *Tag = NNS->getAsType()->getAs<TagType>();
00145     assert(Tag && "Non-tag type in nested-name-specifier");
00146     return Tag->getDecl();
00147   }
00148 
00149   case NestedNameSpecifier::Global:
00150     return Context.getTranslationUnitDecl();
00151 
00152   case NestedNameSpecifier::Super:
00153     return NNS->getAsRecordDecl();
00154   }
00155 
00156   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
00157 }
00158 
00159 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
00160   if (!SS.isSet() || SS.isInvalid())
00161     return false;
00162 
00163   return SS.getScopeRep()->isDependent();
00164 }
00165 
00166 /// \brief If the given nested name specifier refers to the current
00167 /// instantiation, return the declaration that corresponds to that
00168 /// current instantiation (C++0x [temp.dep.type]p1).
00169 ///
00170 /// \param NNS a dependent nested name specifier.
00171 CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
00172   assert(getLangOpts().CPlusPlus && "Only callable in C++");
00173   assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
00174 
00175   if (!NNS->getAsType())
00176     return nullptr;
00177 
00178   QualType T = QualType(NNS->getAsType(), 0);
00179   return ::getCurrentInstantiationOf(T, CurContext);
00180 }
00181 
00182 /// \brief Require that the context specified by SS be complete.
00183 ///
00184 /// If SS refers to a type, this routine checks whether the type is
00185 /// complete enough (or can be made complete enough) for name lookup
00186 /// into the DeclContext. A type that is not yet completed can be
00187 /// considered "complete enough" if it is a class/struct/union/enum
00188 /// that is currently being defined. Or, if we have a type that names
00189 /// a class template specialization that is not a complete type, we
00190 /// will attempt to instantiate that class template.
00191 bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
00192                                       DeclContext *DC) {
00193   assert(DC && "given null context");
00194 
00195   TagDecl *tag = dyn_cast<TagDecl>(DC);
00196 
00197   // If this is a dependent type, then we consider it complete.
00198   if (!tag || tag->isDependentContext())
00199     return false;
00200 
00201   // If we're currently defining this type, then lookup into the
00202   // type is okay: don't complain that it isn't complete yet.
00203   QualType type = Context.getTypeDeclType(tag);
00204   const TagType *tagType = type->getAs<TagType>();
00205   if (tagType && tagType->isBeingDefined())
00206     return false;
00207 
00208   SourceLocation loc = SS.getLastQualifierNameLoc();
00209   if (loc.isInvalid()) loc = SS.getRange().getBegin();
00210 
00211   // The type must be complete.
00212   if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
00213                           SS.getRange())) {
00214     SS.SetInvalid(SS.getRange());
00215     return true;
00216   }
00217 
00218   // Fixed enum types are complete, but they aren't valid as scopes
00219   // until we see a definition, so awkwardly pull out this special
00220   // case.
00221   const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType);
00222   if (!enumType || enumType->getDecl()->isCompleteDefinition())
00223     return false;
00224 
00225   // Try to instantiate the definition, if this is a specialization of an
00226   // enumeration temploid.
00227   EnumDecl *ED = enumType->getDecl();
00228   if (EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
00229     MemberSpecializationInfo *MSI = ED->getMemberSpecializationInfo();
00230     if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
00231       if (InstantiateEnum(loc, ED, Pattern, getTemplateInstantiationArgs(ED),
00232                           TSK_ImplicitInstantiation)) {
00233         SS.SetInvalid(SS.getRange());
00234         return true;
00235       }
00236       return false;
00237     }
00238   }
00239 
00240   Diag(loc, diag::err_incomplete_nested_name_spec)
00241     << type << SS.getRange();
00242   SS.SetInvalid(SS.getRange());
00243   return true;
00244 }
00245 
00246 bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,
00247                                         CXXScopeSpec &SS) {
00248   SS.MakeGlobal(Context, CCLoc);
00249   return false;
00250 }
00251 
00252 bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
00253                                     SourceLocation ColonColonLoc,
00254                                     CXXScopeSpec &SS) {
00255   CXXRecordDecl *RD = nullptr;
00256   for (Scope *S = getCurScope(); S; S = S->getParent()) {
00257     if (S->isFunctionScope()) {
00258       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))
00259         RD = MD->getParent();
00260       break;
00261     }
00262     if (S->isClassScope()) {
00263       RD = cast<CXXRecordDecl>(S->getEntity());
00264       break;
00265     }
00266   }
00267 
00268   if (!RD) {
00269     Diag(SuperLoc, diag::err_invalid_super_scope);
00270     return true;
00271   } else if (RD->isLambda()) {
00272     Diag(SuperLoc, diag::err_super_in_lambda_unsupported);
00273     return true;
00274   } else if (RD->getNumBases() == 0) {
00275     Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();
00276     return true;
00277   }
00278 
00279   SS.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
00280   return false;
00281 }
00282 
00283 /// \brief Determines whether the given declaration is an valid acceptable
00284 /// result for name lookup of a nested-name-specifier.
00285 bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD) {
00286   if (!SD)
00287     return false;
00288 
00289   // Namespace and namespace aliases are fine.
00290   if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
00291     return true;
00292 
00293   if (!isa<TypeDecl>(SD))
00294     return false;
00295 
00296   // Determine whether we have a class (or, in C++11, an enum) or
00297   // a typedef thereof. If so, build the nested-name-specifier.
00298   QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
00299   if (T->isDependentType())
00300     return true;
00301   else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
00302     if (TD->getUnderlyingType()->isRecordType() ||
00303         (Context.getLangOpts().CPlusPlus11 &&
00304          TD->getUnderlyingType()->isEnumeralType()))
00305       return true;
00306   } else if (isa<RecordDecl>(SD) ||
00307              (Context.getLangOpts().CPlusPlus11 && isa<EnumDecl>(SD)))
00308     return true;
00309 
00310   return false;
00311 }
00312 
00313 /// \brief If the given nested-name-specifier begins with a bare identifier
00314 /// (e.g., Base::), perform name lookup for that identifier as a
00315 /// nested-name-specifier within the given scope, and return the result of that
00316 /// name lookup.
00317 NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
00318   if (!S || !NNS)
00319     return nullptr;
00320 
00321   while (NNS->getPrefix())
00322     NNS = NNS->getPrefix();
00323 
00324   if (NNS->getKind() != NestedNameSpecifier::Identifier)
00325     return nullptr;
00326 
00327   LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
00328                      LookupNestedNameSpecifierName);
00329   LookupName(Found, S);
00330   assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
00331 
00332   if (!Found.isSingleResult())
00333     return nullptr;
00334 
00335   NamedDecl *Result = Found.getFoundDecl();
00336   if (isAcceptableNestedNameSpecifier(Result))
00337     return Result;
00338 
00339   return nullptr;
00340 }
00341 
00342 bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
00343                                         SourceLocation IdLoc,
00344                                         IdentifierInfo &II,
00345                                         ParsedType ObjectTypePtr) {
00346   QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
00347   LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
00348   
00349   // Determine where to perform name lookup
00350   DeclContext *LookupCtx = nullptr;
00351   bool isDependent = false;
00352   if (!ObjectType.isNull()) {
00353     // This nested-name-specifier occurs in a member access expression, e.g.,
00354     // x->B::f, and we are looking into the type of the object.
00355     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
00356     LookupCtx = computeDeclContext(ObjectType);
00357     isDependent = ObjectType->isDependentType();
00358   } else if (SS.isSet()) {
00359     // This nested-name-specifier occurs after another nested-name-specifier,
00360     // so long into the context associated with the prior nested-name-specifier.
00361     LookupCtx = computeDeclContext(SS, false);
00362     isDependent = isDependentScopeSpecifier(SS);
00363     Found.setContextRange(SS.getRange());
00364   }
00365   
00366   if (LookupCtx) {
00367     // Perform "qualified" name lookup into the declaration context we
00368     // computed, which is either the type of the base of a member access
00369     // expression or the declaration context associated with a prior
00370     // nested-name-specifier.
00371     
00372     // The declaration context must be complete.
00373     if (!LookupCtx->isDependentContext() &&
00374         RequireCompleteDeclContext(SS, LookupCtx))
00375       return false;
00376     
00377     LookupQualifiedName(Found, LookupCtx);
00378   } else if (isDependent) {
00379     return false;
00380   } else {
00381     LookupName(Found, S);
00382   }
00383   Found.suppressDiagnostics();
00384   
00385   if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
00386     return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
00387   
00388   return false;
00389 }
00390 
00391 namespace {
00392 
00393 // Callback to only accept typo corrections that can be a valid C++ member
00394 // intializer: either a non-static field member or a base class.
00395 class NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback {
00396  public:
00397   explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
00398       : SRef(SRef) {}
00399 
00400   bool ValidateCandidate(const TypoCorrection &candidate) override {
00401     return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
00402   }
00403 
00404  private:
00405   Sema &SRef;
00406 };
00407 
00408 }
00409 
00410 /// \brief Build a new nested-name-specifier for "identifier::", as described
00411 /// by ActOnCXXNestedNameSpecifier.
00412 ///
00413 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
00414 /// that it contains an extra parameter \p ScopeLookupResult.
00415 ///
00416 /// \param S Scope in which the nested-name-specifier occurs.
00417 /// \param Identifier Identifier in the sequence "identifier" "::".
00418 /// \param IdentifierLoc Location of the \p Identifier.
00419 /// \param CCLoc Location of "::" following Identifier.
00420 /// \param ObjectType Type of postfix expression if the nested-name-specifier
00421 ///        occurs in construct like: <tt>ptr->nns::f</tt>.
00422 /// \param EnteringContext If true, enter the context specified by the
00423 ///        nested-name-specifier.
00424 /// \param SS Optional nested name specifier preceding the identifier.
00425 /// \param ScopeLookupResult Provides the result of name lookup within the
00426 ///        scope of the nested-name-specifier that was computed at template
00427 ///        definition time.
00428 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
00429 ///        error recovery and what kind of recovery is performed.
00430 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
00431 ///        are allowed.  The bool value pointed by this parameter is set to
00432 ///       'true' if the identifier is treated as if it was followed by ':',
00433 ///        not '::'.
00434 ///
00435 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
00436 /// that it contains an extra parameter \p ScopeLookupResult, which provides
00437 /// the result of name lookup within the scope of the nested-name-specifier
00438 /// that was computed at template definition time.
00439 ///
00440 /// If ErrorRecoveryLookup is true, then this call is used to improve error
00441 /// recovery.  This means that it should not emit diagnostics, it should
00442 /// just return true on failure.  It also means it should only return a valid
00443 /// scope if it *knows* that the result is correct.  It should not return in a
00444 /// dependent context, for example. Nor will it extend \p SS with the scope
00445 /// specifier.
00446 bool Sema::BuildCXXNestedNameSpecifier(Scope *S,
00447                                        IdentifierInfo &Identifier,
00448                                        SourceLocation IdentifierLoc,
00449                                        SourceLocation CCLoc,
00450                                        QualType ObjectType,
00451                                        bool EnteringContext,
00452                                        CXXScopeSpec &SS,
00453                                        NamedDecl *ScopeLookupResult,
00454                                        bool ErrorRecoveryLookup,
00455                                        bool *IsCorrectedToColon) {
00456   LookupResult Found(*this, &Identifier, IdentifierLoc, 
00457                      LookupNestedNameSpecifierName);
00458 
00459   // Determine where to perform name lookup
00460   DeclContext *LookupCtx = nullptr;
00461   bool isDependent = false;
00462   if (IsCorrectedToColon)
00463     *IsCorrectedToColon = false;
00464   if (!ObjectType.isNull()) {
00465     // This nested-name-specifier occurs in a member access expression, e.g.,
00466     // x->B::f, and we are looking into the type of the object.
00467     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
00468     LookupCtx = computeDeclContext(ObjectType);
00469     isDependent = ObjectType->isDependentType();
00470   } else if (SS.isSet()) {
00471     // This nested-name-specifier occurs after another nested-name-specifier,
00472     // so look into the context associated with the prior nested-name-specifier.
00473     LookupCtx = computeDeclContext(SS, EnteringContext);
00474     isDependent = isDependentScopeSpecifier(SS);
00475     Found.setContextRange(SS.getRange());
00476   }
00477 
00478   bool ObjectTypeSearchedInScope = false;
00479   if (LookupCtx) {
00480     // Perform "qualified" name lookup into the declaration context we
00481     // computed, which is either the type of the base of a member access
00482     // expression or the declaration context associated with a prior
00483     // nested-name-specifier.
00484 
00485     // The declaration context must be complete.
00486     if (!LookupCtx->isDependentContext() &&
00487         RequireCompleteDeclContext(SS, LookupCtx))
00488       return true;
00489 
00490     LookupQualifiedName(Found, LookupCtx);
00491 
00492     if (!ObjectType.isNull() && Found.empty()) {
00493       // C++ [basic.lookup.classref]p4:
00494       //   If the id-expression in a class member access is a qualified-id of
00495       //   the form
00496       //
00497       //        class-name-or-namespace-name::...
00498       //
00499       //   the class-name-or-namespace-name following the . or -> operator is
00500       //   looked up both in the context of the entire postfix-expression and in
00501       //   the scope of the class of the object expression. If the name is found
00502       //   only in the scope of the class of the object expression, the name
00503       //   shall refer to a class-name. If the name is found only in the
00504       //   context of the entire postfix-expression, the name shall refer to a
00505       //   class-name or namespace-name. [...]
00506       //
00507       // Qualified name lookup into a class will not find a namespace-name,
00508       // so we do not need to diagnose that case specifically. However,
00509       // this qualified name lookup may find nothing. In that case, perform
00510       // unqualified name lookup in the given scope (if available) or
00511       // reconstruct the result from when name lookup was performed at template
00512       // definition time.
00513       if (S)
00514         LookupName(Found, S);
00515       else if (ScopeLookupResult)
00516         Found.addDecl(ScopeLookupResult);
00517 
00518       ObjectTypeSearchedInScope = true;
00519     }
00520   } else if (!isDependent) {
00521     // Perform unqualified name lookup in the current scope.
00522     LookupName(Found, S);
00523   }
00524 
00525   // If we performed lookup into a dependent context and did not find anything,
00526   // that's fine: just build a dependent nested-name-specifier.
00527   if (Found.empty() && isDependent &&
00528       !(LookupCtx && LookupCtx->isRecord() &&
00529         (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
00530          !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {
00531     // Don't speculate if we're just trying to improve error recovery.
00532     if (ErrorRecoveryLookup)
00533       return true;
00534 
00535     // We were not able to compute the declaration context for a dependent
00536     // base object type or prior nested-name-specifier, so this
00537     // nested-name-specifier refers to an unknown specialization. Just build
00538     // a dependent nested-name-specifier.
00539     SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
00540     return false;
00541   }
00542 
00543   // FIXME: Deal with ambiguities cleanly.
00544 
00545   if (Found.empty() && !ErrorRecoveryLookup) {
00546     // If identifier is not found as class-name-or-namespace-name, but is found
00547     // as other entity, don't look for typos.
00548     LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
00549     if (LookupCtx)
00550       LookupQualifiedName(R, LookupCtx);
00551     else if (S && !isDependent)
00552       LookupName(R, S);
00553     if (!R.empty()) {
00554       // The identifier is found in ordinary lookup. If correction to colon is
00555       // allowed, suggest replacement to ':'.
00556       if (IsCorrectedToColon) {
00557         *IsCorrectedToColon = true;
00558         Diag(CCLoc, diag::err_nested_name_spec_is_not_class)
00559             << &Identifier << getLangOpts().CPlusPlus
00560             << FixItHint::CreateReplacement(CCLoc, ":");
00561         if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
00562           Diag(ND->getLocation(), diag::note_declared_at);
00563         return true;
00564       }
00565       // Replacement '::' -> ':' is not allowed, just issue respective error.
00566       Diag(R.getNameLoc(), diag::err_expected_class_or_namespace)
00567           << &Identifier << getLangOpts().CPlusPlus;
00568       if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
00569         Diag(ND->getLocation(), diag::note_entity_declared_at) << &Identifier;
00570       return true;
00571     }
00572   }
00573 
00574   if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MSVCCompat) {
00575     // We haven't found anything, and we're not recovering from a
00576     // different kind of error, so look for typos.
00577     DeclarationName Name = Found.getLookupName();
00578     Found.clear();
00579     if (TypoCorrection Corrected = CorrectTypo(
00580             Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
00581             llvm::make_unique<NestedNameSpecifierValidatorCCC>(*this),
00582             CTK_ErrorRecovery, LookupCtx, EnteringContext)) {
00583       if (LookupCtx) {
00584         bool DroppedSpecifier =
00585             Corrected.WillReplaceSpecifier() &&
00586             Name.getAsString() == Corrected.getAsString(getLangOpts());
00587         if (DroppedSpecifier)
00588           SS.clear();
00589         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
00590                                   << Name << LookupCtx << DroppedSpecifier
00591                                   << SS.getRange());
00592       } else
00593         diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
00594                                   << Name);
00595 
00596       if (NamedDecl *ND = Corrected.getCorrectionDecl())
00597         Found.addDecl(ND);
00598       Found.setLookupName(Corrected.getCorrection());
00599     } else {
00600       Found.setLookupName(&Identifier);
00601     }
00602   }
00603 
00604   NamedDecl *SD = Found.getAsSingle<NamedDecl>();
00605   if (isAcceptableNestedNameSpecifier(SD)) {
00606     if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
00607         !getLangOpts().CPlusPlus11) {
00608       // C++03 [basic.lookup.classref]p4:
00609       //   [...] If the name is found in both contexts, the
00610       //   class-name-or-namespace-name shall refer to the same entity.
00611       //
00612       // We already found the name in the scope of the object. Now, look
00613       // into the current scope (the scope of the postfix-expression) to
00614       // see if we can find the same name there. As above, if there is no
00615       // scope, reconstruct the result from the template instantiation itself.
00616       //
00617       // Note that C++11 does *not* perform this redundant lookup.
00618       NamedDecl *OuterDecl;
00619       if (S) {
00620         LookupResult FoundOuter(*this, &Identifier, IdentifierLoc, 
00621                                 LookupNestedNameSpecifierName);
00622         LookupName(FoundOuter, S);
00623         OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
00624       } else
00625         OuterDecl = ScopeLookupResult;
00626 
00627       if (isAcceptableNestedNameSpecifier(OuterDecl) &&
00628           OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
00629           (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
00630            !Context.hasSameType(
00631                             Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
00632                                Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
00633         if (ErrorRecoveryLookup)
00634           return true;
00635 
00636          Diag(IdentifierLoc, 
00637               diag::err_nested_name_member_ref_lookup_ambiguous)
00638            << &Identifier;
00639          Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
00640            << ObjectType;
00641          Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
00642 
00643          // Fall through so that we'll pick the name we found in the object
00644          // type, since that's probably what the user wanted anyway.
00645        }
00646     }
00647 
00648     if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))
00649       MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
00650 
00651     // If we're just performing this lookup for error-recovery purposes,
00652     // don't extend the nested-name-specifier. Just return now.
00653     if (ErrorRecoveryLookup)
00654       return false;
00655 
00656     // The use of a nested name specifier may trigger deprecation warnings.
00657     DiagnoseUseOfDecl(SD, CCLoc);
00658 
00659     
00660     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
00661       SS.Extend(Context, Namespace, IdentifierLoc, CCLoc);
00662       return false;
00663     }
00664 
00665     if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
00666       SS.Extend(Context, Alias, IdentifierLoc, CCLoc);
00667       return false;
00668     }
00669 
00670     QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
00671     TypeLocBuilder TLB;
00672     if (isa<InjectedClassNameType>(T)) {
00673       InjectedClassNameTypeLoc InjectedTL
00674         = TLB.push<InjectedClassNameTypeLoc>(T);
00675       InjectedTL.setNameLoc(IdentifierLoc);
00676     } else if (isa<RecordType>(T)) {
00677       RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
00678       RecordTL.setNameLoc(IdentifierLoc);
00679     } else if (isa<TypedefType>(T)) {
00680       TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
00681       TypedefTL.setNameLoc(IdentifierLoc);
00682     } else if (isa<EnumType>(T)) {
00683       EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
00684       EnumTL.setNameLoc(IdentifierLoc);
00685     } else if (isa<TemplateTypeParmType>(T)) {
00686       TemplateTypeParmTypeLoc TemplateTypeTL
00687         = TLB.push<TemplateTypeParmTypeLoc>(T);
00688       TemplateTypeTL.setNameLoc(IdentifierLoc);
00689     } else if (isa<UnresolvedUsingType>(T)) {
00690       UnresolvedUsingTypeLoc UnresolvedTL
00691         = TLB.push<UnresolvedUsingTypeLoc>(T);
00692       UnresolvedTL.setNameLoc(IdentifierLoc);
00693     } else if (isa<SubstTemplateTypeParmType>(T)) {
00694       SubstTemplateTypeParmTypeLoc TL 
00695         = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
00696       TL.setNameLoc(IdentifierLoc);
00697     } else if (isa<SubstTemplateTypeParmPackType>(T)) {
00698       SubstTemplateTypeParmPackTypeLoc TL
00699         = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
00700       TL.setNameLoc(IdentifierLoc);
00701     } else {
00702       llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
00703     }
00704 
00705     if (T->isEnumeralType())
00706       Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
00707 
00708     SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
00709               CCLoc);
00710     return false;
00711   }
00712 
00713   // Otherwise, we have an error case.  If we don't want diagnostics, just
00714   // return an error now.
00715   if (ErrorRecoveryLookup)
00716     return true;
00717 
00718   // If we didn't find anything during our lookup, try again with
00719   // ordinary name lookup, which can help us produce better error
00720   // messages.
00721   if (Found.empty()) {
00722     Found.clear(LookupOrdinaryName);
00723     LookupName(Found, S);
00724   }
00725 
00726   // In Microsoft mode, if we are within a templated function and we can't
00727   // resolve Identifier, then extend the SS with Identifier. This will have 
00728   // the effect of resolving Identifier during template instantiation. 
00729   // The goal is to be able to resolve a function call whose
00730   // nested-name-specifier is located inside a dependent base class.
00731   // Example: 
00732   //
00733   // class C {
00734   // public:
00735   //    static void foo2() {  }
00736   // };
00737   // template <class T> class A { public: typedef C D; };
00738   //
00739   // template <class T> class B : public A<T> {
00740   // public:
00741   //   void foo() { D::foo2(); }
00742   // };
00743   if (getLangOpts().MSVCCompat) {
00744     DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
00745     if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
00746       CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());
00747       if (ContainingClass && ContainingClass->hasAnyDependentBases()) {
00748         Diag(IdentifierLoc, diag::ext_undeclared_unqual_id_with_dependent_base)
00749             << &Identifier << ContainingClass;
00750         SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
00751         return false;
00752       }
00753     }
00754   }
00755 
00756   if (!Found.empty()) {
00757     if (TypeDecl *TD = Found.getAsSingle<TypeDecl>())
00758       Diag(IdentifierLoc, diag::err_expected_class_or_namespace)
00759           << QualType(TD->getTypeForDecl(), 0) << getLangOpts().CPlusPlus;
00760     else {
00761       Diag(IdentifierLoc, diag::err_expected_class_or_namespace)
00762           << &Identifier << getLangOpts().CPlusPlus;
00763       if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
00764         Diag(ND->getLocation(), diag::note_entity_declared_at) << &Identifier;
00765     }
00766   } else if (SS.isSet())
00767     Diag(IdentifierLoc, diag::err_no_member) << &Identifier << LookupCtx
00768                                              << SS.getRange();
00769   else
00770     Diag(IdentifierLoc, diag::err_undeclared_var_use) << &Identifier;
00771 
00772   return true;
00773 }
00774 
00775 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
00776                                        IdentifierInfo &Identifier,
00777                                        SourceLocation IdentifierLoc,
00778                                        SourceLocation CCLoc,
00779                                        ParsedType ObjectType,
00780                                        bool EnteringContext,
00781                                        CXXScopeSpec &SS,
00782                                        bool ErrorRecoveryLookup,
00783                                        bool *IsCorrectedToColon) {
00784   if (SS.isInvalid())
00785     return true;
00786 
00787   return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc,
00788                                      GetTypeFromParser(ObjectType),
00789                                      EnteringContext, SS, 
00790                                      /*ScopeLookupResult=*/nullptr, false,
00791                                      IsCorrectedToColon);
00792 }
00793 
00794 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
00795                                                const DeclSpec &DS,
00796                                                SourceLocation ColonColonLoc) {
00797   if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
00798     return true;
00799 
00800   assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
00801 
00802   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
00803   if (!T->isDependentType() && !T->getAs<TagType>()) {
00804     Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) 
00805       << T << getLangOpts().CPlusPlus;
00806     return true;
00807   }
00808 
00809   TypeLocBuilder TLB;
00810   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
00811   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
00812   SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
00813             ColonColonLoc);
00814   return false;
00815 }
00816 
00817 /// IsInvalidUnlessNestedName - This method is used for error recovery
00818 /// purposes to determine whether the specified identifier is only valid as
00819 /// a nested name specifier, for example a namespace name.  It is
00820 /// conservatively correct to always return false from this method.
00821 ///
00822 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
00823 bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
00824                                      IdentifierInfo &Identifier, 
00825                                      SourceLocation IdentifierLoc,
00826                                      SourceLocation ColonLoc,
00827                                      ParsedType ObjectType,
00828                                      bool EnteringContext) {
00829   if (SS.isInvalid())
00830     return false;
00831 
00832   return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc,
00833                                       GetTypeFromParser(ObjectType),
00834                                       EnteringContext, SS, 
00835                                       /*ScopeLookupResult=*/nullptr, true);
00836 }
00837 
00838 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
00839                                        CXXScopeSpec &SS,
00840                                        SourceLocation TemplateKWLoc,
00841                                        TemplateTy Template,
00842                                        SourceLocation TemplateNameLoc,
00843                                        SourceLocation LAngleLoc,
00844                                        ASTTemplateArgsPtr TemplateArgsIn,
00845                                        SourceLocation RAngleLoc,
00846                                        SourceLocation CCLoc,
00847                                        bool EnteringContext) {
00848   if (SS.isInvalid())
00849     return true;
00850   
00851   // Translate the parser's template argument list in our AST format.
00852   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
00853   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
00854 
00855   DependentTemplateName *DTN = Template.get().getAsDependentTemplateName();
00856   if (DTN && DTN->isIdentifier()) {
00857     // Handle a dependent template specialization for which we cannot resolve
00858     // the template name.
00859     assert(DTN->getQualifier() == SS.getScopeRep());
00860     QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
00861                                                           DTN->getQualifier(),
00862                                                           DTN->getIdentifier(),
00863                                                                 TemplateArgs);
00864     
00865     // Create source-location information for this type.
00866     TypeLocBuilder Builder;
00867     DependentTemplateSpecializationTypeLoc SpecTL
00868       = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
00869     SpecTL.setElaboratedKeywordLoc(SourceLocation());
00870     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
00871     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
00872     SpecTL.setTemplateNameLoc(TemplateNameLoc);
00873     SpecTL.setLAngleLoc(LAngleLoc);
00874     SpecTL.setRAngleLoc(RAngleLoc);
00875     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
00876       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
00877     
00878     SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
00879               CCLoc);
00880     return false;
00881   }
00882 
00883   TemplateDecl *TD = Template.get().getAsTemplateDecl();
00884   if (Template.get().getAsOverloadedTemplate() || DTN ||
00885       isa<FunctionTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)) {
00886     SourceRange R(TemplateNameLoc, RAngleLoc);
00887     if (SS.getRange().isValid())
00888       R.setBegin(SS.getRange().getBegin());
00889 
00890     Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
00891       << (TD && isa<VarTemplateDecl>(TD)) << Template.get() << R;
00892     NoteAllFoundTemplates(Template.get());
00893     return true;
00894   }
00895 
00896   // We were able to resolve the template name to an actual template. 
00897   // Build an appropriate nested-name-specifier.
00898   QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc, 
00899                                    TemplateArgs);
00900   if (T.isNull())
00901     return true;
00902 
00903   // Alias template specializations can produce types which are not valid
00904   // nested name specifiers.
00905   if (!T->isDependentType() && !T->getAs<TagType>()) {
00906     Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
00907     NoteAllFoundTemplates(Template.get());
00908     return true;
00909   }
00910 
00911   // Provide source-location information for the template specialization type.
00912   TypeLocBuilder Builder;
00913   TemplateSpecializationTypeLoc SpecTL
00914     = Builder.push<TemplateSpecializationTypeLoc>(T);
00915   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
00916   SpecTL.setTemplateNameLoc(TemplateNameLoc);
00917   SpecTL.setLAngleLoc(LAngleLoc);
00918   SpecTL.setRAngleLoc(RAngleLoc);
00919   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
00920     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
00921 
00922 
00923   SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
00924             CCLoc);
00925   return false;
00926 }
00927 
00928 namespace {
00929   /// \brief A structure that stores a nested-name-specifier annotation,
00930   /// including both the nested-name-specifier 
00931   struct NestedNameSpecifierAnnotation {
00932     NestedNameSpecifier *NNS;
00933   };
00934 }
00935 
00936 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
00937   if (SS.isEmpty() || SS.isInvalid())
00938     return nullptr;
00939 
00940   void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) +
00941                                                         SS.location_size()),
00942                                llvm::alignOf<NestedNameSpecifierAnnotation>());
00943   NestedNameSpecifierAnnotation *Annotation
00944     = new (Mem) NestedNameSpecifierAnnotation;
00945   Annotation->NNS = SS.getScopeRep();
00946   memcpy(Annotation + 1, SS.location_data(), SS.location_size());
00947   return Annotation;
00948 }
00949 
00950 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr, 
00951                                                 SourceRange AnnotationRange,
00952                                                 CXXScopeSpec &SS) {
00953   if (!AnnotationPtr) {
00954     SS.SetInvalid(AnnotationRange);
00955     return;
00956   }
00957   
00958   NestedNameSpecifierAnnotation *Annotation
00959     = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
00960   SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
00961 }
00962 
00963 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
00964   assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
00965 
00966   NestedNameSpecifier *Qualifier = SS.getScopeRep();
00967 
00968   // There are only two places a well-formed program may qualify a
00969   // declarator: first, when defining a namespace or class member
00970   // out-of-line, and second, when naming an explicitly-qualified
00971   // friend function.  The latter case is governed by
00972   // C++03 [basic.lookup.unqual]p10:
00973   //   In a friend declaration naming a member function, a name used
00974   //   in the function declarator and not part of a template-argument
00975   //   in a template-id is first looked up in the scope of the member
00976   //   function's class. If it is not found, or if the name is part of
00977   //   a template-argument in a template-id, the look up is as
00978   //   described for unqualified names in the definition of the class
00979   //   granting friendship.
00980   // i.e. we don't push a scope unless it's a class member.
00981 
00982   switch (Qualifier->getKind()) {
00983   case NestedNameSpecifier::Global:
00984   case NestedNameSpecifier::Namespace:
00985   case NestedNameSpecifier::NamespaceAlias:
00986     // These are always namespace scopes.  We never want to enter a
00987     // namespace scope from anything but a file context.
00988     return CurContext->getRedeclContext()->isFileContext();
00989 
00990   case NestedNameSpecifier::Identifier:
00991   case NestedNameSpecifier::TypeSpec:
00992   case NestedNameSpecifier::TypeSpecWithTemplate:
00993   case NestedNameSpecifier::Super:
00994     // These are never namespace scopes.
00995     return true;
00996   }
00997 
00998   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
00999 }
01000 
01001 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
01002 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
01003 /// After this method is called, according to [C++ 3.4.3p3], names should be
01004 /// looked up in the declarator-id's scope, until the declarator is parsed and
01005 /// ActOnCXXExitDeclaratorScope is called.
01006 /// The 'SS' should be a non-empty valid CXXScopeSpec.
01007 bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
01008   assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
01009 
01010   if (SS.isInvalid()) return true;
01011 
01012   DeclContext *DC = computeDeclContext(SS, true);
01013   if (!DC) return true;
01014 
01015   // Before we enter a declarator's context, we need to make sure that
01016   // it is a complete declaration context.
01017   if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
01018     return true;
01019     
01020   EnterDeclaratorContext(S, DC);
01021 
01022   // Rebuild the nested name specifier for the new scope.
01023   if (DC->isDependentContext())
01024     RebuildNestedNameSpecifierInCurrentInstantiation(SS);
01025 
01026   return false;
01027 }
01028 
01029 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
01030 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
01031 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
01032 /// Used to indicate that names should revert to being looked up in the
01033 /// defining scope.
01034 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
01035   assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
01036   if (SS.isInvalid())
01037     return;
01038   assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
01039          "exiting declarator scope we never really entered");
01040   ExitDeclaratorContext(S);
01041 }