| //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/ |
| // |
| // The LLVM Compiler Infrastructure |
| // |
| // This file is distributed under the University of Illinois Open Source |
| // License. See LICENSE.TXT for details. |
| //===----------------------------------------------------------------------===/ |
| // |
| // This file implements semantic analysis for C++ templates. |
| //===----------------------------------------------------------------------===/ |
| |
| #include "TreeTransform.h" |
| #include "clang/AST/ASTConsumer.h" |
| #include "clang/AST/ASTContext.h" |
| #include "clang/AST/DeclFriend.h" |
| #include "clang/AST/DeclTemplate.h" |
| #include "clang/AST/Expr.h" |
| #include "clang/AST/ExprCXX.h" |
| #include "clang/AST/RecursiveASTVisitor.h" |
| #include "clang/AST/TypeVisitor.h" |
| #include "clang/Basic/LangOptions.h" |
| #include "clang/Basic/PartialDiagnostic.h" |
| #include "clang/Basic/TargetInfo.h" |
| #include "clang/Sema/DeclSpec.h" |
| #include "clang/Sema/Lookup.h" |
| #include "clang/Sema/ParsedTemplate.h" |
| #include "clang/Sema/Scope.h" |
| #include "clang/Sema/SemaInternal.h" |
| #include "clang/Sema/Template.h" |
| #include "clang/Sema/TemplateDeduction.h" |
| #include "llvm/ADT/SmallBitVector.h" |
| #include "llvm/ADT/SmallString.h" |
| #include "llvm/ADT/StringExtras.h" |
| using namespace clang; |
| using namespace sema; |
| |
| // Exported for use by Parser. |
| SourceRange |
| clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, |
| unsigned N) { |
| if (!N) return SourceRange(); |
| return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); |
| } |
| |
| /// \brief Determine whether the declaration found is acceptable as the name |
| /// of a template and, if so, return that template declaration. Otherwise, |
| /// returns NULL. |
| static NamedDecl *isAcceptableTemplateName(ASTContext &Context, |
| NamedDecl *Orig, |
| bool AllowFunctionTemplates) { |
| NamedDecl *D = Orig->getUnderlyingDecl(); |
| |
| if (isa<TemplateDecl>(D)) { |
| if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) |
| return 0; |
| |
| return Orig; |
| } |
| |
| if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { |
| // C++ [temp.local]p1: |
| // Like normal (non-template) classes, class templates have an |
| // injected-class-name (Clause 9). The injected-class-name |
| // can be used with or without a template-argument-list. When |
| // it is used without a template-argument-list, it is |
| // equivalent to the injected-class-name followed by the |
| // template-parameters of the class template enclosed in |
| // <>. When it is used with a template-argument-list, it |
| // refers to the specified class template specialization, |
| // which could be the current specialization or another |
| // specialization. |
| if (Record->isInjectedClassName()) { |
| Record = cast<CXXRecordDecl>(Record->getDeclContext()); |
| if (Record->getDescribedClassTemplate()) |
| return Record->getDescribedClassTemplate(); |
| |
| if (ClassTemplateSpecializationDecl *Spec |
| = dyn_cast<ClassTemplateSpecializationDecl>(Record)) |
| return Spec->getSpecializedTemplate(); |
| } |
| |
| return 0; |
| } |
| |
| return 0; |
| } |
| |
| void Sema::FilterAcceptableTemplateNames(LookupResult &R, |
| bool AllowFunctionTemplates) { |
| // The set of class templates we've already seen. |
| llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates; |
| LookupResult::Filter filter = R.makeFilter(); |
| while (filter.hasNext()) { |
| NamedDecl *Orig = filter.next(); |
| NamedDecl *Repl = isAcceptableTemplateName(Context, Orig, |
| AllowFunctionTemplates); |
| if (!Repl) |
| filter.erase(); |
| else if (Repl != Orig) { |
| |
| // C++ [temp.local]p3: |
| // A lookup that finds an injected-class-name (10.2) can result in an |
| // ambiguity in certain cases (for example, if it is found in more than |
| // one base class). If all of the injected-class-names that are found |
| // refer to specializations of the same class template, and if the name |
| // is used as a template-name, the reference refers to the class |
| // template itself and not a specialization thereof, and is not |
| // ambiguous. |
| if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl)) |
| if (!ClassTemplates.insert(ClassTmpl)) { |
| filter.erase(); |
| continue; |
| } |
| |
| // FIXME: we promote access to public here as a workaround to |
| // the fact that LookupResult doesn't let us remember that we |
| // found this template through a particular injected class name, |
| // which means we end up doing nasty things to the invariants. |
| // Pretending that access is public is *much* safer. |
| filter.replace(Repl, AS_public); |
| } |
| } |
| filter.done(); |
| } |
| |
| bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, |
| bool AllowFunctionTemplates) { |
| for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) |
| if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates)) |
| return true; |
| |
| return false; |
| } |
| |
| TemplateNameKind Sema::isTemplateName(Scope *S, |
| CXXScopeSpec &SS, |
| bool hasTemplateKeyword, |
| UnqualifiedId &Name, |
| ParsedType ObjectTypePtr, |
| bool EnteringContext, |
| TemplateTy &TemplateResult, |
| bool &MemberOfUnknownSpecialization) { |
| assert(getLangOpts().CPlusPlus && "No template names in C!"); |
| |
| DeclarationName TName; |
| MemberOfUnknownSpecialization = false; |
| |
| switch (Name.getKind()) { |
| case UnqualifiedId::IK_Identifier: |
| TName = DeclarationName(Name.Identifier); |
| break; |
| |
| case UnqualifiedId::IK_OperatorFunctionId: |
| TName = Context.DeclarationNames.getCXXOperatorName( |
| Name.OperatorFunctionId.Operator); |
| break; |
| |
| case UnqualifiedId::IK_LiteralOperatorId: |
| TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); |
| break; |
| |
| default: |
| return TNK_Non_template; |
| } |
| |
| QualType ObjectType = ObjectTypePtr.get(); |
| |
| LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName); |
| LookupTemplateName(R, S, SS, ObjectType, EnteringContext, |
| MemberOfUnknownSpecialization); |
| if (R.empty()) return TNK_Non_template; |
| if (R.isAmbiguous()) { |
| // Suppress diagnostics; we'll redo this lookup later. |
| R.suppressDiagnostics(); |
| |
| // FIXME: we might have ambiguous templates, in which case we |
| // should at least parse them properly! |
| return TNK_Non_template; |
| } |
| |
| TemplateName Template; |
| TemplateNameKind TemplateKind; |
| |
| unsigned ResultCount = R.end() - R.begin(); |
| if (ResultCount > 1) { |
| // We assume that we'll preserve the qualifier from a function |
| // template name in other ways. |
| Template = Context.getOverloadedTemplateName(R.begin(), R.end()); |
| TemplateKind = TNK_Function_template; |
| |
| // We'll do this lookup again later. |
| R.suppressDiagnostics(); |
| } else { |
| TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl()); |
| |
| if (SS.isSet() && !SS.isInvalid()) { |
| NestedNameSpecifier *Qualifier = SS.getScopeRep(); |
| Template = Context.getQualifiedTemplateName(Qualifier, |
| hasTemplateKeyword, TD); |
| } else { |
| Template = TemplateName(TD); |
| } |
| |
| if (isa<FunctionTemplateDecl>(TD)) { |
| TemplateKind = TNK_Function_template; |
| |
| // We'll do this lookup again later. |
| R.suppressDiagnostics(); |
| } else { |
| assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || |
| isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)); |
| TemplateKind = |
| isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template; |
| } |
| } |
| |
| TemplateResult = TemplateTy::make(Template); |
| return TemplateKind; |
| } |
| |
| bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, |
| SourceLocation IILoc, |
| Scope *S, |
| const CXXScopeSpec *SS, |
| TemplateTy &SuggestedTemplate, |
| TemplateNameKind &SuggestedKind) { |
| // We can't recover unless there's a dependent scope specifier preceding the |
| // template name. |
| // FIXME: Typo correction? |
| if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || |
| computeDeclContext(*SS)) |
| return false; |
| |
| // The code is missing a 'template' keyword prior to the dependent template |
| // name. |
| NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); |
| Diag(IILoc, diag::err_template_kw_missing) |
| << Qualifier << II.getName() |
| << FixItHint::CreateInsertion(IILoc, "template "); |
| SuggestedTemplate |
| = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); |
| SuggestedKind = TNK_Dependent_template_name; |
| return true; |
| } |
| |
| void Sema::LookupTemplateName(LookupResult &Found, |
| Scope *S, CXXScopeSpec &SS, |
| QualType ObjectType, |
| bool EnteringContext, |
| bool &MemberOfUnknownSpecialization) { |
| // Determine where to perform name lookup |
| MemberOfUnknownSpecialization = false; |
| DeclContext *LookupCtx = 0; |
| bool isDependent = false; |
| if (!ObjectType.isNull()) { |
| // This nested-name-specifier occurs in a member access expression, e.g., |
| // x->B::f, and we are looking into the type of the object. |
| assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); |
| LookupCtx = computeDeclContext(ObjectType); |
| isDependent = ObjectType->isDependentType(); |
| assert((isDependent || !ObjectType->isIncompleteType() || |
| ObjectType->castAs<TagType>()->isBeingDefined()) && |
| "Caller should have completed object type"); |
| |
| // Template names cannot appear inside an Objective-C class or object type. |
| if (ObjectType->isObjCObjectOrInterfaceType()) { |
| Found.clear(); |
| return; |
| } |
| } else if (SS.isSet()) { |
| // This nested-name-specifier occurs after another nested-name-specifier, |
| // so long into the context associated with the prior nested-name-specifier. |
| LookupCtx = computeDeclContext(SS, EnteringContext); |
| isDependent = isDependentScopeSpecifier(SS); |
| |
| // The declaration context must be complete. |
| if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) |
| return; |
| } |
| |
| bool ObjectTypeSearchedInScope = false; |
| bool AllowFunctionTemplatesInLookup = true; |
| if (LookupCtx) { |
| // Perform "qualified" name lookup into the declaration context we |
| // computed, which is either the type of the base of a member access |
| // expression or the declaration context associated with a prior |
| // nested-name-specifier. |
| LookupQualifiedName(Found, LookupCtx); |
| if (!ObjectType.isNull() && Found.empty()) { |
| // C++ [basic.lookup.classref]p1: |
| // In a class member access expression (5.2.5), if the . or -> token is |
| // immediately followed by an identifier followed by a <, the |
| // identifier must be looked up to determine whether the < is the |
| // beginning of a template argument list (14.2) or a less-than operator. |
| // The identifier is first looked up in the class of the object |
| // expression. If the identifier is not found, it is then looked up in |
| // the context of the entire postfix-expression and shall name a class |
| // or function template. |
| if (S) LookupName(Found, S); |
| ObjectTypeSearchedInScope = true; |
| AllowFunctionTemplatesInLookup = false; |
| } |
| } else if (isDependent && (!S || ObjectType.isNull())) { |
| // We cannot look into a dependent object type or nested nme |
| // specifier. |
| MemberOfUnknownSpecialization = true; |
| return; |
| } else { |
| // Perform unqualified name lookup in the current scope. |
| LookupName(Found, S); |
| |
| if (!ObjectType.isNull()) |
| AllowFunctionTemplatesInLookup = false; |
| } |
| |
| if (Found.empty() && !isDependent) { |
| // If we did not find any names, attempt to correct any typos. |
| DeclarationName Name = Found.getLookupName(); |
| Found.clear(); |
| // Simple filter callback that, for keywords, only accepts the C++ *_cast |
| CorrectionCandidateCallback FilterCCC; |
| FilterCCC.WantTypeSpecifiers = false; |
| FilterCCC.WantExpressionKeywords = false; |
| FilterCCC.WantRemainingKeywords = false; |
| FilterCCC.WantCXXNamedCasts = true; |
| if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(), |
| Found.getLookupKind(), S, &SS, |
| FilterCCC, CTK_ErrorRecovery, |
| LookupCtx)) { |
| Found.setLookupName(Corrected.getCorrection()); |
| if (Corrected.getCorrectionDecl()) |
| Found.addDecl(Corrected.getCorrectionDecl()); |
| FilterAcceptableTemplateNames(Found); |
| if (!Found.empty()) { |
| if (LookupCtx) { |
| std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
| bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
| Name.getAsString() == CorrectedStr; |
| diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) |
| << Name << LookupCtx << DroppedSpecifier |
| << SS.getRange()); |
| } else { |
| diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); |
| } |
| } |
| } else { |
| Found.setLookupName(Name); |
| } |
| } |
| |
| FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); |
| if (Found.empty()) { |
| if (isDependent) |
| MemberOfUnknownSpecialization = true; |
| return; |
| } |
| |
| if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && |
| !getLangOpts().CPlusPlus11) { |
| // C++03 [basic.lookup.classref]p1: |
| // [...] If the lookup in the class of the object expression finds a |
| // template, the name is also looked up in the context of the entire |
| // postfix-expression and [...] |
| // |
| // Note: C++11 does not perform this second lookup. |
| LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), |
| LookupOrdinaryName); |
| LookupName(FoundOuter, S); |
| FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); |
| |
| if (FoundOuter.empty()) { |
| // - if the name is not found, the name found in the class of the |
| // object expression is used, otherwise |
| } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() || |
| FoundOuter.isAmbiguous()) { |
| // - if the name is found in the context of the entire |
| // postfix-expression and does not name a class template, the name |
| // found in the class of the object expression is used, otherwise |
| FoundOuter.clear(); |
| } else if (!Found.isSuppressingDiagnostics()) { |
| // - if the name found is a class template, it must refer to the same |
| // entity as the one found in the class of the object expression, |
| // otherwise the program is ill-formed. |
| if (!Found.isSingleResult() || |
| Found.getFoundDecl()->getCanonicalDecl() |
| != FoundOuter.getFoundDecl()->getCanonicalDecl()) { |
| Diag(Found.getNameLoc(), |
| diag::ext_nested_name_member_ref_lookup_ambiguous) |
| << Found.getLookupName() |
| << ObjectType; |
| Diag(Found.getRepresentativeDecl()->getLocation(), |
| diag::note_ambig_member_ref_object_type) |
| << ObjectType; |
| Diag(FoundOuter.getFoundDecl()->getLocation(), |
| diag::note_ambig_member_ref_scope); |
| |
| // Recover by taking the template that we found in the object |
| // expression's type. |
| } |
| } |
| } |
| } |
| |
| /// ActOnDependentIdExpression - Handle a dependent id-expression that |
| /// was just parsed. This is only possible with an explicit scope |
| /// specifier naming a dependent type. |
| ExprResult |
| Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, |
| SourceLocation TemplateKWLoc, |
| const DeclarationNameInfo &NameInfo, |
| bool isAddressOfOperand, |
| const TemplateArgumentListInfo *TemplateArgs) { |
| DeclContext *DC = getFunctionLevelDeclContext(); |
| |
| if (!isAddressOfOperand && |
| isa<CXXMethodDecl>(DC) && |
| cast<CXXMethodDecl>(DC)->isInstance()) { |
| QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); |
| |
| // Since the 'this' expression is synthesized, we don't need to |
| // perform the double-lookup check. |
| NamedDecl *FirstQualifierInScope = 0; |
| |
| return Owned(CXXDependentScopeMemberExpr::Create(Context, |
| /*This*/ 0, ThisType, |
| /*IsArrow*/ true, |
| /*Op*/ SourceLocation(), |
| SS.getWithLocInContext(Context), |
| TemplateKWLoc, |
| FirstQualifierInScope, |
| NameInfo, |
| TemplateArgs)); |
| } |
| |
| return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); |
| } |
| |
| ExprResult |
| Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, |
| SourceLocation TemplateKWLoc, |
| const DeclarationNameInfo &NameInfo, |
| const TemplateArgumentListInfo *TemplateArgs) { |
| return Owned(DependentScopeDeclRefExpr::Create(Context, |
| SS.getWithLocInContext(Context), |
| TemplateKWLoc, |
| NameInfo, |
| TemplateArgs)); |
| } |
| |
| /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining |
| /// that the template parameter 'PrevDecl' is being shadowed by a new |
| /// declaration at location Loc. Returns true to indicate that this is |
| /// an error, and false otherwise. |
| void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { |
| assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); |
| |
| // Microsoft Visual C++ permits template parameters to be shadowed. |
| if (getLangOpts().MicrosoftExt) |
| return; |
| |
| // C++ [temp.local]p4: |
| // A template-parameter shall not be redeclared within its |
| // scope (including nested scopes). |
| Diag(Loc, diag::err_template_param_shadow) |
| << cast<NamedDecl>(PrevDecl)->getDeclName(); |
| Diag(PrevDecl->getLocation(), diag::note_template_param_here); |
| return; |
| } |
| |
| /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset |
| /// the parameter D to reference the templated declaration and return a pointer |
| /// to the template declaration. Otherwise, do nothing to D and return null. |
| TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { |
| if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { |
| D = Temp->getTemplatedDecl(); |
| return Temp; |
| } |
| return 0; |
| } |
| |
| ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( |
| SourceLocation EllipsisLoc) const { |
| assert(Kind == Template && |
| "Only template template arguments can be pack expansions here"); |
| assert(getAsTemplate().get().containsUnexpandedParameterPack() && |
| "Template template argument pack expansion without packs"); |
| ParsedTemplateArgument Result(*this); |
| Result.EllipsisLoc = EllipsisLoc; |
| return Result; |
| } |
| |
| static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, |
| const ParsedTemplateArgument &Arg) { |
| |
| switch (Arg.getKind()) { |
| case ParsedTemplateArgument::Type: { |
| TypeSourceInfo *DI; |
| QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); |
| if (!DI) |
| DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); |
| return TemplateArgumentLoc(TemplateArgument(T), DI); |
| } |
| |
| case ParsedTemplateArgument::NonType: { |
| Expr *E = static_cast<Expr *>(Arg.getAsExpr()); |
| return TemplateArgumentLoc(TemplateArgument(E), E); |
| } |
| |
| case ParsedTemplateArgument::Template: { |
| TemplateName Template = Arg.getAsTemplate().get(); |
| TemplateArgument TArg; |
| if (Arg.getEllipsisLoc().isValid()) |
| TArg = TemplateArgument(Template, Optional<unsigned int>()); |
| else |
| TArg = Template; |
| return TemplateArgumentLoc(TArg, |
| Arg.getScopeSpec().getWithLocInContext( |
| SemaRef.Context), |
| Arg.getLocation(), |
| Arg.getEllipsisLoc()); |
| } |
| } |
| |
| llvm_unreachable("Unhandled parsed template argument"); |
| } |
| |
| /// \brief Translates template arguments as provided by the parser |
| /// into template arguments used by semantic analysis. |
| void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, |
| TemplateArgumentListInfo &TemplateArgs) { |
| for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) |
| TemplateArgs.addArgument(translateTemplateArgument(*this, |
| TemplateArgsIn[I])); |
| } |
| |
| static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, |
| SourceLocation Loc, |
| IdentifierInfo *Name) { |
| NamedDecl *PrevDecl = SemaRef.LookupSingleName( |
| S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); |
| if (PrevDecl && PrevDecl->isTemplateParameter()) |
| SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); |
| } |
| |
| /// ActOnTypeParameter - Called when a C++ template type parameter |
| /// (e.g., "typename T") has been parsed. Typename specifies whether |
| /// the keyword "typename" was used to declare the type parameter |
| /// (otherwise, "class" was used), and KeyLoc is the location of the |
| /// "class" or "typename" keyword. ParamName is the name of the |
| /// parameter (NULL indicates an unnamed template parameter) and |
| /// ParamNameLoc is the location of the parameter name (if any). |
| /// If the type parameter has a default argument, it will be added |
| /// later via ActOnTypeParameterDefault. |
| Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, |
| SourceLocation EllipsisLoc, |
| SourceLocation KeyLoc, |
| IdentifierInfo *ParamName, |
| SourceLocation ParamNameLoc, |
| unsigned Depth, unsigned Position, |
| SourceLocation EqualLoc, |
| ParsedType DefaultArg) { |
| assert(S->isTemplateParamScope() && |
| "Template type parameter not in template parameter scope!"); |
| bool Invalid = false; |
| |
| SourceLocation Loc = ParamNameLoc; |
| if (!ParamName) |
| Loc = KeyLoc; |
| |
| TemplateTypeParmDecl *Param |
| = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
| KeyLoc, Loc, Depth, Position, ParamName, |
| Typename, Ellipsis); |
| Param->setAccess(AS_public); |
| if (Invalid) |
| Param->setInvalidDecl(); |
| |
| if (ParamName) { |
| maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); |
| |
| // Add the template parameter into the current scope. |
| S->AddDecl(Param); |
| IdResolver.AddDecl(Param); |
| } |
| |
| // C++0x [temp.param]p9: |
| // A default template-argument may be specified for any kind of |
| // template-parameter that is not a template parameter pack. |
| if (DefaultArg && Ellipsis) { |
| Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
| DefaultArg = ParsedType(); |
| } |
| |
| // Handle the default argument, if provided. |
| if (DefaultArg) { |
| TypeSourceInfo *DefaultTInfo; |
| GetTypeFromParser(DefaultArg, &DefaultTInfo); |
| |
| assert(DefaultTInfo && "expected source information for type"); |
| |
| // Check for unexpanded parameter packs. |
| if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo, |
| UPPC_DefaultArgument)) |
| return Param; |
| |
| // Check the template argument itself. |
| if (CheckTemplateArgument(Param, DefaultTInfo)) { |
| Param->setInvalidDecl(); |
| return Param; |
| } |
| |
| Param->setDefaultArgument(DefaultTInfo, false); |
| } |
| |
| return Param; |
| } |
| |
| /// \brief Check that the type of a non-type template parameter is |
| /// well-formed. |
| /// |
| /// \returns the (possibly-promoted) parameter type if valid; |
| /// otherwise, produces a diagnostic and returns a NULL type. |
| QualType |
| Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { |
| // We don't allow variably-modified types as the type of non-type template |
| // parameters. |
| if (T->isVariablyModifiedType()) { |
| Diag(Loc, diag::err_variably_modified_nontype_template_param) |
| << T; |
| return QualType(); |
| } |
| |
| // C++ [temp.param]p4: |
| // |
| // A non-type template-parameter shall have one of the following |
| // (optionally cv-qualified) types: |
| // |
| // -- integral or enumeration type, |
| if (T->isIntegralOrEnumerationType() || |
| // -- pointer to object or pointer to function, |
| T->isPointerType() || |
| // -- reference to object or reference to function, |
| T->isReferenceType() || |
| // -- pointer to member, |
| T->isMemberPointerType() || |
| // -- std::nullptr_t. |
| T->isNullPtrType() || |
| // If T is a dependent type, we can't do the check now, so we |
| // assume that it is well-formed. |
| T->isDependentType()) { |
| // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter |
| // are ignored when determining its type. |
| return T.getUnqualifiedType(); |
| } |
| |
| // C++ [temp.param]p8: |
| // |
| // A non-type template-parameter of type "array of T" or |
| // "function returning T" is adjusted to be of type "pointer to |
| // T" or "pointer to function returning T", respectively. |
| else if (T->isArrayType()) |
| // FIXME: Keep the type prior to promotion? |
| return Context.getArrayDecayedType(T); |
| else if (T->isFunctionType()) |
| // FIXME: Keep the type prior to promotion? |
| return Context.getPointerType(T); |
| |
| Diag(Loc, diag::err_template_nontype_parm_bad_type) |
| << T; |
| |
| return QualType(); |
| } |
| |
| Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, |
| unsigned Depth, |
| unsigned Position, |
| SourceLocation EqualLoc, |
| Expr *Default) { |
| TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
| QualType T = TInfo->getType(); |
| |
| assert(S->isTemplateParamScope() && |
| "Non-type template parameter not in template parameter scope!"); |
| bool Invalid = false; |
| |
| T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); |
| if (T.isNull()) { |
| T = Context.IntTy; // Recover with an 'int' type. |
| Invalid = true; |
| } |
| |
| IdentifierInfo *ParamName = D.getIdentifier(); |
| bool IsParameterPack = D.hasEllipsis(); |
| NonTypeTemplateParmDecl *Param |
| = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
| D.getLocStart(), |
| D.getIdentifierLoc(), |
| Depth, Position, ParamName, T, |
| IsParameterPack, TInfo); |
| Param->setAccess(AS_public); |
| |
| if (Invalid) |
| Param->setInvalidDecl(); |
| |
| if (ParamName) { |
| maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), |
| ParamName); |
| |
| // Add the template parameter into the current scope. |
| S->AddDecl(Param); |
| IdResolver.AddDecl(Param); |
| } |
| |
| // C++0x [temp.param]p9: |
| // A default template-argument may be specified for any kind of |
| // template-parameter that is not a template parameter pack. |
| if (Default && IsParameterPack) { |
| Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
| Default = 0; |
| } |
| |
| // Check the well-formedness of the default template argument, if provided. |
| if (Default) { |
| // Check for unexpanded parameter packs. |
| if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) |
| return Param; |
| |
| TemplateArgument Converted; |
| ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted); |
| if (DefaultRes.isInvalid()) { |
| Param->setInvalidDecl(); |
| return Param; |
| } |
| Default = DefaultRes.take(); |
| |
| Param->setDefaultArgument(Default, false); |
| } |
| |
| return Param; |
| } |
| |
| /// ActOnTemplateTemplateParameter - Called when a C++ template template |
| /// parameter (e.g. T in template <template \<typename> class T> class array) |
| /// has been parsed. S is the current scope. |
| Decl *Sema::ActOnTemplateTemplateParameter(Scope* S, |
| SourceLocation TmpLoc, |
| TemplateParameterList *Params, |
| SourceLocation EllipsisLoc, |
| IdentifierInfo *Name, |
| SourceLocation NameLoc, |
| unsigned Depth, |
| unsigned Position, |
| SourceLocation EqualLoc, |
| ParsedTemplateArgument Default) { |
| assert(S->isTemplateParamScope() && |
| "Template template parameter not in template parameter scope!"); |
| |
| // Construct the parameter object. |
| bool IsParameterPack = EllipsisLoc.isValid(); |
| TemplateTemplateParmDecl *Param = |
| TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), |
| NameLoc.isInvalid()? TmpLoc : NameLoc, |
| Depth, Position, IsParameterPack, |
| Name, Params); |
| Param->setAccess(AS_public); |
| |
| // If the template template parameter has a name, then link the identifier |
| // into the scope and lookup mechanisms. |
| if (Name) { |
| maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); |
| |
| S->AddDecl(Param); |
| IdResolver.AddDecl(Param); |
| } |
| |
| if (Params->size() == 0) { |
| Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) |
| << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); |
| Param->setInvalidDecl(); |
| } |
| |
| // C++0x [temp.param]p9: |
| // A default template-argument may be specified for any kind of |
| // template-parameter that is not a template parameter pack. |
| if (IsParameterPack && !Default.isInvalid()) { |
| Diag(EqualLoc, diag::err_template_param_pack_default_arg); |
| Default = ParsedTemplateArgument(); |
| } |
| |
| if (!Default.isInvalid()) { |
| // Check only that we have a template template argument. We don't want to |
| // try to check well-formedness now, because our template template parameter |
| // might have dependent types in its template parameters, which we wouldn't |
| // be able to match now. |
| // |
| // If none of the template template parameter's template arguments mention |
| // other template parameters, we could actually perform more checking here. |
| // However, it isn't worth doing. |
| TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); |
| if (DefaultArg.getArgument().getAsTemplate().isNull()) { |
| Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) |
| << DefaultArg.getSourceRange(); |
| return Param; |
| } |
| |
| // Check for unexpanded parameter packs. |
| if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), |
| DefaultArg.getArgument().getAsTemplate(), |
| UPPC_DefaultArgument)) |
| return Param; |
| |
| Param->setDefaultArgument(DefaultArg, false); |
| } |
| |
| return Param; |
| } |
| |
| /// ActOnTemplateParameterList - Builds a TemplateParameterList that |
| /// contains the template parameters in Params/NumParams. |
| TemplateParameterList * |
| Sema::ActOnTemplateParameterList(unsigned Depth, |
| SourceLocation ExportLoc, |
| SourceLocation TemplateLoc, |
| SourceLocation LAngleLoc, |
| Decl **Params, unsigned NumParams, |
| SourceLocation RAngleLoc) { |
| if (ExportLoc.isValid()) |
| Diag(ExportLoc, diag::warn_template_export_unsupported); |
| |
| return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, |
| (NamedDecl**)Params, NumParams, |
| RAngleLoc); |
| } |
| |
| static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) { |
| if (SS.isSet()) |
| T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext())); |
| } |
| |
| DeclResult |
| Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, |
| SourceLocation KWLoc, CXXScopeSpec &SS, |
| IdentifierInfo *Name, SourceLocation NameLoc, |
| AttributeList *Attr, |
| TemplateParameterList *TemplateParams, |
| AccessSpecifier AS, SourceLocation ModulePrivateLoc, |
| unsigned NumOuterTemplateParamLists, |
| TemplateParameterList** OuterTemplateParamLists) { |
| assert(TemplateParams && TemplateParams->size() > 0 && |
| "No template parameters"); |
| assert(TUK != TUK_Reference && "Can only declare or define class templates"); |
| bool Invalid = false; |
| |
| // Check that we can declare a template here. |
| if (CheckTemplateDeclScope(S, TemplateParams)) |
| return true; |
| |
| TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| assert(Kind != TTK_Enum && "can't build template of enumerated type"); |
| |
| // There is no such thing as an unnamed class template. |
| if (!Name) { |
| Diag(KWLoc, diag::err_template_unnamed_class); |
| return true; |
| } |
| |
| // Find any previous declaration with this name. For a friend with no |
| // scope explicitly specified, we only look for tag declarations (per |
| // C++11 [basic.lookup.elab]p2). |
| DeclContext *SemanticContext; |
| LookupResult Previous(*this, Name, NameLoc, |
| (SS.isEmpty() && TUK == TUK_Friend) |
| ? LookupTagName : LookupOrdinaryName, |
| ForRedeclaration); |
| if (SS.isNotEmpty() && !SS.isInvalid()) { |
| SemanticContext = computeDeclContext(SS, true); |
| if (!SemanticContext) { |
| // FIXME: Horrible, horrible hack! We can't currently represent this |
| // in the AST, and historically we have just ignored such friend |
| // class templates, so don't complain here. |
| Diag(NameLoc, TUK == TUK_Friend |
| ? diag::warn_template_qualified_friend_ignored |
| : diag::err_template_qualified_declarator_no_match) |
| << SS.getScopeRep() << SS.getRange(); |
| return TUK != TUK_Friend; |
| } |
| |
| if (RequireCompleteDeclContext(SS, SemanticContext)) |
| return true; |
| |
| // If we're adding a template to a dependent context, we may need to |
| // rebuilding some of the types used within the template parameter list, |
| // now that we know what the current instantiation is. |
| if (SemanticContext->isDependentContext()) { |
| ContextRAII SavedContext(*this, SemanticContext); |
| if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) |
| Invalid = true; |
| } else if (TUK != TUK_Friend && TUK != TUK_Reference) |
| diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc); |
| |
| LookupQualifiedName(Previous, SemanticContext); |
| } else { |
| SemanticContext = CurContext; |
| LookupName(Previous, S); |
| } |
| |
| if (Previous.isAmbiguous()) |
| return true; |
| |
| NamedDecl *PrevDecl = 0; |
| if (Previous.begin() != Previous.end()) |
| PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
| |
| // If there is a previous declaration with the same name, check |
| // whether this is a valid redeclaration. |
| ClassTemplateDecl *PrevClassTemplate |
| = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); |
| |
| // We may have found the injected-class-name of a class template, |
| // class template partial specialization, or class template specialization. |
| // In these cases, grab the template that is being defined or specialized. |
| if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && |
| cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { |
| PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); |
| PrevClassTemplate |
| = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); |
| if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { |
| PrevClassTemplate |
| = cast<ClassTemplateSpecializationDecl>(PrevDecl) |
| ->getSpecializedTemplate(); |
| } |
| } |
| |
| if (TUK == TUK_Friend) { |
| // C++ [namespace.memdef]p3: |
| // [...] When looking for a prior declaration of a class or a function |
| // declared as a friend, and when the name of the friend class or |
| // function is neither a qualified name nor a template-id, scopes outside |
| // the innermost enclosing namespace scope are not considered. |
| if (!SS.isSet()) { |
| DeclContext *OutermostContext = CurContext; |
| while (!OutermostContext->isFileContext()) |
| OutermostContext = OutermostContext->getLookupParent(); |
| |
| if (PrevDecl && |
| (OutermostContext->Equals(PrevDecl->getDeclContext()) || |
| OutermostContext->Encloses(PrevDecl->getDeclContext()))) { |
| SemanticContext = PrevDecl->getDeclContext(); |
| } else { |
| // Declarations in outer scopes don't matter. However, the outermost |
| // context we computed is the semantic context for our new |
| // declaration. |
| PrevDecl = PrevClassTemplate = 0; |
| SemanticContext = OutermostContext; |
| |
| // Check that the chosen semantic context doesn't already contain a |
| // declaration of this name as a non-tag type. |
| LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, |
| ForRedeclaration); |
| DeclContext *LookupContext = SemanticContext; |
| while (LookupContext->isTransparentContext()) |
| LookupContext = LookupContext->getLookupParent(); |
| LookupQualifiedName(Previous, LookupContext); |
| |
| if (Previous.isAmbiguous()) |
| return true; |
| |
| if (Previous.begin() != Previous.end()) |
| PrevDecl = (*Previous.begin())->getUnderlyingDecl(); |
| } |
| } |
| } else if (PrevDecl && |
| !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid())) |
| PrevDecl = PrevClassTemplate = 0; |
| |
| if (PrevClassTemplate) { |
| // Ensure that the template parameter lists are compatible. Skip this check |
| // for a friend in a dependent context: the template parameter list itself |
| // could be dependent. |
| if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
| !TemplateParameterListsAreEqual(TemplateParams, |
| PrevClassTemplate->getTemplateParameters(), |
| /*Complain=*/true, |
| TPL_TemplateMatch)) |
| return true; |
| |
| // C++ [temp.class]p4: |
| // In a redeclaration, partial specialization, explicit |
| // specialization or explicit instantiation of a class template, |
| // the class-key shall agree in kind with the original class |
| // template declaration (7.1.5.3). |
| RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); |
| if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, |
| TUK == TUK_Definition, KWLoc, *Name)) { |
| Diag(KWLoc, diag::err_use_with_wrong_tag) |
| << Name |
| << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); |
| Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); |
| Kind = PrevRecordDecl->getTagKind(); |
| } |
| |
| // Check for redefinition of this class template. |
| if (TUK == TUK_Definition) { |
| if (TagDecl *Def = PrevRecordDecl->getDefinition()) { |
| Diag(NameLoc, diag::err_redefinition) << Name; |
| Diag(Def->getLocation(), diag::note_previous_definition); |
| // FIXME: Would it make sense to try to "forget" the previous |
| // definition, as part of error recovery? |
| return true; |
| } |
| } |
| } else if (PrevDecl && PrevDecl->isTemplateParameter()) { |
| // Maybe we will complain about the shadowed template parameter. |
| DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); |
| // Just pretend that we didn't see the previous declaration. |
| PrevDecl = 0; |
| } else if (PrevDecl) { |
| // C++ [temp]p5: |
| // A class template shall not have the same name as any other |
| // template, class, function, object, enumeration, enumerator, |
| // namespace, or type in the same scope (3.3), except as specified |
| // in (14.5.4). |
| Diag(NameLoc, diag::err_redefinition_different_kind) << Name; |
| Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
| return true; |
| } |
| |
| // Check the template parameter list of this declaration, possibly |
| // merging in the template parameter list from the previous class |
| // template declaration. Skip this check for a friend in a dependent |
| // context, because the template parameter list might be dependent. |
| if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && |
| CheckTemplateParameterList( |
| TemplateParams, |
| PrevClassTemplate ? PrevClassTemplate->getTemplateParameters() : 0, |
| (SS.isSet() && SemanticContext && SemanticContext->isRecord() && |
| SemanticContext->isDependentContext()) |
| ? TPC_ClassTemplateMember |
| : TUK == TUK_Friend ? TPC_FriendClassTemplate |
| : TPC_ClassTemplate)) |
| Invalid = true; |
| |
| if (SS.isSet()) { |
| // If the name of the template was qualified, we must be defining the |
| // template out-of-line. |
| if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { |
| Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match |
| : diag::err_member_decl_does_not_match) |
| << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); |
| Invalid = true; |
| } |
| } |
| |
| CXXRecordDecl *NewClass = |
| CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, |
| PrevClassTemplate? |
| PrevClassTemplate->getTemplatedDecl() : 0, |
| /*DelayTypeCreation=*/true); |
| SetNestedNameSpecifier(NewClass, SS); |
| if (NumOuterTemplateParamLists > 0) |
| NewClass->setTemplateParameterListsInfo(Context, |
| NumOuterTemplateParamLists, |
| OuterTemplateParamLists); |
| |
| // Add alignment attributes if necessary; these attributes are checked when |
| // the ASTContext lays out the structure. |
| if (TUK == TUK_Definition) { |
| AddAlignmentAttributesForRecord(NewClass); |
| AddMsStructLayoutForRecord(NewClass); |
| } |
| |
| ClassTemplateDecl *NewTemplate |
| = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, |
| DeclarationName(Name), TemplateParams, |
| NewClass, PrevClassTemplate); |
| NewClass->setDescribedClassTemplate(NewTemplate); |
| |
| if (ModulePrivateLoc.isValid()) |
| NewTemplate->setModulePrivate(); |
| |
| // Build the type for the class template declaration now. |
| QualType T = NewTemplate->getInjectedClassNameSpecialization(); |
| T = Context.getInjectedClassNameType(NewClass, T); |
| assert(T->isDependentType() && "Class template type is not dependent?"); |
| (void)T; |
| |
| // If we are providing an explicit specialization of a member that is a |
| // class template, make a note of that. |
| if (PrevClassTemplate && |
| PrevClassTemplate->getInstantiatedFromMemberTemplate()) |
| PrevClassTemplate->setMemberSpecialization(); |
| |
| // Set the access specifier. |
| if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) |
| SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); |
| |
| // Set the lexical context of these templates |
| NewClass->setLexicalDeclContext(CurContext); |
| NewTemplate->setLexicalDeclContext(CurContext); |
| |
| if (TUK == TUK_Definition) |
| NewClass->startDefinition(); |
| |
| if (Attr) |
| ProcessDeclAttributeList(S, NewClass, Attr); |
| |
| if (PrevClassTemplate) |
| mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); |
| |
| AddPushedVisibilityAttribute(NewClass); |
| |
| if (TUK != TUK_Friend) |
| PushOnScopeChains(NewTemplate, S); |
| else { |
| if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { |
| NewTemplate->setAccess(PrevClassTemplate->getAccess()); |
| NewClass->setAccess(PrevClassTemplate->getAccess()); |
| } |
| |
| NewTemplate->setObjectOfFriendDecl(); |
| |
| // Friend templates are visible in fairly strange ways. |
| if (!CurContext->isDependentContext()) { |
| DeclContext *DC = SemanticContext->getRedeclContext(); |
| DC->makeDeclVisibleInContext(NewTemplate); |
| if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
| PushOnScopeChains(NewTemplate, EnclosingScope, |
| /* AddToContext = */ false); |
| } |
| |
| FriendDecl *Friend = FriendDecl::Create(Context, CurContext, |
| NewClass->getLocation(), |
| NewTemplate, |
| /*FIXME:*/NewClass->getLocation()); |
| Friend->setAccess(AS_public); |
| CurContext->addDecl(Friend); |
| } |
| |
| if (Invalid) { |
| NewTemplate->setInvalidDecl(); |
| NewClass->setInvalidDecl(); |
| } |
| |
| ActOnDocumentableDecl(NewTemplate); |
| |
| return NewTemplate; |
| } |
| |
| /// \brief Diagnose the presence of a default template argument on a |
| /// template parameter, which is ill-formed in certain contexts. |
| /// |
| /// \returns true if the default template argument should be dropped. |
| static bool DiagnoseDefaultTemplateArgument(Sema &S, |
| Sema::TemplateParamListContext TPC, |
| SourceLocation ParamLoc, |
| SourceRange DefArgRange) { |
| switch (TPC) { |
| case Sema::TPC_ClassTemplate: |
| case Sema::TPC_VarTemplate: |
| case Sema::TPC_TypeAliasTemplate: |
| return false; |
| |
| case Sema::TPC_FunctionTemplate: |
| case Sema::TPC_FriendFunctionTemplateDefinition: |
| // C++ [temp.param]p9: |
| // A default template-argument shall not be specified in a |
| // function template declaration or a function template |
| // definition [...] |
| // If a friend function template declaration specifies a default |
| // template-argument, that declaration shall be a definition and shall be |
| // the only declaration of the function template in the translation unit. |
| // (C++98/03 doesn't have this wording; see DR226). |
| S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? |
| diag::warn_cxx98_compat_template_parameter_default_in_function_template |
| : diag::ext_template_parameter_default_in_function_template) |
| << DefArgRange; |
| return false; |
| |
| case Sema::TPC_ClassTemplateMember: |
| // C++0x [temp.param]p9: |
| // A default template-argument shall not be specified in the |
| // template-parameter-lists of the definition of a member of a |
| // class template that appears outside of the member's class. |
| S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) |
| << DefArgRange; |
| return true; |
| |
| case Sema::TPC_FriendClassTemplate: |
| case Sema::TPC_FriendFunctionTemplate: |
| // C++ [temp.param]p9: |
| // A default template-argument shall not be specified in a |
| // friend template declaration. |
| S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) |
| << DefArgRange; |
| return true; |
| |
| // FIXME: C++0x [temp.param]p9 allows default template-arguments |
| // for friend function templates if there is only a single |
| // declaration (and it is a definition). Strange! |
| } |
| |
| llvm_unreachable("Invalid TemplateParamListContext!"); |
| } |
| |
| /// \brief Check for unexpanded parameter packs within the template parameters |
| /// of a template template parameter, recursively. |
| static bool DiagnoseUnexpandedParameterPacks(Sema &S, |
| TemplateTemplateParmDecl *TTP) { |
| // A template template parameter which is a parameter pack is also a pack |
| // expansion. |
| if (TTP->isParameterPack()) |
| return false; |
| |
| TemplateParameterList *Params = TTP->getTemplateParameters(); |
| for (unsigned I = 0, N = Params->size(); I != N; ++I) { |
| NamedDecl *P = Params->getParam(I); |
| if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { |
| if (!NTTP->isParameterPack() && |
| S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), |
| NTTP->getTypeSourceInfo(), |
| Sema::UPPC_NonTypeTemplateParameterType)) |
| return true; |
| |
| continue; |
| } |
| |
| if (TemplateTemplateParmDecl *InnerTTP |
| = dyn_cast<TemplateTemplateParmDecl>(P)) |
| if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) |
| return true; |
| } |
| |
| return false; |
| } |
| |
| /// \brief Checks the validity of a template parameter list, possibly |
| /// considering the template parameter list from a previous |
| /// declaration. |
| /// |
| /// If an "old" template parameter list is provided, it must be |
| /// equivalent (per TemplateParameterListsAreEqual) to the "new" |
| /// template parameter list. |
| /// |
| /// \param NewParams Template parameter list for a new template |
| /// declaration. This template parameter list will be updated with any |
| /// default arguments that are carried through from the previous |
| /// template parameter list. |
| /// |
| /// \param OldParams If provided, template parameter list from a |
| /// previous declaration of the same template. Default template |
| /// arguments will be merged from the old template parameter list to |
| /// the new template parameter list. |
| /// |
| /// \param TPC Describes the context in which we are checking the given |
| /// template parameter list. |
| /// |
| /// \returns true if an error occurred, false otherwise. |
| bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, |
| TemplateParameterList *OldParams, |
| TemplateParamListContext TPC) { |
| bool Invalid = false; |
| |
| // C++ [temp.param]p10: |
| // The set of default template-arguments available for use with a |
| // template declaration or definition is obtained by merging the |
| // default arguments from the definition (if in scope) and all |
| // declarations in scope in the same way default function |
| // arguments are (8.3.6). |
| bool SawDefaultArgument = false; |
| SourceLocation PreviousDefaultArgLoc; |
| |
| // Dummy initialization to avoid warnings. |
| TemplateParameterList::iterator OldParam = NewParams->end(); |
| if (OldParams) |
| OldParam = OldParams->begin(); |
| |
| bool RemoveDefaultArguments = false; |
| for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
| NewParamEnd = NewParams->end(); |
| NewParam != NewParamEnd; ++NewParam) { |
| // Variables used to diagnose redundant default arguments |
| bool RedundantDefaultArg = false; |
| SourceLocation OldDefaultLoc; |
| SourceLocation NewDefaultLoc; |
| |
| // Variable used to diagnose missing default arguments |
| bool MissingDefaultArg = false; |
| |
| // Variable used to diagnose non-final parameter packs |
| bool SawParameterPack = false; |
| |
| if (TemplateTypeParmDecl *NewTypeParm |
| = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { |
| // Check the presence of a default argument here. |
| if (NewTypeParm->hasDefaultArgument() && |
| DiagnoseDefaultTemplateArgument(*this, TPC, |
| NewTypeParm->getLocation(), |
| NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() |
| .getSourceRange())) |
| NewTypeParm->removeDefaultArgument(); |
| |
| // Merge default arguments for template type parameters. |
| TemplateTypeParmDecl *OldTypeParm |
| = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; |
| |
| if (NewTypeParm->isParameterPack()) { |
| assert(!NewTypeParm->hasDefaultArgument() && |
| "Parameter packs can't have a default argument!"); |
| SawParameterPack = true; |
| } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && |
| NewTypeParm->hasDefaultArgument()) { |
| OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); |
| NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); |
| SawDefaultArgument = true; |
| RedundantDefaultArg = true; |
| PreviousDefaultArgLoc = NewDefaultLoc; |
| } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { |
| // Merge the default argument from the old declaration to the |
| // new declaration. |
| NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), |
| true); |
| PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); |
| } else if (NewTypeParm->hasDefaultArgument()) { |
| SawDefaultArgument = true; |
| PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); |
| } else if (SawDefaultArgument) |
| MissingDefaultArg = true; |
| } else if (NonTypeTemplateParmDecl *NewNonTypeParm |
| = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { |
| // Check for unexpanded parameter packs. |
| if (!NewNonTypeParm->isParameterPack() && |
| DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), |
| NewNonTypeParm->getTypeSourceInfo(), |
| UPPC_NonTypeTemplateParameterType)) { |
| Invalid = true; |
| continue; |
| } |
| |
| // Check the presence of a default argument here. |
| if (NewNonTypeParm->hasDefaultArgument() && |
| DiagnoseDefaultTemplateArgument(*this, TPC, |
| NewNonTypeParm->getLocation(), |
| NewNonTypeParm->getDefaultArgument()->getSourceRange())) { |
| NewNonTypeParm->removeDefaultArgument(); |
| } |
| |
| // Merge default arguments for non-type template parameters |
| NonTypeTemplateParmDecl *OldNonTypeParm |
| = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; |
| if (NewNonTypeParm->isParameterPack()) { |
| assert(!NewNonTypeParm->hasDefaultArgument() && |
| "Parameter packs can't have a default argument!"); |
| if (!NewNonTypeParm->isPackExpansion()) |
| SawParameterPack = true; |
| } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && |
| NewNonTypeParm->hasDefaultArgument()) { |
| OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
| NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
| SawDefaultArgument = true; |
| RedundantDefaultArg = true; |
| PreviousDefaultArgLoc = NewDefaultLoc; |
| } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { |
| // Merge the default argument from the old declaration to the |
| // new declaration. |
| // FIXME: We need to create a new kind of "default argument" |
| // expression that points to a previous non-type template |
| // parameter. |
| NewNonTypeParm->setDefaultArgument( |
| OldNonTypeParm->getDefaultArgument(), |
| /*Inherited=*/ true); |
| PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); |
| } else if (NewNonTypeParm->hasDefaultArgument()) { |
| SawDefaultArgument = true; |
| PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); |
| } else if (SawDefaultArgument) |
| MissingDefaultArg = true; |
| } else { |
| TemplateTemplateParmDecl *NewTemplateParm |
| = cast<TemplateTemplateParmDecl>(*NewParam); |
| |
| // Check for unexpanded parameter packs, recursively. |
| if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { |
| Invalid = true; |
| continue; |
| } |
| |
| // Check the presence of a default argument here. |
| if (NewTemplateParm->hasDefaultArgument() && |
| DiagnoseDefaultTemplateArgument(*this, TPC, |
| NewTemplateParm->getLocation(), |
| NewTemplateParm->getDefaultArgument().getSourceRange())) |
| NewTemplateParm->removeDefaultArgument(); |
| |
| // Merge default arguments for template template parameters |
| TemplateTemplateParmDecl *OldTemplateParm |
| = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; |
| if (NewTemplateParm->isParameterPack()) { |
| assert(!NewTemplateParm->hasDefaultArgument() && |
| "Parameter packs can't have a default argument!"); |
| if (!NewTemplateParm->isPackExpansion()) |
| SawParameterPack = true; |
| } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && |
| NewTemplateParm->hasDefaultArgument()) { |
| OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); |
| NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); |
| SawDefaultArgument = true; |
| RedundantDefaultArg = true; |
| PreviousDefaultArgLoc = NewDefaultLoc; |
| } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { |
| // Merge the default argument from the old declaration to the |
| // new declaration. |
| // FIXME: We need to create a new kind of "default argument" expression |
| // that points to a previous template template parameter. |
| NewTemplateParm->setDefaultArgument( |
| OldTemplateParm->getDefaultArgument(), |
| /*Inherited=*/ true); |
| PreviousDefaultArgLoc |
| = OldTemplateParm->getDefaultArgument().getLocation(); |
| } else if (NewTemplateParm->hasDefaultArgument()) { |
| SawDefaultArgument = true; |
| PreviousDefaultArgLoc |
| = NewTemplateParm->getDefaultArgument().getLocation(); |
| } else if (SawDefaultArgument) |
| MissingDefaultArg = true; |
| } |
| |
| // C++11 [temp.param]p11: |
| // If a template parameter of a primary class template or alias template |
| // is a template parameter pack, it shall be the last template parameter. |
| if (SawParameterPack && (NewParam + 1) != NewParamEnd && |
| (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || |
| TPC == TPC_TypeAliasTemplate)) { |
| Diag((*NewParam)->getLocation(), |
| diag::err_template_param_pack_must_be_last_template_parameter); |
| Invalid = true; |
| } |
| |
| if (RedundantDefaultArg) { |
| // C++ [temp.param]p12: |
| // A template-parameter shall not be given default arguments |
| // by two different declarations in the same scope. |
| Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); |
| Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); |
| Invalid = true; |
| } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { |
| // C++ [temp.param]p11: |
| // If a template-parameter of a class template has a default |
| // template-argument, each subsequent template-parameter shall either |
| // have a default template-argument supplied or be a template parameter |
| // pack. |
| Diag((*NewParam)->getLocation(), |
| diag::err_template_param_default_arg_missing); |
| Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); |
| Invalid = true; |
| RemoveDefaultArguments = true; |
| } |
| |
| // If we have an old template parameter list that we're merging |
| // in, move on to the next parameter. |
| if (OldParams) |
| ++OldParam; |
| } |
| |
| // We were missing some default arguments at the end of the list, so remove |
| // all of the default arguments. |
| if (RemoveDefaultArguments) { |
| for (TemplateParameterList::iterator NewParam = NewParams->begin(), |
| NewParamEnd = NewParams->end(); |
| NewParam != NewParamEnd; ++NewParam) { |
| if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) |
| TTP->removeDefaultArgument(); |
| else if (NonTypeTemplateParmDecl *NTTP |
| = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) |
| NTTP->removeDefaultArgument(); |
| else |
| cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); |
| } |
| } |
| |
| return Invalid; |
| } |
| |
| namespace { |
| |
| /// A class which looks for a use of a certain level of template |
| /// parameter. |
| struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { |
| typedef RecursiveASTVisitor<DependencyChecker> super; |
| |
| unsigned Depth; |
| bool Match; |
| SourceLocation MatchLoc; |
| |
| DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {} |
| |
| DependencyChecker(TemplateParameterList *Params) : Match(false) { |
| NamedDecl *ND = Params->getParam(0); |
| if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { |
| Depth = PD->getDepth(); |
| } else if (NonTypeTemplateParmDecl *PD = |
| dyn_cast<NonTypeTemplateParmDecl>(ND)) { |
| Depth = PD->getDepth(); |
| } else { |
| Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); |
| } |
| } |
| |
| bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { |
| if (ParmDepth >= Depth) { |
| Match = true; |
| MatchLoc = Loc; |
| return true; |
| } |
| return false; |
| } |
| |
| bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { |
| return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); |
| } |
| |
| bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { |
| return !Matches(T->getDepth()); |
| } |
| |
| bool TraverseTemplateName(TemplateName N) { |
| if (TemplateTemplateParmDecl *PD = |
| dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) |
| if (Matches(PD->getDepth())) |
| return false; |
| return super::TraverseTemplateName(N); |
| } |
| |
| bool VisitDeclRefExpr(DeclRefExpr *E) { |
| if (NonTypeTemplateParmDecl *PD = |
| dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) |
| if (Matches(PD->getDepth(), E->getExprLoc())) |
| return false; |
| return super::VisitDeclRefExpr(E); |
| } |
| |
| bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { |
| return TraverseType(T->getReplacementType()); |
| } |
| |
| bool |
| VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { |
| return TraverseTemplateArgument(T->getArgumentPack()); |
| } |
| |
| bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { |
| return TraverseType(T->getInjectedSpecializationType()); |
| } |
| }; |
| } |
| |
| /// Determines whether a given type depends on the given parameter |
| /// list. |
| static bool |
| DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { |
| DependencyChecker Checker(Params); |
| Checker.TraverseType(T); |
| return Checker.Match; |
| } |
| |
| // Find the source range corresponding to the named type in the given |
| // nested-name-specifier, if any. |
| static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, |
| QualType T, |
| const CXXScopeSpec &SS) { |
| NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); |
| while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { |
| if (const Type *CurType = NNS->getAsType()) { |
| if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) |
| return NNSLoc.getTypeLoc().getSourceRange(); |
| } else |
| break; |
| |
| NNSLoc = NNSLoc.getPrefix(); |
| } |
| |
| return SourceRange(); |
| } |
| |
| /// \brief Match the given template parameter lists to the given scope |
| /// specifier, returning the template parameter list that applies to the |
| /// name. |
| /// |
| /// \param DeclStartLoc the start of the declaration that has a scope |
| /// specifier or a template parameter list. |
| /// |
| /// \param DeclLoc The location of the declaration itself. |
| /// |
| /// \param SS the scope specifier that will be matched to the given template |
| /// parameter lists. This scope specifier precedes a qualified name that is |
| /// being declared. |
| /// |
| /// \param TemplateId The template-id following the scope specifier, if there |
| /// is one. Used to check for a missing 'template<>'. |
| /// |
| /// \param ParamLists the template parameter lists, from the outermost to the |
| /// innermost template parameter lists. |
| /// |
| /// \param IsFriend Whether to apply the slightly different rules for |
| /// matching template parameters to scope specifiers in friend |
| /// declarations. |
| /// |
| /// \param IsExplicitSpecialization will be set true if the entity being |
| /// declared is an explicit specialization, false otherwise. |
| /// |
| /// \returns the template parameter list, if any, that corresponds to the |
| /// name that is preceded by the scope specifier @p SS. This template |
| /// parameter list may have template parameters (if we're declaring a |
| /// template) or may have no template parameters (if we're declaring a |
| /// template specialization), or may be NULL (if what we're declaring isn't |
| /// itself a template). |
| TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( |
| SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, |
| TemplateIdAnnotation *TemplateId, |
| ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, |
| bool &IsExplicitSpecialization, bool &Invalid) { |
| IsExplicitSpecialization = false; |
| Invalid = false; |
| |
| // The sequence of nested types to which we will match up the template |
| // parameter lists. We first build this list by starting with the type named |
| // by the nested-name-specifier and walking out until we run out of types. |
| SmallVector<QualType, 4> NestedTypes; |
| QualType T; |
| if (SS.getScopeRep()) { |
| if (CXXRecordDecl *Record |
| = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) |
| T = Context.getTypeDeclType(Record); |
| else |
| T = QualType(SS.getScopeRep()->getAsType(), 0); |
| } |
| |
| // If we found an explicit specialization that prevents us from needing |
| // 'template<>' headers, this will be set to the location of that |
| // explicit specialization. |
| SourceLocation ExplicitSpecLoc; |
| |
| while (!T.isNull()) { |
| NestedTypes.push_back(T); |
| |
| // Retrieve the parent of a record type. |
| if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
| // If this type is an explicit specialization, we're done. |
| if (ClassTemplateSpecializationDecl *Spec |
| = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { |
| if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && |
| Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { |
| ExplicitSpecLoc = Spec->getLocation(); |
| break; |
| } |
| } else if (Record->getTemplateSpecializationKind() |
| == TSK_ExplicitSpecialization) { |
| ExplicitSpecLoc = Record->getLocation(); |
| break; |
| } |
| |
| if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) |
| T = Context.getTypeDeclType(Parent); |
| else |
| T = QualType(); |
| continue; |
| } |
| |
| if (const TemplateSpecializationType *TST |
| = T->getAs<TemplateSpecializationType>()) { |
| if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
| if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) |
| T = Context.getTypeDeclType(Parent); |
| else |
| T = QualType(); |
| continue; |
| } |
| } |
| |
| // Look one step prior in a dependent template specialization type. |
| if (const DependentTemplateSpecializationType *DependentTST |
| = T->getAs<DependentTemplateSpecializationType>()) { |
| if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) |
| T = QualType(NNS->getAsType(), 0); |
| else |
| T = QualType(); |
| continue; |
| } |
| |
| // Look one step prior in a dependent name type. |
| if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ |
| if (NestedNameSpecifier *NNS = DependentName->getQualifier()) |
| T = QualType(NNS->getAsType(), 0); |
| else |
| T = QualType(); |
| continue; |
| } |
| |
| // Retrieve the parent of an enumeration type. |
| if (const EnumType *EnumT = T->getAs<EnumType>()) { |
| // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization |
| // check here. |
| EnumDecl *Enum = EnumT->getDecl(); |
| |
| // Get to the parent type. |
| if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) |
| T = Context.getTypeDeclType(Parent); |
| else |
| T = QualType(); |
| continue; |
| } |
| |
| T = QualType(); |
| } |
| // Reverse the nested types list, since we want to traverse from the outermost |
| // to the innermost while checking template-parameter-lists. |
| std::reverse(NestedTypes.begin(), NestedTypes.end()); |
| |
| // C++0x [temp.expl.spec]p17: |
| // A member or a member template may be nested within many |
| // enclosing class templates. In an explicit specialization for |
| // such a member, the member declaration shall be preceded by a |
| // template<> for each enclosing class template that is |
| // explicitly specialized. |
| bool SawNonEmptyTemplateParameterList = false; |
| |
| auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { |
| if (SawNonEmptyTemplateParameterList) { |
| Diag(DeclLoc, diag::err_specialize_member_of_template) |
| << !Recovery << Range; |
| Invalid = true; |
| IsExplicitSpecialization = false; |
| return true; |
| } |
| |
| return false; |
| }; |
| |
| auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { |
| // Check that we can have an explicit specialization here. |
| if (CheckExplicitSpecialization(Range, true)) |
| return true; |
| |
| // We don't have a template header, but we should. |
| SourceLocation ExpectedTemplateLoc; |
| if (!ParamLists.empty()) |
| ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); |
| else |
| ExpectedTemplateLoc = DeclStartLoc; |
| |
| Diag(DeclLoc, diag::err_template_spec_needs_header) |
| << Range |
| << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); |
| return false; |
| }; |
| |
| unsigned ParamIdx = 0; |
| for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; |
| ++TypeIdx) { |
| T = NestedTypes[TypeIdx]; |
| |
| // Whether we expect a 'template<>' header. |
| bool NeedEmptyTemplateHeader = false; |
| |
| // Whether we expect a template header with parameters. |
| bool NeedNonemptyTemplateHeader = false; |
| |
| // For a dependent type, the set of template parameters that we |
| // expect to see. |
| TemplateParameterList *ExpectedTemplateParams = 0; |
| |
| // C++0x [temp.expl.spec]p15: |
| // A member or a member template may be nested within many enclosing |
| // class templates. In an explicit specialization for such a member, the |
| // member declaration shall be preceded by a template<> for each |
| // enclosing class template that is explicitly specialized. |
| if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { |
| if (ClassTemplatePartialSpecializationDecl *Partial |
| = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { |
| ExpectedTemplateParams = Partial->getTemplateParameters(); |
| NeedNonemptyTemplateHeader = true; |
| } else if (Record->isDependentType()) { |
| if (Record->getDescribedClassTemplate()) { |
| ExpectedTemplateParams = Record->getDescribedClassTemplate() |
| ->getTemplateParameters(); |
| NeedNonemptyTemplateHeader = true; |
| } |
| } else if (ClassTemplateSpecializationDecl *Spec |
| = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { |
| // C++0x [temp.expl.spec]p4: |
| // Members of an explicitly specialized class template are defined |
| // in the same manner as members of normal classes, and not using |
| // the template<> syntax. |
| if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) |
| NeedEmptyTemplateHeader = true; |
| else |
| continue; |
| } else if (Record->getTemplateSpecializationKind()) { |
| if (Record->getTemplateSpecializationKind() |
| != TSK_ExplicitSpecialization && |
| TypeIdx == NumTypes - 1) |
| IsExplicitSpecialization = true; |
| |
| continue; |
| } |
| } else if (const TemplateSpecializationType *TST |
| = T->getAs<TemplateSpecializationType>()) { |
| if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { |
| ExpectedTemplateParams = Template->getTemplateParameters(); |
| NeedNonemptyTemplateHeader = true; |
| } |
| } else if (T->getAs<DependentTemplateSpecializationType>()) { |
| // FIXME: We actually could/should check the template arguments here |
| // against the corresponding template parameter list. |
| NeedNonemptyTemplateHeader = false; |
| } |
| |
| // C++ [temp.expl.spec]p16: |
| // In an explicit specialization declaration for a member of a class |
| // template or a member template that ap- pears in namespace scope, the |
| // member template and some of its enclosing class templates may remain |
| // unspecialized, except that the declaration shall not explicitly |
| // specialize a class member template if its en- closing class templates |
| // are not explicitly specialized as well. |
| if (ParamIdx < ParamLists.size()) { |
| if (ParamLists[ParamIdx]->size() == 0) { |
| if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
| false)) |
| return 0; |
| } else |
| SawNonEmptyTemplateParameterList = true; |
| } |
| |
| if (NeedEmptyTemplateHeader) { |
| // If we're on the last of the types, and we need a 'template<>' header |
| // here, then it's an explicit specialization. |
| if (TypeIdx == NumTypes - 1) |
| IsExplicitSpecialization = true; |
| |
| if (ParamIdx < ParamLists.size()) { |
| if (ParamLists[ParamIdx]->size() > 0) { |
| // The header has template parameters when it shouldn't. Complain. |
| Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
| diag::err_template_param_list_matches_nontemplate) |
| << T |
| << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), |
| ParamLists[ParamIdx]->getRAngleLoc()) |
| << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
| Invalid = true; |
| return 0; |
| } |
| |
| // Consume this template header. |
| ++ParamIdx; |
| continue; |
| } |
| |
| if (!IsFriend) |
| if (DiagnoseMissingExplicitSpecialization( |
| getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) |
| return 0; |
| |
| continue; |
| } |
| |
| if (NeedNonemptyTemplateHeader) { |
| // In friend declarations we can have template-ids which don't |
| // depend on the corresponding template parameter lists. But |
| // assume that empty parameter lists are supposed to match this |
| // template-id. |
| if (IsFriend && T->isDependentType()) { |
| if (ParamIdx < ParamLists.size() && |
| DependsOnTemplateParameters(T, ParamLists[ParamIdx])) |
| ExpectedTemplateParams = 0; |
| else |
| continue; |
| } |
| |
| if (ParamIdx < ParamLists.size()) { |
| // Check the template parameter list, if we can. |
| if (ExpectedTemplateParams && |
| !TemplateParameterListsAreEqual(ParamLists[ParamIdx], |
| ExpectedTemplateParams, |
| true, TPL_TemplateMatch)) |
| Invalid = true; |
| |
| if (!Invalid && |
| CheckTemplateParameterList(ParamLists[ParamIdx], 0, |
| TPC_ClassTemplateMember)) |
| Invalid = true; |
| |
| ++ParamIdx; |
| continue; |
| } |
| |
| Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) |
| << T |
| << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); |
| Invalid = true; |
| continue; |
| } |
| } |
| |
| // If there were at least as many template-ids as there were template |
| // parameter lists, then there are no template parameter lists remaining for |
| // the declaration itself. |
| if (ParamIdx >= ParamLists.size()) { |
| if (TemplateId && !IsFriend) { |
| // We don't have a template header for the declaration itself, but we |
| // should. |
| IsExplicitSpecialization = true; |
| DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, |
| TemplateId->RAngleLoc)); |
| |
| // Fabricate an empty template parameter list for the invented header. |
| return TemplateParameterList::Create(Context, SourceLocation(), |
| SourceLocation(), 0, 0, |
| SourceLocation()); |
| } |
| |
| return 0; |
| } |
| |
| // If there were too many template parameter lists, complain about that now. |
| if (ParamIdx < ParamLists.size() - 1) { |
| bool HasAnyExplicitSpecHeader = false; |
| bool AllExplicitSpecHeaders = true; |
| for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { |
| if (ParamLists[I]->size() == 0) |
| HasAnyExplicitSpecHeader = true; |
| else |
| AllExplicitSpecHeaders = false; |
| } |
| |
| Diag(ParamLists[ParamIdx]->getTemplateLoc(), |
| AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers |
| : diag::err_template_spec_extra_headers) |
| << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), |
| ParamLists[ParamLists.size() - 2]->getRAngleLoc()); |
| |
| // If there was a specialization somewhere, such that 'template<>' is |
| // not required, and there were any 'template<>' headers, note where the |
| // specialization occurred. |
| if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader) |
| Diag(ExplicitSpecLoc, |
| diag::note_explicit_template_spec_does_not_need_header) |
| << NestedTypes.back(); |
| |
| // We have a template parameter list with no corresponding scope, which |
| // means that the resulting template declaration can't be instantiated |
| // properly (we'll end up with dependent nodes when we shouldn't). |
| if (!AllExplicitSpecHeaders) |
| Invalid = true; |
| } |
| |
| // C++ [temp.expl.spec]p16: |
| // In an explicit specialization declaration for a member of a class |
| // template or a member template that ap- pears in namespace scope, the |
| // member template and some of its enclosing class templates may remain |
| // unspecialized, except that the declaration shall not explicitly |
| // specialize a class member template if its en- closing class templates |
| // are not explicitly specialized as well. |
| if (ParamLists.back()->size() == 0 && |
| CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), |
| false)) |
| return 0; |
| |
| // Return the last template parameter list, which corresponds to the |
| // entity being declared. |
| return ParamLists.back(); |
| } |
| |
| void Sema::NoteAllFoundTemplates(TemplateName Name) { |
| if (TemplateDecl *Template = Name.getAsTemplateDecl()) { |
| Diag(Template->getLocation(), diag::note_template_declared_here) |
| << (isa<FunctionTemplateDecl>(Template) |
| ? 0 |
| : isa<ClassTemplateDecl>(Template) |
| ? 1 |
| : isa<VarTemplateDecl>(Template) |
| ? 2 |
| : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) |
| << Template->getDeclName(); |
| return; |
| } |
| |
| if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { |
| for (OverloadedTemplateStorage::iterator I = OST->begin(), |
| IEnd = OST->end(); |
| I != IEnd; ++I) |
| Diag((*I)->getLocation(), diag::note_template_declared_here) |
| << 0 << (*I)->getDeclName(); |
| |
| return; |
| } |
| } |
| |
| QualType Sema::CheckTemplateIdType(TemplateName Name, |
| SourceLocation TemplateLoc, |
| TemplateArgumentListInfo &TemplateArgs) { |
| DependentTemplateName *DTN |
| = Name.getUnderlying().getAsDependentTemplateName(); |
| if (DTN && DTN->isIdentifier()) |
| // When building a template-id where the template-name is dependent, |
| // assume the template is a type template. Either our assumption is |
| // correct, or the code is ill-formed and will be diagnosed when the |
| // dependent name is substituted. |
| return Context.getDependentTemplateSpecializationType(ETK_None, |
| DTN->getQualifier(), |
| DTN->getIdentifier(), |
| TemplateArgs); |
| |
| TemplateDecl *Template = Name.getAsTemplateDecl(); |
| if (!Template || isa<FunctionTemplateDecl>(Template) || |
| isa<VarTemplateDecl>(Template)) { |
| // We might have a substituted template template parameter pack. If so, |
| // build a template specialization type for it. |
| if (Name.getAsSubstTemplateTemplateParmPack()) |
| return Context.getTemplateSpecializationType(Name, TemplateArgs); |
| |
| Diag(TemplateLoc, diag::err_template_id_not_a_type) |
| << Name; |
| NoteAllFoundTemplates(Name); |
| return QualType(); |
| } |
| |
| // Check that the template argument list is well-formed for this |
| // template. |
| SmallVector<TemplateArgument, 4> Converted; |
| if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, |
| false, Converted)) |
| return QualType(); |
| |
| QualType CanonType; |
| |
| bool InstantiationDependent = false; |
| if (TypeAliasTemplateDecl *AliasTemplate = |
| dyn_cast<TypeAliasTemplateDecl>(Template)) { |
| // Find the canonical type for this type alias template specialization. |
| TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); |
| if (Pattern->isInvalidDecl()) |
| return QualType(); |
| |
| TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, |
| Converted.data(), Converted.size()); |
| |
| // Only substitute for the innermost template argument list. |
| MultiLevelTemplateArgumentList TemplateArgLists; |
| TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); |
| unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth(); |
| for (unsigned I = 0; I < Depth; ++I) |
| TemplateArgLists.addOuterTemplateArguments(None); |
| |
| LocalInstantiationScope Scope(*this); |
| InstantiatingTemplate Inst(*this, TemplateLoc, Template); |
| if (Inst.isInvalid()) |
| return QualType(); |
| |
| CanonType = SubstType(Pattern->getUnderlyingType(), |
| TemplateArgLists, AliasTemplate->getLocation(), |
| AliasTemplate->getDeclName()); |
| if (CanonType.isNull()) |
| return QualType(); |
| } else if (Name.isDependent() || |
| TemplateSpecializationType::anyDependentTemplateArguments( |
| TemplateArgs, InstantiationDependent)) { |
| // This class template specialization is a dependent |
| // type. Therefore, its canonical type is another class template |
| // specialization type that contains all of the converted |
| // arguments in canonical form. This ensures that, e.g., A<T> and |
| // A<T, T> have identical types when A is declared as: |
| // |
| // template<typename T, typename U = T> struct A; |
| TemplateName CanonName = Context.getCanonicalTemplateName(Name); |
| CanonType = Context.getTemplateSpecializationType(CanonName, |
| Converted.data(), |
| Converted.size()); |
| |
| // FIXME: CanonType is not actually the canonical type, and unfortunately |
| // it is a TemplateSpecializationType that we will never use again. |
| // In the future, we need to teach getTemplateSpecializationType to only |
| // build the canonical type and return that to us. |
| CanonType = Context.getCanonicalType(CanonType); |
| |
| // This might work out to be a current instantiation, in which |
| // case the canonical type needs to be the InjectedClassNameType. |
| // |
| // TODO: in theory this could be a simple hashtable lookup; most |
| // changes to CurContext don't change the set of current |
| // instantiations. |
| if (isa<ClassTemplateDecl>(Template)) { |
| for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { |
| // If we get out to a namespace, we're done. |
| if (Ctx->isFileContext()) break; |
| |
| // If this isn't a record, keep looking. |
| CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); |
| if (!Record) continue; |
| |
| // Look for one of the two cases with InjectedClassNameTypes |
| // and check whether it's the same template. |
| if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && |
| !Record->getDescribedClassTemplate()) |
| continue; |
| |
| // Fetch the injected class name type and check whether its |
| // injected type is equal to the type we just built. |
| QualType ICNT = Context.getTypeDeclType(Record); |
| QualType Injected = cast<InjectedClassNameType>(ICNT) |
| ->getInjectedSpecializationType(); |
| |
| if (CanonType != Injected->getCanonicalTypeInternal()) |
| continue; |
| |
| // If so, the canonical type of this TST is the injected |
| // class name type of the record we just found. |
| assert(ICNT.isCanonical()); |
| CanonType = ICNT; |
| break; |
| } |
| } |
| } else if (ClassTemplateDecl *ClassTemplate |
| = dyn_cast<ClassTemplateDecl>(Template)) { |
| // Find the class template specialization declaration that |
| // corresponds to these arguments. |
| void *InsertPos = 0; |
| ClassTemplateSpecializationDecl *Decl |
| = ClassTemplate->findSpecialization(Converted.data(), Converted.size(), |
| InsertPos); |
| if (!Decl) { |
| // This is the first time we have referenced this class template |
| // specialization. Create the canonical declaration and add it to |
| // the set of specializations. |
| Decl = ClassTemplateSpecializationDecl::Create(Context, |
| ClassTemplate->getTemplatedDecl()->getTagKind(), |
| ClassTemplate->getDeclContext(), |
| ClassTemplate->getTemplatedDecl()->getLocStart(), |
| ClassTemplate->getLocation(), |
| ClassTemplate, |
| Converted.data(), |
| Converted.size(), 0); |
| ClassTemplate->AddSpecialization(Decl, InsertPos); |
| if (ClassTemplate->isOutOfLine()) |
| Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); |
| } |
| |
| // Diagnose uses of this specialization. |
| (void)DiagnoseUseOfDecl(Decl, TemplateLoc); |
| |
| CanonType = Context.getTypeDeclType(Decl); |
| assert(isa<RecordType>(CanonType) && |
| "type of non-dependent specialization is not a RecordType"); |
| } |
| |
| // Build the fully-sugared type for this class template |
| // specialization, which refers back to the class template |
| // specialization we created or found. |
| return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); |
| } |
| |
| TypeResult |
| Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, |
| TemplateTy TemplateD, SourceLocation TemplateLoc, |
| SourceLocation LAngleLoc, |
| ASTTemplateArgsPtr TemplateArgsIn, |
| SourceLocation RAngleLoc, |
| bool IsCtorOrDtorName) { |
| if (SS.isInvalid()) |
| return true; |
| |
| TemplateName Template = TemplateD.get(); |
| |
| // Translate the parser's template argument list in our AST format. |
| TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
| translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
| |
| if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
| QualType T |
| = Context.getDependentTemplateSpecializationType(ETK_None, |
| DTN->getQualifier(), |
| DTN->getIdentifier(), |
| TemplateArgs); |
| // Build type-source information. |
| TypeLocBuilder TLB; |
| DependentTemplateSpecializationTypeLoc SpecTL |
| = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
| SpecTL.setElaboratedKeywordLoc(SourceLocation()); |
| SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| SpecTL.setTemplateNameLoc(TemplateLoc); |
| SpecTL.setLAngleLoc(LAngleLoc); |
| SpecTL.setRAngleLoc(RAngleLoc); |
| for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
| SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
| return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); |
| } |
| |
| QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); |
| |
| if (Result.isNull()) |
| return true; |
| |
| // Build type-source information. |
| TypeLocBuilder TLB; |
| TemplateSpecializationTypeLoc SpecTL |
| = TLB.push<TemplateSpecializationTypeLoc>(Result); |
| SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| SpecTL.setTemplateNameLoc(TemplateLoc); |
| SpecTL.setLAngleLoc(LAngleLoc); |
| SpecTL.setRAngleLoc(RAngleLoc); |
| for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
| SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); |
| |
| // NOTE: avoid constructing an ElaboratedTypeLoc if this is a |
| // constructor or destructor name (in such a case, the scope specifier |
| // will be attached to the enclosing Decl or Expr node). |
| if (SS.isNotEmpty() && !IsCtorOrDtorName) { |
| // Create an elaborated-type-specifier containing the nested-name-specifier. |
| Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result); |
| ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); |
| ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
| ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| } |
| |
| return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); |
| } |
| |
| TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, |
| TypeSpecifierType TagSpec, |
| SourceLocation TagLoc, |
| CXXScopeSpec &SS, |
| SourceLocation TemplateKWLoc, |
| TemplateTy TemplateD, |
| SourceLocation TemplateLoc, |
| SourceLocation LAngleLoc, |
| ASTTemplateArgsPtr TemplateArgsIn, |
| SourceLocation RAngleLoc) { |
| TemplateName Template = TemplateD.get(); |
| |
| // Translate the parser's template argument list in our AST format. |
| TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); |
| translateTemplateArguments(TemplateArgsIn, TemplateArgs); |
| |
| // Determine the tag kind |
| TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
| ElaboratedTypeKeyword Keyword |
| = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); |
| |
| if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { |
| QualType T = Context.getDependentTemplateSpecializationType(Keyword, |
| DTN->getQualifier(), |
| DTN->getIdentifier(), |
| TemplateArgs); |
| |
| // Build type-source information. |
| TypeLocBuilder TLB; |
| DependentTemplateSpecializationTypeLoc SpecTL |
| = TLB.push<DependentTemplateSpecializationTypeLoc>(T); |
| SpecTL.setElaboratedKeywordLoc(TagLoc); |
| SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| SpecTL.setTemplateNameLoc(TemplateLoc); |
| SpecTL.setLAngleLoc(LAngleLoc); |
| SpecTL.setRAngleLoc(RAngleLoc); |
| for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) |
| SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); |
| return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); |
| } |
| |
| if (TypeAliasTemplateDecl *TAT = |
| dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { |
| // C++0x [dcl.type.elab]p2: |
| // If the identifier resolves to a typedef-name or the simple-template-id |
| // resolves to an alias template specialization, the |
| // elaborated-type-specifier is ill-formed. |
| Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4; |
| Diag(TAT->getLocation(), diag::note_declared_at); |
| } |
| |
| QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); |
| if (Result.isNull()) |
| return TypeResult(true); |
| |
| // Check the tag kind |
| if (const RecordType *RT = Result->getAs<RecordType>()) { |
| RecordDecl *D = RT->getDecl(); |
| |
| IdentifierInfo *Id = D->getIdentifier(); |
| assert(Id && "templated class must have an identifier"); |
| |
| if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, |
| TagLoc, *Id)) { |
| Diag(TagLoc, diag::err_use_with_wrong_tag) |
| << Result |
| << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); |
| Diag(D->getLocation(), diag::note_previous_use); |
| } |
| } |
| |
| // Provide source-location information for the template specialization. |
| TypeLocBuilder TLB; |
| TemplateSpecializationTypeLoc SpecTL |
| = TLB.push<TemplateSpecializationTypeLoc>(Result); |
| SpecTL.setTemplateKeywordLoc(TemplateKWLoc); |
| SpecTL.setTemplateNameLoc(TemplateLoc); |
| SpecTL.setLAngleLoc(LAngleLoc); |
| SpecTL.setRAngleLoc(RAngleLoc); |
| for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) |
| SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); |
| |
| // Construct an elaborated type containing the nested-name-specifier (if any) |
| // and tag keyword. |
| Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); |
| ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); |
| ElabTL.setElaboratedKeywordLoc(TagLoc); |
| ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
| return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); |
| } |
| |
| static bool CheckTemplatePartialSpecializationArgs( |
| Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams, |
| unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs); |
| |
| static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, |
| NamedDecl *PrevDecl, |
| SourceLocation Loc, |
| bool IsPartialSpecialization); |
| |
| static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); |
| |
| static bool isTemplateArgumentTemplateParameter( |
| const TemplateArgument &Arg, unsigned Depth, unsigned Index) { |
| switch (Arg.getKind()) { |
| case TemplateArgument::Null: |
| case TemplateArgument::NullPtr: |
| case TemplateArgument::Integral: |
| case TemplateArgument::Declaration: |
| case TemplateArgument::Pack: |
| case TemplateArgument::TemplateExpansion: |
| return false; |
| |
| case TemplateArgument::Type: { |
| QualType Type = Arg.getAsType(); |
| const TemplateTypeParmType *TPT = |
| Arg.getAsType()->getAs<TemplateTypeParmType>(); |
| return TPT && !Type.hasQualifiers() && |
| TPT->getDepth() == Depth && TPT->getIndex() == Index; |
| } |
| |
| case TemplateArgument::Expression: { |
| DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); |
| if (!DRE || !DRE->getDecl()) |
| return false; |
| const NonTypeTemplateParmDecl *NTTP = |
| dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); |
| return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; |
| } |
| |
| case TemplateArgument::Template: |
| const TemplateTemplateParmDecl *TTP = |
| dyn_cast_or_null<TemplateTemplateParmDecl>( |
| Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); |
| return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; |
| } |
| llvm_unreachable("unexpected kind of template argument"); |
| } |
| |
| static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, |
| ArrayRef<TemplateArgument> Args) { |
| if (Params->size() != Args.size()) |
| return false; |
| |
| unsigned Depth = Params->getDepth(); |
| |
| for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
| TemplateArgument Arg = Args[I]; |
| |
| // If the parameter is a pack expansion, the argument must be a pack |
| // whose only element is a pack expansion. |
| if (Params->getParam(I)->isParameterPack()) { |
| if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || |
| !Arg.pack_begin()->isPackExpansion()) |
| return false; |
| Arg = Arg.pack_begin()->getPackExpansionPattern(); |
| } |
| |
| if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) |
| return false; |
| } |
| |
| return true; |
| } |
| |
| /// Convert the parser's template argument list representation into our form. |
| static TemplateArgumentListInfo |
| makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { |
| TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, |
| TemplateId.RAngleLoc); |
| ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), |
| TemplateId.NumArgs); |
| S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); |
| return TemplateArgs; |
| } |
| |
| DeclResult Sema::ActOnVarTemplateSpecialization( |
| Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, |
| TemplateParameterList *TemplateParams, VarDecl::StorageClass SC, |
| bool IsPartialSpecialization) { |
| // D must be variable template id. |
| assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId && |
| "Variable template specialization is declared with a template it."); |
| |
| TemplateIdAnnotation *TemplateId = D.getName().TemplateId; |
| TemplateArgumentListInfo TemplateArgs = |
| makeTemplateArgumentListInfo(*this, *TemplateId); |
| SourceLocation TemplateNameLoc = D.getIdentifierLoc(); |
| SourceLocation LAngleLoc = TemplateId->LAngleLoc; |
| SourceLocation RAngleLoc = TemplateId->RAngleLoc; |
| |
| TemplateName Name = TemplateId->Template.get(); |
| |
| // The template-id must name a variable template. |
| VarTemplateDecl *VarTemplate = |
| dyn_cast<VarTemplateDecl>(Name.getAsTemplateDecl()); |
| if (!VarTemplate) |
| return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) |
| << IsPartialSpecialization; |
| |
| // Check for unexpanded parameter packs in any of the template arguments. |
| for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) |
| if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], |
| UPPC_PartialSpecialization)) |
| return true; |
| |
| // Check that the template argument list is well-formed for this |
| // template. |
| SmallVector<TemplateArgument, 4> Converted; |
| if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, |
| false, Converted)) |
| return true; |
| |
| // Check that the type of this variable template specialization |
| // matches the expected type. |
| TypeSourceInfo *ExpectedDI; |
| { |
| // Do substitution on the type of the declaration |
| TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, |
| Converted.data(), Converted.size()); |
| InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate); |
| if (Inst.isInvalid()) |
| return true; |
| VarDecl *Templated = VarTemplate->getTemplatedDecl(); |
| ExpectedDI = |
| SubstType(Templated->getTypeSourceInfo(), |
| MultiLevelTemplateArgumentList(TemplateArgList), |
| Templated->getTypeSpecStartLoc(), Templated->getDeclName()); |
| } |
| if (!ExpectedDI) |
| return true; |
| |
| // Find the variable template (partial) specialization declaration that |
| // corresponds to these arguments. |
| if (IsPartialSpecialization) { |
| if (CheckTemplatePartialSpecializationArgs( |
| *this, TemplateNameLoc, VarTemplate->getTemplateParameters(), |
| TemplateArgs.size(), Converted)) |
| return true; |
| |
| bool InstantiationDependent; |
| if (!Name.isDependent() && |
| !TemplateSpecializationType::anyDependentTemplateArguments( |
| TemplateArgs.getArgumentArray(), TemplateArgs.size(), |
| InstantiationDependent)) { |
| Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) |
| << VarTemplate->getDeclName(); |
| IsPartialSpecialization = false; |
| } |
| |
| if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), |
| Converted)) { |
| // C++ [temp.class.spec]p9b3: |
| // |
| // -- The argument list of the specialization shall not be identical |
| // to the implicit argument list of the primary template. |
| Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) |
| << /*variable template*/ 1 |
| << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) |
| << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); |
| // FIXME: Recover from this by treating the declaration as a redeclaration |
| // of the primary template. |
| return true; |
| } |
| } |
| |
| void *InsertPos = 0; |
| VarTemplateSpecializationDecl *PrevDecl = 0; |
| |
| if (IsPartialSpecialization) |
| // FIXME: Template parameter list matters too |
| PrevDecl = VarTemplate->findPartialSpecialization( |
| Converted.data(), Converted.size(), InsertPos); |
| else |
| PrevDecl = VarTemplate->findSpecialization(Converted.data(), |
| Converted.size(), InsertPos); |
| |
| VarTemplateSpecializationDecl *Specialization = 0; |
| |
| // Check whether we can declare a variable template specialization in |
| // the current scope. |
| if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, |
| TemplateNameLoc, |
| IsPartialSpecialization)) |
| return true; |
| |
| if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { |
| // Since the only prior variable template specialization with these |
| // arguments was referenced but not declared, reuse that |
| // declaration node as our own, updating its source location and |
| // the list of outer template parameters to reflect our new declaration. |
| Specialization = PrevDecl; |
| Specialization->setLocation(TemplateNameLoc); |
| PrevDecl = 0; |
| } else if (IsPartialSpecialization) { |
| // Create a new class template partial specialization declaration node. |
| VarTemplatePartialSpecializationDecl *PrevPartial = |
| cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); |
| VarTemplatePartialSpecializationDecl *Partial = |
| VarTemplatePartialSpecializationDecl::Create( |
| Context, VarTemplate->getDeclContext(), TemplateKWLoc, |
| TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, |
| Converted.data(), Converted.size(), TemplateArgs); |
| |
| if (!PrevPartial) |
| VarTemplate->AddPartialSpecialization(Partial, InsertPos); |
| Specialization = Partial; |
| |
| // If we are providing an explicit specialization of a member variable |
| // template specialization, make a note of that. |
| if (PrevPartial && PrevPartial->getInstantiatedFromMember()) |
| PrevPartial->setMemberSpecialization(); |
| |
| // Check that all of the template parameters of the variable template |
| // partial specialization are deducible from the template |
| // arguments. If not, this variable template partial specialization |
| // will never be used. |
| llvm::SmallBitVector DeducibleParams(TemplateParams->size()); |
| MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, |
| TemplateParams->getDepth(), DeducibleParams); |
| |
| if (!DeducibleParams.all()) { |
| unsigned NumNonDeducible = |
| DeducibleParams.size() - DeducibleParams.count(); |
| Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) |
| << /*variable template*/ 1 << (NumNonDeducible > 1) |
| << SourceRange(TemplateNameLoc, RAngleLoc); |
| for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { |
| if (!DeducibleParams[I]) { |
| NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); |
| if (Param->getDeclName()) |
| Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter) |
| << Param->getDeclName(); |
| else |
| Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter) |
| << "(anonymous)"; |
| } |
| } |
| } |
| } else { |
| // Create a new class template specialization declaration node for |
| // this explicit specialization or friend declaration. |
| Specialization = VarTemplateSpecializationDecl::Create( |
| Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, |
| VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size()); |
| Specialization->setTemplateArgsInfo(TemplateArgs); |
| |
| if (!PrevDecl) |
| VarTemplate->AddSpecialization(Specialization, InsertPos); |
| } |
| |
| // C++ [temp.expl.spec]p6: |
| // If a template, a member template or the member of a class template is |
| // explicitly specialized then that specialization shall be declared |
| // before the first use of that specialization that would cause an implicit |
| // instantiation to take place, in every translation unit in which such a |
| // use occurs; no diagnostic is required. |
| if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { |
| bool Okay = false; |
| for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { |
| // Is there any previous explicit specialization declaration? |
| if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { |
| Okay = true; |
| break; |
| } |
| } |
| |
| if (!Okay) { |
| SourceRange Range(TemplateNameLoc, RAngleLoc); |
| Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) |
| << Name << Range; |
| |
| Diag(PrevDecl->getPointOfInstantiation(), |
| diag::note_instantiation_required_here) |
| << (PrevDecl->getTemplateSpecializationKind() != |
| TSK_ImplicitInstantiation); |
| return true; |
| } |
| } |
| |
| Specialization->setTemplateKeywordLoc(TemplateKWLoc); |
| Specialization->setLexicalDeclContext(CurContext); |
| |
| // Add the specialization into its lexical context, so that it can |
| // be seen when iterating through the list of declarations in that |
| // context. However, specializations are not found by name lookup. |
| CurContext->addDecl(Specialization); |
| |
| // Note that this is an explicit specialization. |
| Specialization->setSpecializationKind(TSK_ExplicitSpecialization); |
| |
| if (PrevDecl) { |
| // Check that this isn't a redefinition of this specialization, |
| // merging with previous declarations. |
| LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, |
| ForRedeclaration); |
| PrevSpec.addDecl(PrevDecl); |
| D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); |
| } else if (Specialization->isStaticDataMember() && |
| Specialization->isOutOfLine()) { |
| Specialization->setAccess(VarTemplate->getAccess()); |
| } |
| |
| // Link instantiations of static data members back to the template from |
| // which they were instantiated. |
| if (Specialization->isStaticDataMember()) |
| Specialization->setInstantiationOfStaticDataMember( |
| VarTemplate->getTemplatedDecl(), |
| Specialization->getSpecializationKind()); |
| |
| return Specialization; |
| } |
| |
| namespace { |
| /// \brief A partial specialization whose template arguments have matched |
| /// a given template-id. |
| struct PartialSpecMatchResult { |
| VarTemplatePartialSpecializationDecl *Partial; |
| TemplateArgumentList *Args; |
| }; |
| } |
| |
| DeclResult |
| Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, |
| SourceLocation TemplateNameLoc, |
| const TemplateArgumentListInfo &TemplateArgs) { |
| assert(Template && "A variable template id without template?"); |
| |
| // Check that the template argument list is well-formed for this template. |
| SmallVector<TemplateArgument, 4> Converted; |
| if (CheckTemplateArgumentList( |
| Template, TemplateNameLoc, |
| const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, |
| Converted)) |
| return true; |
| |
| // Find the variable template specialization declaration that |
| // corresponds to these arguments. |
| void *InsertPos = 0; |
| if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization( |
| Converted.data(), Converted.size(), InsertPos)) |
| // If we already have a variable template specialization, return it. |
| return Spec; |
| |
| // This is the first time we have referenced this variable template |
| // specialization. Create the canonical declaration and add it to |
| // the set of specializations, based on the closest partial specialization |
| // that it represents. That is, |
| VarDecl *InstantiationPattern = Template->getTemplatedDecl(); |
| TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, |
| Converted.data(), Converted.size()); |
| TemplateArgumentList *InstantiationArgs = &TemplateArgList; |
| bool AmbiguousPartialSpec = false; |
| typedef PartialSpecMatchResult MatchResult; |
| SmallVector<MatchResult, 4> Matched; |
| SourceLocation PointOfInstantiation = TemplateNameLoc; |
| TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); |
| |
| // 1. Attempt to find the closest partial specialization that this |
| // specializes, if any. |
| // If any of the template arguments is dependent, then this is probably |
| // a placeholder for an incomplete declarative context; which must be |
| // complete by instantiation time. Thus, do not search through the partial |
| // specializations yet. |
| // TODO: Unify with InstantiateClassTemplateSpecialization()? |
| // Perhaps better after unification of DeduceTemplateArguments() and |
| // getMoreSpecializedPartialSpecialization(). |
| bool InstantiationDependent = false; |
| if (!TemplateSpecializationType::anyDependentTemplateArguments( |
| TemplateArgs, InstantiationDependent)) { |
| |
| SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
| Template->getPartialSpecializations(PartialSpecs); |
| |
| for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { |
| VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; |
| TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
| |
| if (TemplateDeductionResult Result = |
| DeduceTemplateArguments(Partial, TemplateArgList, Info)) { |
| // Store the failed-deduction information for use in diagnostics, later. |
| // TODO: Actually use the failed-deduction info? |
| FailedCandidates.addCandidate() |
| .set(Partial, MakeDeductionFailureInfo(Context, Result, Info)); |
| (void)Result; |
| } else { |
| Matched.push_back(PartialSpecMatchResult()); |
| Matched.back().Partial = Partial; |
| Matched.back().Args = Info.take(); |
| } |
| } |
| |
| if (Matched.size() >= 1) { |
| SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); |
| if (Matched.size() == 1) { |
| // -- If exactly one matching specialization is found, the |
| // instantiation is generated from that specialization. |
| // We don't need to do anything for this. |
| } else { |
| // -- If more than one matching specialization is found, the |
| // partial order rules (14.5.4.2) are used to determine |
| // whether one of the specializations is more specialized |
| // than the others. If none of the specializations is more |
| // specialized than all of the other matching |
| // specializations, then the use of the variable template is |
| // ambiguous and the program is ill-formed. |
| for (SmallVector<MatchResult, 4>::iterator P = Best + 1, |
| PEnd = Matched.end(); |
| P != PEnd; ++P) { |
| if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, |
| PointOfInstantiation) == |
| P->Partial) |
| Best = P; |
| } |
| |
| // Determine if the best partial specialization is more specialized than |
| // the others. |
| for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), |
| PEnd = Matched.end(); |
| P != PEnd; ++P) { |
| if (P != Best && getMoreSpecializedPartialSpecialization( |
| P->Partial, Best->Partial, |
| PointOfInstantiation) != Best->Partial) { |
| AmbiguousPartialSpec = true; |
| break; |
| } |
| } |
| } |
| |
| // Instantiate using the best variable template partial specialization. |
| InstantiationPattern = Best->Partial; |
| InstantiationArgs = Best->Args; |
| } else { |
| // -- If no match is found, the instantiation is generated |
| // from the primary template. |
| // InstantiationPattern = Template->getTemplatedDecl(); |
| } |
| } |
| |
| // 2. Create the canonical declaration. |
| // Note that we do not instantiate the variable just yet, since |
| // instantiation is handled in DoMarkVarDeclReferenced(). |
| // FIXME: LateAttrs et al.? |
| VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( |
| Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, |
| Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/); |
| if (!Decl) |
| return true; |
| |
| if (AmbiguousPartialSpec) { |
| // Partial ordering did not produce a clear winner. Complain. |
| Decl->setInvalidDecl(); |
| Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) |
| << Decl; |
| |
| // Print the matching partial specializations. |
| for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), |
| PEnd = Matched.end(); |
| P != PEnd; ++P) |
| Diag(P->Partial->getLocation(), diag::note_partial_spec_match) |
| << getTemplateArgumentBindingsText( |
| P->Partial->getTemplateParameters(), *P->Args); |
| return true; |
| } |
| |
| if (VarTemplatePartialSpecializationDecl *D = |
| dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) |
| Decl->setInstantiationOf(D, InstantiationArgs); |
| |
| assert(Decl && "No variable template specialization?"); |
| return Decl; |
| } |
| |
| ExprResult |
| Sema::CheckVarTemplateId(const CXXScopeSpec &SS, |
| const DeclarationNameInfo &NameInfo, |
| VarTemplateDecl *Template, SourceLocation TemplateLoc, |
| const TemplateArgumentListInfo *TemplateArgs) { |
| |
| DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo |