//===------- 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 "Sema.h" #include "Lookup.h" #include "TreeTransform.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/DeclTemplate.h" #include "clang/Parse/DeclSpec.h" #include "clang/Parse/Template.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/PartialDiagnostic.h" #include "llvm/ADT/StringExtras.h" using namespace clang; /// \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 *D) { if (!D) return 0; if (isa(D)) return D; if (CXXRecordDecl *Record = dyn_cast(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(Record->getDeclContext()); if (Record->getDescribedClassTemplate()) return Record->getDescribedClassTemplate(); if (ClassTemplateSpecializationDecl *Spec = dyn_cast(Record)) return Spec->getSpecializedTemplate(); } return 0; } return 0; } static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) { LookupResult::Filter filter = R.makeFilter(); while (filter.hasNext()) { NamedDecl *Orig = filter.next(); NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl()); if (!Repl) filter.erase(); else if (Repl != Orig) filter.replace(Repl); } filter.done(); } TemplateNameKind Sema::isTemplateName(Scope *S, const CXXScopeSpec &SS, UnqualifiedId &Name, TypeTy *ObjectTypePtr, bool EnteringContext, TemplateTy &TemplateResult) { DeclarationName TName; 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 = QualType::getFromOpaquePtr(ObjectTypePtr); LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName); R.suppressDiagnostics(); LookupTemplateName(R, S, SS, ObjectType, EnteringContext); if (R.empty()) 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; } else { TemplateDecl *TD = cast((*R.begin())->getUnderlyingDecl()); if (SS.isSet() && !SS.isInvalid()) { NestedNameSpecifier *Qualifier = static_cast(SS.getScopeRep()); Template = Context.getQualifiedTemplateName(Qualifier, false, TD); } else { Template = TemplateName(TD); } if (isa(TD)) TemplateKind = TNK_Function_template; else { assert(isa(TD) || isa(TD)); TemplateKind = TNK_Type_template; } } TemplateResult = TemplateTy::make(Template); return TemplateKind; } void Sema::LookupTemplateName(LookupResult &Found, Scope *S, const CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext) { // Determine where to perform name lookup 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()) && "Caller should have completed object type"); } 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)) return; } bool ObjectTypeSearchedInScope = false; 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. // // FIXME: When we're instantiating a template, do we actually have to // look in the scope of the template? Seems fishy... if (S) LookupName(Found, S); ObjectTypeSearchedInScope = true; } } else if (isDependent) { // We cannot look into a dependent object type or return; } else { // Perform unqualified name lookup in the current scope. LookupName(Found, S); } // FIXME: Cope with ambiguous name-lookup results. assert(!Found.isAmbiguous() && "Cannot handle template name-lookup ambiguities"); FilterAcceptableTemplateNames(Context, Found); if (Found.empty()) return; if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { // C++ [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 [...] // LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), LookupOrdinaryName); LookupName(FoundOuter, S); FilterAcceptableTemplateNames(Context, FoundOuter); // FIXME: Handle ambiguities in this lookup better 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()) { // - 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 } else { // - 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::err_nested_name_member_ref_lookup_ambiguous) << Found.getLookupName(); 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. Sema::OwningExprResult Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, DeclarationName Name, SourceLocation NameLoc, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs) { NestedNameSpecifier *Qualifier = static_cast(SS.getScopeRep()); if (!isAddressOfOperand && isa(CurContext) && cast(CurContext)->isInstance()) { QualType ThisType = cast(CurContext)->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(), Qualifier, SS.getRange(), FirstQualifierInScope, Name, NameLoc, TemplateArgs)); } return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs); } Sema::OwningExprResult Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, DeclarationName Name, SourceLocation NameLoc, const TemplateArgumentListInfo *TemplateArgs) { return Owned(DependentScopeDeclRefExpr::Create(Context, static_cast(SS.getScopeRep()), SS.getRange(), Name, NameLoc, 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. bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); // Microsoft Visual C++ permits template parameters to be shadowed. if (getLangOptions().Microsoft) return false; // 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(PrevDecl)->getDeclName(); Diag(PrevDecl->getLocation(), diag::note_template_param_here); return true; } /// 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(DeclPtrTy &D) { if (TemplateDecl *Temp = dyn_cast_or_null(D.getAs())) { D = DeclPtrTy::make(Temp->getTemplatedDecl()); return Temp; } return 0; } 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(Arg.getAsExpr()); return TemplateArgumentLoc(TemplateArgument(E), E); } case ParsedTemplateArgument::Template: { TemplateName Template = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get()); return TemplateArgumentLoc(TemplateArgument(Template), Arg.getScopeSpec().getRange(), Arg.getLocation()); } } llvm::llvm_unreachable("Unhandled parsed template argument"); return TemplateArgumentLoc(); } /// \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])); } /// 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 /// ParamName is the location of the parameter name (if any). /// If the type parameter has a default argument, it will be added /// later via ActOnTypeParameterDefault. Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position) { assert(S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"); bool Invalid = false; if (ParamName) { NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); if (PrevDecl && PrevDecl->isTemplateParameter()) Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl); } SourceLocation Loc = ParamNameLoc; if (!ParamName) Loc = KeyLoc; TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(Context, CurContext, Loc, Depth, Position, ParamName, Typename, Ellipsis); if (Invalid) Param->setInvalidDecl(); if (ParamName) { // Add the template parameter into the current scope. S->AddDecl(DeclPtrTy::make(Param)); IdResolver.AddDecl(Param); } return DeclPtrTy::make(Param); } /// ActOnTypeParameterDefault - Adds a default argument (the type /// Default) to the given template type parameter (TypeParam). void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam, SourceLocation EqualLoc, SourceLocation DefaultLoc, TypeTy *DefaultT) { TemplateTypeParmDecl *Parm = cast(TypeParam.getAs()); TypeSourceInfo *DefaultTInfo; GetTypeFromParser(DefaultT, &DefaultTInfo); assert(DefaultTInfo && "expected source information for type"); // 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 (Parm->isParameterPack()) { Diag(DefaultLoc, diag::err_template_param_pack_default_arg); return; } // C++ [temp.param]p14: // A template-parameter shall not be used in its own default argument. // FIXME: Implement this check! Needs a recursive walk over the types. // Check the template argument itself. if (CheckTemplateArgument(Parm, DefaultTInfo)) { Parm->setInvalidDecl(); return; } Parm->setDefaultArgument(DefaultTInfo, false); } /// \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) { // 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->isIntegralType() || T->isEnumeralType() || // -- pointer to object or pointer to function, (T->isPointerType() && (T->getAs()->getPointeeType()->isObjectType() || T->getAs()->getPointeeType()->isFunctionType())) || // -- reference to object or reference to function, T->isReferenceType() || // -- pointer to member. T->isMemberPointerType() || // If T is a dependent type, we can't do the check now, so we // assume that it is well-formed. T->isDependentType()) return T; // 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(); } /// ActOnNonTypeTemplateParameter - Called when a C++ non-type /// template parameter (e.g., "int Size" in "template /// class Array") has been parsed. S is the current scope and D is /// the parsed declarator. Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position) { TypeSourceInfo *TInfo = 0; QualType T = GetTypeForDeclarator(D, S, &TInfo); assert(S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"); bool Invalid = false; IdentifierInfo *ParamName = D.getIdentifier(); if (ParamName) { NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); if (PrevDecl && PrevDecl->isTemplateParameter()) Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); } T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); if (T.isNull()) { T = Context.IntTy; // Recover with an 'int' type. Invalid = true; } NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(), Depth, Position, ParamName, T, TInfo); if (Invalid) Param->setInvalidDecl(); if (D.getIdentifier()) { // Add the template parameter into the current scope. S->AddDecl(DeclPtrTy::make(Param)); IdResolver.AddDecl(Param); } return DeclPtrTy::make(Param); } /// \brief Adds a default argument to the given non-type template /// parameter. void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD, SourceLocation EqualLoc, ExprArg DefaultE) { NonTypeTemplateParmDecl *TemplateParm = cast(TemplateParamD.getAs()); Expr *Default = static_cast(DefaultE.get()); // C++ [temp.param]p14: // A template-parameter shall not be used in its own default argument. // FIXME: Implement this check! Needs a recursive walk over the types. // Check the well-formedness of the default template argument. TemplateArgument Converted; if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default, Converted)) { TemplateParm->setInvalidDecl(); return; } TemplateParm->setDefaultArgument(DefaultE.takeAs()); } /// ActOnTemplateTemplateParameter - Called when a C++ template template /// parameter (e.g. T in template