blob: 7b29c9432a97114559bf6f863619c57832b06811 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregordd861062008-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 Gregor74296542009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor3f220e82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregord406b032009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor3f220e82009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregordd861062008-12-05 18:15:24 +000021
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregord6ea07d2009-07-29 16:56:42 +000068 } else if (OverloadedFunctionDecl *Ovl
69 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregor2fa10442008-12-18 19:37:40 +000070 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
71 FEnd = Ovl->function_end();
72 F != FEnd; ++F) {
Douglas Gregord6ea07d2009-07-29 16:56:42 +000073 if (FunctionTemplateDecl *FuncTmpl
74 = dyn_cast<FunctionTemplateDecl>(*F)) {
75 // We've found a function template. Determine whether there are
76 // any other function templates we need to bundle together in an
77 // OverloadedFunctionDecl
78 for (++F; F != FEnd; ++F) {
79 if (isa<FunctionTemplateDecl>(*F))
80 break;
81 }
82
83 if (F != FEnd) {
84 // Build an overloaded function decl containing only the
85 // function templates in Ovl.
86 OverloadedFunctionDecl *OvlTemplate
87 = OverloadedFunctionDecl::Create(Context,
88 Ovl->getDeclContext(),
89 Ovl->getDeclName());
90 OvlTemplate->addOverload(FuncTmpl);
91 OvlTemplate->addOverload(*F);
92 for (++F; F != FEnd; ++F) {
93 if (isa<FunctionTemplateDecl>(*F))
94 OvlTemplate->addOverload(*F);
95 }
Douglas Gregor6631cb42009-07-29 18:26:50 +000096
97 // Form the resulting TemplateName
98 if (SS && SS->isSet() && !SS->isInvalid()) {
99 NestedNameSpecifier *Qualifier
100 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
101 TemplateResult
102 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
103 false,
104 OvlTemplate));
105 } else {
106 TemplateResult = TemplateTy::make(TemplateName(OvlTemplate));
107 }
Douglas Gregord6ea07d2009-07-29 16:56:42 +0000108 return TNK_Function_template;
109 }
110
111 TNK = TNK_Function_template;
112 Template = FuncTmpl;
113 break;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000114 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000115 }
116 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000117
118 if (TNK != TNK_Non_template) {
119 if (SS && SS->isSet() && !SS->isInvalid()) {
120 NestedNameSpecifier *Qualifier
121 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
122 TemplateResult
123 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
124 false,
125 Template));
126 } else
127 TemplateResult = TemplateTy::make(TemplateName(Template));
128 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000129 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000130 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000131}
132
Douglas Gregordd861062008-12-05 18:15:24 +0000133/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
134/// that the template parameter 'PrevDecl' is being shadowed by a new
135/// declaration at location Loc. Returns true to indicate that this is
136/// an error, and false otherwise.
137bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000138 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000139
140 // Microsoft Visual C++ permits template parameters to be shadowed.
141 if (getLangOptions().Microsoft)
142 return false;
143
144 // C++ [temp.local]p4:
145 // A template-parameter shall not be redeclared within its
146 // scope (including nested scopes).
147 Diag(Loc, diag::err_template_param_shadow)
148 << cast<NamedDecl>(PrevDecl)->getDeclName();
149 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
150 return true;
151}
152
Douglas Gregored3a3982009-03-03 04:44:36 +0000153/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000154/// the parameter D to reference the templated declaration and return a pointer
155/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000156TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
157 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
158 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000159 return Temp;
160 }
161 return 0;
162}
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164/// ActOnTypeParameter - Called when a C++ template type parameter
165/// (e.g., "typename T") has been parsed. Typename specifies whether
166/// the keyword "typename" was used to declare the type parameter
167/// (otherwise, "class" was used), and KeyLoc is the location of the
168/// "class" or "typename" keyword. ParamName is the name of the
169/// parameter (NULL indicates an unnamed template parameter) and
170/// ParamName is the location of the parameter name (if any).
171/// If the type parameter has a default argument, it will be added
172/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000173Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
174 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000175 SourceLocation KeyLoc,
176 IdentifierInfo *ParamName,
177 SourceLocation ParamNameLoc,
178 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000179 assert(S->isTemplateParamScope() &&
180 "Template type parameter not in template parameter scope!");
181 bool Invalid = false;
182
183 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000184 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000185 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000186 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
187 PrevDecl);
188 }
189
Douglas Gregord406b032009-02-06 22:42:48 +0000190 SourceLocation Loc = ParamNameLoc;
191 if (!ParamName)
192 Loc = KeyLoc;
193
Douglas Gregordd861062008-12-05 18:15:24 +0000194 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000195 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000196 Depth, Position, ParamName, Typename,
197 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000198 if (Invalid)
199 Param->setInvalidDecl();
200
201 if (ParamName) {
202 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000203 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000204 IdResolver.AddDecl(Param);
205 }
206
Chris Lattner5261d0c2009-03-28 19:18:32 +0000207 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000208}
209
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000210/// ActOnTypeParameterDefault - Adds a default argument (the type
211/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000212void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000213 SourceLocation EqualLoc,
214 SourceLocation DefaultLoc,
215 TypeTy *DefaultT) {
216 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000217 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000218 // FIXME: Preserve type source info.
219 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000220
Anders Carlssona2333782009-06-12 22:30:13 +0000221 // C++0x [temp.param]p9:
222 // A default template-argument may be specified for any kind of
223 // template-parameter that is not a template parameter pack.
224 if (Parm->isParameterPack()) {
225 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000226 return;
227 }
228
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000229 // C++ [temp.param]p14:
230 // A template-parameter shall not be used in its own default argument.
231 // FIXME: Implement this check! Needs a recursive walk over the types.
232
233 // Check the template argument itself.
234 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
235 Parm->setInvalidDecl();
236 return;
237 }
238
239 Parm->setDefaultArgument(Default, DefaultLoc, false);
240}
241
Douglas Gregored3a3982009-03-03 04:44:36 +0000242/// \brief Check that the type of a non-type template parameter is
243/// well-formed.
244///
245/// \returns the (possibly-promoted) parameter type if valid;
246/// otherwise, produces a diagnostic and returns a NULL type.
247QualType
248Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
249 // C++ [temp.param]p4:
250 //
251 // A non-type template-parameter shall have one of the following
252 // (optionally cv-qualified) types:
253 //
254 // -- integral or enumeration type,
255 if (T->isIntegralType() || T->isEnumeralType() ||
256 // -- pointer to object or pointer to function,
257 (T->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000258 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
259 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregored3a3982009-03-03 04:44:36 +0000260 // -- reference to object or reference to function,
261 T->isReferenceType() ||
262 // -- pointer to member.
263 T->isMemberPointerType() ||
264 // If T is a dependent type, we can't do the check now, so we
265 // assume that it is well-formed.
266 T->isDependentType())
267 return T;
268 // C++ [temp.param]p8:
269 //
270 // A non-type template-parameter of type "array of T" or
271 // "function returning T" is adjusted to be of type "pointer to
272 // T" or "pointer to function returning T", respectively.
273 else if (T->isArrayType())
274 // FIXME: Keep the type prior to promotion?
275 return Context.getArrayDecayedType(T);
276 else if (T->isFunctionType())
277 // FIXME: Keep the type prior to promotion?
278 return Context.getPointerType(T);
279
280 Diag(Loc, diag::err_template_nontype_parm_bad_type)
281 << T;
282
283 return QualType();
284}
285
Douglas Gregordd861062008-12-05 18:15:24 +0000286/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
287/// template parameter (e.g., "int Size" in "template<int Size>
288/// class Array") has been parsed. S is the current scope and D is
289/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000290Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
291 unsigned Depth,
292 unsigned Position) {
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000293 DeclaratorInfo *DInfo = 0;
294 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregordd861062008-12-05 18:15:24 +0000295
Douglas Gregor279272e2009-02-04 19:02:06 +0000296 assert(S->isTemplateParamScope() &&
297 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000298 bool Invalid = false;
299
300 IdentifierInfo *ParamName = D.getIdentifier();
301 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000302 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000303 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000304 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000305 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000306 }
307
Douglas Gregored3a3982009-03-03 04:44:36 +0000308 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000309 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000310 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000311 Invalid = true;
312 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000313
Douglas Gregordd861062008-12-05 18:15:24 +0000314 NonTypeTemplateParmDecl *Param
315 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000316 Depth, Position, ParamName, T, DInfo);
Douglas Gregordd861062008-12-05 18:15:24 +0000317 if (Invalid)
318 Param->setInvalidDecl();
319
320 if (D.getIdentifier()) {
321 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000322 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000323 IdResolver.AddDecl(Param);
324 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000325 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000326}
Douglas Gregor52473432008-12-24 02:52:09 +0000327
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000328/// \brief Adds a default argument to the given non-type template
329/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000330void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000331 SourceLocation EqualLoc,
332 ExprArg DefaultE) {
333 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000334 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000335 Expr *Default = static_cast<Expr *>(DefaultE.get());
336
337 // C++ [temp.param]p14:
338 // A template-parameter shall not be used in its own default argument.
339 // FIXME: Implement this check! Needs a recursive walk over the types.
340
341 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000342 TemplateArgument Converted;
343 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
344 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000345 TemplateParm->setInvalidDecl();
346 return;
347 }
348
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000349 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000350}
351
Douglas Gregor279272e2009-02-04 19:02:06 +0000352
353/// ActOnTemplateTemplateParameter - Called when a C++ template template
354/// parameter (e.g. T in template <template <typename> class T> class array)
355/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000356Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
357 SourceLocation TmpLoc,
358 TemplateParamsTy *Params,
359 IdentifierInfo *Name,
360 SourceLocation NameLoc,
361 unsigned Depth,
362 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000363{
364 assert(S->isTemplateParamScope() &&
365 "Template template parameter not in template parameter scope!");
366
367 // Construct the parameter object.
368 TemplateTemplateParmDecl *Param =
369 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
370 Position, Name,
371 (TemplateParameterList*)Params);
372
373 // Make sure the parameter is valid.
374 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
375 // do anything yet. However, if the template parameter list or (eventual)
376 // default value is ever invalidated, that will propagate here.
377 bool Invalid = false;
378 if (Invalid) {
379 Param->setInvalidDecl();
380 }
381
382 // If the tt-param has a name, then link the identifier into the scope
383 // and lookup mechanisms.
384 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000385 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000386 IdResolver.AddDecl(Param);
387 }
388
Chris Lattner5261d0c2009-03-28 19:18:32 +0000389 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000390}
391
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000392/// \brief Adds a default argument to the given template template
393/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000394void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000395 SourceLocation EqualLoc,
396 ExprArg DefaultE) {
397 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000398 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000399
400 // Since a template-template parameter's default argument is an
401 // id-expression, it must be a DeclRefExpr.
402 DeclRefExpr *Default
403 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
404
405 // C++ [temp.param]p14:
406 // A template-parameter shall not be used in its own default argument.
407 // FIXME: Implement this check! Needs a recursive walk over the types.
408
409 // Check the well-formedness of the template argument.
410 if (!isa<TemplateDecl>(Default->getDecl())) {
411 Diag(Default->getSourceRange().getBegin(),
412 diag::err_template_arg_must_be_template)
413 << Default->getSourceRange();
414 TemplateParm->setInvalidDecl();
415 return;
416 }
417 if (CheckTemplateArgument(TemplateParm, Default)) {
418 TemplateParm->setInvalidDecl();
419 return;
420 }
421
422 DefaultE.release();
423 TemplateParm->setDefaultArgument(Default);
424}
425
Douglas Gregor52473432008-12-24 02:52:09 +0000426/// ActOnTemplateParameterList - Builds a TemplateParameterList that
427/// contains the template parameters in Params/NumParams.
428Sema::TemplateParamsTy *
429Sema::ActOnTemplateParameterList(unsigned Depth,
430 SourceLocation ExportLoc,
431 SourceLocation TemplateLoc,
432 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000433 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000434 SourceLocation RAngleLoc) {
435 if (ExportLoc.isValid())
436 Diag(ExportLoc, diag::note_template_export_unsupported);
437
Douglas Gregord406b032009-02-06 22:42:48 +0000438 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
439 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000440}
Douglas Gregor279272e2009-02-04 19:02:06 +0000441
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000442Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +0000443Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregord406b032009-02-06 22:42:48 +0000444 SourceLocation KWLoc, const CXXScopeSpec &SS,
445 IdentifierInfo *Name, SourceLocation NameLoc,
446 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000447 MultiTemplateParamsArg TemplateParameterLists,
448 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000449 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
John McCall069c23a2009-07-31 02:45:11 +0000450 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000451 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000452
453 // Check that we can declare a template here.
454 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000455 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000456
457 TagDecl::TagKind Kind;
458 switch (TagSpec) {
459 default: assert(0 && "Unknown tag type!");
460 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
461 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
462 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
463 }
464
465 // There is no such thing as an unnamed class template.
466 if (!Name) {
467 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000468 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000469 }
470
471 // Find any previous declaration with this name.
472 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
473 true);
474 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
475 NamedDecl *PrevDecl = 0;
476 if (Previous.begin() != Previous.end())
477 PrevDecl = *Previous.begin();
478
Douglas Gregor23521802009-06-17 23:37:01 +0000479 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
480 PrevDecl = 0;
481
Douglas Gregord406b032009-02-06 22:42:48 +0000482 DeclContext *SemanticContext = CurContext;
483 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000484 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000485
Mike Stumpe127ae32009-05-16 07:39:55 +0000486 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000487 }
488
489 // FIXME: member templates!
490 TemplateParameterList *TemplateParams
491 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
492
493 // If there is a previous declaration with the same name, check
494 // whether this is a valid redeclaration.
495 ClassTemplateDecl *PrevClassTemplate
496 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
497 if (PrevClassTemplate) {
498 // Ensure that the template parameter lists are compatible.
499 if (!TemplateParameterListsAreEqual(TemplateParams,
500 PrevClassTemplate->getTemplateParameters(),
501 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000502 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000503
504 // C++ [temp.class]p4:
505 // In a redeclaration, partial specialization, explicit
506 // specialization or explicit instantiation of a class template,
507 // the class-key shall agree in kind with the original class
508 // template declaration (7.1.5.3).
509 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000510 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000511 Diag(KWLoc, diag::err_use_with_wrong_tag)
512 << Name
513 << CodeModificationHint::CreateReplacement(KWLoc,
514 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000515 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000516 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000517 }
518
Douglas Gregord406b032009-02-06 22:42:48 +0000519 // Check for redefinition of this class template.
John McCall069c23a2009-07-31 02:45:11 +0000520 if (TUK == TUK_Definition) {
Douglas Gregord406b032009-02-06 22:42:48 +0000521 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
522 Diag(NameLoc, diag::err_redefinition) << Name;
523 Diag(Def->getLocation(), diag::note_previous_definition);
524 // FIXME: Would it make sense to try to "forget" the previous
525 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000526 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000527 }
528 }
529 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
530 // Maybe we will complain about the shadowed template parameter.
531 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
532 // Just pretend that we didn't see the previous declaration.
533 PrevDecl = 0;
534 } else if (PrevDecl) {
535 // C++ [temp]p5:
536 // A class template shall not have the same name as any other
537 // template, class, function, object, enumeration, enumerator,
538 // namespace, or type in the same scope (3.3), except as specified
539 // in (14.5.4).
540 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
541 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000542 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000543 }
544
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000545 // Check the template parameter list of this declaration, possibly
546 // merging in the template parameter list from the previous class
547 // template declaration.
548 if (CheckTemplateParameterList(TemplateParams,
549 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
550 Invalid = true;
551
Douglas Gregor9054f982009-05-10 22:57:19 +0000552 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000553 // declaration!
554
Douglas Gregor55216ac2009-03-26 00:10:35 +0000555 CXXRecordDecl *NewClass =
Douglas Gregor9060d0e2009-07-21 14:46:17 +0000556 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregord406b032009-02-06 22:42:48 +0000557 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000558 PrevClassTemplate->getTemplatedDecl() : 0,
559 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000560
561 ClassTemplateDecl *NewTemplate
562 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
563 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000564 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000565 NewClass->setDescribedClassTemplate(NewTemplate);
566
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000567 // Build the type for the class template declaration now.
568 QualType T =
569 Context.getTypeDeclType(NewClass,
570 PrevClassTemplate?
571 PrevClassTemplate->getTemplatedDecl() : 0);
572 assert(T->isDependentType() && "Class template type is not dependent?");
573 (void)T;
574
Anders Carlsson4ca43492009-03-26 01:24:28 +0000575 // Set the access specifier.
576 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
577
Douglas Gregord406b032009-02-06 22:42:48 +0000578 // Set the lexical context of these templates
579 NewClass->setLexicalDeclContext(CurContext);
580 NewTemplate->setLexicalDeclContext(CurContext);
581
John McCall069c23a2009-07-31 02:45:11 +0000582 if (TUK == TUK_Definition)
Douglas Gregord406b032009-02-06 22:42:48 +0000583 NewClass->startDefinition();
584
585 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000586 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000587
588 PushOnScopeChains(NewTemplate, S);
589
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000590 if (Invalid) {
591 NewTemplate->setInvalidDecl();
592 NewClass->setInvalidDecl();
593 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000594 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000595}
596
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000597/// \brief Checks the validity of a template parameter list, possibly
598/// considering the template parameter list from a previous
599/// declaration.
600///
601/// If an "old" template parameter list is provided, it must be
602/// equivalent (per TemplateParameterListsAreEqual) to the "new"
603/// template parameter list.
604///
605/// \param NewParams Template parameter list for a new template
606/// declaration. This template parameter list will be updated with any
607/// default arguments that are carried through from the previous
608/// template parameter list.
609///
610/// \param OldParams If provided, template parameter list from a
611/// previous declaration of the same template. Default template
612/// arguments will be merged from the old template parameter list to
613/// the new template parameter list.
614///
615/// \returns true if an error occurred, false otherwise.
616bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
617 TemplateParameterList *OldParams) {
618 bool Invalid = false;
619
620 // C++ [temp.param]p10:
621 // The set of default template-arguments available for use with a
622 // template declaration or definition is obtained by merging the
623 // default arguments from the definition (if in scope) and all
624 // declarations in scope in the same way default function
625 // arguments are (8.3.6).
626 bool SawDefaultArgument = false;
627 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000628
Anders Carlssonb1929502009-06-12 23:20:15 +0000629 bool SawParameterPack = false;
630 SourceLocation ParameterPackLoc;
631
Mike Stumpe0b7e032009-02-11 23:03:27 +0000632 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000633 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000634 if (OldParams)
635 OldParam = OldParams->begin();
636
637 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
638 NewParamEnd = NewParams->end();
639 NewParam != NewParamEnd; ++NewParam) {
640 // Variables used to diagnose redundant default arguments
641 bool RedundantDefaultArg = false;
642 SourceLocation OldDefaultLoc;
643 SourceLocation NewDefaultLoc;
644
645 // Variables used to diagnose missing default arguments
646 bool MissingDefaultArg = false;
647
Anders Carlssonb1929502009-06-12 23:20:15 +0000648 // C++0x [temp.param]p11:
649 // If a template parameter of a class template is a template parameter pack,
650 // it must be the last template parameter.
651 if (SawParameterPack) {
652 Diag(ParameterPackLoc,
653 diag::err_template_param_pack_must_be_last_template_parameter);
654 Invalid = true;
655 }
656
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000657 // Merge default arguments for template type parameters.
658 if (TemplateTypeParmDecl *NewTypeParm
659 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
660 TemplateTypeParmDecl *OldTypeParm
661 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
662
Anders Carlssonb1929502009-06-12 23:20:15 +0000663 if (NewTypeParm->isParameterPack()) {
664 assert(!NewTypeParm->hasDefaultArgument() &&
665 "Parameter packs can't have a default argument!");
666 SawParameterPack = true;
667 ParameterPackLoc = NewTypeParm->getLocation();
668 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000669 NewTypeParm->hasDefaultArgument()) {
670 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
671 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
672 SawDefaultArgument = true;
673 RedundantDefaultArg = true;
674 PreviousDefaultArgLoc = NewDefaultLoc;
675 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
676 // Merge the default argument from the old declaration to the
677 // new declaration.
678 SawDefaultArgument = true;
679 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
680 OldTypeParm->getDefaultArgumentLoc(),
681 true);
682 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
683 } else if (NewTypeParm->hasDefaultArgument()) {
684 SawDefaultArgument = true;
685 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
686 } else if (SawDefaultArgument)
687 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000688 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000689 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000690 // Merge default arguments for non-type template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000691 NonTypeTemplateParmDecl *OldNonTypeParm
692 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
693 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
694 NewNonTypeParm->hasDefaultArgument()) {
695 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
696 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
697 SawDefaultArgument = true;
698 RedundantDefaultArg = true;
699 PreviousDefaultArgLoc = NewDefaultLoc;
700 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
701 // Merge the default argument from the old declaration to the
702 // new declaration.
703 SawDefaultArgument = true;
704 // FIXME: We need to create a new kind of "default argument"
705 // expression that points to a previous template template
706 // parameter.
707 NewNonTypeParm->setDefaultArgument(
708 OldNonTypeParm->getDefaultArgument());
709 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
710 } else if (NewNonTypeParm->hasDefaultArgument()) {
711 SawDefaultArgument = true;
712 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
713 } else if (SawDefaultArgument)
714 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000715 } else {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000716 // Merge default arguments for template template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000717 TemplateTemplateParmDecl *NewTemplateParm
718 = cast<TemplateTemplateParmDecl>(*NewParam);
719 TemplateTemplateParmDecl *OldTemplateParm
720 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
721 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
722 NewTemplateParm->hasDefaultArgument()) {
723 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
724 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
725 SawDefaultArgument = true;
726 RedundantDefaultArg = true;
727 PreviousDefaultArgLoc = NewDefaultLoc;
728 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
729 // Merge the default argument from the old declaration to the
730 // new declaration.
731 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000732 // FIXME: We need to create a new kind of "default argument" expression
733 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000734 NewTemplateParm->setDefaultArgument(
735 OldTemplateParm->getDefaultArgument());
736 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
737 } else if (NewTemplateParm->hasDefaultArgument()) {
738 SawDefaultArgument = true;
739 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
740 } else if (SawDefaultArgument)
741 MissingDefaultArg = true;
742 }
743
744 if (RedundantDefaultArg) {
745 // C++ [temp.param]p12:
746 // A template-parameter shall not be given default arguments
747 // by two different declarations in the same scope.
748 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
749 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
750 Invalid = true;
751 } else if (MissingDefaultArg) {
752 // C++ [temp.param]p11:
753 // If a template-parameter has a default template-argument,
754 // all subsequent template-parameters shall have a default
755 // template-argument supplied.
756 Diag((*NewParam)->getLocation(),
757 diag::err_template_param_default_arg_missing);
758 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
759 Invalid = true;
760 }
761
762 // If we have an old template parameter list that we're merging
763 // in, move on to the next parameter.
764 if (OldParams)
765 ++OldParam;
766 }
767
768 return Invalid;
769}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000770
Douglas Gregorb462c322009-07-21 23:53:31 +0000771/// \brief Match the given template parameter lists to the given scope
772/// specifier, returning the template parameter list that applies to the
773/// name.
774///
775/// \param DeclStartLoc the start of the declaration that has a scope
776/// specifier or a template parameter list.
777///
778/// \param SS the scope specifier that will be matched to the given template
779/// parameter lists. This scope specifier precedes a qualified name that is
780/// being declared.
781///
782/// \param ParamLists the template parameter lists, from the outermost to the
783/// innermost template parameter lists.
784///
785/// \param NumParamLists the number of template parameter lists in ParamLists.
786///
787/// \returns the template parameter list, if any, that corresponds to the
788/// name that is preceded by the scope specifier @p SS. This template
789/// parameter list may be have template parameters (if we're declaring a
790/// template) or may have no template parameters (if we're declaring a
791/// template specialization), or may be NULL (if we were's declaring isn't
792/// itself a template).
793TemplateParameterList *
794Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
795 const CXXScopeSpec &SS,
796 TemplateParameterList **ParamLists,
797 unsigned NumParamLists) {
798 // FIXME: This routine will need a lot more testing once we have support for
799 // member templates.
800
801 // Find the template-ids that occur within the nested-name-specifier. These
802 // template-ids will match up with the template parameter lists.
803 llvm::SmallVector<const TemplateSpecializationType *, 4>
804 TemplateIdsInSpecifier;
805 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
806 NNS; NNS = NNS->getPrefix()) {
807 if (const TemplateSpecializationType *SpecType
808 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
809 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
810 if (!Template)
811 continue; // FIXME: should this be an error? probably...
812
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000813 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorb462c322009-07-21 23:53:31 +0000814 ClassTemplateSpecializationDecl *SpecDecl
815 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
816 // If the nested name specifier refers to an explicit specialization,
817 // we don't need a template<> header.
Douglas Gregor1930d202009-07-30 17:40:51 +0000818 // FIXME: revisit this approach once we cope with specialization
819 // properly.
Douglas Gregorb462c322009-07-21 23:53:31 +0000820 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
821 continue;
822 }
823
824 TemplateIdsInSpecifier.push_back(SpecType);
825 }
826 }
827
828 // Reverse the list of template-ids in the scope specifier, so that we can
829 // more easily match up the template-ids and the template parameter lists.
830 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
831
832 SourceLocation FirstTemplateLoc = DeclStartLoc;
833 if (NumParamLists)
834 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
835
836 // Match the template-ids found in the specifier to the template parameter
837 // lists.
838 unsigned Idx = 0;
839 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
840 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor1930d202009-07-30 17:40:51 +0000841 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
842 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorb462c322009-07-21 23:53:31 +0000843 if (Idx >= NumParamLists) {
844 // We have a template-id without a corresponding template parameter
845 // list.
846 if (DependentTemplateId) {
847 // FIXME: the location information here isn't great.
848 Diag(SS.getRange().getBegin(),
849 diag::err_template_spec_needs_template_parameters)
Douglas Gregor1930d202009-07-30 17:40:51 +0000850 << TemplateId
Douglas Gregorb462c322009-07-21 23:53:31 +0000851 << SS.getRange();
852 } else {
853 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
854 << SS.getRange()
855 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
856 "template<> ");
857 }
858 return 0;
859 }
860
861 // Check the template parameter list against its corresponding template-id.
Douglas Gregor1930d202009-07-30 17:40:51 +0000862 if (DependentTemplateId) {
863 TemplateDecl *Template
864 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
865
866 if (ClassTemplateDecl *ClassTemplate
867 = dyn_cast<ClassTemplateDecl>(Template)) {
868 TemplateParameterList *ExpectedTemplateParams = 0;
869 // Is this template-id naming the primary template?
870 if (Context.hasSameType(TemplateId,
871 ClassTemplate->getInjectedClassNameType(Context)))
872 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
873 // ... or a partial specialization?
874 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
875 = ClassTemplate->findPartialSpecialization(TemplateId))
876 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
877
878 if (ExpectedTemplateParams)
879 TemplateParameterListsAreEqual(ParamLists[Idx],
880 ExpectedTemplateParams,
881 true);
882 }
883 } else if (ParamLists[Idx]->size() > 0)
884 Diag(ParamLists[Idx]->getTemplateLoc(),
885 diag::err_template_param_list_matches_nontemplate)
886 << TemplateId
887 << ParamLists[Idx]->getSourceRange();
Douglas Gregorb462c322009-07-21 23:53:31 +0000888 }
889
890 // If there were at least as many template-ids as there were template
891 // parameter lists, then there are no template parameter lists remaining for
892 // the declaration itself.
893 if (Idx >= NumParamLists)
894 return 0;
895
896 // If there were too many template parameter lists, complain about that now.
897 if (Idx != NumParamLists - 1) {
898 while (Idx < NumParamLists - 1) {
899 Diag(ParamLists[Idx]->getTemplateLoc(),
900 diag::err_template_spec_extra_headers)
901 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
902 ParamLists[Idx]->getRAngleLoc());
903 ++Idx;
904 }
905 }
906
907 // Return the last template parameter list, which corresponds to the
908 // entity being declared.
909 return ParamLists[NumParamLists - 1];
910}
911
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000912/// \brief Translates template arguments as provided by the parser
913/// into template arguments used by semantic analysis.
914static void
915translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
916 SourceLocation *TemplateArgLocs,
917 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
918 TemplateArgs.reserve(TemplateArgsIn.size());
919
920 void **Args = TemplateArgsIn.getArgs();
921 bool *ArgIsType = TemplateArgsIn.getArgIsType();
922 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
923 TemplateArgs.push_back(
924 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000925 //FIXME: Preserve type source info.
926 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000927 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
928 }
929}
930
Douglas Gregordd13e842009-03-30 22:58:21 +0000931QualType Sema::CheckTemplateIdType(TemplateName Name,
932 SourceLocation TemplateLoc,
933 SourceLocation LAngleLoc,
934 const TemplateArgument *TemplateArgs,
935 unsigned NumTemplateArgs,
936 SourceLocation RAngleLoc) {
937 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000938 if (!Template) {
939 // The template name does not resolve to a template, so we just
940 // build a dependent template-id type.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000941 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor4262bc92009-07-28 23:00:59 +0000942 NumTemplateArgs);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000943 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000944
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000945 // Check that the template argument list is well-formed for this
946 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000947 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
948 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +0000949 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000950 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +0000951 false, Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000952 return QualType();
953
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000954 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000955 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000956 "Converted template argument list is too short!");
957
958 QualType CanonType;
959
Douglas Gregordd13e842009-03-30 22:58:21 +0000960 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000961 TemplateArgs,
962 NumTemplateArgs)) {
963 // This class template specialization is a dependent
964 // type. Therefore, its canonical type is another class template
965 // specialization type that contains all of the converted
966 // arguments in canonical form. This ensures that, e.g., A<T> and
967 // A<T, T> have identical types when A is declared as:
968 //
969 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000970 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
971 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000972 Converted.getFlatArguments(),
973 Converted.flatSize());
Douglas Gregor4262bc92009-07-28 23:00:59 +0000974
975 // FIXME: CanonType is not actually the canonical type, and unfortunately
976 // it is a TemplateTypeSpecializationType that we will never use again.
977 // In the future, we need to teach getTemplateSpecializationType to only
978 // build the canonical type and return that to us.
979 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +0000980 } else if (ClassTemplateDecl *ClassTemplate
981 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000982 // Find the class template specialization declaration that
983 // corresponds to these arguments.
984 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000985 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000986 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +0000987 Converted.flatSize(),
988 Context);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000989 void *InsertPos = 0;
990 ClassTemplateSpecializationDecl *Decl
991 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
992 if (!Decl) {
993 // This is the first time we have referenced this class template
994 // specialization. Create the canonical declaration and add it to
995 // the set of specializations.
996 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000997 ClassTemplate->getDeclContext(),
998 TemplateLoc,
999 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001000 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001001 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1002 Decl->setLexicalDeclContext(CurContext);
1003 }
1004
1005 CanonType = Context.getTypeDeclType(Decl);
1006 }
1007
1008 // Build the fully-sugared type for this class template
1009 // specialization, which refers back to the class template
1010 // specialization we created or found.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001011 //FIXME: Preserve type source info.
Douglas Gregordd13e842009-03-30 22:58:21 +00001012 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1013 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001014}
1015
Douglas Gregora08b6c72009-02-17 23:15:12 +00001016Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +00001017Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1018 SourceLocation LAngleLoc,
1019 ASTTemplateArgsPtr TemplateArgsIn,
1020 SourceLocation *TemplateArgLocs,
1021 SourceLocation RAngleLoc) {
1022 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001023
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001024 // Translate the parser's template argument list in our AST format.
1025 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1026 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001027
Douglas Gregordd13e842009-03-30 22:58:21 +00001028 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +00001029 TemplateArgs.data(),
1030 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +00001031 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001032 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +00001033
1034 if (Result.isNull())
1035 return true;
1036
Douglas Gregor6f37b582009-02-09 19:34:22 +00001037 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001038}
1039
Douglas Gregor28857752009-06-30 22:34:41 +00001040Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1041 SourceLocation TemplateNameLoc,
1042 SourceLocation LAngleLoc,
1043 const TemplateArgument *TemplateArgs,
1044 unsigned NumTemplateArgs,
1045 SourceLocation RAngleLoc) {
1046 // FIXME: Can we do any checking at this point? I guess we could check the
1047 // template arguments that we have against the template name, if the template
1048 // name refers to a single template. That's not a terribly common case,
1049 // though.
1050 return Owned(TemplateIdRefExpr::Create(Context,
1051 /*FIXME: New type?*/Context.OverloadTy,
1052 /*FIXME: Necessary?*/0,
1053 /*FIXME: Necessary?*/SourceRange(),
1054 Template, TemplateNameLoc, LAngleLoc,
1055 TemplateArgs,
1056 NumTemplateArgs, RAngleLoc));
1057}
1058
1059Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1060 SourceLocation TemplateNameLoc,
1061 SourceLocation LAngleLoc,
1062 ASTTemplateArgsPtr TemplateArgsIn,
1063 SourceLocation *TemplateArgLocs,
1064 SourceLocation RAngleLoc) {
1065 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1066
1067 // Translate the parser's template argument list in our AST format.
1068 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1069 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorf2fedc62009-07-22 20:55:49 +00001070 TemplateArgsIn.release();
Douglas Gregor28857752009-06-30 22:34:41 +00001071
1072 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1073 TemplateArgs.data(), TemplateArgs.size(),
1074 RAngleLoc);
1075}
1076
Douglas Gregoraabb8502009-03-31 00:43:58 +00001077/// \brief Form a dependent template name.
1078///
1079/// This action forms a dependent template name given the template
1080/// name and its (presumably dependent) scope specifier. For
1081/// example, given "MetaFun::template apply", the scope specifier \p
1082/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1083/// of the "template" keyword, and "apply" is the \p Name.
1084Sema::TemplateTy
1085Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1086 const IdentifierInfo &Name,
1087 SourceLocation NameLoc,
1088 const CXXScopeSpec &SS) {
1089 if (!SS.isSet() || SS.isInvalid())
1090 return TemplateTy();
1091
1092 NestedNameSpecifier *Qualifier
1093 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1094
1095 // FIXME: member of the current instantiation
1096
1097 if (!Qualifier->isDependent()) {
1098 // C++0x [temp.names]p5:
1099 // If a name prefixed by the keyword template is not the name of
1100 // a template, the program is ill-formed. [Note: the keyword
1101 // template may not be applied to non-template members of class
1102 // templates. -end note ] [ Note: as is the case with the
1103 // typename prefix, the template prefix is allowed in cases
1104 // where it is not strictly necessary; i.e., when the
1105 // nested-name-specifier or the expression on the left of the ->
1106 // or . is not dependent on a template-parameter, or the use
1107 // does not appear in the scope of a template. -end note]
1108 //
1109 // Note: C++03 was more strict here, because it banned the use of
1110 // the "template" keyword prior to a template-name that was not a
1111 // dependent name. C++ DR468 relaxed this requirement (the
1112 // "template" keyword is now permitted). We follow the C++0x
1113 // rules, even in C++03 mode, retroactively applying the DR.
1114 TemplateTy Template;
1115 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1116 if (TNK == TNK_Non_template) {
1117 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1118 << &Name;
1119 return TemplateTy();
1120 }
1121
1122 return Template;
1123 }
1124
1125 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1126}
1127
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001128bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1129 const TemplateArgument &Arg,
1130 TemplateArgumentListBuilder &Converted) {
1131 // Check template type parameter.
1132 if (Arg.getKind() != TemplateArgument::Type) {
1133 // C++ [temp.arg.type]p1:
1134 // A template-argument for a template-parameter which is a
1135 // type shall be a type-id.
1136
1137 // We have a template type parameter but the template argument
1138 // is not a type.
1139 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1140 Diag(Param->getLocation(), diag::note_template_param_here);
1141
1142 return true;
1143 }
1144
1145 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1146 return true;
1147
1148 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001149 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001150 TemplateArgument(Arg.getLocation(),
1151 Context.getCanonicalType(Arg.getAsType())));
1152 return false;
1153}
1154
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001155/// \brief Check that the given template argument list is well-formed
1156/// for specializing the given template.
1157bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1158 SourceLocation TemplateLoc,
1159 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001160 const TemplateArgument *TemplateArgs,
1161 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001162 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001163 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001164 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001165 TemplateParameterList *Params = Template->getTemplateParameters();
1166 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001167 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001168 bool Invalid = false;
1169
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001170 bool HasParameterPack =
1171 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1172
1173 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001174 (NumArgs < Params->getMinRequiredArguments() &&
1175 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001176 // FIXME: point at either the first arg beyond what we can handle,
1177 // or the '>', depending on whether we have too many or too few
1178 // arguments.
1179 SourceRange Range;
1180 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001181 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001182 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1183 << (NumArgs > NumParams)
1184 << (isa<ClassTemplateDecl>(Template)? 0 :
1185 isa<FunctionTemplateDecl>(Template)? 1 :
1186 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1187 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001188 Diag(Template->getLocation(), diag::note_template_decl_here)
1189 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001190 Invalid = true;
1191 }
1192
1193 // C++ [temp.arg]p1:
1194 // [...] The type and form of each template-argument specified in
1195 // a template-id shall match the type and form specified for the
1196 // corresponding parameter declared by the template in its
1197 // template-parameter-list.
1198 unsigned ArgIdx = 0;
1199 for (TemplateParameterList::iterator Param = Params->begin(),
1200 ParamEnd = Params->end();
1201 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001202 if (ArgIdx > NumArgs && PartialTemplateArgs)
1203 break;
1204
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001205 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001206 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001207 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001208 // Retrieve the default template argument from the template
1209 // parameter.
1210 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001211 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001212 // We have an empty argument pack.
1213 Converted.BeginPack();
1214 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001215 break;
1216 }
1217
Douglas Gregorad964b32009-02-17 01:05:43 +00001218 if (!TTP->hasDefaultArgument())
1219 break;
1220
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001221 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001222
1223 // If the argument type is dependent, instantiate it now based
1224 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001225 if (ArgType->isDependentType()) {
1226 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001227 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001228 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001229 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001230
Anders Carlsson0233eb62009-06-05 04:47:51 +00001231 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001232 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001233 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001234 TTP->getDefaultArgumentLoc(),
1235 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001236 }
Douglas Gregor74296542009-02-27 19:31:52 +00001237
1238 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001239 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001240
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001241 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001242 } else if (NonTypeTemplateParmDecl *NTTP
1243 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1244 if (!NTTP->hasDefaultArgument())
1245 break;
1246
Anders Carlsson0297caf2009-06-11 16:06:49 +00001247 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001248 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001249 Converted.flatSize(),
1250 SourceRange(TemplateLoc, RAngleLoc));
1251
1252 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001253 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001254
1255 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1256 TemplateArgs);
1257 if (E.isInvalid())
1258 return true;
1259
1260 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001261 } else {
1262 TemplateTemplateParmDecl *TempParm
1263 = cast<TemplateTemplateParmDecl>(*Param);
1264
1265 if (!TempParm->hasDefaultArgument())
1266 break;
1267
Douglas Gregored3a3982009-03-03 04:44:36 +00001268 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001269 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001270 }
1271 } else {
1272 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001273 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001274 }
1275
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001276
1277 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001278 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001279 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001280 // Check all the remaining arguments (if any).
1281 for (; ArgIdx < NumArgs; ++ArgIdx) {
1282 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1283 Invalid = true;
1284 }
1285
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001286 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001287 } else {
1288 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1289 Invalid = true;
1290 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001291 } else if (NonTypeTemplateParmDecl *NTTP
1292 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1293 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001294
1295 // Instantiate the type of the non-type template parameter with
1296 // the template arguments we've seen thus far.
1297 QualType NTTPType = NTTP->getType();
1298 if (NTTPType->isDependentType()) {
1299 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001300 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001301 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001302 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001303 SourceRange(TemplateLoc, RAngleLoc));
1304
Anders Carlsson0233eb62009-06-05 04:47:51 +00001305 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001306 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001307 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001308 NTTP->getLocation(),
1309 NTTP->getDeclName());
1310 // If that worked, check the non-type template parameter type
1311 // for validity.
1312 if (!NTTPType.isNull())
1313 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1314 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001315 if (NTTPType.isNull()) {
1316 Invalid = true;
1317 break;
1318 }
1319 }
1320
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001321 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001322 case TemplateArgument::Null:
1323 assert(false && "Should never see a NULL template argument here");
1324 break;
1325
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001326 case TemplateArgument::Expression: {
1327 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001328 TemplateArgument Result;
1329 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001330 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001331 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001332 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001333 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001334 }
1335
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001336 case TemplateArgument::Declaration:
1337 case TemplateArgument::Integral:
1338 // We've already checked this template argument, so just copy
1339 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001340 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001341 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001342
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001343 case TemplateArgument::Type:
1344 // We have a non-type template parameter but the template
1345 // argument is a type.
1346
1347 // C++ [temp.arg]p2:
1348 // In a template-argument, an ambiguity between a type-id and
1349 // an expression is resolved to a type-id, regardless of the
1350 // form of the corresponding template-parameter.
1351 //
1352 // We warn specifically about this case, since it can be rather
1353 // confusing for users.
1354 if (Arg.getAsType()->isFunctionType())
1355 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1356 << Arg.getAsType();
1357 else
1358 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1359 Diag((*Param)->getLocation(), diag::note_template_param_here);
1360 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001361 break;
1362
1363 case TemplateArgument::Pack:
1364 assert(0 && "FIXME: Implement!");
1365 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001366 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001367 } else {
1368 // Check template template parameters.
1369 TemplateTemplateParmDecl *TempParm
1370 = cast<TemplateTemplateParmDecl>(*Param);
1371
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001372 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001373 case TemplateArgument::Null:
1374 assert(false && "Should never see a NULL template argument here");
1375 break;
1376
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001377 case TemplateArgument::Expression: {
1378 Expr *ArgExpr = Arg.getAsExpr();
1379 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1380 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1381 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1382 Invalid = true;
1383
1384 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001385 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001386 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001387 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001388 continue;
1389 }
1390 }
1391 // fall through
1392
1393 case TemplateArgument::Type: {
1394 // We have a template template parameter but the template
1395 // argument does not refer to a template.
1396 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1397 Invalid = true;
1398 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001399 }
1400
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001401 case TemplateArgument::Declaration:
1402 // We've already checked this template argument, so just copy
1403 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001404 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001405 break;
1406
1407 case TemplateArgument::Integral:
1408 assert(false && "Integral argument with template template parameter");
1409 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001410
1411 case TemplateArgument::Pack:
1412 assert(0 && "FIXME: Implement!");
1413 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001414 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001415 }
1416 }
1417
1418 return Invalid;
1419}
1420
1421/// \brief Check a template argument against its corresponding
1422/// template type parameter.
1423///
1424/// This routine implements the semantics of C++ [temp.arg.type]. It
1425/// returns true if an error occurred, and false otherwise.
1426bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1427 QualType Arg, SourceLocation ArgLoc) {
1428 // C++ [temp.arg.type]p2:
1429 // A local type, a type with no linkage, an unnamed type or a type
1430 // compounded from any of these types shall not be used as a
1431 // template-argument for a template type-parameter.
1432 //
1433 // FIXME: Perform the recursive and no-linkage type checks.
1434 const TagType *Tag = 0;
1435 if (const EnumType *EnumT = Arg->getAsEnumType())
1436 Tag = EnumT;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001437 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001438 Tag = RecordT;
1439 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1440 return Diag(ArgLoc, diag::err_template_arg_local_type)
1441 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001442 else if (Tag && !Tag->getDecl()->getDeclName() &&
1443 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001444 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1445 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1446 return true;
1447 }
1448
1449 return false;
1450}
1451
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001452/// \brief Checks whether the given template argument is the address
1453/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001454bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1455 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001456 bool Invalid = false;
1457
1458 // See through any implicit casts we added to fix the type.
1459 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1460 Arg = Cast->getSubExpr();
1461
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001462 // C++0x allows nullptr, and there's no further checking to be done for that.
1463 if (Arg->getType()->isNullPtrType())
1464 return false;
1465
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001466 // C++ [temp.arg.nontype]p1:
1467 //
1468 // A template-argument for a non-type, non-template
1469 // template-parameter shall be one of: [...]
1470 //
1471 // -- the address of an object or function with external
1472 // linkage, including function templates and function
1473 // template-ids but excluding non-static class members,
1474 // expressed as & id-expression where the & is optional if
1475 // the name refers to a function or array, or if the
1476 // corresponding template-parameter is a reference; or
1477 DeclRefExpr *DRE = 0;
1478
1479 // Ignore (and complain about) any excess parentheses.
1480 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1481 if (!Invalid) {
1482 Diag(Arg->getSourceRange().getBegin(),
1483 diag::err_template_arg_extra_parens)
1484 << Arg->getSourceRange();
1485 Invalid = true;
1486 }
1487
1488 Arg = Parens->getSubExpr();
1489 }
1490
1491 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1492 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1493 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1494 } else
1495 DRE = dyn_cast<DeclRefExpr>(Arg);
1496
1497 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1498 return Diag(Arg->getSourceRange().getBegin(),
1499 diag::err_template_arg_not_object_or_func_form)
1500 << Arg->getSourceRange();
1501
1502 // Cannot refer to non-static data members
1503 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1504 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1505 << Field << Arg->getSourceRange();
1506
1507 // Cannot refer to non-static member functions
1508 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1509 if (!Method->isStatic())
1510 return Diag(Arg->getSourceRange().getBegin(),
1511 diag::err_template_arg_method)
1512 << Method << Arg->getSourceRange();
1513
1514 // Functions must have external linkage.
1515 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1516 if (Func->getStorageClass() == FunctionDecl::Static) {
1517 Diag(Arg->getSourceRange().getBegin(),
1518 diag::err_template_arg_function_not_extern)
1519 << Func << Arg->getSourceRange();
1520 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1521 << true;
1522 return true;
1523 }
1524
1525 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001526 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001527 return Invalid;
1528 }
1529
1530 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1531 if (!Var->hasGlobalStorage()) {
1532 Diag(Arg->getSourceRange().getBegin(),
1533 diag::err_template_arg_object_not_extern)
1534 << Var << Arg->getSourceRange();
1535 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1536 << true;
1537 return true;
1538 }
1539
1540 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001541 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001542 return Invalid;
1543 }
1544
1545 // We found something else, but we don't know specifically what it is.
1546 Diag(Arg->getSourceRange().getBegin(),
1547 diag::err_template_arg_not_object_or_func)
1548 << Arg->getSourceRange();
1549 Diag(DRE->getDecl()->getLocation(),
1550 diag::note_template_arg_refers_here);
1551 return true;
1552}
1553
1554/// \brief Checks whether the given template argument is a pointer to
1555/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001556bool
1557Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001558 bool Invalid = false;
1559
1560 // See through any implicit casts we added to fix the type.
1561 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1562 Arg = Cast->getSubExpr();
1563
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001564 // C++0x allows nullptr, and there's no further checking to be done for that.
1565 if (Arg->getType()->isNullPtrType())
1566 return false;
1567
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001568 // C++ [temp.arg.nontype]p1:
1569 //
1570 // A template-argument for a non-type, non-template
1571 // template-parameter shall be one of: [...]
1572 //
1573 // -- a pointer to member expressed as described in 5.3.1.
1574 QualifiedDeclRefExpr *DRE = 0;
1575
1576 // Ignore (and complain about) any excess parentheses.
1577 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1578 if (!Invalid) {
1579 Diag(Arg->getSourceRange().getBegin(),
1580 diag::err_template_arg_extra_parens)
1581 << Arg->getSourceRange();
1582 Invalid = true;
1583 }
1584
1585 Arg = Parens->getSubExpr();
1586 }
1587
1588 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1589 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1590 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1591
1592 if (!DRE)
1593 return Diag(Arg->getSourceRange().getBegin(),
1594 diag::err_template_arg_not_pointer_to_member_form)
1595 << Arg->getSourceRange();
1596
1597 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1598 assert((isa<FieldDecl>(DRE->getDecl()) ||
1599 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1600 "Only non-static member pointers can make it here");
1601
1602 // Okay: this is the address of a non-static member, and therefore
1603 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001604 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001605 return Invalid;
1606 }
1607
1608 // We found something else, but we don't know specifically what it is.
1609 Diag(Arg->getSourceRange().getBegin(),
1610 diag::err_template_arg_not_pointer_to_member_form)
1611 << Arg->getSourceRange();
1612 Diag(DRE->getDecl()->getLocation(),
1613 diag::note_template_arg_refers_here);
1614 return true;
1615}
1616
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001617/// \brief Check a template argument against its corresponding
1618/// non-type template parameter.
1619///
Douglas Gregored3a3982009-03-03 04:44:36 +00001620/// This routine implements the semantics of C++ [temp.arg.nontype].
1621/// It returns true if an error occurred, and false otherwise. \p
1622/// InstantiatedParamType is the type of the non-type template
1623/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001624///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001625/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001626bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001627 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001628 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001629 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1630
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001631 // If either the parameter has a dependent type or the argument is
1632 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001633 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001634 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1635 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001636 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001637 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001638 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001639
1640 // C++ [temp.arg.nontype]p5:
1641 // The following conversions are performed on each expression used
1642 // as a non-type template-argument. If a non-type
1643 // template-argument cannot be converted to the type of the
1644 // corresponding template-parameter then the program is
1645 // ill-formed.
1646 //
1647 // -- for a non-type template-parameter of integral or
1648 // enumeration type, integral promotions (4.5) and integral
1649 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001650 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001651 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001652 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001653 // C++ [temp.arg.nontype]p1:
1654 // A template-argument for a non-type, non-template
1655 // template-parameter shall be one of:
1656 //
1657 // -- an integral constant-expression of integral or enumeration
1658 // type; or
1659 // -- the name of a non-type template-parameter; or
1660 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001661 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001662 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1663 Diag(Arg->getSourceRange().getBegin(),
1664 diag::err_template_arg_not_integral_or_enumeral)
1665 << ArgType << Arg->getSourceRange();
1666 Diag(Param->getLocation(), diag::note_template_param_here);
1667 return true;
1668 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001669 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001670 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1671 << ArgType << Arg->getSourceRange();
1672 return true;
1673 }
1674
1675 // FIXME: We need some way to more easily get the unqualified form
1676 // of the types without going all the way to the
1677 // canonical type.
1678 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1679 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1680 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1681 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1682
1683 // Try to convert the argument to the parameter's type.
1684 if (ParamType == ArgType) {
1685 // Okay: no conversion necessary
1686 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1687 !ParamType->isEnumeralType()) {
1688 // This is an integral promotion or conversion.
1689 ImpCastExprToType(Arg, ParamType);
1690 } else {
1691 // We can't perform this conversion.
1692 Diag(Arg->getSourceRange().getBegin(),
1693 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001694 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001695 Diag(Param->getLocation(), diag::note_template_param_here);
1696 return true;
1697 }
1698
Douglas Gregorafc86942009-03-14 00:20:21 +00001699 QualType IntegerType = Context.getCanonicalType(ParamType);
1700 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001701 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001702
1703 if (!Arg->isValueDependent()) {
1704 // Check that an unsigned parameter does not receive a negative
1705 // value.
1706 if (IntegerType->isUnsignedIntegerType()
1707 && (Value.isSigned() && Value.isNegative())) {
1708 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1709 << Value.toString(10) << Param->getType()
1710 << Arg->getSourceRange();
1711 Diag(Param->getLocation(), diag::note_template_param_here);
1712 return true;
1713 }
1714
1715 // Check that we don't overflow the template parameter type.
1716 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1717 if (Value.getActiveBits() > AllowedBits) {
1718 Diag(Arg->getSourceRange().getBegin(),
1719 diag::err_template_arg_too_large)
1720 << Value.toString(10) << Param->getType()
1721 << Arg->getSourceRange();
1722 Diag(Param->getLocation(), diag::note_template_param_here);
1723 return true;
1724 }
1725
1726 if (Value.getBitWidth() != AllowedBits)
1727 Value.extOrTrunc(AllowedBits);
1728 Value.setIsSigned(IntegerType->isSignedIntegerType());
1729 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001730
Douglas Gregor8f378a92009-06-11 18:10:32 +00001731 // Add the value of this argument to the list of converted
1732 // arguments. We use the bitwidth and signedness of the template
1733 // parameter.
1734 if (Arg->isValueDependent()) {
1735 // The argument is value-dependent. Create a new
1736 // TemplateArgument with the converted expression.
1737 Converted = TemplateArgument(Arg);
1738 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001739 }
1740
Douglas Gregor8f378a92009-06-11 18:10:32 +00001741 Converted = TemplateArgument(StartLoc, Value,
1742 ParamType->isEnumeralType() ? ParamType
1743 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001744 return false;
1745 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001746
Douglas Gregor3f411962009-02-11 01:18:59 +00001747 // Handle pointer-to-function, reference-to-function, and
1748 // pointer-to-member-function all in (roughly) the same way.
1749 if (// -- For a non-type template-parameter of type pointer to
1750 // function, only the function-to-pointer conversion (4.3) is
1751 // applied. If the template-argument represents a set of
1752 // overloaded functions (or a pointer to such), the matching
1753 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001754 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001755 (ParamType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001756 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001757 // -- For a non-type template-parameter of type reference to
1758 // function, no conversions apply. If the template-argument
1759 // represents a set of overloaded functions, the matching
1760 // function is selected from the set (13.4).
1761 (ParamType->isReferenceType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001762 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001763 // -- For a non-type template-parameter of type pointer to
1764 // member function, no conversions apply. If the
1765 // template-argument represents a set of overloaded member
1766 // functions, the matching member function is selected from
1767 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001768 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001769 (ParamType->isMemberPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001770 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001771 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001772 if (Context.hasSameUnqualifiedType(ArgType,
1773 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001774 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001775 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1776 ParamType->isMemberPointerType())) {
1777 ArgType = ParamType;
1778 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001779 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001780 ArgType = Context.getPointerType(ArgType);
1781 ImpCastExprToType(Arg, ArgType);
1782 } else if (FunctionDecl *Fn
1783 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001784 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1785 return true;
1786
Douglas Gregor2eedd992009-02-11 00:19:33 +00001787 FixOverloadedFunctionReference(Arg, Fn);
1788 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001789 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001790 ArgType = Context.getPointerType(Arg->getType());
1791 ImpCastExprToType(Arg, ArgType);
1792 }
1793 }
1794
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001795 if (!Context.hasSameUnqualifiedType(ArgType,
1796 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001797 // We can't perform this conversion.
1798 Diag(Arg->getSourceRange().getBegin(),
1799 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001800 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001801 Diag(Param->getLocation(), diag::note_template_param_here);
1802 return true;
1803 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001804
Douglas Gregorad964b32009-02-17 01:05:43 +00001805 if (ParamType->isMemberPointerType()) {
1806 NamedDecl *Member = 0;
1807 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1808 return true;
1809
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001810 if (Member)
1811 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001812 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001813 return false;
1814 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001815
Douglas Gregorad964b32009-02-17 01:05:43 +00001816 NamedDecl *Entity = 0;
1817 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1818 return true;
1819
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001820 if (Entity)
1821 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001822 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001823 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001824 }
1825
Chris Lattner320dff22009-02-20 21:37:53 +00001826 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001827 // -- for a non-type template-parameter of type pointer to
1828 // object, qualification conversions (4.4) and the
1829 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001830 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001831 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001832 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001833
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001834 if (ArgType->isNullPtrType()) {
1835 ArgType = ParamType;
1836 ImpCastExprToType(Arg, ParamType);
1837 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001838 ArgType = Context.getArrayDecayedType(ArgType);
1839 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001840 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001841
Douglas Gregor3f411962009-02-11 01:18:59 +00001842 if (IsQualificationConversion(ArgType, ParamType)) {
1843 ArgType = ParamType;
1844 ImpCastExprToType(Arg, ParamType);
1845 }
1846
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001847 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001848 // We can't perform this conversion.
1849 Diag(Arg->getSourceRange().getBegin(),
1850 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001851 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001852 Diag(Param->getLocation(), diag::note_template_param_here);
1853 return true;
1854 }
1855
Douglas Gregorad964b32009-02-17 01:05:43 +00001856 NamedDecl *Entity = 0;
1857 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1858 return true;
1859
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001860 if (Entity)
1861 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001862 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001863 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001864 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001865
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001866 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001867 // -- For a non-type template-parameter of type reference to
1868 // object, no conversions apply. The type referred to by the
1869 // reference may be more cv-qualified than the (otherwise
1870 // identical) type of the template-argument. The
1871 // template-parameter is bound directly to the
1872 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001873 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001874 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001875
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001876 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001877 Diag(Arg->getSourceRange().getBegin(),
1878 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001879 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001880 << Arg->getSourceRange();
1881 Diag(Param->getLocation(), diag::note_template_param_here);
1882 return true;
1883 }
1884
1885 unsigned ParamQuals
1886 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1887 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1888
1889 if ((ParamQuals | ArgQuals) != ParamQuals) {
1890 Diag(Arg->getSourceRange().getBegin(),
1891 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001892 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001893 << Arg->getSourceRange();
1894 Diag(Param->getLocation(), diag::note_template_param_here);
1895 return true;
1896 }
1897
Douglas Gregorad964b32009-02-17 01:05:43 +00001898 NamedDecl *Entity = 0;
1899 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1900 return true;
1901
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001902 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001903 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001904 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001905 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001906
1907 // -- For a non-type template-parameter of type pointer to data
1908 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001909 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001910 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1911
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001912 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001913 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001914 } else if (ArgType->isNullPtrType()) {
1915 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001916 } else if (IsQualificationConversion(ArgType, ParamType)) {
1917 ImpCastExprToType(Arg, ParamType);
1918 } else {
1919 // We can't perform this conversion.
1920 Diag(Arg->getSourceRange().getBegin(),
1921 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001922 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001923 Diag(Param->getLocation(), diag::note_template_param_here);
1924 return true;
1925 }
1926
Douglas Gregorad964b32009-02-17 01:05:43 +00001927 NamedDecl *Member = 0;
1928 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1929 return true;
1930
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001931 if (Member)
1932 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001933 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001934 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001935}
1936
1937/// \brief Check a template argument against its corresponding
1938/// template template parameter.
1939///
1940/// This routine implements the semantics of C++ [temp.arg.template].
1941/// It returns true if an error occurred, and false otherwise.
1942bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1943 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001944 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1945 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1946
1947 // C++ [temp.arg.template]p1:
1948 // A template-argument for a template template-parameter shall be
1949 // the name of a class template, expressed as id-expression. Only
1950 // primary class templates are considered when matching the
1951 // template template argument with the corresponding parameter;
1952 // partial specializations are not considered even if their
1953 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001954 //
1955 // Note that we also allow template template parameters here, which
1956 // will happen when we are dealing with, e.g., class template
1957 // partial specializations.
1958 if (!isa<ClassTemplateDecl>(Template) &&
1959 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001960 assert(isa<FunctionTemplateDecl>(Template) &&
1961 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001962 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1963 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001964 << Template;
1965 }
1966
1967 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1968 Param->getTemplateParameters(),
1969 true, true,
1970 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001971}
1972
Douglas Gregord406b032009-02-06 22:42:48 +00001973/// \brief Determine whether the given template parameter lists are
1974/// equivalent.
1975///
1976/// \param New The new template parameter list, typically written in the
1977/// source code as part of a new template declaration.
1978///
1979/// \param Old The old template parameter list, typically found via
1980/// name lookup of the template declared with this template parameter
1981/// list.
1982///
1983/// \param Complain If true, this routine will produce a diagnostic if
1984/// the template parameter lists are not equivalent.
1985///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001986/// \param IsTemplateTemplateParm If true, this routine is being
1987/// called to compare the template parameter lists of a template
1988/// template parameter.
1989///
1990/// \param TemplateArgLoc If this source location is valid, then we
1991/// are actually checking the template parameter list of a template
1992/// argument (New) against the template parameter list of its
1993/// corresponding template template parameter (Old). We produce
1994/// slightly different diagnostics in this scenario.
1995///
Douglas Gregord406b032009-02-06 22:42:48 +00001996/// \returns True if the template parameter lists are equal, false
1997/// otherwise.
1998bool
1999Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2000 TemplateParameterList *Old,
2001 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002002 bool IsTemplateTemplateParm,
2003 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00002004 if (Old->size() != New->size()) {
2005 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002006 unsigned NextDiag = diag::err_template_param_list_different_arity;
2007 if (TemplateArgLoc.isValid()) {
2008 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2009 NextDiag = diag::note_template_param_list_different_arity;
2010 }
2011 Diag(New->getTemplateLoc(), NextDiag)
2012 << (New->size() > Old->size())
2013 << IsTemplateTemplateParm
2014 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00002015 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2016 << IsTemplateTemplateParm
2017 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2018 }
2019
2020 return false;
2021 }
2022
2023 for (TemplateParameterList::iterator OldParm = Old->begin(),
2024 OldParmEnd = Old->end(), NewParm = New->begin();
2025 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2026 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00002027 if (Complain) {
2028 unsigned NextDiag = diag::err_template_param_different_kind;
2029 if (TemplateArgLoc.isValid()) {
2030 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2031 NextDiag = diag::note_template_param_different_kind;
2032 }
2033 Diag((*NewParm)->getLocation(), NextDiag)
2034 << IsTemplateTemplateParm;
2035 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2036 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00002037 }
Douglas Gregord406b032009-02-06 22:42:48 +00002038 return false;
2039 }
2040
2041 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2042 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00002043 // know we're at the same index).
2044#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00002045 // FIXME: Enable this code in debug mode *after* we properly go through
2046 // and "instantiate" the template parameter lists of template template
2047 // parameters. It's only after this instantiation that (1) any dependent
2048 // types within the template parameter list of the template template
2049 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00002050 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00002051 QualType OldParmType
2052 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2053 QualType NewParmType
2054 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2055 assert(Context.getCanonicalType(OldParmType) ==
2056 Context.getCanonicalType(NewParmType) &&
2057 "type parameter mismatch?");
2058#endif
2059 } else if (NonTypeTemplateParmDecl *OldNTTP
2060 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2061 // The types of non-type template parameters must agree.
2062 NonTypeTemplateParmDecl *NewNTTP
2063 = cast<NonTypeTemplateParmDecl>(*NewParm);
2064 if (Context.getCanonicalType(OldNTTP->getType()) !=
2065 Context.getCanonicalType(NewNTTP->getType())) {
2066 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002067 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2068 if (TemplateArgLoc.isValid()) {
2069 Diag(TemplateArgLoc,
2070 diag::err_template_arg_template_params_mismatch);
2071 NextDiag = diag::note_template_nontype_parm_different_type;
2072 }
2073 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002074 << NewNTTP->getType()
2075 << IsTemplateTemplateParm;
2076 Diag(OldNTTP->getLocation(),
2077 diag::note_template_nontype_parm_prev_declaration)
2078 << OldNTTP->getType();
2079 }
2080 return false;
2081 }
2082 } else {
2083 // The template parameter lists of template template
2084 // parameters must agree.
2085 // FIXME: Could we perform a faster "type" comparison here?
2086 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2087 "Only template template parameters handled here");
2088 TemplateTemplateParmDecl *OldTTP
2089 = cast<TemplateTemplateParmDecl>(*OldParm);
2090 TemplateTemplateParmDecl *NewTTP
2091 = cast<TemplateTemplateParmDecl>(*NewParm);
2092 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2093 OldTTP->getTemplateParameters(),
2094 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002095 /*IsTemplateTemplateParm=*/true,
2096 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002097 return false;
2098 }
2099 }
2100
2101 return true;
2102}
2103
2104/// \brief Check whether a template can be declared within this scope.
2105///
2106/// If the template declaration is valid in this scope, returns
2107/// false. Otherwise, issues a diagnostic and returns true.
2108bool
2109Sema::CheckTemplateDeclScope(Scope *S,
2110 MultiTemplateParamsArg &TemplateParameterLists) {
2111 assert(TemplateParameterLists.size() > 0 && "Not a template");
2112
2113 // Find the nearest enclosing declaration scope.
2114 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2115 (S->getFlags() & Scope::TemplateParamScope) != 0)
2116 S = S->getParent();
2117
2118 TemplateParameterList *TemplateParams =
2119 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2120 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2121 SourceRange TemplateRange
2122 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2123
2124 // C++ [temp]p2:
2125 // A template-declaration can appear only as a namespace scope or
2126 // class scope declaration.
2127 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandda81522009-07-31 01:43:05 +00002128 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2129 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2130 return Diag(TemplateLoc, diag::err_template_linkage) << TemplateRange;
2131
2132 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregord406b032009-02-06 22:42:48 +00002133 Ctx = Ctx->getParent();
Douglas Gregord406b032009-02-06 22:42:48 +00002134
2135 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2136 return false;
2137
2138 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2139 << TemplateRange;
2140}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002141
Douglas Gregor90177912009-05-13 18:28:20 +00002142/// \brief Check whether a class template specialization or explicit
2143/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002144///
Douglas Gregor90177912009-05-13 18:28:20 +00002145/// This routine determines whether a class template specialization or
2146/// explicit instantiation can be declared in the current context
2147/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2148/// appropriate diagnostics if there was an error. It returns true if
2149// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002150bool
2151Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2152 ClassTemplateSpecializationDecl *PrevDecl,
2153 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002154 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002155 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002156 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002157 // C++ [temp.expl.spec]p2:
2158 // An explicit specialization shall be declared in the namespace
2159 // of which the template is a member, or, for member templates, in
2160 // the namespace of which the enclosing class or enclosing class
2161 // template is a member. An explicit specialization of a member
2162 // function, member class or static data member of a class
2163 // template shall be declared in the namespace of which the class
2164 // template is a member. Such a declaration may also be a
2165 // definition. If the declaration is not a definition, the
2166 // specialization may be defined later in the name- space in which
2167 // the explicit specialization was declared, or in a namespace
2168 // that encloses the one in which the explicit specialization was
2169 // declared.
2170 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002171 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002172 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002173 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002174 return true;
2175 }
2176
2177 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2178 DeclContext *TemplateContext
2179 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002180 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2181 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002182 // There is no prior declaration of this entity, so this
2183 // specialization must be in the same context as the template
2184 // itself.
2185 if (DC != TemplateContext) {
2186 if (isa<TranslationUnitDecl>(TemplateContext))
2187 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002188 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002189 << ClassTemplate << ScopeSpecifierRange;
2190 else if (isa<NamespaceDecl>(TemplateContext))
2191 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002192 << PartialSpecialization << ClassTemplate
2193 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002194
2195 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2196 }
2197
2198 return false;
2199 }
2200
2201 // We have a previous declaration of this entity. Make sure that
2202 // this redeclaration (or definition) occurs in an enclosing namespace.
2203 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002204 // FIXME: In C++98, we would like to turn these errors into warnings,
2205 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002206 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002207 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002208 if (isa<TranslationUnitDecl>(TemplateContext)) {
2209 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2210 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002211 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002212 else
2213 SuppressedDiag = true;
2214 } else if (isa<NamespaceDecl>(TemplateContext)) {
2215 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2216 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002217 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002218 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2219 else
2220 SuppressedDiag = true;
2221 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002222
Douglas Gregor90177912009-05-13 18:28:20 +00002223 if (!SuppressedDiag)
2224 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002225 }
2226
2227 return false;
2228}
2229
Douglas Gregor76e79952009-06-12 21:21:02 +00002230/// \brief Check the non-type template arguments of a class template
2231/// partial specialization according to C++ [temp.class.spec]p9.
2232///
Douglas Gregor42476442009-06-12 22:08:06 +00002233/// \param TemplateParams the template parameters of the primary class
2234/// template.
2235///
2236/// \param TemplateArg the template arguments of the class template
2237/// partial specialization.
2238///
2239/// \param MirrorsPrimaryTemplate will be set true if the class
2240/// template partial specialization arguments are identical to the
2241/// implicit template arguments of the primary template. This is not
2242/// necessarily an error (C++0x), and it is left to the caller to diagnose
2243/// this condition when it is an error.
2244///
Douglas Gregor76e79952009-06-12 21:21:02 +00002245/// \returns true if there was an error, false otherwise.
2246bool Sema::CheckClassTemplatePartialSpecializationArgs(
2247 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002248 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002249 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002250 // FIXME: the interface to this function will have to change to
2251 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002252 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002253
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002254 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002255
Douglas Gregor76e79952009-06-12 21:21:02 +00002256 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002257 // Determine whether the template argument list of the partial
2258 // specialization is identical to the implicit argument list of
2259 // the primary template. The caller may need to diagnostic this as
2260 // an error per C++ [temp.class.spec]p9b3.
2261 if (MirrorsPrimaryTemplate) {
2262 if (TemplateTypeParmDecl *TTP
2263 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2264 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002265 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002266 MirrorsPrimaryTemplate = false;
2267 } else if (TemplateTemplateParmDecl *TTP
2268 = dyn_cast<TemplateTemplateParmDecl>(
2269 TemplateParams->getParam(I))) {
2270 // FIXME: We should settle on either Declaration storage or
2271 // Expression storage for template template parameters.
2272 TemplateTemplateParmDecl *ArgDecl
2273 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002274 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002275 if (!ArgDecl)
2276 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002277 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002278 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2279
2280 if (!ArgDecl ||
2281 ArgDecl->getIndex() != TTP->getIndex() ||
2282 ArgDecl->getDepth() != TTP->getDepth())
2283 MirrorsPrimaryTemplate = false;
2284 }
2285 }
2286
Douglas Gregor76e79952009-06-12 21:21:02 +00002287 NonTypeTemplateParmDecl *Param
2288 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002289 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002290 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002291 }
2292
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002293 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002294 if (!ArgExpr) {
2295 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002296 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002297 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002298
2299 // C++ [temp.class.spec]p8:
2300 // A non-type argument is non-specialized if it is the name of a
2301 // non-type parameter. All other non-type arguments are
2302 // specialized.
2303 //
2304 // Below, we check the two conditions that only apply to
2305 // specialized non-type arguments, so skip any non-specialized
2306 // arguments.
2307 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002308 if (NonTypeTemplateParmDecl *NTTP
2309 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2310 if (MirrorsPrimaryTemplate &&
2311 (Param->getIndex() != NTTP->getIndex() ||
2312 Param->getDepth() != NTTP->getDepth()))
2313 MirrorsPrimaryTemplate = false;
2314
Douglas Gregor76e79952009-06-12 21:21:02 +00002315 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002316 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002317
2318 // C++ [temp.class.spec]p9:
2319 // Within the argument list of a class template partial
2320 // specialization, the following restrictions apply:
2321 // -- A partially specialized non-type argument expression
2322 // shall not involve a template parameter of the partial
2323 // specialization except when the argument expression is a
2324 // simple identifier.
2325 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2326 Diag(ArgExpr->getLocStart(),
2327 diag::err_dependent_non_type_arg_in_partial_spec)
2328 << ArgExpr->getSourceRange();
2329 return true;
2330 }
2331
2332 // -- The type of a template parameter corresponding to a
2333 // specialized non-type argument shall not be dependent on a
2334 // parameter of the specialization.
2335 if (Param->getType()->isDependentType()) {
2336 Diag(ArgExpr->getLocStart(),
2337 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2338 << Param->getType()
2339 << ArgExpr->getSourceRange();
2340 Diag(Param->getLocation(), diag::note_template_param_here);
2341 return true;
2342 }
Douglas Gregor42476442009-06-12 22:08:06 +00002343
2344 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002345 }
2346
2347 return false;
2348}
2349
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002350Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +00002351Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2352 TagUseKind TUK,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002353 SourceLocation KWLoc,
2354 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002355 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002356 SourceLocation TemplateNameLoc,
2357 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002358 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002359 SourceLocation *TemplateArgLocs,
2360 SourceLocation RAngleLoc,
2361 AttributeList *Attr,
2362 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002363 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002364 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002365 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002366 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002367
Douglas Gregor58944ac2009-05-31 09:31:02 +00002368 bool isPartialSpecialization = false;
2369
Douglas Gregor0d93f692009-02-25 22:02:03 +00002370 // Check the validity of the template headers that introduce this
2371 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002372 // FIXME: Once we have member templates, we'll need to check
2373 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2374 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002375 if (TemplateParameterLists.size() == 0)
2376 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002377 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002378 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002379 TemplateParameterList *TemplateParams
2380 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002381 if (TemplateParameterLists.size() > 1) {
2382 Diag(TemplateParams->getTemplateLoc(),
2383 diag::err_template_spec_extra_headers);
2384 return true;
2385 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002386
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002387 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002388 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002389
2390 // C++ [temp.class.spec]p10:
2391 // The template parameter list of a specialization shall not
2392 // contain default template argument values.
2393 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2394 Decl *Param = TemplateParams->getParam(I);
2395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2396 if (TTP->hasDefaultArgument()) {
2397 Diag(TTP->getDefaultArgumentLoc(),
2398 diag::err_default_arg_in_partial_spec);
2399 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2400 }
2401 } else if (NonTypeTemplateParmDecl *NTTP
2402 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2403 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2404 Diag(NTTP->getDefaultArgumentLoc(),
2405 diag::err_default_arg_in_partial_spec)
2406 << DefArg->getSourceRange();
2407 NTTP->setDefaultArgument(0);
2408 DefArg->Destroy(Context);
2409 }
2410 } else {
2411 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2412 if (Expr *DefArg = TTP->getDefaultArgument()) {
2413 Diag(TTP->getDefaultArgumentLoc(),
2414 diag::err_default_arg_in_partial_spec)
2415 << DefArg->getSourceRange();
2416 TTP->setDefaultArgument(0);
2417 DefArg->Destroy(Context);
2418 }
2419 }
2420 }
2421 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002422 }
2423
Douglas Gregora08b6c72009-02-17 23:15:12 +00002424 // Check that the specialization uses the same tag kind as the
2425 // original template.
2426 TagDecl::TagKind Kind;
2427 switch (TagSpec) {
2428 default: assert(0 && "Unknown tag type!");
2429 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2430 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2431 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2432 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002433 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2434 Kind, KWLoc,
2435 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002436 Diag(KWLoc, diag::err_use_with_wrong_tag)
2437 << ClassTemplate
2438 << CodeModificationHint::CreateReplacement(KWLoc,
2439 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002440 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2441 diag::note_previous_use);
2442 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2443 }
2444
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002445 // Translate the parser's template argument list in our AST format.
2446 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2447 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2448
Douglas Gregora08b6c72009-02-17 23:15:12 +00002449 // Check that the template argument list is well-formed for this
2450 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002451 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2452 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002453 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002454 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002455 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002456 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002457
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002458 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002459 ClassTemplate->getTemplateParameters()->size()) &&
2460 "Converted template argument list is too short!");
2461
Douglas Gregor58944ac2009-05-31 09:31:02 +00002462 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002463 // corresponds to these arguments.
2464 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002465 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002466 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002467 if (CheckClassTemplatePartialSpecializationArgs(
2468 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002469 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002470 return true;
2471
Douglas Gregor42476442009-06-12 22:08:06 +00002472 if (MirrorsPrimaryTemplate) {
2473 // C++ [temp.class.spec]p9b3:
2474 //
2475 // -- The argument list of the specialization shall not be identical
2476 // to the implicit argument list of the primary template.
2477 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall069c23a2009-07-31 02:45:11 +00002478 << (TUK == TUK_Definition)
Douglas Gregor42476442009-06-12 22:08:06 +00002479 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2480 RAngleLoc));
John McCall069c23a2009-07-31 02:45:11 +00002481 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor42476442009-06-12 22:08:06 +00002482 ClassTemplate->getIdentifier(),
2483 TemplateNameLoc,
2484 Attr,
2485 move(TemplateParameterLists),
2486 AS_none);
2487 }
2488
Douglas Gregor58944ac2009-05-31 09:31:02 +00002489 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002490 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002491 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002492 Converted.flatSize(),
2493 Context);
Mike Stump90fc78e2009-08-04 21:02:39 +00002494 } else
Anders Carlssona35faf92009-06-05 03:43:12 +00002495 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002496 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002497 Converted.flatSize(),
2498 Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002499 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002500 ClassTemplateSpecializationDecl *PrevDecl = 0;
2501
2502 if (isPartialSpecialization)
2503 PrevDecl
2504 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2505 InsertPos);
2506 else
2507 PrevDecl
2508 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002509
2510 ClassTemplateSpecializationDecl *Specialization = 0;
2511
Douglas Gregor0d93f692009-02-25 22:02:03 +00002512 // Check whether we can declare a class template specialization in
2513 // the current scope.
2514 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2515 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002516 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002517 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002518 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002519 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002520
Douglas Gregor1930d202009-07-30 17:40:51 +00002521 // The canonical type
2522 QualType CanonType;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002523 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2524 // Since the only prior class template specialization with these
2525 // arguments was referenced but not declared, reuse that
2526 // declaration node as our own, updating its source location to
2527 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002528 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002529 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002530 PrevDecl = 0;
Douglas Gregor1930d202009-07-30 17:40:51 +00002531 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002532 } else if (isPartialSpecialization) {
Douglas Gregor1930d202009-07-30 17:40:51 +00002533 // Build the canonical type that describes the converted template
2534 // arguments of the class template partial specialization.
2535 CanonType = Context.getTemplateSpecializationType(
2536 TemplateName(ClassTemplate),
2537 Converted.getFlatArguments(),
2538 Converted.flatSize());
2539
Douglas Gregor58944ac2009-05-31 09:31:02 +00002540 // Create a new class template partial specialization declaration node.
2541 TemplateParameterList *TemplateParams
2542 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2543 ClassTemplatePartialSpecializationDecl *PrevPartial
2544 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2545 ClassTemplatePartialSpecializationDecl *Partial
2546 = ClassTemplatePartialSpecializationDecl::Create(Context,
2547 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002548 TemplateNameLoc,
2549 TemplateParams,
2550 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002551 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002552 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002553
2554 if (PrevPartial) {
2555 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2556 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2557 } else {
2558 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2559 }
2560 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002561
2562 // Check that all of the template parameters of the class template
2563 // partial specialization are deducible from the template
2564 // arguments. If not, this class template partial specialization
2565 // will never be used.
2566 llvm::SmallVector<bool, 8> DeducibleParams;
2567 DeducibleParams.resize(TemplateParams->size());
2568 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2569 unsigned NumNonDeducible = 0;
2570 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2571 if (!DeducibleParams[I])
2572 ++NumNonDeducible;
2573
2574 if (NumNonDeducible) {
2575 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2576 << (NumNonDeducible > 1)
2577 << SourceRange(TemplateNameLoc, RAngleLoc);
2578 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2579 if (!DeducibleParams[I]) {
2580 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2581 if (Param->getDeclName())
2582 Diag(Param->getLocation(),
2583 diag::note_partial_spec_unused_parameter)
2584 << Param->getDeclName();
2585 else
2586 Diag(Param->getLocation(),
2587 diag::note_partial_spec_unused_parameter)
2588 << std::string("<anonymous>");
2589 }
2590 }
2591 }
Douglas Gregora08b6c72009-02-17 23:15:12 +00002592 } else {
2593 // Create a new class template specialization declaration node for
2594 // this explicit specialization.
2595 Specialization
2596 = ClassTemplateSpecializationDecl::Create(Context,
2597 ClassTemplate->getDeclContext(),
2598 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002599 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002600 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002601 PrevDecl);
2602
2603 if (PrevDecl) {
2604 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2605 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2606 } else {
2607 ClassTemplate->getSpecializations().InsertNode(Specialization,
2608 InsertPos);
2609 }
Douglas Gregor1930d202009-07-30 17:40:51 +00002610
2611 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002612 }
2613
2614 // Note that this is an explicit specialization.
2615 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2616
2617 // Check that this isn't a redefinition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002618 if (TUK == TUK_Definition) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002619 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002620 // FIXME: Should also handle explicit specialization after implicit
2621 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002622 SourceRange Range(TemplateNameLoc, RAngleLoc);
2623 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002624 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002625 Diag(Def->getLocation(), diag::note_previous_definition);
2626 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002627 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002628 }
2629 }
2630
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002631 // Build the fully-sugared type for this class template
2632 // specialization as the user wrote in the specialization
2633 // itself. This means that we'll pretty-print the type retrieved
2634 // from the specialization's declaration the way that the user
2635 // actually wrote the specialization, rather than formatting the
2636 // name based on the "canonical" representation used to store the
2637 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002638 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002639 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002640 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002641 TemplateArgs.size(),
Douglas Gregor1930d202009-07-30 17:40:51 +00002642 CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +00002643 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002644 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002645
Douglas Gregor50113ca2009-02-25 22:18:32 +00002646 // C++ [temp.expl.spec]p9:
2647 // A template explicit specialization is in the scope of the
2648 // namespace in which the template was defined.
2649 //
2650 // We actually implement this paragraph where we set the semantic
2651 // context (in the creation of the ClassTemplateSpecializationDecl),
2652 // but we also maintain the lexical context where the actual
2653 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002654 Specialization->setLexicalDeclContext(CurContext);
2655
2656 // We may be starting the definition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002657 if (TUK == TUK_Definition)
Douglas Gregora08b6c72009-02-17 23:15:12 +00002658 Specialization->startDefinition();
2659
2660 // Add the specialization into its lexical context, so that it can
2661 // be seen when iterating through the list of declarations in that
2662 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002663 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002664 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002665}
Douglas Gregord3022602009-03-27 23:10:48 +00002666
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002667Sema::DeclPtrTy
2668Sema::ActOnTemplateDeclarator(Scope *S,
2669 MultiTemplateParamsArg TemplateParameterLists,
2670 Declarator &D) {
2671 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2672}
2673
Douglas Gregor19d10652009-06-24 00:54:41 +00002674Sema::DeclPtrTy
2675Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2676 MultiTemplateParamsArg TemplateParameterLists,
2677 Declarator &D) {
2678 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2679 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2680 "Not a function declarator!");
2681 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2682
2683 if (FTI.hasPrototype) {
2684 // FIXME: Diagnose arguments without names in C.
2685 }
2686
2687 Scope *ParentScope = FnBodyScope->getParent();
2688
2689 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2690 move(TemplateParameterLists),
2691 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002692 if (FunctionTemplateDecl *FunctionTemplate
2693 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002694 return ActOnStartOfFunctionDef(FnBodyScope,
2695 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002696 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2697 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002698 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002699}
2700
Douglas Gregor96b6df92009-05-14 00:28:11 +00002701// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002702Sema::DeclResult
2703Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2704 unsigned TagSpec,
2705 SourceLocation KWLoc,
2706 const CXXScopeSpec &SS,
2707 TemplateTy TemplateD,
2708 SourceLocation TemplateNameLoc,
2709 SourceLocation LAngleLoc,
2710 ASTTemplateArgsPtr TemplateArgsIn,
2711 SourceLocation *TemplateArgLocs,
2712 SourceLocation RAngleLoc,
2713 AttributeList *Attr) {
2714 // Find the class template we're specializing
2715 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2716 ClassTemplateDecl *ClassTemplate
2717 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2718
2719 // Check that the specialization uses the same tag kind as the
2720 // original template.
2721 TagDecl::TagKind Kind;
2722 switch (TagSpec) {
2723 default: assert(0 && "Unknown tag type!");
2724 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2725 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2726 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2727 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002728 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2729 Kind, KWLoc,
2730 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002731 Diag(KWLoc, diag::err_use_with_wrong_tag)
2732 << ClassTemplate
2733 << CodeModificationHint::CreateReplacement(KWLoc,
2734 ClassTemplate->getTemplatedDecl()->getKindName());
2735 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2736 diag::note_previous_use);
2737 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2738 }
2739
Douglas Gregor90177912009-05-13 18:28:20 +00002740 // C++0x [temp.explicit]p2:
2741 // [...] An explicit instantiation shall appear in an enclosing
2742 // namespace of its template. [...]
2743 //
2744 // This is C++ DR 275.
2745 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2746 TemplateNameLoc,
2747 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002748 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002749 /*ExplicitInstantiation=*/true))
2750 return true;
2751
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002752 // Translate the parser's template argument list in our AST format.
2753 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2754 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2755
2756 // Check that the template argument list is well-formed for this
2757 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002758 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2759 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002760 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002761 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002762 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002763 return true;
2764
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002765 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002766 ClassTemplate->getTemplateParameters()->size()) &&
2767 "Converted template argument list is too short!");
2768
2769 // Find the class template specialization declaration that
2770 // corresponds to these arguments.
2771 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002772 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002773 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002774 Converted.flatSize(),
2775 Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002776 void *InsertPos = 0;
2777 ClassTemplateSpecializationDecl *PrevDecl
2778 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2779
2780 ClassTemplateSpecializationDecl *Specialization = 0;
2781
Douglas Gregor90177912009-05-13 18:28:20 +00002782 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002783 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002784 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002785 // This particular specialization has already been declared or
2786 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002787 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2788 << Context.getTypeDeclType(PrevDecl);
2789 Diag(PrevDecl->getLocation(),
2790 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002791 return DeclPtrTy::make(PrevDecl);
2792 }
2793
Douglas Gregor90177912009-05-13 18:28:20 +00002794 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002795 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002796 // For a given set of template parameters, if an explicit
2797 // instantiation of a template appears after a declaration of
2798 // an explicit specialization for that template, the explicit
2799 // instantiation has no effect.
2800 if (!getLangOptions().CPlusPlus0x) {
2801 Diag(TemplateNameLoc,
2802 diag::ext_explicit_instantiation_after_specialization)
2803 << Context.getTypeDeclType(PrevDecl);
2804 Diag(PrevDecl->getLocation(),
2805 diag::note_previous_template_specialization);
2806 }
2807
2808 // Create a new class template specialization declaration node
2809 // for this explicit specialization. This node is only used to
2810 // record the existence of this explicit instantiation for
2811 // accurate reproduction of the source code; we don't actually
2812 // use it for anything, since it is semantically irrelevant.
2813 Specialization
2814 = ClassTemplateSpecializationDecl::Create(Context,
2815 ClassTemplate->getDeclContext(),
2816 TemplateNameLoc,
2817 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002818 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002819 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002820 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002821 return DeclPtrTy::make(Specialization);
2822 }
2823
2824 // If we have already (implicitly) instantiated this
2825 // specialization, there is less work to do.
2826 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2827 SpecializationRequiresInstantiation = false;
2828
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002829 // Since the only prior class template specialization with these
2830 // arguments was referenced but not declared, reuse that
2831 // declaration node as our own, updating its source location to
2832 // reflect our new declaration.
2833 Specialization = PrevDecl;
2834 Specialization->setLocation(TemplateNameLoc);
2835 PrevDecl = 0;
2836 } else {
2837 // Create a new class template specialization declaration node for
2838 // this explicit specialization.
2839 Specialization
2840 = ClassTemplateSpecializationDecl::Create(Context,
2841 ClassTemplate->getDeclContext(),
2842 TemplateNameLoc,
2843 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002844 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002845
2846 ClassTemplate->getSpecializations().InsertNode(Specialization,
2847 InsertPos);
2848 }
2849
2850 // Build the fully-sugared type for this explicit instantiation as
2851 // the user wrote in the explicit instantiation itself. This means
2852 // that we'll pretty-print the type retrieved from the
2853 // specialization's declaration the way that the user actually wrote
2854 // the explicit instantiation, rather than formatting the name based
2855 // on the "canonical" representation used to store the template
2856 // arguments in the specialization.
2857 QualType WrittenTy
2858 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002859 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002860 TemplateArgs.size(),
2861 Context.getTypeDeclType(Specialization));
2862 Specialization->setTypeAsWritten(WrittenTy);
2863 TemplateArgsIn.release();
2864
2865 // Add the explicit instantiation into its lexical context. However,
2866 // since explicit instantiations are never found by name lookup, we
2867 // just put it into the declaration context directly.
2868 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002869 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002870
2871 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002872 // A definition of a class template or class member template
2873 // shall be in scope at the point of the explicit instantiation of
2874 // the class template or class member template.
2875 //
2876 // This check comes when we actually try to perform the
2877 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002878 if (SpecializationRequiresInstantiation)
2879 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002880 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002881 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002882
2883 return DeclPtrTy::make(Specialization);
2884}
2885
Douglas Gregor96b6df92009-05-14 00:28:11 +00002886// Explicit instantiation of a member class of a class template.
2887Sema::DeclResult
2888Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2889 unsigned TagSpec,
2890 SourceLocation KWLoc,
2891 const CXXScopeSpec &SS,
2892 IdentifierInfo *Name,
2893 SourceLocation NameLoc,
2894 AttributeList *Attr) {
2895
Douglas Gregor71f06032009-05-28 23:31:59 +00002896 bool Owned = false;
John McCall069c23a2009-07-31 02:45:11 +00002897 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor84a20812009-07-22 23:48:44 +00002898 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2899 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002900 if (!TagD)
2901 return true;
2902
2903 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2904 if (Tag->isEnum()) {
2905 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2906 << Context.getTypeDeclType(Tag);
2907 return true;
2908 }
2909
Douglas Gregord769bfa2009-05-27 17:30:49 +00002910 if (Tag->isInvalidDecl())
2911 return true;
2912
Douglas Gregor96b6df92009-05-14 00:28:11 +00002913 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2914 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2915 if (!Pattern) {
2916 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2917 << Context.getTypeDeclType(Record);
2918 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2919 return true;
2920 }
2921
2922 // C++0x [temp.explicit]p2:
2923 // [...] An explicit instantiation shall appear in an enclosing
2924 // namespace of its template. [...]
2925 //
2926 // This is C++ DR 275.
2927 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002928 // FIXME: In C++98, we would like to turn these errors into warnings,
2929 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002930 DeclContext *PatternContext
2931 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2932 if (!CurContext->Encloses(PatternContext)) {
2933 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2934 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2935 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2936 }
2937 }
2938
Douglas Gregor96b6df92009-05-14 00:28:11 +00002939 if (!Record->getDefinition(Context)) {
2940 // If the class has a definition, instantiate it (and all of its
2941 // members, recursively).
2942 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2943 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002944 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002945 /*ExplicitInstantiation=*/true))
2946 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002947 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002948 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002949 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002950
Mike Stumpe127ae32009-05-16 07:39:55 +00002951 // FIXME: We don't have any representation for explicit instantiations of
2952 // member classes. Such a representation is not needed for compilation, but it
2953 // should be available for clients that want to see all of the declarations in
2954 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002955 return TagD;
2956}
2957
Douglas Gregord3022602009-03-27 23:10:48 +00002958Sema::TypeResult
2959Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2960 const IdentifierInfo &II, SourceLocation IdLoc) {
2961 NestedNameSpecifier *NNS
2962 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2963 if (!NNS)
2964 return true;
2965
2966 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002967 if (T.isNull())
2968 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002969 return T.getAsOpaquePtr();
2970}
2971
Douglas Gregor77da5802009-04-01 00:28:59 +00002972Sema::TypeResult
2973Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2974 SourceLocation TemplateLoc, TypeTy *Ty) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002975 QualType T = GetTypeFromParser(Ty);
Douglas Gregor77da5802009-04-01 00:28:59 +00002976 NestedNameSpecifier *NNS
2977 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2978 const TemplateSpecializationType *TemplateId
2979 = T->getAsTemplateSpecializationType();
2980 assert(TemplateId && "Expected a template specialization type");
2981
2982 if (NNS->isDependent())
2983 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2984
2985 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2986}
2987
Douglas Gregord3022602009-03-27 23:10:48 +00002988/// \brief Build the type that describes a C++ typename specifier,
2989/// e.g., "typename T::type".
2990QualType
2991Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2992 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002993 CXXRecordDecl *CurrentInstantiation = 0;
2994 if (NNS->isDependent()) {
2995 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002996
Douglas Gregor3eb20702009-05-11 19:58:34 +00002997 // If the nested-name-specifier does not refer to the current
2998 // instantiation, then build a typename type.
2999 if (!CurrentInstantiation)
3000 return Context.getTypenameType(NNS, &II);
3001 }
Douglas Gregord3022602009-03-27 23:10:48 +00003002
Douglas Gregor3eb20702009-05-11 19:58:34 +00003003 DeclContext *Ctx = 0;
3004
3005 if (CurrentInstantiation)
3006 Ctx = CurrentInstantiation;
3007 else {
3008 CXXScopeSpec SS;
3009 SS.setScopeRep(NNS);
3010 SS.setRange(Range);
3011 if (RequireCompleteDeclContext(SS))
3012 return QualType();
3013
3014 Ctx = computeDeclContext(SS);
3015 }
Douglas Gregord3022602009-03-27 23:10:48 +00003016 assert(Ctx && "No declaration context?");
3017
3018 DeclarationName Name(&II);
3019 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3020 false);
3021 unsigned DiagID = 0;
3022 Decl *Referenced = 0;
3023 switch (Result.getKind()) {
3024 case LookupResult::NotFound:
3025 if (Ctx->isTranslationUnit())
3026 DiagID = diag::err_typename_nested_not_found_global;
3027 else
3028 DiagID = diag::err_typename_nested_not_found;
3029 break;
3030
3031 case LookupResult::Found:
3032 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3033 // We found a type. Build a QualifiedNameType, since the
3034 // typename-specifier was just sugar. FIXME: Tell
3035 // QualifiedNameType that it has a "typename" prefix.
3036 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3037 }
3038
3039 DiagID = diag::err_typename_nested_not_type;
3040 Referenced = Result.getAsDecl();
3041 break;
3042
3043 case LookupResult::FoundOverloaded:
3044 DiagID = diag::err_typename_nested_not_type;
3045 Referenced = *Result.begin();
3046 break;
3047
3048 case LookupResult::AmbiguousBaseSubobjectTypes:
3049 case LookupResult::AmbiguousBaseSubobjects:
3050 case LookupResult::AmbiguousReference:
3051 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3052 return QualType();
3053 }
3054
3055 // If we get here, it's because name lookup did not find a
3056 // type. Emit an appropriate diagnostic and return an error.
3057 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3058 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3059 else
3060 Diag(Range.getEnd(), DiagID) << Range << Name;
3061 if (Referenced)
3062 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3063 << Name;
3064 return QualType();
3065}
Douglas Gregor3f220e82009-08-06 16:20:37 +00003066
3067namespace {
3068 // See Sema::RebuildTypeInCurrentInstantiation
3069 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3070 : public TreeTransform<CurrentInstantiationRebuilder>
3071 {
3072 SourceLocation Loc;
3073 DeclarationName Entity;
3074
3075 public:
3076 CurrentInstantiationRebuilder(Sema &SemaRef,
3077 SourceLocation Loc,
3078 DeclarationName Entity)
3079 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3080 Loc(Loc), Entity(Entity) { }
3081
3082 /// \brief Determine whether the given type \p T has already been
3083 /// transformed.
3084 ///
3085 /// For the purposes of type reconstruction, a type has already been
3086 /// transformed if it is NULL or if it is not dependent.
3087 bool AlreadyTransformed(QualType T) {
3088 return T.isNull() || !T->isDependentType();
3089 }
3090
3091 /// \brief Returns the location of the entity whose type is being
3092 /// rebuilt.
3093 SourceLocation getBaseLocation() { return Loc; }
3094
3095 /// \brief Returns the name of the entity whose type is being rebuilt.
3096 DeclarationName getBaseEntity() { return Entity; }
3097
3098 /// \brief Transforms an expression by returning the expression itself
3099 /// (an identity function).
3100 ///
3101 /// FIXME: This is completely unsafe; we will need to actually clone the
3102 /// expressions.
3103 Sema::OwningExprResult TransformExpr(Expr *E) {
3104 return getSema().Owned(E);
3105 }
3106
3107 /// \brief Transforms a typename type by determining whether the type now
3108 /// refers to a member of the current instantiation, and then
3109 /// type-checking and building a QualifiedNameType (when possible).
3110 QualType TransformTypenameType(const TypenameType *T);
3111 };
3112}
3113
3114QualType
3115CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3116 NestedNameSpecifier *NNS
3117 = TransformNestedNameSpecifier(T->getQualifier(),
3118 /*FIXME:*/SourceRange(getBaseLocation()));
3119 if (!NNS)
3120 return QualType();
3121
3122 // If the nested-name-specifier did not change, and we cannot compute the
3123 // context corresponding to the nested-name-specifier, then this
3124 // typename type will not change; exit early.
3125 CXXScopeSpec SS;
3126 SS.setRange(SourceRange(getBaseLocation()));
3127 SS.setScopeRep(NNS);
3128 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3129 return QualType(T, 0);
3130
3131 // Rebuild the typename type, which will probably turn into a
3132 // QualifiedNameType.
3133 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3134 QualType NewTemplateId
3135 = TransformType(QualType(TemplateId, 0));
3136 if (NewTemplateId.isNull())
3137 return QualType();
3138
3139 if (NNS == T->getQualifier() &&
3140 NewTemplateId == QualType(TemplateId, 0))
3141 return QualType(T, 0);
3142
3143 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3144 }
3145
3146 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3147}
3148
3149/// \brief Rebuilds a type within the context of the current instantiation.
3150///
3151/// The type \p T is part of the type of an out-of-line member definition of
3152/// a class template (or class template partial specialization) that was parsed
3153/// and constructed before we entered the scope of the class template (or
3154/// partial specialization thereof). This routine will rebuild that type now
3155/// that we have entered the declarator's scope, which may produce different
3156/// canonical types, e.g.,
3157///
3158/// \code
3159/// template<typename T>
3160/// struct X {
3161/// typedef T* pointer;
3162/// pointer data();
3163/// };
3164///
3165/// template<typename T>
3166/// typename X<T>::pointer X<T>::data() { ... }
3167/// \endcode
3168///
3169/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3170/// since we do not know that we can look into X<T> when we parsed the type.
3171/// This function will rebuild the type, performing the lookup of "pointer"
3172/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3173/// as the canonical type of T*, allowing the return types of the out-of-line
3174/// definition and the declaration to match.
3175QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3176 DeclarationName Name) {
3177 if (T.isNull() || !T->isDependentType())
3178 return T;
3179
3180 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3181 return Rebuilder.TransformType(T);
Benjamin Kramer3e2ac772009-08-11 22:33:06 +00003182}