blob: 0f7106135b2cedb34ed5ec6926b4c2544727fa57 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregor2dd078a2009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000031
Douglas Gregor2dd078a2009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000034
Douglas Gregor2dd078a2009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000048 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000049 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump1eb44332009-09-09 15:08:12 +000056
Douglas Gregor2dd078a2009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump1eb44332009-09-09 15:08:12 +000059
Douglas Gregor2dd078a2009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Douglas Gregor2dd078a2009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump1eb44332009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregor2dd078a2009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregor2dd078a2009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump1eb44332009-09-09 15:08:12 +000096
Douglas Gregor2dd078a2009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000101 const CXXScopeSpec &SS,
102 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000103 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000104 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000105 TemplateTy &TemplateResult) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000106 DeclarationName TName;
107
108 switch (Name.getKind()) {
109 case UnqualifiedId::IK_Identifier:
110 TName = DeclarationName(Name.Identifier);
111 break;
112
113 case UnqualifiedId::IK_OperatorFunctionId:
114 TName = Context.DeclarationNames.getCXXOperatorName(
115 Name.OperatorFunctionId.Operator);
116 break;
117
118 default:
119 return TNK_Non_template;
120 }
121
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000122 // Determine where to perform name lookup
123 DeclContext *LookupCtx = 0;
124 bool isDependent = false;
125 if (ObjectTypePtr) {
126 // This nested-name-specifier occurs in a member access expression, e.g.,
127 // x->B::f, and we are looking into the type of the object.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000128 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000129 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
130 LookupCtx = computeDeclContext(ObjectType);
131 isDependent = ObjectType->isDependentType();
Douglas Gregor014e88d2009-11-03 23:16:33 +0000132 } else if (SS.isSet()) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000133 // This nested-name-specifier occurs after another nested-name-specifier,
134 // so long into the context associated with the prior nested-name-specifier.
135
Douglas Gregor014e88d2009-11-03 23:16:33 +0000136 LookupCtx = computeDeclContext(SS, EnteringContext);
137 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000140 LookupResult Found;
141 bool ObjectTypeSearchedInScope = false;
142 if (LookupCtx) {
143 // Perform "qualified" name lookup into the declaration context we
144 // computed, which is either the type of the base of a member access
Mike Stump1eb44332009-09-09 15:08:12 +0000145 // expression or the declaration context associated with a prior
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000146 // nested-name-specifier.
147
148 // The declaration context must be complete.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000149 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000150 return TNK_Non_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Douglas Gregor014e88d2009-11-03 23:16:33 +0000152 LookupQualifiedName(Found, LookupCtx, TName, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000154 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
155 // C++ [basic.lookup.classref]p1:
156 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump1eb44332009-09-09 15:08:12 +0000157 // immediately followed by an identifier followed by a <, the
158 // identifier must be looked up to determine whether the < is the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000159 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000160 // The identifier is first looked up in the class of the object
161 // expression. If the identifier is not found, it is then looked up in
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000162 // the context of the entire postfix-expression and shall name a class
163 // or function template.
164 //
165 // FIXME: When we're instantiating a template, do we actually have to
166 // look in the scope of the template? Seems fishy...
Douglas Gregor014e88d2009-11-03 23:16:33 +0000167 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000168 ObjectTypeSearchedInScope = true;
169 }
170 } else if (isDependent) {
Mike Stump1eb44332009-09-09 15:08:12 +0000171 // We cannot look into a dependent object type or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000172 return TNK_Non_template;
173 } else {
174 // Perform unqualified name lookup in the current scope.
Douglas Gregor014e88d2009-11-03 23:16:33 +0000175 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 }
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Douglas Gregor495c35d2009-08-25 22:51:20 +0000178 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump1eb44332009-09-09 15:08:12 +0000179 assert(!Found.isAmbiguous() &&
Douglas Gregor495c35d2009-08-25 22:51:20 +0000180 "Cannot handle template name-lookup ambiguities");
Douglas Gregor7532dc62009-03-30 22:58:21 +0000181
John McCallf36e02d2009-10-09 21:13:30 +0000182 NamedDecl *Template
183 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000184 if (!Template)
185 return TNK_Non_template;
186
187 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
188 // C++ [basic.lookup.classref]p1:
Mike Stump1eb44332009-09-09 15:08:12 +0000189 // [...] If the lookup in the class of the object expression finds a
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000190 // template, the name is also looked up in the context of the entire
191 // postfix-expression and [...]
192 //
John McCallf36e02d2009-10-09 21:13:30 +0000193 LookupResult FoundOuter;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000194 LookupName(FoundOuter, S, TName, LookupOrdinaryName);
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000195 // FIXME: Handle ambiguities in this lookup better
John McCallf36e02d2009-10-09 21:13:30 +0000196 NamedDecl *OuterTemplate
197 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000199 if (!OuterTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +0000200 // - if the name is not found, the name found in the class of the
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000201 // object expression is used, otherwise
202 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000203 // - if the name is found in the context of the entire
204 // postfix-expression and does not name a class template, the name
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000205 // found in the class of the object expression is used, otherwise
206 } else {
207 // - if the name found is a class template, it must refer to the same
Mike Stump1eb44332009-09-09 15:08:12 +0000208 // entity as the one found in the class of the object expression,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000209 // otherwise the program is ill-formed.
210 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000211 Diag(Name.getSourceRange().getBegin(),
212 diag::err_nested_name_member_ref_lookup_ambiguous)
213 << TName
214 << Name.getSourceRange();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000215 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
216 << QualType::getFromOpaquePtr(ObjectTypePtr);
217 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump1eb44332009-09-09 15:08:12 +0000218
219 // Recover by taking the template that we found in the object
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000220 // expression's type.
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000221 }
Mike Stump1eb44332009-09-09 15:08:12 +0000222 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Douglas Gregor014e88d2009-11-03 23:16:33 +0000225 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000226 NestedNameSpecifier *Qualifier
Douglas Gregor014e88d2009-11-03 23:16:33 +0000227 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +0000228 if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000229 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump1eb44332009-09-09 15:08:12 +0000230 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000231 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
232 Ovl));
233 else
Mike Stump1eb44332009-09-09 15:08:12 +0000234 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000235 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump1eb44332009-09-09 15:08:12 +0000236 cast<TemplateDecl>(Template)));
237 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000238 = dyn_cast<OverloadedFunctionDecl>(Template)) {
239 TemplateResult = TemplateTy::make(TemplateName(Ovl));
240 } else {
241 TemplateResult = TemplateTy::make(
242 TemplateName(cast<TemplateDecl>(Template)));
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
245 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000246 isa<TemplateTemplateParmDecl>(Template))
247 return TNK_Type_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000248
249 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000250 isa<OverloadedFunctionDecl>(Template)) &&
251 "Unhandled template kind in Sema::isTemplateName");
252 return TNK_Function_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000253}
254
Douglas Gregor72c3f312008-12-05 18:15:24 +0000255/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
256/// that the template parameter 'PrevDecl' is being shadowed by a new
257/// declaration at location Loc. Returns true to indicate that this is
258/// an error, and false otherwise.
259bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000260 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000261
262 // Microsoft Visual C++ permits template parameters to be shadowed.
263 if (getLangOptions().Microsoft)
264 return false;
265
266 // C++ [temp.local]p4:
267 // A template-parameter shall not be redeclared within its
268 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000269 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000270 << cast<NamedDecl>(PrevDecl)->getDeclName();
271 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
272 return true;
273}
274
Douglas Gregor2943aed2009-03-03 04:44:36 +0000275/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000276/// the parameter D to reference the templated declaration and return a pointer
277/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000278TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000279 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000280 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000281 return Temp;
282 }
283 return 0;
284}
285
Douglas Gregor72c3f312008-12-05 18:15:24 +0000286/// ActOnTypeParameter - Called when a C++ template type parameter
287/// (e.g., "typename T") has been parsed. Typename specifies whether
288/// the keyword "typename" was used to declare the type parameter
289/// (otherwise, "class" was used), and KeyLoc is the location of the
290/// "class" or "typename" keyword. ParamName is the name of the
291/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000292/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000293/// If the type parameter has a default argument, it will be added
294/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000295Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000296 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000297 SourceLocation KeyLoc,
298 IdentifierInfo *ParamName,
299 SourceLocation ParamNameLoc,
300 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000301 assert(S->isTemplateParamScope() &&
302 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000303 bool Invalid = false;
304
305 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000306 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000307 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000308 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000309 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000310 }
311
Douglas Gregorddc29e12009-02-06 22:42:48 +0000312 SourceLocation Loc = ParamNameLoc;
313 if (!ParamName)
314 Loc = KeyLoc;
315
Douglas Gregor72c3f312008-12-05 18:15:24 +0000316 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000317 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
318 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000319 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000320 if (Invalid)
321 Param->setInvalidDecl();
322
323 if (ParamName) {
324 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000325 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000326 IdResolver.AddDecl(Param);
327 }
328
Chris Lattnerb28317a2009-03-28 19:18:32 +0000329 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000330}
331
Douglas Gregord684b002009-02-10 19:49:53 +0000332/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000333/// Default) to the given template type parameter (TypeParam).
334void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000335 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000336 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000337 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000338 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000340
341 DeclaratorInfo *DefaultDInfo;
342 GetTypeFromParser(DefaultT, &DefaultDInfo);
343
344 assert(DefaultDInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000345
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000346 // C++0x [temp.param]p9:
347 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000348 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000349 if (Parm->isParameterPack()) {
350 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000351 return;
352 }
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Douglas Gregord684b002009-02-10 19:49:53 +0000354 // C++ [temp.param]p14:
355 // A template-parameter shall not be used in its own default argument.
356 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Douglas Gregord684b002009-02-10 19:49:53 +0000358 // Check the template argument itself.
John McCall833ca992009-10-29 08:12:44 +0000359 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000360 Parm->setInvalidDecl();
361 return;
362 }
363
John McCall833ca992009-10-29 08:12:44 +0000364 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000365}
366
Douglas Gregor2943aed2009-03-03 04:44:36 +0000367/// \brief Check that the type of a non-type template parameter is
368/// well-formed.
369///
370/// \returns the (possibly-promoted) parameter type if valid;
371/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000372QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000373Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
374 // C++ [temp.param]p4:
375 //
376 // A non-type template-parameter shall have one of the following
377 // (optionally cv-qualified) types:
378 //
379 // -- integral or enumeration type,
380 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000381 // -- pointer to object or pointer to function,
382 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000383 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
384 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000385 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000386 T->isReferenceType() ||
387 // -- pointer to member.
388 T->isMemberPointerType() ||
389 // If T is a dependent type, we can't do the check now, so we
390 // assume that it is well-formed.
391 T->isDependentType())
392 return T;
393 // C++ [temp.param]p8:
394 //
395 // A non-type template-parameter of type "array of T" or
396 // "function returning T" is adjusted to be of type "pointer to
397 // T" or "pointer to function returning T", respectively.
398 else if (T->isArrayType())
399 // FIXME: Keep the type prior to promotion?
400 return Context.getArrayDecayedType(T);
401 else if (T->isFunctionType())
402 // FIXME: Keep the type prior to promotion?
403 return Context.getPointerType(T);
404
405 Diag(Loc, diag::err_template_nontype_parm_bad_type)
406 << T;
407
408 return QualType();
409}
410
Douglas Gregor72c3f312008-12-05 18:15:24 +0000411/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
412/// template parameter (e.g., "int Size" in "template<int Size>
413/// class Array") has been parsed. S is the current scope and D is
414/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000415Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000416 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000417 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000418 DeclaratorInfo *DInfo = 0;
419 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000420
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000421 assert(S->isTemplateParamScope() &&
422 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000423 bool Invalid = false;
424
425 IdentifierInfo *ParamName = D.getIdentifier();
426 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000427 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000428 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000429 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000430 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000431 }
432
Douglas Gregor2943aed2009-03-03 04:44:36 +0000433 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000434 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000435 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000436 Invalid = true;
437 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000438
Douglas Gregor72c3f312008-12-05 18:15:24 +0000439 NonTypeTemplateParmDecl *Param
440 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000441 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000442 if (Invalid)
443 Param->setInvalidDecl();
444
445 if (D.getIdentifier()) {
446 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000447 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000448 IdResolver.AddDecl(Param);
449 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000450 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000451}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000452
Douglas Gregord684b002009-02-10 19:49:53 +0000453/// \brief Adds a default argument to the given non-type template
454/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000455void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000456 SourceLocation EqualLoc,
457 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000458 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000459 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000460 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregord684b002009-02-10 19:49:53 +0000462 // C++ [temp.param]p14:
463 // A template-parameter shall not be used in its own default argument.
464 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Douglas Gregord684b002009-02-10 19:49:53 +0000466 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000467 TemplateArgument Converted;
468 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
469 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000470 TemplateParm->setInvalidDecl();
471 return;
472 }
473
Anders Carlssone9146f22009-05-01 19:49:17 +0000474 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000475}
476
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000477
478/// ActOnTemplateTemplateParameter - Called when a C++ template template
479/// parameter (e.g. T in template <template <typename> class T> class array)
480/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000481Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
482 SourceLocation TmpLoc,
483 TemplateParamsTy *Params,
484 IdentifierInfo *Name,
485 SourceLocation NameLoc,
486 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000487 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000488 assert(S->isTemplateParamScope() &&
489 "Template template parameter not in template parameter scope!");
490
491 // Construct the parameter object.
492 TemplateTemplateParmDecl *Param =
493 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
494 Position, Name,
495 (TemplateParameterList*)Params);
496
497 // Make sure the parameter is valid.
498 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
499 // do anything yet. However, if the template parameter list or (eventual)
500 // default value is ever invalidated, that will propagate here.
501 bool Invalid = false;
502 if (Invalid) {
503 Param->setInvalidDecl();
504 }
505
506 // If the tt-param has a name, then link the identifier into the scope
507 // and lookup mechanisms.
508 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000509 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000510 IdResolver.AddDecl(Param);
511 }
512
Chris Lattnerb28317a2009-03-28 19:18:32 +0000513 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000514}
515
Douglas Gregord684b002009-02-10 19:49:53 +0000516/// \brief Adds a default argument to the given template template
517/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000518void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000519 SourceLocation EqualLoc,
520 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000521 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000522 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000523
524 // Since a template-template parameter's default argument is an
525 // id-expression, it must be a DeclRefExpr.
Mike Stump1eb44332009-09-09 15:08:12 +0000526 DeclRefExpr *Default
Douglas Gregord684b002009-02-10 19:49:53 +0000527 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
528
529 // C++ [temp.param]p14:
530 // A template-parameter shall not be used in its own default argument.
531 // FIXME: Implement this check! Needs a recursive walk over the types.
532
533 // Check the well-formedness of the template argument.
534 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000535 Diag(Default->getSourceRange().getBegin(),
Douglas Gregord684b002009-02-10 19:49:53 +0000536 diag::err_template_arg_must_be_template)
537 << Default->getSourceRange();
538 TemplateParm->setInvalidDecl();
539 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000540 }
Douglas Gregord684b002009-02-10 19:49:53 +0000541 if (CheckTemplateArgument(TemplateParm, Default)) {
542 TemplateParm->setInvalidDecl();
543 return;
544 }
545
546 DefaultE.release();
547 TemplateParm->setDefaultArgument(Default);
548}
549
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000550/// ActOnTemplateParameterList - Builds a TemplateParameterList that
551/// contains the template parameters in Params/NumParams.
552Sema::TemplateParamsTy *
553Sema::ActOnTemplateParameterList(unsigned Depth,
554 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000555 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000556 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000557 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000558 SourceLocation RAngleLoc) {
559 if (ExportLoc.isValid())
560 Diag(ExportLoc, diag::note_template_export_unsupported);
561
Douglas Gregorddc29e12009-02-06 22:42:48 +0000562 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000563 (NamedDecl**)Params, NumParams,
564 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000565}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000566
Douglas Gregor212e81c2009-03-25 00:13:59 +0000567Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000568Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000569 SourceLocation KWLoc, const CXXScopeSpec &SS,
570 IdentifierInfo *Name, SourceLocation NameLoc,
571 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000572 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000573 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000574 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000575 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000576 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000577 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000578
579 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000580 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000581 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000582
John McCall05b23ea2009-09-14 21:59:20 +0000583 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
584 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000585
586 // There is no such thing as an unnamed class template.
587 if (!Name) {
588 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000589 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000590 }
591
592 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000593 DeclContext *SemanticContext;
594 LookupResult Previous;
595 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000596 if (RequireCompleteDeclContext(SS))
597 return true;
598
Douglas Gregor05396e22009-08-25 17:23:04 +0000599 SemanticContext = computeDeclContext(SS, true);
600 if (!SemanticContext) {
601 // FIXME: Produce a reasonable diagnostic here
602 return true;
603 }
Mike Stump1eb44332009-09-09 15:08:12 +0000604
John McCallf36e02d2009-10-09 21:13:30 +0000605 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor05396e22009-08-25 17:23:04 +0000606 true);
607 } else {
608 SemanticContext = CurContext;
John McCallf36e02d2009-10-09 21:13:30 +0000609 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor05396e22009-08-25 17:23:04 +0000610 }
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Douglas Gregorddc29e12009-02-06 22:42:48 +0000612 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
613 NamedDecl *PrevDecl = 0;
614 if (Previous.begin() != Previous.end())
615 PrevDecl = *Previous.begin();
616
Douglas Gregor6102d982009-09-26 07:05:09 +0000617 if (PrevDecl && TUK == TUK_Friend) {
618 // C++ [namespace.memdef]p3:
619 // [...] When looking for a prior declaration of a class or a function
620 // declared as a friend, and when the name of the friend class or
621 // function is neither a qualified name nor a template-id, scopes outside
622 // the innermost enclosing namespace scope are not considered.
623 DeclContext *OutermostContext = CurContext;
624 while (!OutermostContext->isFileContext())
625 OutermostContext = OutermostContext->getLookupParent();
626
627 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
628 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
629 SemanticContext = PrevDecl->getDeclContext();
630 } else {
631 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregor259571e2009-10-30 22:42:42 +0000632 // context we computed is the semantic context for our new
Douglas Gregor6102d982009-09-26 07:05:09 +0000633 // declaration.
634 PrevDecl = 0;
635 SemanticContext = OutermostContext;
636 }
Douglas Gregor259571e2009-10-30 22:42:42 +0000637
638 if (CurContext->isDependentContext()) {
639 // If this is a dependent context, we don't want to link the friend
640 // class template to the template in scope, because that would perform
641 // checking of the template parameter lists that can't be performed
642 // until the outer context is instantiated.
643 PrevDecl = 0;
644 }
Douglas Gregor6102d982009-09-26 07:05:09 +0000645 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000646 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Douglas Gregorddc29e12009-02-06 22:42:48 +0000648 // If there is a previous declaration with the same name, check
649 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000650 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000651 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000652
653 // We may have found the injected-class-name of a class template,
654 // class template partial specialization, or class template specialization.
655 // In these cases, grab the template that is being defined or specialized.
656 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
657 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
658 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
659 PrevClassTemplate
660 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
661 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
662 PrevClassTemplate
663 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
664 ->getSpecializedTemplate();
665 }
666 }
667
Douglas Gregorddc29e12009-02-06 22:42:48 +0000668 if (PrevClassTemplate) {
669 // Ensure that the template parameter lists are compatible.
670 if (!TemplateParameterListsAreEqual(TemplateParams,
671 PrevClassTemplate->getTemplateParameters(),
672 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000673 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000674
675 // C++ [temp.class]p4:
676 // In a redeclaration, partial specialization, explicit
677 // specialization or explicit instantiation of a class template,
678 // the class-key shall agree in kind with the original class
679 // template declaration (7.1.5.3).
680 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000681 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000682 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000683 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000684 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000685 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000686 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000687 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000688 }
689
Douglas Gregorddc29e12009-02-06 22:42:48 +0000690 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000691 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000692 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
693 Diag(NameLoc, diag::err_redefinition) << Name;
694 Diag(Def->getLocation(), diag::note_previous_definition);
695 // FIXME: Would it make sense to try to "forget" the previous
696 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000697 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000698 }
699 }
700 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
701 // Maybe we will complain about the shadowed template parameter.
702 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
703 // Just pretend that we didn't see the previous declaration.
704 PrevDecl = 0;
705 } else if (PrevDecl) {
706 // C++ [temp]p5:
707 // A class template shall not have the same name as any other
708 // template, class, function, object, enumeration, enumerator,
709 // namespace, or type in the same scope (3.3), except as specified
710 // in (14.5.4).
711 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
712 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000713 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000714 }
715
Douglas Gregord684b002009-02-10 19:49:53 +0000716 // Check the template parameter list of this declaration, possibly
717 // merging in the template parameter list from the previous class
718 // template declaration.
719 if (CheckTemplateParameterList(TemplateParams,
720 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
721 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Douglas Gregor7da97d02009-05-10 22:57:19 +0000723 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000724 // declaration!
725
Mike Stump1eb44332009-09-09 15:08:12 +0000726 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000727 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000728 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000729 PrevClassTemplate->getTemplatedDecl() : 0,
730 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000731
732 ClassTemplateDecl *NewTemplate
733 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
734 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000735 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000736 NewClass->setDescribedClassTemplate(NewTemplate);
737
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000738 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000739 QualType T =
740 Context.getTypeDeclType(NewClass,
741 PrevClassTemplate?
742 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000743 assert(T->isDependentType() && "Class template type is not dependent?");
744 (void)T;
745
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000746 // If we are providing an explicit specialization of a member that is a
747 // class template, make a note of that.
748 if (PrevClassTemplate &&
749 PrevClassTemplate->getInstantiatedFromMemberTemplate())
750 PrevClassTemplate->setMemberSpecialization();
751
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000752 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000753 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000754 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Douglas Gregorddc29e12009-02-06 22:42:48 +0000756 // Set the lexical context of these templates
757 NewClass->setLexicalDeclContext(CurContext);
758 NewTemplate->setLexicalDeclContext(CurContext);
759
John McCall0f434ec2009-07-31 02:45:11 +0000760 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000761 NewClass->startDefinition();
762
763 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000764 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000765
John McCall05b23ea2009-09-14 21:59:20 +0000766 if (TUK != TUK_Friend)
767 PushOnScopeChains(NewTemplate, S);
768 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000769 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000770 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000771 NewClass->setAccess(PrevClassTemplate->getAccess());
772 }
John McCall05b23ea2009-09-14 21:59:20 +0000773
Douglas Gregord85bea22009-09-26 06:47:28 +0000774 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
775 PrevClassTemplate != NULL);
776
John McCall05b23ea2009-09-14 21:59:20 +0000777 // Friend templates are visible in fairly strange ways.
778 if (!CurContext->isDependentContext()) {
779 DeclContext *DC = SemanticContext->getLookupContext();
780 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
781 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
782 PushOnScopeChains(NewTemplate, EnclosingScope,
783 /* AddToContext = */ false);
784 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000785
786 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
787 NewClass->getLocation(),
788 NewTemplate,
789 /*FIXME:*/NewClass->getLocation());
790 Friend->setAccess(AS_public);
791 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000792 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000793
Douglas Gregord684b002009-02-10 19:49:53 +0000794 if (Invalid) {
795 NewTemplate->setInvalidDecl();
796 NewClass->setInvalidDecl();
797 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000798 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000799}
800
Douglas Gregord684b002009-02-10 19:49:53 +0000801/// \brief Checks the validity of a template parameter list, possibly
802/// considering the template parameter list from a previous
803/// declaration.
804///
805/// If an "old" template parameter list is provided, it must be
806/// equivalent (per TemplateParameterListsAreEqual) to the "new"
807/// template parameter list.
808///
809/// \param NewParams Template parameter list for a new template
810/// declaration. This template parameter list will be updated with any
811/// default arguments that are carried through from the previous
812/// template parameter list.
813///
814/// \param OldParams If provided, template parameter list from a
815/// previous declaration of the same template. Default template
816/// arguments will be merged from the old template parameter list to
817/// the new template parameter list.
818///
819/// \returns true if an error occurred, false otherwise.
820bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
821 TemplateParameterList *OldParams) {
822 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Douglas Gregord684b002009-02-10 19:49:53 +0000824 // C++ [temp.param]p10:
825 // The set of default template-arguments available for use with a
826 // template declaration or definition is obtained by merging the
827 // default arguments from the definition (if in scope) and all
828 // declarations in scope in the same way default function
829 // arguments are (8.3.6).
830 bool SawDefaultArgument = false;
831 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000832
Anders Carlsson49d25572009-06-12 23:20:15 +0000833 bool SawParameterPack = false;
834 SourceLocation ParameterPackLoc;
835
Mike Stump1a35fde2009-02-11 23:03:27 +0000836 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000837 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000838 if (OldParams)
839 OldParam = OldParams->begin();
840
841 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
842 NewParamEnd = NewParams->end();
843 NewParam != NewParamEnd; ++NewParam) {
844 // Variables used to diagnose redundant default arguments
845 bool RedundantDefaultArg = false;
846 SourceLocation OldDefaultLoc;
847 SourceLocation NewDefaultLoc;
848
849 // Variables used to diagnose missing default arguments
850 bool MissingDefaultArg = false;
851
Anders Carlsson49d25572009-06-12 23:20:15 +0000852 // C++0x [temp.param]p11:
853 // If a template parameter of a class template is a template parameter pack,
854 // it must be the last template parameter.
855 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +0000856 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +0000857 diag::err_template_param_pack_must_be_last_template_parameter);
858 Invalid = true;
859 }
860
Douglas Gregord684b002009-02-10 19:49:53 +0000861 // Merge default arguments for template type parameters.
862 if (TemplateTypeParmDecl *NewTypeParm
863 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000864 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000865 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Anders Carlsson49d25572009-06-12 23:20:15 +0000867 if (NewTypeParm->isParameterPack()) {
868 assert(!NewTypeParm->hasDefaultArgument() &&
869 "Parameter packs can't have a default argument!");
870 SawParameterPack = true;
871 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000872 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +0000873 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +0000874 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
875 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
876 SawDefaultArgument = true;
877 RedundantDefaultArg = true;
878 PreviousDefaultArgLoc = NewDefaultLoc;
879 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
880 // Merge the default argument from the old declaration to the
881 // new declaration.
882 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +0000883 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +0000884 true);
885 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
886 } else if (NewTypeParm->hasDefaultArgument()) {
887 SawDefaultArgument = true;
888 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
889 } else if (SawDefaultArgument)
890 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000891 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000892 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000893 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000894 NonTypeTemplateParmDecl *OldNonTypeParm
895 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000896 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000897 NewNonTypeParm->hasDefaultArgument()) {
898 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
899 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
900 SawDefaultArgument = true;
901 RedundantDefaultArg = true;
902 PreviousDefaultArgLoc = NewDefaultLoc;
903 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
904 // Merge the default argument from the old declaration to the
905 // new declaration.
906 SawDefaultArgument = true;
907 // FIXME: We need to create a new kind of "default argument"
908 // expression that points to a previous template template
909 // parameter.
910 NewNonTypeParm->setDefaultArgument(
911 OldNonTypeParm->getDefaultArgument());
912 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
913 } else if (NewNonTypeParm->hasDefaultArgument()) {
914 SawDefaultArgument = true;
915 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
916 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000917 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000918 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000919 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000920 TemplateTemplateParmDecl *NewTemplateParm
921 = cast<TemplateTemplateParmDecl>(*NewParam);
922 TemplateTemplateParmDecl *OldTemplateParm
923 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000924 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000925 NewTemplateParm->hasDefaultArgument()) {
926 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
927 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
928 SawDefaultArgument = true;
929 RedundantDefaultArg = true;
930 PreviousDefaultArgLoc = NewDefaultLoc;
931 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
932 // Merge the default argument from the old declaration to the
933 // new declaration.
934 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000935 // FIXME: We need to create a new kind of "default argument" expression
936 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000937 NewTemplateParm->setDefaultArgument(
938 OldTemplateParm->getDefaultArgument());
939 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
940 } else if (NewTemplateParm->hasDefaultArgument()) {
941 SawDefaultArgument = true;
942 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
943 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000944 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +0000945 }
946
947 if (RedundantDefaultArg) {
948 // C++ [temp.param]p12:
949 // A template-parameter shall not be given default arguments
950 // by two different declarations in the same scope.
951 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
952 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
953 Invalid = true;
954 } else if (MissingDefaultArg) {
955 // C++ [temp.param]p11:
956 // If a template-parameter has a default template-argument,
957 // all subsequent template-parameters shall have a default
958 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +0000959 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +0000960 diag::err_template_param_default_arg_missing);
961 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
962 Invalid = true;
963 }
964
965 // If we have an old template parameter list that we're merging
966 // in, move on to the next parameter.
967 if (OldParams)
968 ++OldParam;
969 }
970
971 return Invalid;
972}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000973
Mike Stump1eb44332009-09-09 15:08:12 +0000974/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000975/// specifier, returning the template parameter list that applies to the
976/// name.
977///
978/// \param DeclStartLoc the start of the declaration that has a scope
979/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000980///
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000981/// \param SS the scope specifier that will be matched to the given template
982/// parameter lists. This scope specifier precedes a qualified name that is
983/// being declared.
984///
985/// \param ParamLists the template parameter lists, from the outermost to the
986/// innermost template parameter lists.
987///
988/// \param NumParamLists the number of template parameter lists in ParamLists.
989///
Douglas Gregor1fef4e62009-10-07 22:35:40 +0000990/// \param IsExplicitSpecialization will be set true if the entity being
991/// declared is an explicit specialization, false otherwise.
992///
Mike Stump1eb44332009-09-09 15:08:12 +0000993/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000994/// name that is preceded by the scope specifier @p SS. This template
995/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +0000996/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000997/// template specialization), or may be NULL (if we were's declaring isn't
998/// itself a template).
999TemplateParameterList *
1000Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1001 const CXXScopeSpec &SS,
1002 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001003 unsigned NumParamLists,
1004 bool &IsExplicitSpecialization) {
1005 IsExplicitSpecialization = false;
1006
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001007 // Find the template-ids that occur within the nested-name-specifier. These
1008 // template-ids will match up with the template parameter lists.
1009 llvm::SmallVector<const TemplateSpecializationType *, 4>
1010 TemplateIdsInSpecifier;
1011 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1012 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001013 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001014 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1015 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1016 if (!Template)
1017 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Ted Kremenek6217b802009-07-29 21:53:49 +00001019 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001020 ClassTemplateSpecializationDecl *SpecDecl
1021 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1022 // If the nested name specifier refers to an explicit specialization,
1023 // we don't need a template<> header.
Douglas Gregor861d0e82009-09-16 00:01:48 +00001024 // FIXME: revisit this approach once we cope with specializations
Douglas Gregorb88e8882009-07-30 17:40:51 +00001025 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001026 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1027 continue;
1028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001030 TemplateIdsInSpecifier.push_back(SpecType);
1031 }
1032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001034 // Reverse the list of template-ids in the scope specifier, so that we can
1035 // more easily match up the template-ids and the template parameter lists.
1036 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001038 SourceLocation FirstTemplateLoc = DeclStartLoc;
1039 if (NumParamLists)
1040 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001042 // Match the template-ids found in the specifier to the template parameter
1043 // lists.
1044 unsigned Idx = 0;
1045 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1046 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001047 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1048 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001049 if (Idx >= NumParamLists) {
1050 // We have a template-id without a corresponding template parameter
1051 // list.
1052 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001053 // FIXME: the location information here isn't great.
1054 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001055 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001056 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001057 << SS.getRange();
1058 } else {
1059 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1060 << SS.getRange()
1061 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1062 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001063 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001064 }
1065 return 0;
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001068 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001069 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001070 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001071 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1072
Mike Stump1eb44332009-09-09 15:08:12 +00001073 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001074 = dyn_cast<ClassTemplateDecl>(Template)) {
1075 TemplateParameterList *ExpectedTemplateParams = 0;
1076 // Is this template-id naming the primary template?
1077 if (Context.hasSameType(TemplateId,
1078 ClassTemplate->getInjectedClassNameType(Context)))
1079 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1080 // ... or a partial specialization?
1081 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1082 = ClassTemplate->findPartialSpecialization(TemplateId))
1083 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1084
1085 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001086 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001087 ExpectedTemplateParams,
1088 true);
Mike Stump1eb44332009-09-09 15:08:12 +00001089 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00001090 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001091 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001092 diag::err_template_param_list_matches_nontemplate)
1093 << TemplateId
1094 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001095 else
1096 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001097 }
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001099 // If there were at least as many template-ids as there were template
1100 // parameter lists, then there are no template parameter lists remaining for
1101 // the declaration itself.
1102 if (Idx >= NumParamLists)
1103 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001105 // If there were too many template parameter lists, complain about that now.
1106 if (Idx != NumParamLists - 1) {
1107 while (Idx < NumParamLists - 1) {
Mike Stump1eb44332009-09-09 15:08:12 +00001108 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001109 diag::err_template_spec_extra_headers)
1110 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1111 ParamLists[Idx]->getRAngleLoc());
1112 ++Idx;
1113 }
1114 }
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001116 // Return the last template parameter list, which corresponds to the
1117 // entity being declared.
1118 return ParamLists[NumParamLists - 1];
1119}
1120
Douglas Gregor40808ce2009-03-09 23:48:35 +00001121/// \brief Translates template arguments as provided by the parser
1122/// into template arguments used by semantic analysis.
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00001123void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1124 SourceLocation *TemplateArgLocs,
John McCall833ca992009-10-29 08:12:44 +00001125 llvm::SmallVector<TemplateArgumentLoc, 16> &TemplateArgs) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001126 TemplateArgs.reserve(TemplateArgsIn.size());
1127
1128 void **Args = TemplateArgsIn.getArgs();
1129 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1130 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
John McCall833ca992009-10-29 08:12:44 +00001131 if (ArgIsType[Arg]) {
1132 DeclaratorInfo *DI;
1133 QualType T = Sema::GetTypeFromParser(Args[Arg], &DI);
1134 if (!DI) DI = Context.getTrivialDeclaratorInfo(T, TemplateArgLocs[Arg]);
1135 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(T), DI));
1136 } else {
1137 Expr *E = reinterpret_cast<Expr *>(Args[Arg]);
1138 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(E), E));
1139 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00001140 }
1141}
1142
Douglas Gregor7532dc62009-03-30 22:58:21 +00001143QualType Sema::CheckTemplateIdType(TemplateName Name,
1144 SourceLocation TemplateLoc,
1145 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001146 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001147 unsigned NumTemplateArgs,
1148 SourceLocation RAngleLoc) {
1149 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001150 if (!Template) {
1151 // The template name does not resolve to a template, so we just
1152 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +00001153 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001154 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001155 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001156
Douglas Gregor40808ce2009-03-09 23:48:35 +00001157 // Check that the template argument list is well-formed for this
1158 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001159 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1160 NumTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001161 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001162 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001163 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001164 return QualType();
1165
Mike Stump1eb44332009-09-09 15:08:12 +00001166 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001167 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001168 "Converted template argument list is too short!");
1169
1170 QualType CanonType;
1171
Douglas Gregor7532dc62009-03-30 22:58:21 +00001172 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +00001173 TemplateArgs,
1174 NumTemplateArgs)) {
1175 // This class template specialization is a dependent
1176 // type. Therefore, its canonical type is another class template
1177 // specialization type that contains all of the converted
1178 // arguments in canonical form. This ensures that, e.g., A<T> and
1179 // A<T, T> have identical types when A is declared as:
1180 //
1181 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001182 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001183 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001184 Converted.getFlatArguments(),
1185 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Douglas Gregor1275ae02009-07-28 23:00:59 +00001187 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001188 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001189 // In the future, we need to teach getTemplateSpecializationType to only
1190 // build the canonical type and return that to us.
1191 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001192 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001193 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001194 // Find the class template specialization declaration that
1195 // corresponds to these arguments.
1196 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001197 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001198 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001199 Converted.flatSize(),
1200 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001201 void *InsertPos = 0;
1202 ClassTemplateSpecializationDecl *Decl
1203 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1204 if (!Decl) {
1205 // This is the first time we have referenced this class template
1206 // specialization. Create the canonical declaration and add it to
1207 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001208 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001209 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001210 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001211 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001212 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001213 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1214 Decl->setLexicalDeclContext(CurContext);
1215 }
1216
1217 CanonType = Context.getTypeDeclType(Decl);
1218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregor40808ce2009-03-09 23:48:35 +00001220 // Build the fully-sugared type for this class template
1221 // specialization, which refers back to the class template
1222 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001223 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1224 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001225}
1226
Douglas Gregorcc636682009-02-17 23:15:12 +00001227Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001228Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001229 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001230 ASTTemplateArgsPtr TemplateArgsIn,
John McCall833ca992009-10-29 08:12:44 +00001231 SourceLocation *TemplateArgLocsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001232 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001233 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001234
Douglas Gregor40808ce2009-03-09 23:48:35 +00001235 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001236 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
1237 translateTemplateArguments(TemplateArgsIn, TemplateArgLocsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001238
Douglas Gregor7532dc62009-03-30 22:58:21 +00001239 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001240 TemplateArgs.data(),
1241 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001242 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001243 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001244
1245 if (Result.isNull())
1246 return true;
1247
John McCall833ca992009-10-29 08:12:44 +00001248 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1249 TemplateSpecializationTypeLoc TL
1250 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1251 TL.setTemplateNameLoc(TemplateLoc);
1252 TL.setLAngleLoc(LAngleLoc);
1253 TL.setRAngleLoc(RAngleLoc);
1254 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1255 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1256
1257 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001258}
John McCallf1bbbb42009-09-04 01:14:41 +00001259
John McCall6b2becf2009-09-08 17:47:29 +00001260Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1261 TagUseKind TUK,
1262 DeclSpec::TST TagSpec,
1263 SourceLocation TagLoc) {
1264 if (TypeResult.isInvalid())
1265 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001266
John McCall833ca992009-10-29 08:12:44 +00001267 // FIXME: preserve source info, ideally without copying the DI.
1268 DeclaratorInfo *DI;
1269 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001270
John McCall6b2becf2009-09-08 17:47:29 +00001271 // Verify the tag specifier.
1272 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
John McCall6b2becf2009-09-08 17:47:29 +00001274 if (const RecordType *RT = Type->getAs<RecordType>()) {
1275 RecordDecl *D = RT->getDecl();
1276
1277 IdentifierInfo *Id = D->getIdentifier();
1278 assert(Id && "templated class must have an identifier");
1279
1280 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1281 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001282 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001283 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1284 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001285 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001286 }
1287 }
1288
John McCall6b2becf2009-09-08 17:47:29 +00001289 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1290
1291 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001292}
1293
Douglas Gregorf17bb742009-10-22 17:20:55 +00001294Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1295 SourceRange QualifierRange,
1296 TemplateName Template,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001297 SourceLocation TemplateNameLoc,
1298 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001299 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001300 unsigned NumTemplateArgs,
1301 SourceLocation RAngleLoc) {
1302 // FIXME: Can we do any checking at this point? I guess we could check the
1303 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001304 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001305 // though.
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001306
1307 // Cope with an implicit member access in a C++ non-static member function.
1308 NamedDecl *D = Template.getAsTemplateDecl();
1309 if (!D)
1310 D = Template.getAsOverloadedFunctionDecl();
1311
Douglas Gregorf17bb742009-10-22 17:20:55 +00001312 CXXScopeSpec SS;
1313 SS.setRange(QualifierRange);
1314 SS.setScopeRep(Qualifier);
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001315 QualType ThisType, MemberType;
Douglas Gregorf17bb742009-10-22 17:20:55 +00001316 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001317 ThisType, MemberType)) {
1318 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1319 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregorf17bb742009-10-22 17:20:55 +00001320 Qualifier, QualifierRange,
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001321 D, TemplateNameLoc, true,
1322 LAngleLoc, TemplateArgs,
1323 NumTemplateArgs, RAngleLoc,
1324 Context.OverloadTy));
1325 }
1326
Douglas Gregorf17bb742009-10-22 17:20:55 +00001327 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1328 Qualifier, QualifierRange,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001329 Template, TemplateNameLoc, LAngleLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001330 TemplateArgs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001331 NumTemplateArgs, RAngleLoc));
1332}
1333
Douglas Gregorf17bb742009-10-22 17:20:55 +00001334Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1335 TemplateTy TemplateD,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001336 SourceLocation TemplateNameLoc,
1337 SourceLocation LAngleLoc,
1338 ASTTemplateArgsPtr TemplateArgsIn,
John McCall833ca992009-10-29 08:12:44 +00001339 SourceLocation *TemplateArgSLs,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001340 SourceLocation RAngleLoc) {
1341 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001343 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00001344 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
1345 translateTemplateArguments(TemplateArgsIn, TemplateArgSLs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001346 TemplateArgsIn.release();
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Douglas Gregorf17bb742009-10-22 17:20:55 +00001348 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1349 SS.getRange(),
1350 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001351 TemplateArgs.data(), TemplateArgs.size(),
1352 RAngleLoc);
1353}
1354
Douglas Gregorc45c2322009-03-31 00:43:58 +00001355/// \brief Form a dependent template name.
1356///
1357/// This action forms a dependent template name given the template
1358/// name and its (presumably dependent) scope specifier. For
1359/// example, given "MetaFun::template apply", the scope specifier \p
1360/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1361/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001362Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001363Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001364 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001365 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001366 TypeTy *ObjectType) {
Mike Stump1eb44332009-09-09 15:08:12 +00001367 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001368 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1369 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001370 // C++0x [temp.names]p5:
1371 // If a name prefixed by the keyword template is not the name of
1372 // a template, the program is ill-formed. [Note: the keyword
1373 // template may not be applied to non-template members of class
1374 // templates. -end note ] [ Note: as is the case with the
1375 // typename prefix, the template prefix is allowed in cases
1376 // where it is not strictly necessary; i.e., when the
1377 // nested-name-specifier or the expression on the left of the ->
1378 // or . is not dependent on a template-parameter, or the use
1379 // does not appear in the scope of a template. -end note]
1380 //
1381 // Note: C++03 was more strict here, because it banned the use of
1382 // the "template" keyword prior to a template-name that was not a
1383 // dependent name. C++ DR468 relaxed this requirement (the
1384 // "template" keyword is now permitted). We follow the C++0x
1385 // rules, even in C++03 mode, retroactively applying the DR.
1386 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001387 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001388 false, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001389 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001390 Diag(Name.getSourceRange().getBegin(),
1391 diag::err_template_kw_refers_to_non_template)
1392 << GetNameFromUnqualifiedId(Name)
1393 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001394 return TemplateTy();
1395 }
1396
1397 return Template;
1398 }
1399
Mike Stump1eb44332009-09-09 15:08:12 +00001400 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001401 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001402
1403 switch (Name.getKind()) {
1404 case UnqualifiedId::IK_Identifier:
1405 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1406 Name.Identifier));
1407
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001408 case UnqualifiedId::IK_OperatorFunctionId:
1409 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1410 Name.OperatorFunctionId.Operator));
1411
Douglas Gregor014e88d2009-11-03 23:16:33 +00001412 default:
1413 break;
1414 }
1415
1416 Diag(Name.getSourceRange().getBegin(),
1417 diag::err_template_kw_refers_to_non_template)
1418 << GetNameFromUnqualifiedId(Name)
1419 << Name.getSourceRange();
1420 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001421}
1422
Mike Stump1eb44332009-09-09 15:08:12 +00001423bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001424 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001425 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001426 const TemplateArgument &Arg = AL.getArgument();
1427
Anders Carlsson436b1562009-06-13 00:33:33 +00001428 // Check template type parameter.
1429 if (Arg.getKind() != TemplateArgument::Type) {
1430 // C++ [temp.arg.type]p1:
1431 // A template-argument for a template-parameter which is a
1432 // type shall be a type-id.
1433
1434 // We have a template type parameter but the template argument
1435 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001436 SourceRange SR = AL.getSourceRange();
1437 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001438 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Anders Carlsson436b1562009-06-13 00:33:33 +00001440 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001441 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001442
John McCall833ca992009-10-29 08:12:44 +00001443 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001444 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Anders Carlsson436b1562009-06-13 00:33:33 +00001446 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001447 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001448 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001449 return false;
1450}
1451
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001452/// \brief Substitute template arguments into the default template argument for
1453/// the given template type parameter.
1454///
1455/// \param SemaRef the semantic analysis object for which we are performing
1456/// the substitution.
1457///
1458/// \param Template the template that we are synthesizing template arguments
1459/// for.
1460///
1461/// \param TemplateLoc the location of the template name that started the
1462/// template-id we are checking.
1463///
1464/// \param RAngleLoc the location of the right angle bracket ('>') that
1465/// terminates the template-id.
1466///
1467/// \param Param the template template parameter whose default we are
1468/// substituting into.
1469///
1470/// \param Converted the list of template arguments provided for template
1471/// parameters that precede \p Param in the template parameter list.
1472///
1473/// \returns the substituted template argument, or NULL if an error occurred.
1474static DeclaratorInfo *
1475SubstDefaultTemplateArgument(Sema &SemaRef,
1476 TemplateDecl *Template,
1477 SourceLocation TemplateLoc,
1478 SourceLocation RAngleLoc,
1479 TemplateTypeParmDecl *Param,
1480 TemplateArgumentListBuilder &Converted) {
1481 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1482
1483 // If the argument type is dependent, instantiate it now based
1484 // on the previously-computed template arguments.
1485 if (ArgType->getType()->isDependentType()) {
1486 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1487 /*TakeArgs=*/false);
1488
1489 MultiLevelTemplateArgumentList AllTemplateArgs
1490 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1491
1492 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1493 Template, Converted.getFlatArguments(),
1494 Converted.flatSize(),
1495 SourceRange(TemplateLoc, RAngleLoc));
1496
1497 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1498 Param->getDefaultArgumentLoc(),
1499 Param->getDeclName());
1500 }
1501
1502 return ArgType;
1503}
1504
1505/// \brief Substitute template arguments into the default template argument for
1506/// the given non-type template parameter.
1507///
1508/// \param SemaRef the semantic analysis object for which we are performing
1509/// the substitution.
1510///
1511/// \param Template the template that we are synthesizing template arguments
1512/// for.
1513///
1514/// \param TemplateLoc the location of the template name that started the
1515/// template-id we are checking.
1516///
1517/// \param RAngleLoc the location of the right angle bracket ('>') that
1518/// terminates the template-id.
1519///
1520/// \param Param the template template parameter whose default we are
1521/// substituting into.
1522///
1523/// \param Converted the list of template arguments provided for template
1524/// parameters that precede \p Param in the template parameter list.
1525///
1526/// \returns the substituted template argument, or NULL if an error occurred.
1527static Sema::OwningExprResult
1528SubstDefaultTemplateArgument(Sema &SemaRef,
1529 TemplateDecl *Template,
1530 SourceLocation TemplateLoc,
1531 SourceLocation RAngleLoc,
1532 NonTypeTemplateParmDecl *Param,
1533 TemplateArgumentListBuilder &Converted) {
1534 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1535 /*TakeArgs=*/false);
1536
1537 MultiLevelTemplateArgumentList AllTemplateArgs
1538 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1539
1540 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1541 Template, Converted.getFlatArguments(),
1542 Converted.flatSize(),
1543 SourceRange(TemplateLoc, RAngleLoc));
1544
1545 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1546}
1547
Douglas Gregorc15cb382009-02-09 23:23:08 +00001548/// \brief Check that the given template argument list is well-formed
1549/// for specializing the given template.
1550bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1551 SourceLocation TemplateLoc,
1552 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00001553 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001554 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001555 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001556 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001557 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001558 TemplateParameterList *Params = Template->getTemplateParameters();
1559 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001560 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001561 bool Invalid = false;
1562
Mike Stump1eb44332009-09-09 15:08:12 +00001563 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001564 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001566 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001567 (NumArgs < Params->getMinRequiredArguments() &&
1568 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001569 // FIXME: point at either the first arg beyond what we can handle,
1570 // or the '>', depending on whether we have too many or too few
1571 // arguments.
1572 SourceRange Range;
1573 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001574 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001575 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1576 << (NumArgs > NumParams)
1577 << (isa<ClassTemplateDecl>(Template)? 0 :
1578 isa<FunctionTemplateDecl>(Template)? 1 :
1579 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1580 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001581 Diag(Template->getLocation(), diag::note_template_decl_here)
1582 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001583 Invalid = true;
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
1586 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00001587 // [...] The type and form of each template-argument specified in
1588 // a template-id shall match the type and form specified for the
1589 // corresponding parameter declared by the template in its
1590 // template-parameter-list.
1591 unsigned ArgIdx = 0;
1592 for (TemplateParameterList::iterator Param = Params->begin(),
1593 ParamEnd = Params->end();
1594 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001595 if (ArgIdx > NumArgs && PartialTemplateArgs)
1596 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Douglas Gregorc15cb382009-02-09 23:23:08 +00001598 // Decode the template argument
John McCall833ca992009-10-29 08:12:44 +00001599 TemplateArgumentLoc Arg;
1600
Douglas Gregorc15cb382009-02-09 23:23:08 +00001601 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001602 // Retrieve the default template argument from the template
1603 // parameter.
1604 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001605 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001606 // We have an empty argument pack.
1607 Converted.BeginPack();
1608 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001609 break;
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001612 if (!TTP->hasDefaultArgument())
1613 break;
1614
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001615 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
1616 Template,
1617 TemplateLoc,
1618 RAngleLoc,
1619 TTP,
1620 Converted);
John McCall833ca992009-10-29 08:12:44 +00001621 if (!ArgType)
Douglas Gregorcd281c32009-02-28 00:25:32 +00001622 return true;
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001623
1624 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
1625 ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00001626 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001627 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1628 if (!NTTP->hasDefaultArgument())
1629 break;
1630
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001631 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
1632 TemplateLoc,
1633 RAngleLoc,
1634 NTTP,
1635 Converted);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001636 if (E.isInvalid())
1637 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
John McCall833ca992009-10-29 08:12:44 +00001639 Expr *Ex = E.takeAs<Expr>();
1640 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001641 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001642 TemplateTemplateParmDecl *TempParm
1643 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001644
1645 if (!TempParm->hasDefaultArgument())
1646 break;
1647
John McCallce3ff2b2009-08-25 22:02:44 +00001648 // FIXME: Subst default argument
John McCall828bff22009-10-29 18:45:58 +00001649 Arg = TemplateArgumentLoc(TemplateArgument(TempParm->getDefaultArgument()),
1650 TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001651 }
1652 } else {
1653 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001654 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001655 }
1656
Douglas Gregorc15cb382009-02-09 23:23:08 +00001657
1658 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001659 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001660 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001661 // Check all the remaining arguments (if any).
1662 for (; ArgIdx < NumArgs; ++ArgIdx) {
1663 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1664 Invalid = true;
1665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Anders Carlssonfb250522009-06-23 01:26:57 +00001667 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001668 } else {
1669 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1670 Invalid = true;
1671 }
Mike Stump1eb44332009-09-09 15:08:12 +00001672 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorc15cb382009-02-09 23:23:08 +00001673 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1674 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001675
John McCallce3ff2b2009-08-25 22:02:44 +00001676 // Do substitution on the type of the non-type template parameter
1677 // with the template arguments we've seen thus far.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001678 QualType NTTPType = NTTP->getType();
1679 if (NTTPType->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +00001680 // Do substitution on the type of the non-type template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001681 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001682 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001683 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001684 SourceRange(TemplateLoc, RAngleLoc));
1685
Anders Carlssone9c904b2009-06-05 04:47:51 +00001686 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001687 /*TakeArgs=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001688 NTTPType = SubstType(NTTPType,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001689 MultiLevelTemplateArgumentList(TemplateArgs),
John McCallce3ff2b2009-08-25 22:02:44 +00001690 NTTP->getLocation(),
1691 NTTP->getDeclName());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001692 // If that worked, check the non-type template parameter type
1693 // for validity.
1694 if (!NTTPType.isNull())
Mike Stump1eb44332009-09-09 15:08:12 +00001695 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001696 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001697 if (NTTPType.isNull()) {
1698 Invalid = true;
1699 break;
1700 }
1701 }
1702
John McCall833ca992009-10-29 08:12:44 +00001703 switch (Arg.getArgument().getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001704 case TemplateArgument::Null:
1705 assert(false && "Should never see a NULL template argument here");
1706 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Douglas Gregor40808ce2009-03-09 23:48:35 +00001708 case TemplateArgument::Expression: {
John McCall833ca992009-10-29 08:12:44 +00001709 Expr *E = Arg.getArgument().getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001710 TemplateArgument Result;
1711 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001712 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001713 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001714 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001715 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001716 }
1717
Douglas Gregor40808ce2009-03-09 23:48:35 +00001718 case TemplateArgument::Declaration:
1719 case TemplateArgument::Integral:
1720 // We've already checked this template argument, so just copy
1721 // it to the list of converted arguments.
John McCall833ca992009-10-29 08:12:44 +00001722 Converted.Append(Arg.getArgument());
Douglas Gregor40808ce2009-03-09 23:48:35 +00001723 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001724
John McCall833ca992009-10-29 08:12:44 +00001725 case TemplateArgument::Type: {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001726 // We have a non-type template parameter but the template
1727 // argument is a type.
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregor40808ce2009-03-09 23:48:35 +00001729 // C++ [temp.arg]p2:
1730 // In a template-argument, an ambiguity between a type-id and
1731 // an expression is resolved to a type-id, regardless of the
1732 // form of the corresponding template-parameter.
1733 //
1734 // We warn specifically about this case, since it can be rather
1735 // confusing for users.
John McCall833ca992009-10-29 08:12:44 +00001736 QualType T = Arg.getArgument().getAsType();
John McCall828bff22009-10-29 18:45:58 +00001737 SourceRange SR = Arg.getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00001738 if (T->isFunctionType())
John McCall828bff22009-10-29 18:45:58 +00001739 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig)
1740 << SR << T;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001741 else
John McCall828bff22009-10-29 18:45:58 +00001742 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001743 Diag((*Param)->getLocation(), diag::note_template_param_here);
1744 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001745 break;
John McCall833ca992009-10-29 08:12:44 +00001746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Anders Carlssond01b1da2009-06-15 17:04:53 +00001748 case TemplateArgument::Pack:
1749 assert(0 && "FIXME: Implement!");
1750 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001751 }
Mike Stump1eb44332009-09-09 15:08:12 +00001752 } else {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001753 // Check template template parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001754 TemplateTemplateParmDecl *TempParm
Douglas Gregorc15cb382009-02-09 23:23:08 +00001755 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
John McCall833ca992009-10-29 08:12:44 +00001757 switch (Arg.getArgument().getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001758 case TemplateArgument::Null:
1759 assert(false && "Should never see a NULL template argument here");
1760 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor40808ce2009-03-09 23:48:35 +00001762 case TemplateArgument::Expression: {
John McCall833ca992009-10-29 08:12:44 +00001763 Expr *ArgExpr = Arg.getArgument().getAsExpr();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001764 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1765 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1766 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1767 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Douglas Gregor40808ce2009-03-09 23:48:35 +00001769 // Add the converted template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001770 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001771 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
John McCall833ca992009-10-29 08:12:44 +00001772 Converted.Append(TemplateArgument(D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001773 continue;
1774 }
1775 }
1776 // fall through
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Douglas Gregor40808ce2009-03-09 23:48:35 +00001778 case TemplateArgument::Type: {
1779 // We have a template template parameter but the template
1780 // argument does not refer to a template.
1781 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1782 Invalid = true;
1783 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001784 }
1785
Douglas Gregor40808ce2009-03-09 23:48:35 +00001786 case TemplateArgument::Declaration:
1787 // We've already checked this template argument, so just copy
1788 // it to the list of converted arguments.
John McCall833ca992009-10-29 08:12:44 +00001789 Converted.Append(Arg.getArgument());
Douglas Gregor40808ce2009-03-09 23:48:35 +00001790 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Douglas Gregor40808ce2009-03-09 23:48:35 +00001792 case TemplateArgument::Integral:
1793 assert(false && "Integral argument with template template parameter");
1794 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Anders Carlssond01b1da2009-06-15 17:04:53 +00001796 case TemplateArgument::Pack:
1797 assert(0 && "FIXME: Implement!");
1798 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001799 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001800 }
1801 }
1802
1803 return Invalid;
1804}
1805
1806/// \brief Check a template argument against its corresponding
1807/// template type parameter.
1808///
1809/// This routine implements the semantics of C++ [temp.arg.type]. It
1810/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001811bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001812 DeclaratorInfo *ArgInfo) {
1813 assert(ArgInfo && "invalid DeclaratorInfo");
1814 QualType Arg = ArgInfo->getType();
1815
Douglas Gregorc15cb382009-02-09 23:23:08 +00001816 // C++ [temp.arg.type]p2:
1817 // A local type, a type with no linkage, an unnamed type or a type
1818 // compounded from any of these types shall not be used as a
1819 // template-argument for a template type-parameter.
1820 //
1821 // FIXME: Perform the recursive and no-linkage type checks.
1822 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00001823 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001824 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001825 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001826 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00001827 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1828 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1829 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1830 << QualType(Tag, 0) << SR;
1831 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00001832 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00001833 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1834 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001835 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1836 return true;
1837 }
1838
1839 return false;
1840}
1841
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001842/// \brief Checks whether the given template argument is the address
1843/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001844bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1845 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001846 bool Invalid = false;
1847
1848 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001849 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001850 Arg = Cast->getSubExpr();
1851
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001852 // C++0x allows nullptr, and there's no further checking to be done for that.
1853 if (Arg->getType()->isNullPtrType())
1854 return false;
1855
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001856 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00001857 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001858 // A template-argument for a non-type, non-template
1859 // template-parameter shall be one of: [...]
1860 //
1861 // -- the address of an object or function with external
1862 // linkage, including function templates and function
1863 // template-ids but excluding non-static class members,
1864 // expressed as & id-expression where the & is optional if
1865 // the name refers to a function or array, or if the
1866 // corresponding template-parameter is a reference; or
1867 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001869 // Ignore (and complain about) any excess parentheses.
1870 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1871 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00001872 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001873 diag::err_template_arg_extra_parens)
1874 << Arg->getSourceRange();
1875 Invalid = true;
1876 }
1877
1878 Arg = Parens->getSubExpr();
1879 }
1880
1881 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1882 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1883 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1884 } else
1885 DRE = dyn_cast<DeclRefExpr>(Arg);
1886
1887 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001888 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001889 diag::err_template_arg_not_object_or_func_form)
1890 << Arg->getSourceRange();
1891
1892 // Cannot refer to non-static data members
1893 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1894 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1895 << Field << Arg->getSourceRange();
1896
1897 // Cannot refer to non-static member functions
1898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1899 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00001900 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001901 diag::err_template_arg_method)
1902 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001904 // Functions must have external linkage.
1905 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1906 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00001907 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001908 diag::err_template_arg_function_not_extern)
1909 << Func << Arg->getSourceRange();
1910 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1911 << true;
1912 return true;
1913 }
1914
1915 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001916 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001917 return Invalid;
1918 }
1919
1920 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1921 if (!Var->hasGlobalStorage()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001922 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001923 diag::err_template_arg_object_not_extern)
1924 << Var << Arg->getSourceRange();
1925 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1926 << true;
1927 return true;
1928 }
1929
1930 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001931 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001932 return Invalid;
1933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001935 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00001936 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001937 diag::err_template_arg_not_object_or_func)
1938 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001939 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001940 diag::note_template_arg_refers_here);
1941 return true;
1942}
1943
1944/// \brief Checks whether the given template argument is a pointer to
1945/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump1eb44332009-09-09 15:08:12 +00001946bool
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001947Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001948 bool Invalid = false;
1949
1950 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00001951 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001952 Arg = Cast->getSubExpr();
1953
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001954 // C++0x allows nullptr, and there's no further checking to be done for that.
1955 if (Arg->getType()->isNullPtrType())
1956 return false;
1957
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001958 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00001959 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001960 // A template-argument for a non-type, non-template
1961 // template-parameter shall be one of: [...]
1962 //
1963 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00001964 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001965
1966 // Ignore (and complain about) any excess parentheses.
1967 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1968 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00001969 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001970 diag::err_template_arg_extra_parens)
1971 << Arg->getSourceRange();
1972 Invalid = true;
1973 }
1974
1975 Arg = Parens->getSubExpr();
1976 }
1977
1978 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregora2813ce2009-10-23 18:54:35 +00001979 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
1980 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1981 if (DRE && !DRE->getQualifier())
1982 DRE = 0;
1983 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001984
1985 if (!DRE)
1986 return Diag(Arg->getSourceRange().getBegin(),
1987 diag::err_template_arg_not_pointer_to_member_form)
1988 << Arg->getSourceRange();
1989
1990 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1991 assert((isa<FieldDecl>(DRE->getDecl()) ||
1992 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1993 "Only non-static member pointers can make it here");
1994
1995 // Okay: this is the address of a non-static member, and therefore
1996 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001997 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001998 return Invalid;
1999 }
2000
2001 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002002 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002003 diag::err_template_arg_not_pointer_to_member_form)
2004 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002005 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002006 diag::note_template_arg_refers_here);
2007 return true;
2008}
2009
Douglas Gregorc15cb382009-02-09 23:23:08 +00002010/// \brief Check a template argument against its corresponding
2011/// non-type template parameter.
2012///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002013/// This routine implements the semantics of C++ [temp.arg.nontype].
2014/// It returns true if an error occurred, and false otherwise. \p
2015/// InstantiatedParamType is the type of the non-type template
2016/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002017///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002018/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002019bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002020 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002021 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002022 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2023
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002024 // If either the parameter has a dependent type or the argument is
2025 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002026 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002027 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2028 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002029 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002030 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002031 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002032
2033 // C++ [temp.arg.nontype]p5:
2034 // The following conversions are performed on each expression used
2035 // as a non-type template-argument. If a non-type
2036 // template-argument cannot be converted to the type of the
2037 // corresponding template-parameter then the program is
2038 // ill-formed.
2039 //
2040 // -- for a non-type template-parameter of integral or
2041 // enumeration type, integral promotions (4.5) and integral
2042 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002043 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002044 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002045 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002046 // C++ [temp.arg.nontype]p1:
2047 // A template-argument for a non-type, non-template
2048 // template-parameter shall be one of:
2049 //
2050 // -- an integral constant-expression of integral or enumeration
2051 // type; or
2052 // -- the name of a non-type template-parameter; or
2053 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002054 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002055 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002056 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002057 diag::err_template_arg_not_integral_or_enumeral)
2058 << ArgType << Arg->getSourceRange();
2059 Diag(Param->getLocation(), diag::note_template_param_here);
2060 return true;
2061 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002062 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002063 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2064 << ArgType << Arg->getSourceRange();
2065 return true;
2066 }
2067
2068 // FIXME: We need some way to more easily get the unqualified form
2069 // of the types without going all the way to the
2070 // canonical type.
2071 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2072 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2073 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2074 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2075
2076 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002077 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002078 // Okay: no conversion necessary
2079 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2080 !ParamType->isEnumeralType()) {
2081 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002082 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002083 } else {
2084 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002085 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002086 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002087 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002088 Diag(Param->getLocation(), diag::note_template_param_here);
2089 return true;
2090 }
2091
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002092 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002093 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002094 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002095
2096 if (!Arg->isValueDependent()) {
2097 // Check that an unsigned parameter does not receive a negative
2098 // value.
2099 if (IntegerType->isUnsignedIntegerType()
2100 && (Value.isSigned() && Value.isNegative())) {
2101 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2102 << Value.toString(10) << Param->getType()
2103 << Arg->getSourceRange();
2104 Diag(Param->getLocation(), diag::note_template_param_here);
2105 return true;
2106 }
2107
2108 // Check that we don't overflow the template parameter type.
2109 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2110 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002111 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002112 diag::err_template_arg_too_large)
2113 << Value.toString(10) << Param->getType()
2114 << Arg->getSourceRange();
2115 Diag(Param->getLocation(), diag::note_template_param_here);
2116 return true;
2117 }
2118
2119 if (Value.getBitWidth() != AllowedBits)
2120 Value.extOrTrunc(AllowedBits);
2121 Value.setIsSigned(IntegerType->isSignedIntegerType());
2122 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002123
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002124 // Add the value of this argument to the list of converted
2125 // arguments. We use the bitwidth and signedness of the template
2126 // parameter.
2127 if (Arg->isValueDependent()) {
2128 // The argument is value-dependent. Create a new
2129 // TemplateArgument with the converted expression.
2130 Converted = TemplateArgument(Arg);
2131 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002132 }
2133
John McCall833ca992009-10-29 08:12:44 +00002134 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002135 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002136 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002137 return false;
2138 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002139
Douglas Gregorb86b0572009-02-11 01:18:59 +00002140 // Handle pointer-to-function, reference-to-function, and
2141 // pointer-to-member-function all in (roughly) the same way.
2142 if (// -- For a non-type template-parameter of type pointer to
2143 // function, only the function-to-pointer conversion (4.3) is
2144 // applied. If the template-argument represents a set of
2145 // overloaded functions (or a pointer to such), the matching
2146 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002147 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002148 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002149 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002150 // -- For a non-type template-parameter of type reference to
2151 // function, no conversions apply. If the template-argument
2152 // represents a set of overloaded functions, the matching
2153 // function is selected from the set (13.4).
2154 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002155 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002156 // -- For a non-type template-parameter of type pointer to
2157 // member function, no conversions apply. If the
2158 // template-argument represents a set of overloaded member
2159 // functions, the matching member function is selected from
2160 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002161 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002162 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002163 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002164 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002165 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002166 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002167 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002168 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2169 ParamType->isMemberPointerType())) {
2170 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002171 if (ParamType->isMemberPointerType())
2172 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2173 else
2174 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002175 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002176 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002177 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002178 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002179 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002180 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2181 return true;
2182
Anders Carlsson96ad5332009-10-21 17:16:23 +00002183 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002184 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002185 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002186 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002187 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002188 }
2189 }
2190
Mike Stump1eb44332009-09-09 15:08:12 +00002191 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002192 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002193 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002194 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002195 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002196 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002197 Diag(Param->getLocation(), diag::note_template_param_here);
2198 return true;
2199 }
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002201 if (ParamType->isMemberPointerType()) {
2202 NamedDecl *Member = 0;
2203 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2204 return true;
2205
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002206 if (Member)
2207 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002208 Converted = TemplateArgument(Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002209 return false;
2210 }
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002212 NamedDecl *Entity = 0;
2213 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2214 return true;
2215
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002216 if (Entity)
2217 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002218 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002219 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002220 }
2221
Chris Lattnerfe90de72009-02-20 21:37:53 +00002222 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002223 // -- for a non-type template-parameter of type pointer to
2224 // object, qualification conversions (4.4) and the
2225 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002226 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002227 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002228 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002229
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002230 if (ArgType->isNullPtrType()) {
2231 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002232 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002233 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002234 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002235 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002236 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002237
Douglas Gregorb86b0572009-02-11 01:18:59 +00002238 if (IsQualificationConversion(ArgType, ParamType)) {
2239 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002240 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002241 }
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002243 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002244 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002245 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002246 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002247 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002248 Diag(Param->getLocation(), diag::note_template_param_here);
2249 return true;
2250 }
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002252 NamedDecl *Entity = 0;
2253 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2254 return true;
2255
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002256 if (Entity)
2257 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002258 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002259 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002260 }
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Ted Kremenek6217b802009-07-29 21:53:49 +00002262 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002263 // -- For a non-type template-parameter of type reference to
2264 // object, no conversions apply. The type referred to by the
2265 // reference may be more cv-qualified than the (otherwise
2266 // identical) type of the template-argument. The
2267 // template-parameter is bound directly to the
2268 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002269 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002270 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002271
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002272 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002273 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002274 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002275 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002276 << Arg->getSourceRange();
2277 Diag(Param->getLocation(), diag::note_template_param_here);
2278 return true;
2279 }
2280
Mike Stump1eb44332009-09-09 15:08:12 +00002281 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002282 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2283 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Douglas Gregorb86b0572009-02-11 01:18:59 +00002285 if ((ParamQuals | ArgQuals) != ParamQuals) {
2286 Diag(Arg->getSourceRange().getBegin(),
2287 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002288 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002289 << Arg->getSourceRange();
2290 Diag(Param->getLocation(), diag::note_template_param_here);
2291 return true;
2292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002294 NamedDecl *Entity = 0;
2295 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2296 return true;
2297
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002298 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002299 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002300 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002301 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002302
2303 // -- For a non-type template-parameter of type pointer to data
2304 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002305 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002306 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2307
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002308 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002309 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002310 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002311 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002312 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002313 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002314 } else {
2315 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002316 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002317 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002318 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002319 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002320 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002321 }
2322
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002323 NamedDecl *Member = 0;
2324 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2325 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002327 if (Member)
2328 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002329 Converted = TemplateArgument(Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002330 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002331}
2332
2333/// \brief Check a template argument against its corresponding
2334/// template template parameter.
2335///
2336/// This routine implements the semantics of C++ [temp.arg.template].
2337/// It returns true if an error occurred, and false otherwise.
2338bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2339 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002340 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2341 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2342
2343 // C++ [temp.arg.template]p1:
2344 // A template-argument for a template template-parameter shall be
2345 // the name of a class template, expressed as id-expression. Only
2346 // primary class templates are considered when matching the
2347 // template template argument with the corresponding parameter;
2348 // partial specializations are not considered even if their
2349 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002350 //
2351 // Note that we also allow template template parameters here, which
2352 // will happen when we are dealing with, e.g., class template
2353 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002354 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002355 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002356 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002357 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00002358 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2359 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002360 << Template;
2361 }
2362
2363 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2364 Param->getTemplateParameters(),
2365 true, true,
2366 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002367}
2368
Douglas Gregorddc29e12009-02-06 22:42:48 +00002369/// \brief Determine whether the given template parameter lists are
2370/// equivalent.
2371///
Mike Stump1eb44332009-09-09 15:08:12 +00002372/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002373/// source code as part of a new template declaration.
2374///
2375/// \param Old The old template parameter list, typically found via
2376/// name lookup of the template declared with this template parameter
2377/// list.
2378///
2379/// \param Complain If true, this routine will produce a diagnostic if
2380/// the template parameter lists are not equivalent.
2381///
Douglas Gregordd0574e2009-02-10 00:24:35 +00002382/// \param IsTemplateTemplateParm If true, this routine is being
2383/// called to compare the template parameter lists of a template
2384/// template parameter.
2385///
2386/// \param TemplateArgLoc If this source location is valid, then we
2387/// are actually checking the template parameter list of a template
2388/// argument (New) against the template parameter list of its
2389/// corresponding template template parameter (Old). We produce
2390/// slightly different diagnostics in this scenario.
2391///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002392/// \returns True if the template parameter lists are equal, false
2393/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002394bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002395Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2396 TemplateParameterList *Old,
2397 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002398 bool IsTemplateTemplateParm,
2399 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002400 if (Old->size() != New->size()) {
2401 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002402 unsigned NextDiag = diag::err_template_param_list_different_arity;
2403 if (TemplateArgLoc.isValid()) {
2404 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2405 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002406 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002407 Diag(New->getTemplateLoc(), NextDiag)
2408 << (New->size() > Old->size())
2409 << IsTemplateTemplateParm
2410 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002411 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2412 << IsTemplateTemplateParm
2413 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2414 }
2415
2416 return false;
2417 }
2418
2419 for (TemplateParameterList::iterator OldParm = Old->begin(),
2420 OldParmEnd = Old->end(), NewParm = New->begin();
2421 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2422 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002423 if (Complain) {
2424 unsigned NextDiag = diag::err_template_param_different_kind;
2425 if (TemplateArgLoc.isValid()) {
2426 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2427 NextDiag = diag::note_template_param_different_kind;
2428 }
2429 Diag((*NewParm)->getLocation(), NextDiag)
2430 << IsTemplateTemplateParm;
2431 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2432 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002433 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002434 return false;
2435 }
2436
2437 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2438 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002439 // know we're at the same index).
2440#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002441 // FIXME: Enable this code in debug mode *after* we properly go through
2442 // and "instantiate" the template parameter lists of template template
2443 // parameters. It's only after this instantiation that (1) any dependent
2444 // types within the template parameter list of the template template
2445 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002446 // will match up.
Mike Stump1eb44332009-09-09 15:08:12 +00002447 QualType OldParmType
Douglas Gregorddc29e12009-02-06 22:42:48 +00002448 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump1eb44332009-09-09 15:08:12 +00002449 QualType NewParmType
Douglas Gregorddc29e12009-02-06 22:42:48 +00002450 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump1eb44332009-09-09 15:08:12 +00002451 assert(Context.getCanonicalType(OldParmType) ==
2452 Context.getCanonicalType(NewParmType) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002453 "type parameter mismatch?");
2454#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002455 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002456 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2457 // The types of non-type template parameters must agree.
2458 NonTypeTemplateParmDecl *NewNTTP
2459 = cast<NonTypeTemplateParmDecl>(*NewParm);
2460 if (Context.getCanonicalType(OldNTTP->getType()) !=
2461 Context.getCanonicalType(NewNTTP->getType())) {
2462 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002463 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2464 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002465 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002466 diag::err_template_arg_template_params_mismatch);
2467 NextDiag = diag::note_template_nontype_parm_different_type;
2468 }
2469 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002470 << NewNTTP->getType()
2471 << IsTemplateTemplateParm;
Mike Stump1eb44332009-09-09 15:08:12 +00002472 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002473 diag::note_template_nontype_parm_prev_declaration)
2474 << OldNTTP->getType();
2475 }
2476 return false;
2477 }
2478 } else {
2479 // The template parameter lists of template template
2480 // parameters must agree.
2481 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump1eb44332009-09-09 15:08:12 +00002482 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002483 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002484 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002485 = cast<TemplateTemplateParmDecl>(*OldParm);
2486 TemplateTemplateParmDecl *NewTTP
2487 = cast<TemplateTemplateParmDecl>(*NewParm);
2488 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2489 OldTTP->getTemplateParameters(),
2490 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002491 /*IsTemplateTemplateParm=*/true,
2492 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002493 return false;
2494 }
2495 }
2496
2497 return true;
2498}
2499
2500/// \brief Check whether a template can be declared within this scope.
2501///
2502/// If the template declaration is valid in this scope, returns
2503/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002504bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002505Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002506 // Find the nearest enclosing declaration scope.
2507 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2508 (S->getFlags() & Scope::TemplateParamScope) != 0)
2509 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Douglas Gregorddc29e12009-02-06 22:42:48 +00002511 // C++ [temp]p2:
2512 // A template-declaration can appear only as a namespace scope or
2513 // class scope declaration.
2514 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002515 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2516 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002517 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002518 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Eli Friedman1503f772009-07-31 01:43:05 +00002520 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002521 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002522
2523 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2524 return false;
2525
Mike Stump1eb44332009-09-09 15:08:12 +00002526 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002527 diag::err_template_outside_namespace_or_class_scope)
2528 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002529}
Douglas Gregorcc636682009-02-17 23:15:12 +00002530
Douglas Gregord5cb8762009-10-07 00:13:32 +00002531/// \brief Determine what kind of template specialization the given declaration
2532/// is.
2533static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2534 if (!D)
2535 return TSK_Undeclared;
2536
Douglas Gregorf6b11852009-10-08 15:14:33 +00002537 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2538 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002539 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2540 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002541 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2542 return Var->getTemplateSpecializationKind();
2543
Douglas Gregord5cb8762009-10-07 00:13:32 +00002544 return TSK_Undeclared;
2545}
2546
Douglas Gregor9302da62009-10-14 23:50:59 +00002547/// \brief Check whether a specialization is well-formed in the current
2548/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002549///
Douglas Gregor9302da62009-10-14 23:50:59 +00002550/// This routine determines whether a template specialization can be declared
2551/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002552///
2553/// \param S the semantic analysis object for which this check is being
2554/// performed.
2555///
2556/// \param Specialized the entity being specialized or instantiated, which
2557/// may be a kind of template (class template, function template, etc.) or
2558/// a member of a class template (member function, static data member,
2559/// member class).
2560///
2561/// \param PrevDecl the previous declaration of this entity, if any.
2562///
2563/// \param Loc the location of the explicit specialization or instantiation of
2564/// this entity.
2565///
2566/// \param IsPartialSpecialization whether this is a partial specialization of
2567/// a class template.
2568///
Douglas Gregord5cb8762009-10-07 00:13:32 +00002569/// \returns true if there was an error that we cannot recover from, false
2570/// otherwise.
2571static bool CheckTemplateSpecializationScope(Sema &S,
2572 NamedDecl *Specialized,
2573 NamedDecl *PrevDecl,
2574 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00002575 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002576 // Keep these "kind" numbers in sync with the %select statements in the
2577 // various diagnostics emitted by this routine.
2578 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002579 bool isTemplateSpecialization = false;
2580 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002581 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002582 isTemplateSpecialization = true;
2583 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002584 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002585 isTemplateSpecialization = true;
2586 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00002587 EntityKind = 3;
2588 else if (isa<VarDecl>(Specialized))
2589 EntityKind = 4;
2590 else if (isa<RecordDecl>(Specialized))
2591 EntityKind = 5;
2592 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00002593 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2594 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00002595 return true;
2596 }
2597
Douglas Gregor88b70942009-02-25 22:02:03 +00002598 // C++ [temp.expl.spec]p2:
2599 // An explicit specialization shall be declared in the namespace
2600 // of which the template is a member, or, for member templates, in
2601 // the namespace of which the enclosing class or enclosing class
2602 // template is a member. An explicit specialization of a member
2603 // function, member class or static data member of a class
2604 // template shall be declared in the namespace of which the class
2605 // template is a member. Such a declaration may also be a
2606 // definition. If the declaration is not a definition, the
2607 // specialization may be defined later in the name- space in which
2608 // the explicit specialization was declared, or in a namespace
2609 // that encloses the one in which the explicit specialization was
2610 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002611 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2612 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002613 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00002614 return true;
2615 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002616
Douglas Gregor0a407472009-10-07 17:30:37 +00002617 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2618 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00002619 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00002620 return true;
2621 }
2622
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002623 // C++ [temp.class.spec]p6:
2624 // A class template partial specialization may be declared or redeclared
2625 // in any namespace scope in which its definition may be defined (14.5.1
2626 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002627 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002628 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00002629 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002630 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00002631 if ((!PrevDecl ||
2632 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2633 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2634 // There is no prior declaration of this entity, so this
2635 // specialization must be in the same context as the template
2636 // itself.
2637 if (!DC->Equals(SpecializedContext)) {
2638 if (isa<TranslationUnitDecl>(SpecializedContext))
2639 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2640 << EntityKind << Specialized;
2641 else if (isa<NamespaceDecl>(SpecializedContext))
2642 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2643 << EntityKind << Specialized
2644 << cast<NamedDecl>(SpecializedContext);
2645
2646 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2647 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002648 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002649 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002650
2651 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00002652 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00002653 // Note that HandleDeclarator() performs this check for explicit
2654 // specializations of function templates, static data members, and member
2655 // functions, so we skip the check here for those kinds of entities.
2656 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00002657 // Should we refactor that check, so that it occurs later?
2658 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00002659 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2660 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00002661 if (isa<TranslationUnitDecl>(SpecializedContext))
2662 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2663 << EntityKind << Specialized;
2664 else if (isa<NamespaceDecl>(SpecializedContext))
2665 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2666 << EntityKind << Specialized
2667 << cast<NamedDecl>(SpecializedContext);
2668
Douglas Gregor9302da62009-10-14 23:50:59 +00002669 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00002670 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00002671
2672 // FIXME: check for specialization-after-instantiation errors and such.
2673
Douglas Gregor88b70942009-02-25 22:02:03 +00002674 return false;
2675}
Douglas Gregord5cb8762009-10-07 00:13:32 +00002676
Douglas Gregore94866f2009-06-12 21:21:02 +00002677/// \brief Check the non-type template arguments of a class template
2678/// partial specialization according to C++ [temp.class.spec]p9.
2679///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002680/// \param TemplateParams the template parameters of the primary class
2681/// template.
2682///
2683/// \param TemplateArg the template arguments of the class template
2684/// partial specialization.
2685///
2686/// \param MirrorsPrimaryTemplate will be set true if the class
2687/// template partial specialization arguments are identical to the
2688/// implicit template arguments of the primary template. This is not
2689/// necessarily an error (C++0x), and it is left to the caller to diagnose
2690/// this condition when it is an error.
2691///
Douglas Gregore94866f2009-06-12 21:21:02 +00002692/// \returns true if there was an error, false otherwise.
2693bool Sema::CheckClassTemplatePartialSpecializationArgs(
2694 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002695 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002696 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002697 // FIXME: the interface to this function will have to change to
2698 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002699 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Anders Carlssonfb250522009-06-23 01:26:57 +00002701 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Douglas Gregore94866f2009-06-12 21:21:02 +00002703 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002704 // Determine whether the template argument list of the partial
2705 // specialization is identical to the implicit argument list of
2706 // the primary template. The caller may need to diagnostic this as
2707 // an error per C++ [temp.class.spec]p9b3.
2708 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00002709 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002710 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2711 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002712 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002713 MirrorsPrimaryTemplate = false;
2714 } else if (TemplateTemplateParmDecl *TTP
2715 = dyn_cast<TemplateTemplateParmDecl>(
2716 TemplateParams->getParam(I))) {
2717 // FIXME: We should settle on either Declaration storage or
2718 // Expression storage for template template parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002719 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002720 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002721 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002722 if (!ArgDecl)
Mike Stump1eb44332009-09-09 15:08:12 +00002723 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002724 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002725 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2726
2727 if (!ArgDecl ||
2728 ArgDecl->getIndex() != TTP->getIndex() ||
2729 ArgDecl->getDepth() != TTP->getDepth())
2730 MirrorsPrimaryTemplate = false;
2731 }
2732 }
2733
Mike Stump1eb44332009-09-09 15:08:12 +00002734 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00002735 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002736 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002737 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002738 }
2739
Anders Carlsson6360be72009-06-13 18:20:51 +00002740 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002741 if (!ArgExpr) {
2742 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002743 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002744 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002745
2746 // C++ [temp.class.spec]p8:
2747 // A non-type argument is non-specialized if it is the name of a
2748 // non-type parameter. All other non-type arguments are
2749 // specialized.
2750 //
2751 // Below, we check the two conditions that only apply to
2752 // specialized non-type arguments, so skip any non-specialized
2753 // arguments.
2754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00002755 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002756 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002757 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002758 (Param->getIndex() != NTTP->getIndex() ||
2759 Param->getDepth() != NTTP->getDepth()))
2760 MirrorsPrimaryTemplate = false;
2761
Douglas Gregore94866f2009-06-12 21:21:02 +00002762 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002763 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002764
2765 // C++ [temp.class.spec]p9:
2766 // Within the argument list of a class template partial
2767 // specialization, the following restrictions apply:
2768 // -- A partially specialized non-type argument expression
2769 // shall not involve a template parameter of the partial
2770 // specialization except when the argument expression is a
2771 // simple identifier.
2772 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002773 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002774 diag::err_dependent_non_type_arg_in_partial_spec)
2775 << ArgExpr->getSourceRange();
2776 return true;
2777 }
2778
2779 // -- The type of a template parameter corresponding to a
2780 // specialized non-type argument shall not be dependent on a
2781 // parameter of the specialization.
2782 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002783 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00002784 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2785 << Param->getType()
2786 << ArgExpr->getSourceRange();
2787 Diag(Param->getLocation(), diag::note_template_param_here);
2788 return true;
2789 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002790
2791 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002792 }
2793
2794 return false;
2795}
2796
Douglas Gregor212e81c2009-03-25 00:13:59 +00002797Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002798Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2799 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00002800 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00002801 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002802 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002803 SourceLocation TemplateNameLoc,
2804 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002805 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002806 SourceLocation *TemplateArgLocs,
2807 SourceLocation RAngleLoc,
2808 AttributeList *Attr,
2809 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002810 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00002811
Douglas Gregorcc636682009-02-17 23:15:12 +00002812 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002813 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00002814 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002815 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002816
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002817 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002818 bool isPartialSpecialization = false;
2819
Douglas Gregor88b70942009-02-25 22:02:03 +00002820 // Check the validity of the template headers that introduce this
2821 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002822 // FIXME: We probably shouldn't complain about these headers for
2823 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00002824 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00002825 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2826 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002827 TemplateParameterLists.size(),
2828 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00002829 if (TemplateParams && TemplateParams->size() > 0) {
2830 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002831
Douglas Gregor05396e22009-08-25 17:23:04 +00002832 // C++ [temp.class.spec]p10:
2833 // The template parameter list of a specialization shall not
2834 // contain default template argument values.
2835 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2836 Decl *Param = TemplateParams->getParam(I);
2837 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2838 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002839 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002840 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00002841 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00002842 }
2843 } else if (NonTypeTemplateParmDecl *NTTP
2844 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2845 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002846 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002847 diag::err_default_arg_in_partial_spec)
2848 << DefArg->getSourceRange();
2849 NTTP->setDefaultArgument(0);
2850 DefArg->Destroy(Context);
2851 }
2852 } else {
2853 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2854 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002855 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002856 diag::err_default_arg_in_partial_spec)
2857 << DefArg->getSourceRange();
2858 TTP->setDefaultArgument(0);
2859 DefArg->Destroy(Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002860 }
2861 }
2862 }
Douglas Gregora735b202009-10-13 14:39:41 +00002863 } else if (TemplateParams) {
2864 if (TUK == TUK_Friend)
2865 Diag(KWLoc, diag::err_template_spec_friend)
2866 << CodeModificationHint::CreateRemoval(
2867 SourceRange(TemplateParams->getTemplateLoc(),
2868 TemplateParams->getRAngleLoc()))
2869 << SourceRange(LAngleLoc, RAngleLoc);
2870 else
2871 isExplicitSpecialization = true;
2872 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00002873 Diag(KWLoc, diag::err_template_spec_needs_header)
2874 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002875 isExplicitSpecialization = true;
2876 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002877
Douglas Gregorcc636682009-02-17 23:15:12 +00002878 // Check that the specialization uses the same tag kind as the
2879 // original template.
2880 TagDecl::TagKind Kind;
2881 switch (TagSpec) {
2882 default: assert(0 && "Unknown tag type!");
2883 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2884 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2885 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2886 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002887 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00002888 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002889 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002890 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00002891 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00002892 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00002893 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00002894 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00002895 diag::note_previous_use);
2896 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2897 }
2898
Douglas Gregor40808ce2009-03-09 23:48:35 +00002899 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00002900 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002901 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2902
Douglas Gregorcc636682009-02-17 23:15:12 +00002903 // Check that the template argument list is well-formed for this
2904 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002905 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2906 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00002907 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002908 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002909 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002910 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002911
Mike Stump1eb44332009-09-09 15:08:12 +00002912 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002913 ClassTemplate->getTemplateParameters()->size()) &&
2914 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002916 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002917 // corresponds to these arguments.
2918 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002919 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002920 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002921 if (CheckClassTemplatePartialSpecializationArgs(
2922 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002923 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002924 return true;
2925
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002926 if (MirrorsPrimaryTemplate) {
2927 // C++ [temp.class.spec]p9b3:
2928 //
Mike Stump1eb44332009-09-09 15:08:12 +00002929 // -- The argument list of the specialization shall not be identical
2930 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002931 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00002932 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00002933 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002934 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00002935 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002936 ClassTemplate->getIdentifier(),
2937 TemplateNameLoc,
2938 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00002939 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002940 AS_none);
2941 }
2942
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002943 // FIXME: Diagnose friend partial specializations
2944
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002945 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00002946 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002947 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002948 Converted.flatSize(),
2949 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002950 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002951 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002952 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002953 Converted.flatSize(),
2954 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002955 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002956 ClassTemplateSpecializationDecl *PrevDecl = 0;
2957
2958 if (isPartialSpecialization)
2959 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00002960 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002961 InsertPos);
2962 else
2963 PrevDecl
2964 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002965
2966 ClassTemplateSpecializationDecl *Specialization = 0;
2967
Douglas Gregor88b70942009-02-25 22:02:03 +00002968 // Check whether we can declare a class template specialization in
2969 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002970 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00002971 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00002972 TemplateNameLoc,
2973 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002974 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002975
Douglas Gregorb88e8882009-07-30 17:40:51 +00002976 // The canonical type
2977 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002978 if (PrevDecl &&
2979 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2980 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002981 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00002982 // arguments was referenced but not declared, or we're only
2983 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00002984 // declaration node as our own, updating its source location to
2985 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002986 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002987 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002988 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00002989 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002990 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002991 // Build the canonical type that describes the converted template
2992 // arguments of the class template partial specialization.
2993 CanonType = Context.getTemplateSpecializationType(
2994 TemplateName(ClassTemplate),
2995 Converted.getFlatArguments(),
2996 Converted.flatSize());
2997
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002998 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002999 ClassTemplatePartialSpecializationDecl *PrevPartial
3000 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003001 ClassTemplatePartialSpecializationDecl *Partial
3002 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003003 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003004 TemplateNameLoc,
3005 TemplateParams,
3006 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003007 Converted,
John McCall833ca992009-10-29 08:12:44 +00003008 TemplateArgs.data(),
3009 TemplateArgs.size(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003010 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003011
3012 if (PrevPartial) {
3013 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3014 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3015 } else {
3016 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3017 }
3018 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003019
Douglas Gregored9c0f92009-10-29 00:04:11 +00003020 // If we are providing an explicit specialization of a member class
3021 // template specialization, make a note of that.
3022 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3023 PrevPartial->setMemberSpecialization();
3024
Douglas Gregor031a5882009-06-13 00:26:55 +00003025 // Check that all of the template parameters of the class template
3026 // partial specialization are deducible from the template
3027 // arguments. If not, this class template partial specialization
3028 // will never be used.
3029 llvm::SmallVector<bool, 8> DeducibleParams;
3030 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003031 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003032 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003033 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003034 unsigned NumNonDeducible = 0;
3035 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3036 if (!DeducibleParams[I])
3037 ++NumNonDeducible;
3038
3039 if (NumNonDeducible) {
3040 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3041 << (NumNonDeducible > 1)
3042 << SourceRange(TemplateNameLoc, RAngleLoc);
3043 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3044 if (!DeducibleParams[I]) {
3045 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3046 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003047 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003048 diag::note_partial_spec_unused_parameter)
3049 << Param->getDeclName();
3050 else
Mike Stump1eb44332009-09-09 15:08:12 +00003051 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003052 diag::note_partial_spec_unused_parameter)
3053 << std::string("<anonymous>");
3054 }
3055 }
3056 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003057 } else {
3058 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003059 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003060 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003061 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003062 ClassTemplate->getDeclContext(),
3063 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003064 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003065 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003066 PrevDecl);
3067
3068 if (PrevDecl) {
3069 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3070 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3071 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003072 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003073 InsertPos);
3074 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003075
3076 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003077 }
3078
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003079 // C++ [temp.expl.spec]p6:
3080 // If a template, a member template or the member of a class template is
3081 // explicitly specialized then that specialization shall be declared
3082 // before the first use of that specialization that would cause an implicit
3083 // instantiation to take place, in every translation unit in which such a
3084 // use occurs; no diagnostic is required.
3085 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3086 SourceRange Range(TemplateNameLoc, RAngleLoc);
3087 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3088 << Context.getTypeDeclType(Specialization) << Range;
3089
3090 Diag(PrevDecl->getPointOfInstantiation(),
3091 diag::note_instantiation_required_here)
3092 << (PrevDecl->getTemplateSpecializationKind()
3093 != TSK_ImplicitInstantiation);
3094 return true;
3095 }
3096
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003097 // If this is not a friend, note that this is an explicit specialization.
3098 if (TUK != TUK_Friend)
3099 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003100
3101 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003102 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003103 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003104 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003105 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003106 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003107 Diag(Def->getLocation(), diag::note_previous_definition);
3108 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003109 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003110 }
3111 }
3112
Douglas Gregorfc705b82009-02-26 22:19:44 +00003113 // Build the fully-sugared type for this class template
3114 // specialization as the user wrote in the specialization
3115 // itself. This means that we'll pretty-print the type retrieved
3116 // from the specialization's declaration the way that the user
3117 // actually wrote the specialization, rather than formatting the
3118 // name based on the "canonical" representation used to store the
3119 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003120 QualType WrittenTy
3121 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00003122 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00003123 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00003124 CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003125 if (TUK != TUK_Friend)
3126 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003127 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003128
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003129 // C++ [temp.expl.spec]p9:
3130 // A template explicit specialization is in the scope of the
3131 // namespace in which the template was defined.
3132 //
3133 // We actually implement this paragraph where we set the semantic
3134 // context (in the creation of the ClassTemplateSpecializationDecl),
3135 // but we also maintain the lexical context where the actual
3136 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003137 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Douglas Gregorcc636682009-02-17 23:15:12 +00003139 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003140 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003141 Specialization->startDefinition();
3142
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003143 if (TUK == TUK_Friend) {
3144 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3145 TemplateNameLoc,
3146 WrittenTy.getTypePtr(),
3147 /*FIXME:*/KWLoc);
3148 Friend->setAccess(AS_public);
3149 CurContext->addDecl(Friend);
3150 } else {
3151 // Add the specialization into its lexical context, so that it can
3152 // be seen when iterating through the list of declarations in that
3153 // context. However, specializations are not found by name lookup.
3154 CurContext->addDecl(Specialization);
3155 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003156 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003157}
Douglas Gregord57959a2009-03-27 23:10:48 +00003158
Mike Stump1eb44332009-09-09 15:08:12 +00003159Sema::DeclPtrTy
3160Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003161 MultiTemplateParamsArg TemplateParameterLists,
3162 Declarator &D) {
3163 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3164}
3165
Mike Stump1eb44332009-09-09 15:08:12 +00003166Sema::DeclPtrTy
3167Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003168 MultiTemplateParamsArg TemplateParameterLists,
3169 Declarator &D) {
3170 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3171 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3172 "Not a function declarator!");
3173 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003174
Douglas Gregor52591bf2009-06-24 00:54:41 +00003175 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003176 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Douglas Gregor52591bf2009-06-24 00:54:41 +00003179 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003180
3181 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003182 move(TemplateParameterLists),
3183 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003184 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003185 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003186 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003187 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003188 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3189 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003190 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003191}
3192
Douglas Gregor454885e2009-10-15 15:54:05 +00003193/// \brief Diagnose cases where we have an explicit template specialization
3194/// before/after an explicit template instantiation, producing diagnostics
3195/// for those cases where they are required and determining whether the
3196/// new specialization/instantiation will have any effect.
3197///
Douglas Gregor454885e2009-10-15 15:54:05 +00003198/// \param NewLoc the location of the new explicit specialization or
3199/// instantiation.
3200///
3201/// \param NewTSK the kind of the new explicit specialization or instantiation.
3202///
3203/// \param PrevDecl the previous declaration of the entity.
3204///
3205/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3206///
3207/// \param PrevPointOfInstantiation if valid, indicates where the previus
3208/// declaration was instantiated (either implicitly or explicitly).
3209///
3210/// \param SuppressNew will be set to true to indicate that the new
3211/// specialization or instantiation has no effect and should be ignored.
3212///
3213/// \returns true if there was an error that should prevent the introduction of
3214/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003215bool
3216Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3217 TemplateSpecializationKind NewTSK,
3218 NamedDecl *PrevDecl,
3219 TemplateSpecializationKind PrevTSK,
3220 SourceLocation PrevPointOfInstantiation,
3221 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003222 SuppressNew = false;
3223
3224 switch (NewTSK) {
3225 case TSK_Undeclared:
3226 case TSK_ImplicitInstantiation:
3227 assert(false && "Don't check implicit instantiations here");
3228 return false;
3229
3230 case TSK_ExplicitSpecialization:
3231 switch (PrevTSK) {
3232 case TSK_Undeclared:
3233 case TSK_ExplicitSpecialization:
3234 // Okay, we're just specializing something that is either already
3235 // explicitly specialized or has merely been mentioned without any
3236 // instantiation.
3237 return false;
3238
3239 case TSK_ImplicitInstantiation:
3240 if (PrevPointOfInstantiation.isInvalid()) {
3241 // The declaration itself has not actually been instantiated, so it is
3242 // still okay to specialize it.
3243 return false;
3244 }
3245 // Fall through
3246
3247 case TSK_ExplicitInstantiationDeclaration:
3248 case TSK_ExplicitInstantiationDefinition:
3249 assert((PrevTSK == TSK_ImplicitInstantiation ||
3250 PrevPointOfInstantiation.isValid()) &&
3251 "Explicit instantiation without point of instantiation?");
3252
3253 // C++ [temp.expl.spec]p6:
3254 // If a template, a member template or the member of a class template
3255 // is explicitly specialized then that specialization shall be declared
3256 // before the first use of that specialization that would cause an
3257 // implicit instantiation to take place, in every translation unit in
3258 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003259 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003260 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003261 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003262 << (PrevTSK != TSK_ImplicitInstantiation);
3263
3264 return true;
3265 }
3266 break;
3267
3268 case TSK_ExplicitInstantiationDeclaration:
3269 switch (PrevTSK) {
3270 case TSK_ExplicitInstantiationDeclaration:
3271 // This explicit instantiation declaration is redundant (that's okay).
3272 SuppressNew = true;
3273 return false;
3274
3275 case TSK_Undeclared:
3276 case TSK_ImplicitInstantiation:
3277 // We're explicitly instantiating something that may have already been
3278 // implicitly instantiated; that's fine.
3279 return false;
3280
3281 case TSK_ExplicitSpecialization:
3282 // C++0x [temp.explicit]p4:
3283 // For a given set of template parameters, if an explicit instantiation
3284 // of a template appears after a declaration of an explicit
3285 // specialization for that template, the explicit instantiation has no
3286 // effect.
3287 return false;
3288
3289 case TSK_ExplicitInstantiationDefinition:
3290 // C++0x [temp.explicit]p10:
3291 // If an entity is the subject of both an explicit instantiation
3292 // declaration and an explicit instantiation definition in the same
3293 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003294 Diag(NewLoc,
3295 diag::err_explicit_instantiation_declaration_after_definition);
3296 Diag(PrevPointOfInstantiation,
3297 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003298 assert(PrevPointOfInstantiation.isValid() &&
3299 "Explicit instantiation without point of instantiation?");
3300 SuppressNew = true;
3301 return false;
3302 }
3303 break;
3304
3305 case TSK_ExplicitInstantiationDefinition:
3306 switch (PrevTSK) {
3307 case TSK_Undeclared:
3308 case TSK_ImplicitInstantiation:
3309 // We're explicitly instantiating something that may have already been
3310 // implicitly instantiated; that's fine.
3311 return false;
3312
3313 case TSK_ExplicitSpecialization:
3314 // C++ DR 259, C++0x [temp.explicit]p4:
3315 // For a given set of template parameters, if an explicit
3316 // instantiation of a template appears after a declaration of
3317 // an explicit specialization for that template, the explicit
3318 // instantiation has no effect.
3319 //
3320 // In C++98/03 mode, we only give an extension warning here, because it
3321 // is not not harmful to try to explicitly instantiate something that
3322 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003323 if (!getLangOptions().CPlusPlus0x) {
3324 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003325 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003326 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003327 diag::note_previous_template_specialization);
3328 }
3329 SuppressNew = true;
3330 return false;
3331
3332 case TSK_ExplicitInstantiationDeclaration:
3333 // We're explicity instantiating a definition for something for which we
3334 // were previously asked to suppress instantiations. That's fine.
3335 return false;
3336
3337 case TSK_ExplicitInstantiationDefinition:
3338 // C++0x [temp.spec]p5:
3339 // For a given template and a given set of template-arguments,
3340 // - an explicit instantiation definition shall appear at most once
3341 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003342 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003343 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003344 Diag(PrevPointOfInstantiation,
3345 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003346 SuppressNew = true;
3347 return false;
3348 }
3349 break;
3350 }
3351
3352 assert(false && "Missing specialization/instantiation case?");
3353
3354 return false;
3355}
3356
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003357/// \brief Perform semantic analysis for the given function template
3358/// specialization.
3359///
3360/// This routine performs all of the semantic analysis required for an
3361/// explicit function template specialization. On successful completion,
3362/// the function declaration \p FD will become a function template
3363/// specialization.
3364///
3365/// \param FD the function declaration, which will be updated to become a
3366/// function template specialization.
3367///
3368/// \param HasExplicitTemplateArgs whether any template arguments were
3369/// explicitly provided.
3370///
3371/// \param LAngleLoc the location of the left angle bracket ('<'), if
3372/// template arguments were explicitly provided.
3373///
3374/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3375/// if any.
3376///
3377/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3378/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3379/// true as in, e.g., \c void sort<>(char*, char*);
3380///
3381/// \param RAngleLoc the location of the right angle bracket ('>'), if
3382/// template arguments were explicitly provided.
3383///
3384/// \param PrevDecl the set of declarations that
3385bool
3386Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3387 bool HasExplicitTemplateArgs,
3388 SourceLocation LAngleLoc,
John McCall833ca992009-10-29 08:12:44 +00003389 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003390 unsigned NumExplicitTemplateArgs,
3391 SourceLocation RAngleLoc,
3392 NamedDecl *&PrevDecl) {
3393 // The set of function template specializations that could match this
3394 // explicit function template specialization.
3395 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3396 CandidateSet Candidates;
3397
3398 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3399 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3400 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3401 // Only consider templates found within the same semantic lookup scope as
3402 // FD.
3403 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3404 continue;
3405
3406 // C++ [temp.expl.spec]p11:
3407 // A trailing template-argument can be left unspecified in the
3408 // template-id naming an explicit function template specialization
3409 // provided it can be deduced from the function argument type.
3410 // Perform template argument deduction to determine whether we may be
3411 // specializing this template.
3412 // FIXME: It is somewhat wasteful to build
3413 TemplateDeductionInfo Info(Context);
3414 FunctionDecl *Specialization = 0;
3415 if (TemplateDeductionResult TDK
3416 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3417 ExplicitTemplateArgs,
3418 NumExplicitTemplateArgs,
3419 FD->getType(),
3420 Specialization,
3421 Info)) {
3422 // FIXME: Template argument deduction failed; record why it failed, so
3423 // that we can provide nifty diagnostics.
3424 (void)TDK;
3425 continue;
3426 }
3427
3428 // Record this candidate.
3429 Candidates.push_back(Specialization);
3430 }
3431 }
3432
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003433 // Find the most specialized function template.
3434 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3435 Candidates.size(),
3436 TPOC_Other,
3437 FD->getLocation(),
3438 PartialDiagnostic(diag::err_function_template_spec_no_match)
3439 << FD->getDeclName(),
3440 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3441 << FD->getDeclName() << HasExplicitTemplateArgs,
3442 PartialDiagnostic(diag::note_function_template_spec_matched));
3443 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003444 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003445
3446 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003447 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003448
Douglas Gregord5cb8762009-10-07 00:13:32 +00003449 // Check the scope of this explicit specialization.
3450 if (CheckTemplateSpecializationScope(*this,
3451 Specialization->getPrimaryTemplate(),
3452 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003453 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003454 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003455
3456 // C++ [temp.expl.spec]p6:
3457 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003458 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003459 // before the first use of that specialization that would cause an implicit
3460 // instantiation to take place, in every translation unit in which such a
3461 // use occurs; no diagnostic is required.
3462 FunctionTemplateSpecializationInfo *SpecInfo
3463 = Specialization->getTemplateSpecializationInfo();
3464 assert(SpecInfo && "Function template specialization info missing?");
3465 if (SpecInfo->getPointOfInstantiation().isValid()) {
3466 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3467 << FD;
3468 Diag(SpecInfo->getPointOfInstantiation(),
3469 diag::note_instantiation_required_here)
3470 << (Specialization->getTemplateSpecializationKind()
3471 != TSK_ImplicitInstantiation);
3472 return true;
3473 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003474
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003475 // Mark the prior declaration as an explicit specialization, so that later
3476 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003477 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003478
3479 // Turn the given function declaration into a function template
3480 // specialization, with the template arguments from the previous
3481 // specialization.
3482 FD->setFunctionTemplateSpecialization(Context,
3483 Specialization->getPrimaryTemplate(),
3484 new (Context) TemplateArgumentList(
3485 *Specialization->getTemplateSpecializationArgs()),
3486 /*InsertPos=*/0,
3487 TSK_ExplicitSpecialization);
3488
3489 // The "previous declaration" for this function template specialization is
3490 // the prior function template specialization.
3491 PrevDecl = Specialization;
3492 return false;
3493}
3494
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003495/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003496/// specialization.
3497///
3498/// This routine performs all of the semantic analysis required for an
3499/// explicit member function specialization. On successful completion,
3500/// the function declaration \p FD will become a member function
3501/// specialization.
3502///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003503/// \param Member the member declaration, which will be updated to become a
3504/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003505///
3506/// \param PrevDecl the set of declarations, one of which may be specialized
3507/// by this function specialization.
3508bool
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003509Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3510 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3511
3512 // Try to find the member we are instantiating.
3513 NamedDecl *Instantiation = 0;
3514 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003515 MemberSpecializationInfo *MSInfo = 0;
3516
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003517 if (!PrevDecl) {
3518 // Nowhere to look anyway.
3519 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3520 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3521 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3522 if (Context.hasSameType(Function->getType(), Method->getType())) {
3523 Instantiation = Method;
3524 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003525 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003526 break;
3527 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003528 }
3529 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003530 } else if (isa<VarDecl>(Member)) {
3531 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3532 if (PrevVar->isStaticDataMember()) {
3533 Instantiation = PrevDecl;
3534 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003535 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003536 }
3537 } else if (isa<RecordDecl>(Member)) {
3538 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3539 Instantiation = PrevDecl;
3540 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003541 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003542 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003543 }
3544
3545 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003546 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003547 // specializations are always out-of-line, the caller will complain about
3548 // this mismatch later.
3549 return false;
3550 }
3551
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003552 // Make sure that this is a specialization of a member.
3553 if (!InstantiatedFrom) {
3554 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3555 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003556 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3557 return true;
3558 }
3559
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003560 // C++ [temp.expl.spec]p6:
3561 // If a template, a member template or the member of a class template is
3562 // explicitly specialized then that spe- cialization shall be declared
3563 // before the first use of that specialization that would cause an implicit
3564 // instantiation to take place, in every translation unit in which such a
3565 // use occurs; no diagnostic is required.
3566 assert(MSInfo && "Member specialization info missing?");
3567 if (MSInfo->getPointOfInstantiation().isValid()) {
3568 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3569 << Member;
3570 Diag(MSInfo->getPointOfInstantiation(),
3571 diag::note_instantiation_required_here)
3572 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3573 return true;
3574 }
3575
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003576 // Check the scope of this explicit specialization.
3577 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003578 InstantiatedFrom,
3579 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003580 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003581 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00003582
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003583 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00003584 // the original declaration to note that it is an explicit specialization
3585 // (if it was previously an implicit instantiation). This latter step
3586 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003587 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003588 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3589 if (InstantiationFunction->getTemplateSpecializationKind() ==
3590 TSK_ImplicitInstantiation) {
3591 InstantiationFunction->setTemplateSpecializationKind(
3592 TSK_ExplicitSpecialization);
3593 InstantiationFunction->setLocation(Member->getLocation());
3594 }
3595
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003596 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3597 cast<CXXMethodDecl>(InstantiatedFrom),
3598 TSK_ExplicitSpecialization);
3599 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00003600 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3601 if (InstantiationVar->getTemplateSpecializationKind() ==
3602 TSK_ImplicitInstantiation) {
3603 InstantiationVar->setTemplateSpecializationKind(
3604 TSK_ExplicitSpecialization);
3605 InstantiationVar->setLocation(Member->getLocation());
3606 }
3607
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003608 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3609 cast<VarDecl>(InstantiatedFrom),
3610 TSK_ExplicitSpecialization);
3611 } else {
3612 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00003613 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3614 if (InstantiationClass->getTemplateSpecializationKind() ==
3615 TSK_ImplicitInstantiation) {
3616 InstantiationClass->setTemplateSpecializationKind(
3617 TSK_ExplicitSpecialization);
3618 InstantiationClass->setLocation(Member->getLocation());
3619 }
3620
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003621 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00003622 cast<CXXRecordDecl>(InstantiatedFrom),
3623 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003624 }
3625
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003626 // Save the caller the trouble of having to figure out which declaration
3627 // this specialization matches.
3628 PrevDecl = Instantiation;
3629 return false;
3630}
3631
Douglas Gregor558c0322009-10-14 23:41:34 +00003632/// \brief Check the scope of an explicit instantiation.
3633static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3634 SourceLocation InstLoc,
3635 bool WasQualifiedName) {
3636 DeclContext *ExpectedContext
3637 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3638 DeclContext *CurContext = S.CurContext->getLookupContext();
3639
3640 // C++0x [temp.explicit]p2:
3641 // An explicit instantiation shall appear in an enclosing namespace of its
3642 // template.
3643 //
3644 // This is DR275, which we do not retroactively apply to C++98/03.
3645 if (S.getLangOptions().CPlusPlus0x &&
3646 !CurContext->Encloses(ExpectedContext)) {
3647 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3648 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3649 << D << NS;
3650 else
3651 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3652 << D;
3653 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3654 return;
3655 }
3656
3657 // C++0x [temp.explicit]p2:
3658 // If the name declared in the explicit instantiation is an unqualified
3659 // name, the explicit instantiation shall appear in the namespace where
3660 // its template is declared or, if that namespace is inline (7.3.1), any
3661 // namespace from its enclosing namespace set.
3662 if (WasQualifiedName)
3663 return;
3664
3665 if (CurContext->Equals(ExpectedContext))
3666 return;
3667
3668 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3669 << D << ExpectedContext;
3670 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3671}
3672
3673/// \brief Determine whether the given scope specifier has a template-id in it.
3674static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3675 if (!SS.isSet())
3676 return false;
3677
3678 // C++0x [temp.explicit]p2:
3679 // If the explicit instantiation is for a member function, a member class
3680 // or a static data member of a class template specialization, the name of
3681 // the class template specialization in the qualified-id for the member
3682 // name shall be a simple-template-id.
3683 //
3684 // C++98 has the same restriction, just worded differently.
3685 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3686 NNS; NNS = NNS->getPrefix())
3687 if (Type *T = NNS->getAsType())
3688 if (isa<TemplateSpecializationType>(T))
3689 return true;
3690
3691 return false;
3692}
3693
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003694// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00003695// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003696Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003697Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003698 SourceLocation ExternLoc,
3699 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003700 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003701 SourceLocation KWLoc,
3702 const CXXScopeSpec &SS,
3703 TemplateTy TemplateD,
3704 SourceLocation TemplateNameLoc,
3705 SourceLocation LAngleLoc,
3706 ASTTemplateArgsPtr TemplateArgsIn,
3707 SourceLocation *TemplateArgLocs,
3708 SourceLocation RAngleLoc,
3709 AttributeList *Attr) {
3710 // Find the class template we're specializing
3711 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003712 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003713 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3714
3715 // Check that the specialization uses the same tag kind as the
3716 // original template.
3717 TagDecl::TagKind Kind;
3718 switch (TagSpec) {
3719 default: assert(0 && "Unknown tag type!");
3720 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3721 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3722 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3723 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003724 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003725 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003726 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003727 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003728 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003729 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003730 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003731 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003732 diag::note_previous_use);
3733 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3734 }
3735
Douglas Gregor558c0322009-10-14 23:41:34 +00003736 // C++0x [temp.explicit]p2:
3737 // There are two forms of explicit instantiation: an explicit instantiation
3738 // definition and an explicit instantiation declaration. An explicit
3739 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00003740 TemplateSpecializationKind TSK
3741 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3742 : TSK_ExplicitInstantiationDeclaration;
3743
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003744 // Translate the parser's template argument list in our AST format.
John McCall833ca992009-10-29 08:12:44 +00003745 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003746 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3747
3748 // Check that the template argument list is well-formed for this
3749 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003750 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3751 TemplateArgs.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003752 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00003753 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00003754 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003755 return true;
3756
Mike Stump1eb44332009-09-09 15:08:12 +00003757 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003758 ClassTemplate->getTemplateParameters()->size()) &&
3759 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003760
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003761 // Find the class template specialization declaration that
3762 // corresponds to these arguments.
3763 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00003764 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003765 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003766 Converted.flatSize(),
3767 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003768 void *InsertPos = 0;
3769 ClassTemplateSpecializationDecl *PrevDecl
3770 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3771
Douglas Gregord5cb8762009-10-07 00:13:32 +00003772 // C++0x [temp.explicit]p2:
3773 // [...] An explicit instantiation shall appear in an enclosing
3774 // namespace of its template. [...]
3775 //
3776 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003777 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3778 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00003779
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003780 ClassTemplateSpecializationDecl *Specialization = 0;
3781
3782 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003783 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00003784 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003785 PrevDecl,
3786 PrevDecl->getSpecializationKind(),
3787 PrevDecl->getPointOfInstantiation(),
3788 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003789 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003790
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003791 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00003792 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003793
Douglas Gregor52604ab2009-09-11 21:19:12 +00003794 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3795 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3796 // Since the only prior class template specialization with these
3797 // arguments was referenced but not declared, reuse that
3798 // declaration node as our own, updating its source location to
3799 // reflect our new declaration.
3800 Specialization = PrevDecl;
3801 Specialization->setLocation(TemplateNameLoc);
3802 PrevDecl = 0;
3803 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003804 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00003805
3806 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003807 // Create a new class template specialization declaration node for
3808 // this explicit specialization.
3809 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003810 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003811 ClassTemplate->getDeclContext(),
3812 TemplateNameLoc,
3813 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00003814 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003815
Douglas Gregor52604ab2009-09-11 21:19:12 +00003816 if (PrevDecl) {
3817 // Remove the previous declaration from the folding set, since we want
3818 // to introduce a new declaration.
3819 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3820 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3821 }
3822
3823 // Insert the new specialization.
3824 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003825 }
3826
3827 // Build the fully-sugared type for this explicit instantiation as
3828 // the user wrote in the explicit instantiation itself. This means
3829 // that we'll pretty-print the type retrieved from the
3830 // specialization's declaration the way that the user actually wrote
3831 // the explicit instantiation, rather than formatting the name based
3832 // on the "canonical" representation used to store the template
3833 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003834 QualType WrittenTy
3835 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00003836 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003837 TemplateArgs.size(),
3838 Context.getTypeDeclType(Specialization));
3839 Specialization->setTypeAsWritten(WrittenTy);
3840 TemplateArgsIn.release();
3841
3842 // Add the explicit instantiation into its lexical context. However,
3843 // since explicit instantiations are never found by name lookup, we
3844 // just put it into the declaration context directly.
3845 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003846 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003847
3848 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003849 // A definition of a class template or class member template
3850 // shall be in scope at the point of the explicit instantiation of
3851 // the class template or class member template.
3852 //
3853 // This check comes when we actually try to perform the
3854 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003855 ClassTemplateSpecializationDecl *Def
3856 = cast_or_null<ClassTemplateSpecializationDecl>(
3857 Specialization->getDefinition(Context));
3858 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00003859 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00003860
3861 // Instantiate the members of this class template specialization.
3862 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3863 Specialization->getDefinition(Context));
3864 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003865 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00003866
3867 return DeclPtrTy::make(Specialization);
3868}
3869
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003870// Explicit instantiation of a member class of a class template.
3871Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00003872Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00003873 SourceLocation ExternLoc,
3874 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003875 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003876 SourceLocation KWLoc,
3877 const CXXScopeSpec &SS,
3878 IdentifierInfo *Name,
3879 SourceLocation NameLoc,
3880 AttributeList *Attr) {
3881
Douglas Gregor402abb52009-05-28 23:31:59 +00003882 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00003883 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00003884 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00003885 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00003886 MultiTemplateParamsArg(*this, 0, 0),
3887 Owned, IsDependent);
3888 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3889
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003890 if (!TagD)
3891 return true;
3892
3893 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3894 if (Tag->isEnum()) {
3895 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3896 << Context.getTypeDeclType(Tag);
3897 return true;
3898 }
3899
Douglas Gregord0c87372009-05-27 17:30:49 +00003900 if (Tag->isInvalidDecl())
3901 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00003902
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003903 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3904 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3905 if (!Pattern) {
3906 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3907 << Context.getTypeDeclType(Record);
3908 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3909 return true;
3910 }
3911
Douglas Gregor558c0322009-10-14 23:41:34 +00003912 // C++0x [temp.explicit]p2:
3913 // If the explicit instantiation is for a class or member class, the
3914 // elaborated-type-specifier in the declaration shall include a
3915 // simple-template-id.
3916 //
3917 // C++98 has the same restriction, just worded differently.
3918 if (!ScopeSpecifierHasTemplateId(SS))
3919 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
3920 << Record << SS.getRange();
3921
3922 // C++0x [temp.explicit]p2:
3923 // There are two forms of explicit instantiation: an explicit instantiation
3924 // definition and an explicit instantiation declaration. An explicit
3925 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00003926 TemplateSpecializationKind TSK
3927 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3928 : TSK_ExplicitInstantiationDeclaration;
3929
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003930 // C++0x [temp.explicit]p2:
3931 // [...] An explicit instantiation shall appear in an enclosing
3932 // namespace of its template. [...]
3933 //
3934 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00003935 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00003936
3937 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00003938 CXXRecordDecl *PrevDecl
3939 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
3940 if (!PrevDecl && Record->getDefinition(Context))
3941 PrevDecl = Record;
3942 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003943 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
3944 bool SuppressNew = false;
3945 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00003946 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00003947 PrevDecl,
3948 MSInfo->getTemplateSpecializationKind(),
3949 MSInfo->getPointOfInstantiation(),
3950 SuppressNew))
3951 return true;
3952 if (SuppressNew)
3953 return TagD;
3954 }
3955
Douglas Gregor89a5bea2009-10-15 22:53:21 +00003956 CXXRecordDecl *RecordDef
3957 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3958 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00003959 // C++ [temp.explicit]p3:
3960 // A definition of a member class of a class template shall be in scope
3961 // at the point of an explicit instantiation of the member class.
3962 CXXRecordDecl *Def
3963 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3964 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003965 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
3966 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00003967 Diag(Pattern->getLocation(), diag::note_forward_declaration)
3968 << Pattern;
3969 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00003970 } else {
3971 if (InstantiateClass(NameLoc, Record, Def,
3972 getTemplateInstantiationArgs(Record),
3973 TSK))
3974 return true;
3975
3976 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3977 if (!RecordDef)
3978 return true;
3979 }
3980 }
3981
3982 // Instantiate all of the members of the class.
3983 InstantiateClassMembers(NameLoc, RecordDef,
3984 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003985
Mike Stump390b4cc2009-05-16 07:39:55 +00003986 // FIXME: We don't have any representation for explicit instantiations of
3987 // member classes. Such a representation is not needed for compilation, but it
3988 // should be available for clients that want to see all of the declarations in
3989 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00003990 return TagD;
3991}
3992
Douglas Gregord5a423b2009-09-25 18:43:00 +00003993Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3994 SourceLocation ExternLoc,
3995 SourceLocation TemplateLoc,
3996 Declarator &D) {
3997 // Explicit instantiations always require a name.
3998 DeclarationName Name = GetNameForDeclarator(D);
3999 if (!Name) {
4000 if (!D.isInvalidType())
4001 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4002 diag::err_explicit_instantiation_requires_name)
4003 << D.getDeclSpec().getSourceRange()
4004 << D.getSourceRange();
4005
4006 return true;
4007 }
4008
4009 // The scope passed in may not be a decl scope. Zip up the scope tree until
4010 // we find one that is.
4011 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4012 (S->getFlags() & Scope::TemplateParamScope) != 0)
4013 S = S->getParent();
4014
4015 // Determine the type of the declaration.
4016 QualType R = GetTypeForDeclarator(D, S, 0);
4017 if (R.isNull())
4018 return true;
4019
4020 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4021 // Cannot explicitly instantiate a typedef.
4022 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4023 << Name;
4024 return true;
4025 }
4026
Douglas Gregor663b5a02009-10-14 20:14:33 +00004027 // C++0x [temp.explicit]p1:
4028 // [...] An explicit instantiation of a function template shall not use the
4029 // inline or constexpr specifiers.
4030 // Presumably, this also applies to member functions of class templates as
4031 // well.
4032 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4033 Diag(D.getDeclSpec().getInlineSpecLoc(),
4034 diag::err_explicit_instantiation_inline)
4035 << CodeModificationHint::CreateRemoval(
4036 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4037
4038 // FIXME: check for constexpr specifier.
4039
Douglas Gregor558c0322009-10-14 23:41:34 +00004040 // C++0x [temp.explicit]p2:
4041 // There are two forms of explicit instantiation: an explicit instantiation
4042 // definition and an explicit instantiation declaration. An explicit
4043 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004044 TemplateSpecializationKind TSK
4045 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4046 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004047
John McCallf36e02d2009-10-09 21:13:30 +00004048 LookupResult Previous;
4049 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
4050 Name, LookupOrdinaryName);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004051
4052 if (!R->isFunctionType()) {
4053 // C++ [temp.explicit]p1:
4054 // A [...] static data member of a class template can be explicitly
4055 // instantiated from the member definition associated with its class
4056 // template.
4057 if (Previous.isAmbiguous()) {
4058 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
4059 D.getSourceRange());
4060 }
4061
John McCallf36e02d2009-10-09 21:13:30 +00004062 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4063 Previous.getAsSingleDecl(Context));
Douglas Gregord5a423b2009-09-25 18:43:00 +00004064 if (!Prev || !Prev->isStaticDataMember()) {
4065 // We expect to see a data data member here.
4066 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4067 << Name;
4068 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4069 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004070 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004071 return true;
4072 }
4073
4074 if (!Prev->getInstantiatedFromStaticDataMember()) {
4075 // FIXME: Check for explicit specialization?
4076 Diag(D.getIdentifierLoc(),
4077 diag::err_explicit_instantiation_data_member_not_instantiated)
4078 << Prev;
4079 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4080 // FIXME: Can we provide a note showing where this was declared?
4081 return true;
4082 }
4083
Douglas Gregor558c0322009-10-14 23:41:34 +00004084 // C++0x [temp.explicit]p2:
4085 // If the explicit instantiation is for a member function, a member class
4086 // or a static data member of a class template specialization, the name of
4087 // the class template specialization in the qualified-id for the member
4088 // name shall be a simple-template-id.
4089 //
4090 // C++98 has the same restriction, just worded differently.
4091 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4092 Diag(D.getIdentifierLoc(),
4093 diag::err_explicit_instantiation_without_qualified_id)
4094 << Prev << D.getCXXScopeSpec().getRange();
4095
4096 // Check the scope of this explicit instantiation.
4097 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4098
Douglas Gregor454885e2009-10-15 15:54:05 +00004099 // Verify that it is okay to explicitly instantiate here.
4100 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4101 assert(MSInfo && "Missing static data member specialization info?");
4102 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004103 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004104 MSInfo->getTemplateSpecializationKind(),
4105 MSInfo->getPointOfInstantiation(),
4106 SuppressNew))
4107 return true;
4108 if (SuppressNew)
4109 return DeclPtrTy();
4110
Douglas Gregord5a423b2009-09-25 18:43:00 +00004111 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004112 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004113 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004114 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4115 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004116
4117 // FIXME: Create an ExplicitInstantiation node?
4118 return DeclPtrTy();
4119 }
4120
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004121 // If the declarator is a template-id, translate the parser's template
4122 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004123 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00004124 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004125 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4126 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregordb422df2009-09-25 21:45:23 +00004127 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4128 TemplateId->getTemplateArgs(),
4129 TemplateId->getTemplateArgIsType(),
4130 TemplateId->NumArgs);
4131 translateTemplateArguments(TemplateArgsPtr,
4132 TemplateId->getTemplateArgLocations(),
4133 TemplateArgs);
4134 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004135 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004136 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004137
Douglas Gregord5a423b2009-09-25 18:43:00 +00004138 // C++ [temp.explicit]p1:
4139 // A [...] function [...] can be explicitly instantiated from its template.
4140 // A member function [...] of a class template can be explicitly
4141 // instantiated from the member definition associated with its class
4142 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004143 llvm::SmallVector<FunctionDecl *, 8> Matches;
4144 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4145 P != PEnd; ++P) {
4146 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004147 if (!HasExplicitTemplateArgs) {
4148 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4149 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4150 Matches.clear();
4151 Matches.push_back(Method);
4152 break;
4153 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004154 }
4155 }
4156
4157 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4158 if (!FunTmpl)
4159 continue;
4160
4161 TemplateDeductionInfo Info(Context);
4162 FunctionDecl *Specialization = 0;
4163 if (TemplateDeductionResult TDK
Douglas Gregordb422df2009-09-25 21:45:23 +00004164 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4165 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004166 R, Specialization, Info)) {
4167 // FIXME: Keep track of almost-matches?
4168 (void)TDK;
4169 continue;
4170 }
4171
4172 Matches.push_back(Specialization);
4173 }
4174
4175 // Find the most specialized function template specialization.
4176 FunctionDecl *Specialization
4177 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4178 D.getIdentifierLoc(),
4179 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4180 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4181 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4182
4183 if (!Specialization)
4184 return true;
4185
Douglas Gregor0a897e32009-10-15 17:21:20 +00004186 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004187 Diag(D.getIdentifierLoc(),
4188 diag::err_explicit_instantiation_member_function_not_instantiated)
4189 << Specialization
4190 << (Specialization->getTemplateSpecializationKind() ==
4191 TSK_ExplicitSpecialization);
4192 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4193 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004194 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004195
Douglas Gregor0a897e32009-10-15 17:21:20 +00004196 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004197 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4198 PrevDecl = Specialization;
4199
Douglas Gregor0a897e32009-10-15 17:21:20 +00004200 if (PrevDecl) {
4201 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004202 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004203 PrevDecl,
4204 PrevDecl->getTemplateSpecializationKind(),
4205 PrevDecl->getPointOfInstantiation(),
4206 SuppressNew))
4207 return true;
4208
4209 // FIXME: We may still want to build some representation of this
4210 // explicit specialization.
4211 if (SuppressNew)
4212 return DeclPtrTy();
4213 }
4214
4215 if (TSK == TSK_ExplicitInstantiationDefinition)
4216 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4217 false, /*DefinitionRequired=*/true);
4218
4219 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4220
Douglas Gregor558c0322009-10-14 23:41:34 +00004221 // C++0x [temp.explicit]p2:
4222 // If the explicit instantiation is for a member function, a member class
4223 // or a static data member of a class template specialization, the name of
4224 // the class template specialization in the qualified-id for the member
4225 // name shall be a simple-template-id.
4226 //
4227 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004228 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004229 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004230 D.getCXXScopeSpec().isSet() &&
4231 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4232 Diag(D.getIdentifierLoc(),
4233 diag::err_explicit_instantiation_without_qualified_id)
4234 << Specialization << D.getCXXScopeSpec().getRange();
4235
4236 CheckExplicitInstantiationScope(*this,
4237 FunTmpl? (NamedDecl *)FunTmpl
4238 : Specialization->getInstantiatedFromMemberFunction(),
4239 D.getIdentifierLoc(),
4240 D.getCXXScopeSpec().isSet());
4241
Douglas Gregord5a423b2009-09-25 18:43:00 +00004242 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4243 return DeclPtrTy();
4244}
4245
Douglas Gregord57959a2009-03-27 23:10:48 +00004246Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004247Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4248 const CXXScopeSpec &SS, IdentifierInfo *Name,
4249 SourceLocation TagLoc, SourceLocation NameLoc) {
4250 // This has to hold, because SS is expected to be defined.
4251 assert(Name && "Expected a name in a dependent tag");
4252
4253 NestedNameSpecifier *NNS
4254 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4255 if (!NNS)
4256 return true;
4257
4258 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4259 if (T.isNull())
4260 return true;
4261
4262 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4263 QualType ElabType = Context.getElaboratedType(T, TagKind);
4264
4265 return ElabType.getAsOpaquePtr();
4266}
4267
4268Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004269Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4270 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004271 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004272 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4273 if (!NNS)
4274 return true;
4275
4276 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004277 if (T.isNull())
4278 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004279 return T.getAsOpaquePtr();
4280}
4281
Douglas Gregor17343172009-04-01 00:28:59 +00004282Sema::TypeResult
4283Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4284 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004285 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004286 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004287 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004288 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004289 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004290 assert(TemplateId && "Expected a template specialization type");
4291
Douglas Gregor6946baf2009-09-02 13:05:45 +00004292 if (computeDeclContext(SS, false)) {
4293 // If we can compute a declaration context, then the "typename"
4294 // keyword was superfluous. Just build a QualifiedNameType to keep
4295 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Douglas Gregor6946baf2009-09-02 13:05:45 +00004297 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4298 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4299 }
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Douglas Gregor6946baf2009-09-02 13:05:45 +00004301 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004302}
4303
Douglas Gregord57959a2009-03-27 23:10:48 +00004304/// \brief Build the type that describes a C++ typename specifier,
4305/// e.g., "typename T::type".
4306QualType
4307Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4308 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004309 CXXRecordDecl *CurrentInstantiation = 0;
4310 if (NNS->isDependent()) {
4311 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004312
Douglas Gregor42af25f2009-05-11 19:58:34 +00004313 // If the nested-name-specifier does not refer to the current
4314 // instantiation, then build a typename type.
4315 if (!CurrentInstantiation)
4316 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004317
Douglas Gregorde18d122009-09-02 13:12:51 +00004318 // The nested-name-specifier refers to the current instantiation, so the
4319 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004320 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004321 // extraneous "typename" keywords, and we retroactively apply this DR to
4322 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004323 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004324
Douglas Gregor42af25f2009-05-11 19:58:34 +00004325 DeclContext *Ctx = 0;
4326
4327 if (CurrentInstantiation)
4328 Ctx = CurrentInstantiation;
4329 else {
4330 CXXScopeSpec SS;
4331 SS.setScopeRep(NNS);
4332 SS.setRange(Range);
4333 if (RequireCompleteDeclContext(SS))
4334 return QualType();
4335
4336 Ctx = computeDeclContext(SS);
4337 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004338 assert(Ctx && "No declaration context?");
4339
4340 DeclarationName Name(&II);
John McCallf36e02d2009-10-09 21:13:30 +00004341 LookupResult Result;
4342 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregord57959a2009-03-27 23:10:48 +00004343 unsigned DiagID = 0;
4344 Decl *Referenced = 0;
4345 switch (Result.getKind()) {
4346 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004347 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004348 break;
4349
4350 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004351 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004352 // We found a type. Build a QualifiedNameType, since the
4353 // typename-specifier was just sugar. FIXME: Tell
4354 // QualifiedNameType that it has a "typename" prefix.
4355 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4356 }
4357
4358 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004359 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004360 break;
4361
4362 case LookupResult::FoundOverloaded:
4363 DiagID = diag::err_typename_nested_not_type;
4364 Referenced = *Result.begin();
4365 break;
4366
John McCall6e247262009-10-10 05:48:19 +00004367 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004368 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4369 return QualType();
4370 }
4371
4372 // If we get here, it's because name lookup did not find a
4373 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004374 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004375 if (Referenced)
4376 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4377 << Name;
4378 return QualType();
4379}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004380
4381namespace {
4382 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump1eb44332009-09-09 15:08:12 +00004383 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4384 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004385 SourceLocation Loc;
4386 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Douglas Gregor4a959d82009-08-06 16:20:37 +00004388 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004389 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004390 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004391 DeclarationName Entity)
4392 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004393 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004394
4395 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004396 /// transformed.
4397 ///
4398 /// For the purposes of type reconstruction, a type has already been
4399 /// transformed if it is NULL or if it is not dependent.
4400 bool AlreadyTransformed(QualType T) {
4401 return T.isNull() || !T->isDependentType();
4402 }
Mike Stump1eb44332009-09-09 15:08:12 +00004403
4404 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004405 /// rebuilt.
4406 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Douglas Gregor4a959d82009-08-06 16:20:37 +00004408 /// \brief Returns the name of the entity whose type is being rebuilt.
4409 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004411 /// \brief Sets the "base" location and entity when that
4412 /// information is known based on another transformation.
4413 void setBase(SourceLocation Loc, DeclarationName Entity) {
4414 this->Loc = Loc;
4415 this->Entity = Entity;
4416 }
4417
Douglas Gregor4a959d82009-08-06 16:20:37 +00004418 /// \brief Transforms an expression by returning the expression itself
4419 /// (an identity function).
4420 ///
4421 /// FIXME: This is completely unsafe; we will need to actually clone the
4422 /// expressions.
4423 Sema::OwningExprResult TransformExpr(Expr *E) {
4424 return getSema().Owned(E);
4425 }
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Douglas Gregor4a959d82009-08-06 16:20:37 +00004427 /// \brief Transforms a typename type by determining whether the type now
4428 /// refers to a member of the current instantiation, and then
4429 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004430 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004431 };
4432}
4433
Mike Stump1eb44332009-09-09 15:08:12 +00004434QualType
John McCalla2becad2009-10-21 00:40:46 +00004435CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4436 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004437 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004438
Douglas Gregor4a959d82009-08-06 16:20:37 +00004439 NestedNameSpecifier *NNS
4440 = TransformNestedNameSpecifier(T->getQualifier(),
4441 /*FIXME:*/SourceRange(getBaseLocation()));
4442 if (!NNS)
4443 return QualType();
4444
4445 // If the nested-name-specifier did not change, and we cannot compute the
4446 // context corresponding to the nested-name-specifier, then this
4447 // typename type will not change; exit early.
4448 CXXScopeSpec SS;
4449 SS.setRange(SourceRange(getBaseLocation()));
4450 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004451
4452 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004453 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004454 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004455
4456 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004457 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004458 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004459 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004460 = TransformType(QualType(TemplateId, 0));
4461 if (NewTemplateId.isNull())
4462 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Douglas Gregor4a959d82009-08-06 16:20:37 +00004464 if (NNS == T->getQualifier() &&
4465 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004466 Result = QualType(T, 0);
4467 else
4468 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4469 } else
4470 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4471 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004472
John McCall833ca992009-10-29 08:12:44 +00004473 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4474 NewTL.setNameLoc(TL.getNameLoc());
4475 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004476}
4477
4478/// \brief Rebuilds a type within the context of the current instantiation.
4479///
Mike Stump1eb44332009-09-09 15:08:12 +00004480/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004481/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004482/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004483/// partial specialization thereof). This routine will rebuild that type now
4484/// that we have entered the declarator's scope, which may produce different
4485/// canonical types, e.g.,
4486///
4487/// \code
4488/// template<typename T>
4489/// struct X {
4490/// typedef T* pointer;
4491/// pointer data();
4492/// };
4493///
4494/// template<typename T>
4495/// typename X<T>::pointer X<T>::data() { ... }
4496/// \endcode
4497///
4498/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4499/// since we do not know that we can look into X<T> when we parsed the type.
4500/// This function will rebuild the type, performing the lookup of "pointer"
4501/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4502/// as the canonical type of T*, allowing the return types of the out-of-line
4503/// definition and the declaration to match.
4504QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4505 DeclarationName Name) {
4506 if (T.isNull() || !T->isDependentType())
4507 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Douglas Gregor4a959d82009-08-06 16:20:37 +00004509 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4510 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004511}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004512
4513/// \brief Produces a formatted string that describes the binding of
4514/// template parameters to template arguments.
4515std::string
4516Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4517 const TemplateArgumentList &Args) {
4518 std::string Result;
4519
4520 if (!Params || Params->size() == 0)
4521 return Result;
4522
4523 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4524 if (I == 0)
4525 Result += "[with ";
4526 else
4527 Result += ", ";
4528
4529 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4530 Result += Id->getName();
4531 } else {
4532 Result += '$';
4533 Result += llvm::utostr(I);
4534 }
4535
4536 Result += " = ";
4537
4538 switch (Args[I].getKind()) {
4539 case TemplateArgument::Null:
4540 Result += "<no value>";
4541 break;
4542
4543 case TemplateArgument::Type: {
4544 std::string TypeStr;
4545 Args[I].getAsType().getAsStringInternal(TypeStr,
4546 Context.PrintingPolicy);
4547 Result += TypeStr;
4548 break;
4549 }
4550
4551 case TemplateArgument::Declaration: {
4552 bool Unnamed = true;
4553 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4554 if (ND->getDeclName()) {
4555 Unnamed = false;
4556 Result += ND->getNameAsString();
4557 }
4558 }
4559
4560 if (Unnamed) {
4561 Result += "<anonymous>";
4562 }
4563 break;
4564 }
4565
4566 case TemplateArgument::Integral: {
4567 Result += Args[I].getAsIntegral()->toString(10);
4568 break;
4569 }
4570
4571 case TemplateArgument::Expression: {
4572 assert(false && "No expressions in deduced template arguments!");
4573 Result += "<expression>";
4574 break;
4575 }
4576
4577 case TemplateArgument::Pack:
4578 // FIXME: Format template argument packs
4579 Result += "<template argument pack>";
4580 break;
4581 }
4582 }
4583
4584 Result += ']';
4585 return Result;
4586}