blob: 9dfa96288cc83282ea9c980c6e031d1a1351c09e [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021
22using namespace clang;
23
Douglas Gregord6fb7ef2008-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 Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-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()) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregorf511e472009-07-29 16:56:42 +000068 } else if (OverloadedFunctionDecl *Ovl
69 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000070 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
71 FEnd = Ovl->function_end();
72 F != FEnd; ++F) {
Douglas Gregorf511e472009-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 Gregord99cbe62009-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 Gregorf511e472009-07-29 16:56:42 +0000108 return TNK_Function_template;
109 }
110
111 TNK = TNK_Function_template;
112 Template = FuncTmpl;
113 break;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000114 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000115 }
116 }
Douglas Gregor7532dc62009-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 Gregord6fb7ef2008-12-18 19:37:40 +0000129 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000130 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000131}
132
Douglas Gregor72c3f312008-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 Gregorf57172b2008-12-08 18:40:42 +0000138 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-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 Gregor2943aed2009-03-03 04:44:36 +0000153/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-02-04 19:02:06 +0000159 return Temp;
160 }
161 return 0;
162}
163
Douglas Gregor72c3f312008-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 Carlsson941df7d2009-06-12 19:58:00 +0000173Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
174 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000175 SourceLocation KeyLoc,
176 IdentifierInfo *ParamName,
177 SourceLocation ParamNameLoc,
178 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-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 Gregor47b9a1c2009-02-04 17:27:36 +0000184 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000185 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000186 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
187 PrevDecl);
188 }
189
Douglas Gregorddc29e12009-02-06 22:42:48 +0000190 SourceLocation Loc = ParamNameLoc;
191 if (!ParamName)
192 Loc = KeyLoc;
193
Douglas Gregor72c3f312008-12-05 18:15:24 +0000194 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000195 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000196 Depth, Position, ParamName, Typename,
197 Ellipsis);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000203 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000204 IdResolver.AddDecl(Param);
205 }
206
Chris Lattnerb28317a2009-03-28 19:18:32 +0000207 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000208}
209
Douglas Gregord684b002009-02-10 19:49:53 +0000210/// ActOnTypeParameterDefault - Adds a default argument (the type
211/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000212void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000213 SourceLocation EqualLoc,
214 SourceLocation DefaultLoc,
215 TypeTy *DefaultT) {
216 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000217 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000218 // FIXME: Preserve type source info.
219 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregord684b002009-02-10 19:49:53 +0000220
Anders Carlsson9c4c5c82009-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 Carlsson9c4c5c82009-06-12 22:30:13 +0000226 return;
227 }
228
Douglas Gregord684b002009-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 Gregor2943aed2009-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 Kremenek6217b802009-07-29 21:53:49 +0000258 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
259 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-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 Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000290Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
291 unsigned Depth,
292 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000293 DeclaratorInfo *DInfo = 0;
294 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000295
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000296 assert(S->isTemplateParamScope() &&
297 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000298 bool Invalid = false;
299
300 IdentifierInfo *ParamName = D.getIdentifier();
301 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000302 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000303 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000304 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000305 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000306 }
307
Douglas Gregor2943aed2009-03-03 04:44:36 +0000308 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000309 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000310 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000311 Invalid = true;
312 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000313
Douglas Gregor72c3f312008-12-05 18:15:24 +0000314 NonTypeTemplateParmDecl *Param
315 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000316 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-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 Lattnerb28317a2009-03-28 19:18:32 +0000322 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000323 IdResolver.AddDecl(Param);
324 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000325 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000326}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000327
Douglas Gregord684b002009-02-10 19:49:53 +0000328/// \brief Adds a default argument to the given non-type template
329/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000330void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000331 SourceLocation EqualLoc,
332 ExprArg DefaultE) {
333 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000334 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-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 Gregor02cbbd22009-06-11 18:10:32 +0000342 TemplateArgument Converted;
343 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
344 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000345 TemplateParm->setInvalidDecl();
346 return;
347 }
348
Anders Carlssone9146f22009-05-01 19:49:17 +0000349 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000350}
351
Douglas Gregoraaba5e32009-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 Lattnerb28317a2009-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 Gregoraaba5e32009-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 Lattnerb28317a2009-03-28 19:18:32 +0000385 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000386 IdResolver.AddDecl(Param);
387 }
388
Chris Lattnerb28317a2009-03-28 19:18:32 +0000389 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000390}
391
Douglas Gregord684b002009-02-10 19:49:53 +0000392/// \brief Adds a default argument to the given template template
393/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000394void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000395 SourceLocation EqualLoc,
396 ExprArg DefaultE) {
397 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000398 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-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 Gregorc4b4e7b2008-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 Lattnerb28317a2009-03-28 19:18:32 +0000433 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000434 SourceLocation RAngleLoc) {
435 if (ExportLoc.isValid())
436 Diag(ExportLoc, diag::note_template_export_unsupported);
437
Douglas Gregorddc29e12009-02-06 22:42:48 +0000438 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
439 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000440}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000441
Douglas Gregor212e81c2009-03-25 00:13:59 +0000442Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000443Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000444 SourceLocation KWLoc, const CXXScopeSpec &SS,
445 IdentifierInfo *Name, SourceLocation NameLoc,
446 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000447 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000448 AccessSpecifier AS) {
Douglas Gregor05396e22009-08-25 17:23:04 +0000449 assert(TemplateParams && TemplateParams->size() > 0 &&
450 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000451 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000452 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000453
454 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000455 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000456 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000457
458 TagDecl::TagKind Kind;
459 switch (TagSpec) {
460 default: assert(0 && "Unknown tag type!");
461 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
462 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
463 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
464 }
465
466 // There is no such thing as an unnamed class template.
467 if (!Name) {
468 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000469 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000470 }
471
472 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000473 DeclContext *SemanticContext;
474 LookupResult Previous;
475 if (SS.isNotEmpty() && !SS.isInvalid()) {
476 SemanticContext = computeDeclContext(SS, true);
477 if (!SemanticContext) {
478 // FIXME: Produce a reasonable diagnostic here
479 return true;
480 }
481
482 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
483 true);
484 } else {
485 SemanticContext = CurContext;
486 Previous = LookupName(S, Name, LookupOrdinaryName, true);
487 }
488
Douglas Gregorddc29e12009-02-06 22:42:48 +0000489 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
490 NamedDecl *PrevDecl = 0;
491 if (Previous.begin() != Previous.end())
492 PrevDecl = *Previous.begin();
493
Douglas Gregor05396e22009-08-25 17:23:04 +0000494 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000495 PrevDecl = 0;
496
Douglas Gregorddc29e12009-02-06 22:42:48 +0000497 // If there is a previous declaration with the same name, check
498 // whether this is a valid redeclaration.
499 ClassTemplateDecl *PrevClassTemplate
500 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
501 if (PrevClassTemplate) {
502 // Ensure that the template parameter lists are compatible.
503 if (!TemplateParameterListsAreEqual(TemplateParams,
504 PrevClassTemplate->getTemplateParameters(),
505 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000506 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000507
508 // C++ [temp.class]p4:
509 // In a redeclaration, partial specialization, explicit
510 // specialization or explicit instantiation of a class template,
511 // the class-key shall agree in kind with the original class
512 // template declaration (7.1.5.3).
513 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000514 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000515 Diag(KWLoc, diag::err_use_with_wrong_tag)
516 << Name
517 << CodeModificationHint::CreateReplacement(KWLoc,
518 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000519 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000520 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000521 }
522
Douglas Gregorddc29e12009-02-06 22:42:48 +0000523 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000524 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000525 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
526 Diag(NameLoc, diag::err_redefinition) << Name;
527 Diag(Def->getLocation(), diag::note_previous_definition);
528 // FIXME: Would it make sense to try to "forget" the previous
529 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000530 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000531 }
532 }
533 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
534 // Maybe we will complain about the shadowed template parameter.
535 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
536 // Just pretend that we didn't see the previous declaration.
537 PrevDecl = 0;
538 } else if (PrevDecl) {
539 // C++ [temp]p5:
540 // A class template shall not have the same name as any other
541 // template, class, function, object, enumeration, enumerator,
542 // namespace, or type in the same scope (3.3), except as specified
543 // in (14.5.4).
544 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
545 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000546 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000547 }
548
Douglas Gregord684b002009-02-10 19:49:53 +0000549 // Check the template parameter list of this declaration, possibly
550 // merging in the template parameter list from the previous class
551 // template declaration.
552 if (CheckTemplateParameterList(TemplateParams,
553 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
554 Invalid = true;
555
Douglas Gregor7da97d02009-05-10 22:57:19 +0000556 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000557 // declaration!
558
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000559 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000560 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000561 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000562 PrevClassTemplate->getTemplatedDecl() : 0,
563 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000564
565 ClassTemplateDecl *NewTemplate
566 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
567 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000568 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000569 NewClass->setDescribedClassTemplate(NewTemplate);
570
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000571 // Build the type for the class template declaration now.
572 QualType T =
573 Context.getTypeDeclType(NewClass,
574 PrevClassTemplate?
575 PrevClassTemplate->getTemplatedDecl() : 0);
576 assert(T->isDependentType() && "Class template type is not dependent?");
577 (void)T;
578
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000579 // Set the access specifier.
580 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
581
Douglas Gregorddc29e12009-02-06 22:42:48 +0000582 // Set the lexical context of these templates
583 NewClass->setLexicalDeclContext(CurContext);
584 NewTemplate->setLexicalDeclContext(CurContext);
585
John McCall0f434ec2009-07-31 02:45:11 +0000586 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000587 NewClass->startDefinition();
588
589 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000590 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000591
592 PushOnScopeChains(NewTemplate, S);
593
Douglas Gregord684b002009-02-10 19:49:53 +0000594 if (Invalid) {
595 NewTemplate->setInvalidDecl();
596 NewClass->setInvalidDecl();
597 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000598 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000599}
600
Douglas Gregord684b002009-02-10 19:49:53 +0000601/// \brief Checks the validity of a template parameter list, possibly
602/// considering the template parameter list from a previous
603/// declaration.
604///
605/// If an "old" template parameter list is provided, it must be
606/// equivalent (per TemplateParameterListsAreEqual) to the "new"
607/// template parameter list.
608///
609/// \param NewParams Template parameter list for a new template
610/// declaration. This template parameter list will be updated with any
611/// default arguments that are carried through from the previous
612/// template parameter list.
613///
614/// \param OldParams If provided, template parameter list from a
615/// previous declaration of the same template. Default template
616/// arguments will be merged from the old template parameter list to
617/// the new template parameter list.
618///
619/// \returns true if an error occurred, false otherwise.
620bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
621 TemplateParameterList *OldParams) {
622 bool Invalid = false;
623
624 // C++ [temp.param]p10:
625 // The set of default template-arguments available for use with a
626 // template declaration or definition is obtained by merging the
627 // default arguments from the definition (if in scope) and all
628 // declarations in scope in the same way default function
629 // arguments are (8.3.6).
630 bool SawDefaultArgument = false;
631 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000632
Anders Carlsson49d25572009-06-12 23:20:15 +0000633 bool SawParameterPack = false;
634 SourceLocation ParameterPackLoc;
635
Mike Stump1a35fde2009-02-11 23:03:27 +0000636 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000637 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000638 if (OldParams)
639 OldParam = OldParams->begin();
640
641 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
642 NewParamEnd = NewParams->end();
643 NewParam != NewParamEnd; ++NewParam) {
644 // Variables used to diagnose redundant default arguments
645 bool RedundantDefaultArg = false;
646 SourceLocation OldDefaultLoc;
647 SourceLocation NewDefaultLoc;
648
649 // Variables used to diagnose missing default arguments
650 bool MissingDefaultArg = false;
651
Anders Carlsson49d25572009-06-12 23:20:15 +0000652 // C++0x [temp.param]p11:
653 // If a template parameter of a class template is a template parameter pack,
654 // it must be the last template parameter.
655 if (SawParameterPack) {
656 Diag(ParameterPackLoc,
657 diag::err_template_param_pack_must_be_last_template_parameter);
658 Invalid = true;
659 }
660
Douglas Gregord684b002009-02-10 19:49:53 +0000661 // Merge default arguments for template type parameters.
662 if (TemplateTypeParmDecl *NewTypeParm
663 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
664 TemplateTypeParmDecl *OldTypeParm
665 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
666
Anders Carlsson49d25572009-06-12 23:20:15 +0000667 if (NewTypeParm->isParameterPack()) {
668 assert(!NewTypeParm->hasDefaultArgument() &&
669 "Parameter packs can't have a default argument!");
670 SawParameterPack = true;
671 ParameterPackLoc = NewTypeParm->getLocation();
672 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000673 NewTypeParm->hasDefaultArgument()) {
674 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
675 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
676 SawDefaultArgument = true;
677 RedundantDefaultArg = true;
678 PreviousDefaultArgLoc = NewDefaultLoc;
679 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
680 // Merge the default argument from the old declaration to the
681 // new declaration.
682 SawDefaultArgument = true;
683 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
684 OldTypeParm->getDefaultArgumentLoc(),
685 true);
686 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
687 } else if (NewTypeParm->hasDefaultArgument()) {
688 SawDefaultArgument = true;
689 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
690 } else if (SawDefaultArgument)
691 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000692 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +0000693 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000694 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000695 NonTypeTemplateParmDecl *OldNonTypeParm
696 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
697 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
698 NewNonTypeParm->hasDefaultArgument()) {
699 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
700 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
701 SawDefaultArgument = true;
702 RedundantDefaultArg = true;
703 PreviousDefaultArgLoc = NewDefaultLoc;
704 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
705 // Merge the default argument from the old declaration to the
706 // new declaration.
707 SawDefaultArgument = true;
708 // FIXME: We need to create a new kind of "default argument"
709 // expression that points to a previous template template
710 // parameter.
711 NewNonTypeParm->setDefaultArgument(
712 OldNonTypeParm->getDefaultArgument());
713 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
714 } else if (NewNonTypeParm->hasDefaultArgument()) {
715 SawDefaultArgument = true;
716 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
717 } else if (SawDefaultArgument)
718 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000719 } else {
Douglas Gregord684b002009-02-10 19:49:53 +0000720 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +0000721 TemplateTemplateParmDecl *NewTemplateParm
722 = cast<TemplateTemplateParmDecl>(*NewParam);
723 TemplateTemplateParmDecl *OldTemplateParm
724 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
725 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
726 NewTemplateParm->hasDefaultArgument()) {
727 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
728 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
729 SawDefaultArgument = true;
730 RedundantDefaultArg = true;
731 PreviousDefaultArgLoc = NewDefaultLoc;
732 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
733 // Merge the default argument from the old declaration to the
734 // new declaration.
735 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000736 // FIXME: We need to create a new kind of "default argument" expression
737 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000738 NewTemplateParm->setDefaultArgument(
739 OldTemplateParm->getDefaultArgument());
740 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
741 } else if (NewTemplateParm->hasDefaultArgument()) {
742 SawDefaultArgument = true;
743 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
744 } else if (SawDefaultArgument)
745 MissingDefaultArg = true;
746 }
747
748 if (RedundantDefaultArg) {
749 // C++ [temp.param]p12:
750 // A template-parameter shall not be given default arguments
751 // by two different declarations in the same scope.
752 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
753 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
754 Invalid = true;
755 } else if (MissingDefaultArg) {
756 // C++ [temp.param]p11:
757 // If a template-parameter has a default template-argument,
758 // all subsequent template-parameters shall have a default
759 // template-argument supplied.
760 Diag((*NewParam)->getLocation(),
761 diag::err_template_param_default_arg_missing);
762 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
763 Invalid = true;
764 }
765
766 // If we have an old template parameter list that we're merging
767 // in, move on to the next parameter.
768 if (OldParams)
769 ++OldParam;
770 }
771
772 return Invalid;
773}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000774
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000775/// \brief Match the given template parameter lists to the given scope
776/// specifier, returning the template parameter list that applies to the
777/// name.
778///
779/// \param DeclStartLoc the start of the declaration that has a scope
780/// specifier or a template parameter list.
781///
782/// \param SS the scope specifier that will be matched to the given template
783/// parameter lists. This scope specifier precedes a qualified name that is
784/// being declared.
785///
786/// \param ParamLists the template parameter lists, from the outermost to the
787/// innermost template parameter lists.
788///
789/// \param NumParamLists the number of template parameter lists in ParamLists.
790///
791/// \returns the template parameter list, if any, that corresponds to the
792/// name that is preceded by the scope specifier @p SS. This template
793/// parameter list may be have template parameters (if we're declaring a
794/// template) or may have no template parameters (if we're declaring a
795/// template specialization), or may be NULL (if we were's declaring isn't
796/// itself a template).
797TemplateParameterList *
798Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
799 const CXXScopeSpec &SS,
800 TemplateParameterList **ParamLists,
801 unsigned NumParamLists) {
802 // FIXME: This routine will need a lot more testing once we have support for
803 // member templates.
804
805 // Find the template-ids that occur within the nested-name-specifier. These
806 // template-ids will match up with the template parameter lists.
807 llvm::SmallVector<const TemplateSpecializationType *, 4>
808 TemplateIdsInSpecifier;
809 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
810 NNS; NNS = NNS->getPrefix()) {
811 if (const TemplateSpecializationType *SpecType
812 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
813 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
814 if (!Template)
815 continue; // FIXME: should this be an error? probably...
816
Ted Kremenek6217b802009-07-29 21:53:49 +0000817 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000818 ClassTemplateSpecializationDecl *SpecDecl
819 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
820 // If the nested name specifier refers to an explicit specialization,
821 // we don't need a template<> header.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000822 // FIXME: revisit this approach once we cope with specialization
823 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000824 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
825 continue;
826 }
827
828 TemplateIdsInSpecifier.push_back(SpecType);
829 }
830 }
831
832 // Reverse the list of template-ids in the scope specifier, so that we can
833 // more easily match up the template-ids and the template parameter lists.
834 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
835
836 SourceLocation FirstTemplateLoc = DeclStartLoc;
837 if (NumParamLists)
838 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
839
840 // Match the template-ids found in the specifier to the template parameter
841 // lists.
842 unsigned Idx = 0;
843 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
844 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +0000845 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
846 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000847 if (Idx >= NumParamLists) {
848 // We have a template-id without a corresponding template parameter
849 // list.
850 if (DependentTemplateId) {
851 // FIXME: the location information here isn't great.
852 Diag(SS.getRange().getBegin(),
853 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +0000854 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000855 << SS.getRange();
856 } else {
857 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
858 << SS.getRange()
859 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
860 "template<> ");
861 }
862 return 0;
863 }
864
865 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000866 if (DependentTemplateId) {
867 TemplateDecl *Template
868 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
869
870 if (ClassTemplateDecl *ClassTemplate
871 = dyn_cast<ClassTemplateDecl>(Template)) {
872 TemplateParameterList *ExpectedTemplateParams = 0;
873 // Is this template-id naming the primary template?
874 if (Context.hasSameType(TemplateId,
875 ClassTemplate->getInjectedClassNameType(Context)))
876 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
877 // ... or a partial specialization?
878 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
879 = ClassTemplate->findPartialSpecialization(TemplateId))
880 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
881
882 if (ExpectedTemplateParams)
883 TemplateParameterListsAreEqual(ParamLists[Idx],
884 ExpectedTemplateParams,
885 true);
886 }
887 } else if (ParamLists[Idx]->size() > 0)
888 Diag(ParamLists[Idx]->getTemplateLoc(),
889 diag::err_template_param_list_matches_nontemplate)
890 << TemplateId
891 << ParamLists[Idx]->getSourceRange();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000892 }
893
894 // If there were at least as many template-ids as there were template
895 // parameter lists, then there are no template parameter lists remaining for
896 // the declaration itself.
897 if (Idx >= NumParamLists)
898 return 0;
899
900 // If there were too many template parameter lists, complain about that now.
901 if (Idx != NumParamLists - 1) {
902 while (Idx < NumParamLists - 1) {
903 Diag(ParamLists[Idx]->getTemplateLoc(),
904 diag::err_template_spec_extra_headers)
905 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
906 ParamLists[Idx]->getRAngleLoc());
907 ++Idx;
908 }
909 }
910
911 // Return the last template parameter list, which corresponds to the
912 // entity being declared.
913 return ParamLists[NumParamLists - 1];
914}
915
Douglas Gregor40808ce2009-03-09 23:48:35 +0000916/// \brief Translates template arguments as provided by the parser
917/// into template arguments used by semantic analysis.
918static void
919translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
920 SourceLocation *TemplateArgLocs,
921 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
922 TemplateArgs.reserve(TemplateArgsIn.size());
923
924 void **Args = TemplateArgsIn.getArgs();
925 bool *ArgIsType = TemplateArgsIn.getArgIsType();
926 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
927 TemplateArgs.push_back(
928 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000929 //FIXME: Preserve type source info.
930 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000931 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
932 }
933}
934
Douglas Gregor7532dc62009-03-30 22:58:21 +0000935QualType Sema::CheckTemplateIdType(TemplateName Name,
936 SourceLocation TemplateLoc,
937 SourceLocation LAngleLoc,
938 const TemplateArgument *TemplateArgs,
939 unsigned NumTemplateArgs,
940 SourceLocation RAngleLoc) {
941 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000942 if (!Template) {
943 // The template name does not resolve to a template, so we just
944 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000945 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000946 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000947 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000948
Douglas Gregor40808ce2009-03-09 23:48:35 +0000949 // Check that the template argument list is well-formed for this
950 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000951 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
952 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000953 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000954 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000955 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000956 return QualType();
957
Anders Carlssonfb250522009-06-23 01:26:57 +0000958 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000959 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000960 "Converted template argument list is too short!");
961
962 QualType CanonType;
963
Douglas Gregor7532dc62009-03-30 22:58:21 +0000964 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000965 TemplateArgs,
966 NumTemplateArgs)) {
967 // This class template specialization is a dependent
968 // type. Therefore, its canonical type is another class template
969 // specialization type that contains all of the converted
970 // arguments in canonical form. This ensures that, e.g., A<T> and
971 // A<T, T> have identical types when A is declared as:
972 //
973 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000974 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
975 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000976 Converted.getFlatArguments(),
977 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +0000978
979 // FIXME: CanonType is not actually the canonical type, and unfortunately
980 // it is a TemplateTypeSpecializationType that we will never use again.
981 // In the future, we need to teach getTemplateSpecializationType to only
982 // build the canonical type and return that to us.
983 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000984 } else if (ClassTemplateDecl *ClassTemplate
985 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000986 // Find the class template specialization declaration that
987 // corresponds to these arguments.
988 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000989 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000990 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000991 Converted.flatSize(),
992 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000993 void *InsertPos = 0;
994 ClassTemplateSpecializationDecl *Decl
995 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
996 if (!Decl) {
997 // This is the first time we have referenced this class template
998 // specialization. Create the canonical declaration and add it to
999 // the set of specializations.
1000 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001001 ClassTemplate->getDeclContext(),
1002 TemplateLoc,
1003 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001004 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001005 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1006 Decl->setLexicalDeclContext(CurContext);
1007 }
1008
1009 CanonType = Context.getTypeDeclType(Decl);
1010 }
1011
1012 // Build the fully-sugared type for this class template
1013 // specialization, which refers back to the class template
1014 // specialization we created or found.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001015 //FIXME: Preserve type source info.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001016 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1017 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001018}
1019
Douglas Gregorcc636682009-02-17 23:15:12 +00001020Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001021Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1022 SourceLocation LAngleLoc,
1023 ASTTemplateArgsPtr TemplateArgsIn,
1024 SourceLocation *TemplateArgLocs,
1025 SourceLocation RAngleLoc) {
1026 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001027
Douglas Gregor40808ce2009-03-09 23:48:35 +00001028 // Translate the parser's template argument list in our AST format.
1029 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1030 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001031
Douglas Gregor7532dc62009-03-30 22:58:21 +00001032 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001033 TemplateArgs.data(),
1034 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001035 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001036 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001037
1038 if (Result.isNull())
1039 return true;
1040
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001041 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001042}
1043
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001044Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1045 SourceLocation TemplateNameLoc,
1046 SourceLocation LAngleLoc,
1047 const TemplateArgument *TemplateArgs,
1048 unsigned NumTemplateArgs,
1049 SourceLocation RAngleLoc) {
1050 // FIXME: Can we do any checking at this point? I guess we could check the
1051 // template arguments that we have against the template name, if the template
1052 // name refers to a single template. That's not a terribly common case,
1053 // though.
1054 return Owned(TemplateIdRefExpr::Create(Context,
1055 /*FIXME: New type?*/Context.OverloadTy,
1056 /*FIXME: Necessary?*/0,
1057 /*FIXME: Necessary?*/SourceRange(),
1058 Template, TemplateNameLoc, LAngleLoc,
1059 TemplateArgs,
1060 NumTemplateArgs, RAngleLoc));
1061}
1062
1063Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1064 SourceLocation TemplateNameLoc,
1065 SourceLocation LAngleLoc,
1066 ASTTemplateArgsPtr TemplateArgsIn,
1067 SourceLocation *TemplateArgLocs,
1068 SourceLocation RAngleLoc) {
1069 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1070
1071 // Translate the parser's template argument list in our AST format.
1072 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1073 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001074 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001075
1076 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1077 TemplateArgs.data(), TemplateArgs.size(),
1078 RAngleLoc);
1079}
1080
Douglas Gregorc45c2322009-03-31 00:43:58 +00001081/// \brief Form a dependent template name.
1082///
1083/// This action forms a dependent template name given the template
1084/// name and its (presumably dependent) scope specifier. For
1085/// example, given "MetaFun::template apply", the scope specifier \p
1086/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1087/// of the "template" keyword, and "apply" is the \p Name.
1088Sema::TemplateTy
1089Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1090 const IdentifierInfo &Name,
1091 SourceLocation NameLoc,
1092 const CXXScopeSpec &SS) {
1093 if (!SS.isSet() || SS.isInvalid())
1094 return TemplateTy();
1095
1096 NestedNameSpecifier *Qualifier
1097 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1098
1099 // FIXME: member of the current instantiation
1100
1101 if (!Qualifier->isDependent()) {
1102 // C++0x [temp.names]p5:
1103 // If a name prefixed by the keyword template is not the name of
1104 // a template, the program is ill-formed. [Note: the keyword
1105 // template may not be applied to non-template members of class
1106 // templates. -end note ] [ Note: as is the case with the
1107 // typename prefix, the template prefix is allowed in cases
1108 // where it is not strictly necessary; i.e., when the
1109 // nested-name-specifier or the expression on the left of the ->
1110 // or . is not dependent on a template-parameter, or the use
1111 // does not appear in the scope of a template. -end note]
1112 //
1113 // Note: C++03 was more strict here, because it banned the use of
1114 // the "template" keyword prior to a template-name that was not a
1115 // dependent name. C++ DR468 relaxed this requirement (the
1116 // "template" keyword is now permitted). We follow the C++0x
1117 // rules, even in C++03 mode, retroactively applying the DR.
1118 TemplateTy Template;
1119 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1120 if (TNK == TNK_Non_template) {
1121 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1122 << &Name;
1123 return TemplateTy();
1124 }
1125
1126 return Template;
1127 }
1128
1129 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1130}
1131
Anders Carlsson436b1562009-06-13 00:33:33 +00001132bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1133 const TemplateArgument &Arg,
1134 TemplateArgumentListBuilder &Converted) {
1135 // Check template type parameter.
1136 if (Arg.getKind() != TemplateArgument::Type) {
1137 // C++ [temp.arg.type]p1:
1138 // A template-argument for a template-parameter which is a
1139 // type shall be a type-id.
1140
1141 // We have a template type parameter but the template argument
1142 // is not a type.
1143 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1144 Diag(Param->getLocation(), diag::note_template_param_here);
1145
1146 return true;
1147 }
1148
1149 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1150 return true;
1151
1152 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001153 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001154 TemplateArgument(Arg.getLocation(),
1155 Context.getCanonicalType(Arg.getAsType())));
1156 return false;
1157}
1158
Douglas Gregorc15cb382009-02-09 23:23:08 +00001159/// \brief Check that the given template argument list is well-formed
1160/// for specializing the given template.
1161bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1162 SourceLocation TemplateLoc,
1163 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001164 const TemplateArgument *TemplateArgs,
1165 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001166 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001167 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001168 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001169 TemplateParameterList *Params = Template->getTemplateParameters();
1170 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001171 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001172 bool Invalid = false;
1173
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001174 bool HasParameterPack =
1175 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1176
1177 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001178 (NumArgs < Params->getMinRequiredArguments() &&
1179 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001180 // FIXME: point at either the first arg beyond what we can handle,
1181 // or the '>', depending on whether we have too many or too few
1182 // arguments.
1183 SourceRange Range;
1184 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001185 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001186 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1187 << (NumArgs > NumParams)
1188 << (isa<ClassTemplateDecl>(Template)? 0 :
1189 isa<FunctionTemplateDecl>(Template)? 1 :
1190 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1191 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001192 Diag(Template->getLocation(), diag::note_template_decl_here)
1193 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001194 Invalid = true;
1195 }
1196
1197 // C++ [temp.arg]p1:
1198 // [...] The type and form of each template-argument specified in
1199 // a template-id shall match the type and form specified for the
1200 // corresponding parameter declared by the template in its
1201 // template-parameter-list.
1202 unsigned ArgIdx = 0;
1203 for (TemplateParameterList::iterator Param = Params->begin(),
1204 ParamEnd = Params->end();
1205 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001206 if (ArgIdx > NumArgs && PartialTemplateArgs)
1207 break;
1208
Douglas Gregorc15cb382009-02-09 23:23:08 +00001209 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001210 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001211 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001212 // Retrieve the default template argument from the template
1213 // parameter.
1214 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001215 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001216 // We have an empty argument pack.
1217 Converted.BeginPack();
1218 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001219 break;
1220 }
1221
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001222 if (!TTP->hasDefaultArgument())
1223 break;
1224
Douglas Gregor40808ce2009-03-09 23:48:35 +00001225 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001226
1227 // If the argument type is dependent, instantiate it now based
1228 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001229 if (ArgType->isDependentType()) {
1230 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001231 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001232 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001233 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001234
Anders Carlssone9c904b2009-06-05 04:47:51 +00001235 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001236 /*TakeArgs=*/false);
John McCallce3ff2b2009-08-25 22:02:44 +00001237 ArgType = SubstType(ArgType, TemplateArgs,
1238 TTP->getDefaultArgumentLoc(),
1239 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001240 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001241
1242 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001243 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001244
Douglas Gregor40808ce2009-03-09 23:48:35 +00001245 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001246 } else if (NonTypeTemplateParmDecl *NTTP
1247 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1248 if (!NTTP->hasDefaultArgument())
1249 break;
1250
Anders Carlsson3b56c002009-06-11 16:06:49 +00001251 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001252 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001253 Converted.flatSize(),
1254 SourceRange(TemplateLoc, RAngleLoc));
1255
1256 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001257 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001258
John McCallce3ff2b2009-08-25 22:02:44 +00001259 Sema::OwningExprResult E = SubstExpr(NTTP->getDefaultArgument(),
1260 TemplateArgs);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001261 if (E.isInvalid())
1262 return true;
1263
1264 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001265 } else {
1266 TemplateTemplateParmDecl *TempParm
1267 = cast<TemplateTemplateParmDecl>(*Param);
1268
1269 if (!TempParm->hasDefaultArgument())
1270 break;
1271
John McCallce3ff2b2009-08-25 22:02:44 +00001272 // FIXME: Subst default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001273 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001274 }
1275 } else {
1276 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001277 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001278 }
1279
Douglas Gregorc15cb382009-02-09 23:23:08 +00001280
1281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001282 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001283 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001284 // Check all the remaining arguments (if any).
1285 for (; ArgIdx < NumArgs; ++ArgIdx) {
1286 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1287 Invalid = true;
1288 }
1289
Anders Carlssonfb250522009-06-23 01:26:57 +00001290 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001291 } else {
1292 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1293 Invalid = true;
1294 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001295 } else if (NonTypeTemplateParmDecl *NTTP
1296 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1297 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001298
John McCallce3ff2b2009-08-25 22:02:44 +00001299 // Do substitution on the type of the non-type template parameter
1300 // with the template arguments we've seen thus far.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001301 QualType NTTPType = NTTP->getType();
1302 if (NTTPType->isDependentType()) {
John McCallce3ff2b2009-08-25 22:02:44 +00001303 // Do substitution on the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001304 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001305 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001306 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001307 SourceRange(TemplateLoc, RAngleLoc));
1308
Anders Carlssone9c904b2009-06-05 04:47:51 +00001309 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001310 /*TakeArgs=*/false);
John McCallce3ff2b2009-08-25 22:02:44 +00001311 NTTPType = SubstType(NTTPType, TemplateArgs,
1312 NTTP->getLocation(),
1313 NTTP->getDeclName());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001314 // If that worked, check the non-type template parameter type
1315 // for validity.
1316 if (!NTTPType.isNull())
1317 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1318 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001319 if (NTTPType.isNull()) {
1320 Invalid = true;
1321 break;
1322 }
1323 }
1324
Douglas Gregor40808ce2009-03-09 23:48:35 +00001325 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001326 case TemplateArgument::Null:
1327 assert(false && "Should never see a NULL template argument here");
1328 break;
1329
Douglas Gregor40808ce2009-03-09 23:48:35 +00001330 case TemplateArgument::Expression: {
1331 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001332 TemplateArgument Result;
1333 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001334 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001335 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001336 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001337 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001338 }
1339
Douglas Gregor40808ce2009-03-09 23:48:35 +00001340 case TemplateArgument::Declaration:
1341 case TemplateArgument::Integral:
1342 // We've already checked this template argument, so just copy
1343 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001344 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001345 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001346
Douglas Gregor40808ce2009-03-09 23:48:35 +00001347 case TemplateArgument::Type:
1348 // We have a non-type template parameter but the template
1349 // argument is a type.
1350
1351 // C++ [temp.arg]p2:
1352 // In a template-argument, an ambiguity between a type-id and
1353 // an expression is resolved to a type-id, regardless of the
1354 // form of the corresponding template-parameter.
1355 //
1356 // We warn specifically about this case, since it can be rather
1357 // confusing for users.
1358 if (Arg.getAsType()->isFunctionType())
1359 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1360 << Arg.getAsType();
1361 else
1362 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1363 Diag((*Param)->getLocation(), diag::note_template_param_here);
1364 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001365 break;
1366
1367 case TemplateArgument::Pack:
1368 assert(0 && "FIXME: Implement!");
1369 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001370 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001371 } else {
1372 // Check template template parameters.
1373 TemplateTemplateParmDecl *TempParm
1374 = cast<TemplateTemplateParmDecl>(*Param);
1375
Douglas Gregor40808ce2009-03-09 23:48:35 +00001376 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001377 case TemplateArgument::Null:
1378 assert(false && "Should never see a NULL template argument here");
1379 break;
1380
Douglas Gregor40808ce2009-03-09 23:48:35 +00001381 case TemplateArgument::Expression: {
1382 Expr *ArgExpr = Arg.getAsExpr();
1383 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1384 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1385 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1386 Invalid = true;
1387
1388 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001389 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001390 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001391 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001392 continue;
1393 }
1394 }
1395 // fall through
1396
1397 case TemplateArgument::Type: {
1398 // We have a template template parameter but the template
1399 // argument does not refer to a template.
1400 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1401 Invalid = true;
1402 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001403 }
1404
Douglas Gregor40808ce2009-03-09 23:48:35 +00001405 case TemplateArgument::Declaration:
1406 // We've already checked this template argument, so just copy
1407 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001408 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001409 break;
1410
1411 case TemplateArgument::Integral:
1412 assert(false && "Integral argument with template template parameter");
1413 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001414
1415 case TemplateArgument::Pack:
1416 assert(0 && "FIXME: Implement!");
1417 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001418 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001419 }
1420 }
1421
1422 return Invalid;
1423}
1424
1425/// \brief Check a template argument against its corresponding
1426/// template type parameter.
1427///
1428/// This routine implements the semantics of C++ [temp.arg.type]. It
1429/// returns true if an error occurred, and false otherwise.
1430bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1431 QualType Arg, SourceLocation ArgLoc) {
1432 // C++ [temp.arg.type]p2:
1433 // A local type, a type with no linkage, an unnamed type or a type
1434 // compounded from any of these types shall not be used as a
1435 // template-argument for a template type-parameter.
1436 //
1437 // FIXME: Perform the recursive and no-linkage type checks.
1438 const TagType *Tag = 0;
1439 if (const EnumType *EnumT = Arg->getAsEnumType())
1440 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001441 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001442 Tag = RecordT;
1443 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1444 return Diag(ArgLoc, diag::err_template_arg_local_type)
1445 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001446 else if (Tag && !Tag->getDecl()->getDeclName() &&
1447 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001448 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1449 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1450 return true;
1451 }
1452
1453 return false;
1454}
1455
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001456/// \brief Checks whether the given template argument is the address
1457/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001458bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1459 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001460 bool Invalid = false;
1461
1462 // See through any implicit casts we added to fix the type.
1463 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1464 Arg = Cast->getSubExpr();
1465
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001466 // C++0x allows nullptr, and there's no further checking to be done for that.
1467 if (Arg->getType()->isNullPtrType())
1468 return false;
1469
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001470 // C++ [temp.arg.nontype]p1:
1471 //
1472 // A template-argument for a non-type, non-template
1473 // template-parameter shall be one of: [...]
1474 //
1475 // -- the address of an object or function with external
1476 // linkage, including function templates and function
1477 // template-ids but excluding non-static class members,
1478 // expressed as & id-expression where the & is optional if
1479 // the name refers to a function or array, or if the
1480 // corresponding template-parameter is a reference; or
1481 DeclRefExpr *DRE = 0;
1482
1483 // Ignore (and complain about) any excess parentheses.
1484 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1485 if (!Invalid) {
1486 Diag(Arg->getSourceRange().getBegin(),
1487 diag::err_template_arg_extra_parens)
1488 << Arg->getSourceRange();
1489 Invalid = true;
1490 }
1491
1492 Arg = Parens->getSubExpr();
1493 }
1494
1495 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1496 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1497 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1498 } else
1499 DRE = dyn_cast<DeclRefExpr>(Arg);
1500
1501 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1502 return Diag(Arg->getSourceRange().getBegin(),
1503 diag::err_template_arg_not_object_or_func_form)
1504 << Arg->getSourceRange();
1505
1506 // Cannot refer to non-static data members
1507 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1508 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1509 << Field << Arg->getSourceRange();
1510
1511 // Cannot refer to non-static member functions
1512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1513 if (!Method->isStatic())
1514 return Diag(Arg->getSourceRange().getBegin(),
1515 diag::err_template_arg_method)
1516 << Method << Arg->getSourceRange();
1517
1518 // Functions must have external linkage.
1519 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1520 if (Func->getStorageClass() == FunctionDecl::Static) {
1521 Diag(Arg->getSourceRange().getBegin(),
1522 diag::err_template_arg_function_not_extern)
1523 << Func << Arg->getSourceRange();
1524 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1525 << true;
1526 return true;
1527 }
1528
1529 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001530 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001531 return Invalid;
1532 }
1533
1534 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1535 if (!Var->hasGlobalStorage()) {
1536 Diag(Arg->getSourceRange().getBegin(),
1537 diag::err_template_arg_object_not_extern)
1538 << Var << Arg->getSourceRange();
1539 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1540 << true;
1541 return true;
1542 }
1543
1544 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001545 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001546 return Invalid;
1547 }
1548
1549 // We found something else, but we don't know specifically what it is.
1550 Diag(Arg->getSourceRange().getBegin(),
1551 diag::err_template_arg_not_object_or_func)
1552 << Arg->getSourceRange();
1553 Diag(DRE->getDecl()->getLocation(),
1554 diag::note_template_arg_refers_here);
1555 return true;
1556}
1557
1558/// \brief Checks whether the given template argument is a pointer to
1559/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001560bool
1561Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001562 bool Invalid = false;
1563
1564 // See through any implicit casts we added to fix the type.
1565 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1566 Arg = Cast->getSubExpr();
1567
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001568 // C++0x allows nullptr, and there's no further checking to be done for that.
1569 if (Arg->getType()->isNullPtrType())
1570 return false;
1571
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001572 // C++ [temp.arg.nontype]p1:
1573 //
1574 // A template-argument for a non-type, non-template
1575 // template-parameter shall be one of: [...]
1576 //
1577 // -- a pointer to member expressed as described in 5.3.1.
1578 QualifiedDeclRefExpr *DRE = 0;
1579
1580 // Ignore (and complain about) any excess parentheses.
1581 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1582 if (!Invalid) {
1583 Diag(Arg->getSourceRange().getBegin(),
1584 diag::err_template_arg_extra_parens)
1585 << Arg->getSourceRange();
1586 Invalid = true;
1587 }
1588
1589 Arg = Parens->getSubExpr();
1590 }
1591
1592 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1593 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1594 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1595
1596 if (!DRE)
1597 return Diag(Arg->getSourceRange().getBegin(),
1598 diag::err_template_arg_not_pointer_to_member_form)
1599 << Arg->getSourceRange();
1600
1601 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1602 assert((isa<FieldDecl>(DRE->getDecl()) ||
1603 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1604 "Only non-static member pointers can make it here");
1605
1606 // Okay: this is the address of a non-static member, and therefore
1607 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001608 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001609 return Invalid;
1610 }
1611
1612 // We found something else, but we don't know specifically what it is.
1613 Diag(Arg->getSourceRange().getBegin(),
1614 diag::err_template_arg_not_pointer_to_member_form)
1615 << Arg->getSourceRange();
1616 Diag(DRE->getDecl()->getLocation(),
1617 diag::note_template_arg_refers_here);
1618 return true;
1619}
1620
Douglas Gregorc15cb382009-02-09 23:23:08 +00001621/// \brief Check a template argument against its corresponding
1622/// non-type template parameter.
1623///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001624/// This routine implements the semantics of C++ [temp.arg.nontype].
1625/// It returns true if an error occurred, and false otherwise. \p
1626/// InstantiatedParamType is the type of the non-type template
1627/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001628///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001629/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001630bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001631 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001632 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001633 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1634
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001635 // If either the parameter has a dependent type or the argument is
1636 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001637 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001638 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1639 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001640 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001641 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001642 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001643
1644 // C++ [temp.arg.nontype]p5:
1645 // The following conversions are performed on each expression used
1646 // as a non-type template-argument. If a non-type
1647 // template-argument cannot be converted to the type of the
1648 // corresponding template-parameter then the program is
1649 // ill-formed.
1650 //
1651 // -- for a non-type template-parameter of integral or
1652 // enumeration type, integral promotions (4.5) and integral
1653 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001654 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001655 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001656 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001657 // C++ [temp.arg.nontype]p1:
1658 // A template-argument for a non-type, non-template
1659 // template-parameter shall be one of:
1660 //
1661 // -- an integral constant-expression of integral or enumeration
1662 // type; or
1663 // -- the name of a non-type template-parameter; or
1664 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001665 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001666 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1667 Diag(Arg->getSourceRange().getBegin(),
1668 diag::err_template_arg_not_integral_or_enumeral)
1669 << ArgType << Arg->getSourceRange();
1670 Diag(Param->getLocation(), diag::note_template_param_here);
1671 return true;
1672 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001673 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001674 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1675 << ArgType << Arg->getSourceRange();
1676 return true;
1677 }
1678
1679 // FIXME: We need some way to more easily get the unqualified form
1680 // of the types without going all the way to the
1681 // canonical type.
1682 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1683 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1684 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1685 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1686
1687 // Try to convert the argument to the parameter's type.
1688 if (ParamType == ArgType) {
1689 // Okay: no conversion necessary
1690 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1691 !ParamType->isEnumeralType()) {
1692 // This is an integral promotion or conversion.
1693 ImpCastExprToType(Arg, ParamType);
1694 } else {
1695 // We can't perform this conversion.
1696 Diag(Arg->getSourceRange().getBegin(),
1697 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001698 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001699 Diag(Param->getLocation(), diag::note_template_param_here);
1700 return true;
1701 }
1702
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001703 QualType IntegerType = Context.getCanonicalType(ParamType);
1704 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001705 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001706
1707 if (!Arg->isValueDependent()) {
1708 // Check that an unsigned parameter does not receive a negative
1709 // value.
1710 if (IntegerType->isUnsignedIntegerType()
1711 && (Value.isSigned() && Value.isNegative())) {
1712 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1713 << Value.toString(10) << Param->getType()
1714 << Arg->getSourceRange();
1715 Diag(Param->getLocation(), diag::note_template_param_here);
1716 return true;
1717 }
1718
1719 // Check that we don't overflow the template parameter type.
1720 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1721 if (Value.getActiveBits() > AllowedBits) {
1722 Diag(Arg->getSourceRange().getBegin(),
1723 diag::err_template_arg_too_large)
1724 << Value.toString(10) << Param->getType()
1725 << Arg->getSourceRange();
1726 Diag(Param->getLocation(), diag::note_template_param_here);
1727 return true;
1728 }
1729
1730 if (Value.getBitWidth() != AllowedBits)
1731 Value.extOrTrunc(AllowedBits);
1732 Value.setIsSigned(IntegerType->isSignedIntegerType());
1733 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001734
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001735 // Add the value of this argument to the list of converted
1736 // arguments. We use the bitwidth and signedness of the template
1737 // parameter.
1738 if (Arg->isValueDependent()) {
1739 // The argument is value-dependent. Create a new
1740 // TemplateArgument with the converted expression.
1741 Converted = TemplateArgument(Arg);
1742 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001743 }
1744
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001745 Converted = TemplateArgument(StartLoc, Value,
1746 ParamType->isEnumeralType() ? ParamType
1747 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001748 return false;
1749 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001750
Douglas Gregorb86b0572009-02-11 01:18:59 +00001751 // Handle pointer-to-function, reference-to-function, and
1752 // pointer-to-member-function all in (roughly) the same way.
1753 if (// -- For a non-type template-parameter of type pointer to
1754 // function, only the function-to-pointer conversion (4.3) is
1755 // applied. If the template-argument represents a set of
1756 // overloaded functions (or a pointer to such), the matching
1757 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001758 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001759 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001760 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001761 // -- For a non-type template-parameter of type reference to
1762 // function, no conversions apply. If the template-argument
1763 // represents a set of overloaded functions, the matching
1764 // function is selected from the set (13.4).
1765 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001766 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001767 // -- For a non-type template-parameter of type pointer to
1768 // member function, no conversions apply. If the
1769 // template-argument represents a set of overloaded member
1770 // functions, the matching member function is selected from
1771 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001772 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001773 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001774 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001775 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001776 if (Context.hasSameUnqualifiedType(ArgType,
1777 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001778 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001779 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1780 ParamType->isMemberPointerType())) {
1781 ArgType = ParamType;
1782 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001783 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001784 ArgType = Context.getPointerType(ArgType);
1785 ImpCastExprToType(Arg, ArgType);
1786 } else if (FunctionDecl *Fn
1787 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001788 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1789 return true;
1790
Douglas Gregora35284b2009-02-11 00:19:33 +00001791 FixOverloadedFunctionReference(Arg, Fn);
1792 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001793 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001794 ArgType = Context.getPointerType(Arg->getType());
1795 ImpCastExprToType(Arg, ArgType);
1796 }
1797 }
1798
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001799 if (!Context.hasSameUnqualifiedType(ArgType,
1800 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001801 // We can't perform this conversion.
1802 Diag(Arg->getSourceRange().getBegin(),
1803 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001804 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001805 Diag(Param->getLocation(), diag::note_template_param_here);
1806 return true;
1807 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001808
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001809 if (ParamType->isMemberPointerType()) {
1810 NamedDecl *Member = 0;
1811 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1812 return true;
1813
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001814 if (Member)
1815 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001816 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001817 return false;
1818 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001819
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001820 NamedDecl *Entity = 0;
1821 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1822 return true;
1823
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001824 if (Entity)
1825 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001826 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001827 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001828 }
1829
Chris Lattnerfe90de72009-02-20 21:37:53 +00001830 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001831 // -- for a non-type template-parameter of type pointer to
1832 // object, qualification conversions (4.4) and the
1833 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001834 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00001835 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001836 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001837
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001838 if (ArgType->isNullPtrType()) {
1839 ArgType = ParamType;
1840 ImpCastExprToType(Arg, ParamType);
1841 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001842 ArgType = Context.getArrayDecayedType(ArgType);
1843 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001844 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001845
Douglas Gregorb86b0572009-02-11 01:18:59 +00001846 if (IsQualificationConversion(ArgType, ParamType)) {
1847 ArgType = ParamType;
1848 ImpCastExprToType(Arg, ParamType);
1849 }
1850
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001851 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001852 // We can't perform this conversion.
1853 Diag(Arg->getSourceRange().getBegin(),
1854 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001855 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001856 Diag(Param->getLocation(), diag::note_template_param_here);
1857 return true;
1858 }
1859
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001860 NamedDecl *Entity = 0;
1861 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1862 return true;
1863
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001864 if (Entity)
1865 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001866 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001867 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001868 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001869
Ted Kremenek6217b802009-07-29 21:53:49 +00001870 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001871 // -- For a non-type template-parameter of type reference to
1872 // object, no conversions apply. The type referred to by the
1873 // reference may be more cv-qualified than the (otherwise
1874 // identical) type of the template-argument. The
1875 // template-parameter is bound directly to the
1876 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001877 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001878 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001879
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001880 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001881 Diag(Arg->getSourceRange().getBegin(),
1882 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001883 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001884 << Arg->getSourceRange();
1885 Diag(Param->getLocation(), diag::note_template_param_here);
1886 return true;
1887 }
1888
1889 unsigned ParamQuals
1890 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1891 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1892
1893 if ((ParamQuals | ArgQuals) != ParamQuals) {
1894 Diag(Arg->getSourceRange().getBegin(),
1895 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001896 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001897 << Arg->getSourceRange();
1898 Diag(Param->getLocation(), diag::note_template_param_here);
1899 return true;
1900 }
1901
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001902 NamedDecl *Entity = 0;
1903 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1904 return true;
1905
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001906 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001907 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001908 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001909 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001910
1911 // -- For a non-type template-parameter of type pointer to data
1912 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001913 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001914 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1915
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001916 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001917 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001918 } else if (ArgType->isNullPtrType()) {
1919 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001920 } else if (IsQualificationConversion(ArgType, ParamType)) {
1921 ImpCastExprToType(Arg, ParamType);
1922 } else {
1923 // We can't perform this conversion.
1924 Diag(Arg->getSourceRange().getBegin(),
1925 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001926 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001927 Diag(Param->getLocation(), diag::note_template_param_here);
1928 return true;
1929 }
1930
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001931 NamedDecl *Member = 0;
1932 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1933 return true;
1934
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001935 if (Member)
1936 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001937 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001938 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001939}
1940
1941/// \brief Check a template argument against its corresponding
1942/// template template parameter.
1943///
1944/// This routine implements the semantics of C++ [temp.arg.template].
1945/// It returns true if an error occurred, and false otherwise.
1946bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1947 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001948 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1949 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1950
1951 // C++ [temp.arg.template]p1:
1952 // A template-argument for a template template-parameter shall be
1953 // the name of a class template, expressed as id-expression. Only
1954 // primary class templates are considered when matching the
1955 // template template argument with the corresponding parameter;
1956 // partial specializations are not considered even if their
1957 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001958 //
1959 // Note that we also allow template template parameters here, which
1960 // will happen when we are dealing with, e.g., class template
1961 // partial specializations.
1962 if (!isa<ClassTemplateDecl>(Template) &&
1963 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001964 assert(isa<FunctionTemplateDecl>(Template) &&
1965 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001966 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1967 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001968 << Template;
1969 }
1970
1971 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1972 Param->getTemplateParameters(),
1973 true, true,
1974 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001975}
1976
Douglas Gregorddc29e12009-02-06 22:42:48 +00001977/// \brief Determine whether the given template parameter lists are
1978/// equivalent.
1979///
1980/// \param New The new template parameter list, typically written in the
1981/// source code as part of a new template declaration.
1982///
1983/// \param Old The old template parameter list, typically found via
1984/// name lookup of the template declared with this template parameter
1985/// list.
1986///
1987/// \param Complain If true, this routine will produce a diagnostic if
1988/// the template parameter lists are not equivalent.
1989///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001990/// \param IsTemplateTemplateParm If true, this routine is being
1991/// called to compare the template parameter lists of a template
1992/// template parameter.
1993///
1994/// \param TemplateArgLoc If this source location is valid, then we
1995/// are actually checking the template parameter list of a template
1996/// argument (New) against the template parameter list of its
1997/// corresponding template template parameter (Old). We produce
1998/// slightly different diagnostics in this scenario.
1999///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002000/// \returns True if the template parameter lists are equal, false
2001/// otherwise.
2002bool
2003Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2004 TemplateParameterList *Old,
2005 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002006 bool IsTemplateTemplateParm,
2007 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002008 if (Old->size() != New->size()) {
2009 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002010 unsigned NextDiag = diag::err_template_param_list_different_arity;
2011 if (TemplateArgLoc.isValid()) {
2012 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2013 NextDiag = diag::note_template_param_list_different_arity;
2014 }
2015 Diag(New->getTemplateLoc(), NextDiag)
2016 << (New->size() > Old->size())
2017 << IsTemplateTemplateParm
2018 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002019 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2020 << IsTemplateTemplateParm
2021 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2022 }
2023
2024 return false;
2025 }
2026
2027 for (TemplateParameterList::iterator OldParm = Old->begin(),
2028 OldParmEnd = Old->end(), NewParm = New->begin();
2029 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2030 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002031 if (Complain) {
2032 unsigned NextDiag = diag::err_template_param_different_kind;
2033 if (TemplateArgLoc.isValid()) {
2034 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2035 NextDiag = diag::note_template_param_different_kind;
2036 }
2037 Diag((*NewParm)->getLocation(), NextDiag)
2038 << IsTemplateTemplateParm;
2039 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2040 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002041 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002042 return false;
2043 }
2044
2045 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2046 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002047 // know we're at the same index).
2048#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002049 // FIXME: Enable this code in debug mode *after* we properly go through
2050 // and "instantiate" the template parameter lists of template template
2051 // parameters. It's only after this instantiation that (1) any dependent
2052 // types within the template parameter list of the template template
2053 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002054 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00002055 QualType OldParmType
2056 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2057 QualType NewParmType
2058 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2059 assert(Context.getCanonicalType(OldParmType) ==
2060 Context.getCanonicalType(NewParmType) &&
2061 "type parameter mismatch?");
2062#endif
2063 } else if (NonTypeTemplateParmDecl *OldNTTP
2064 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2065 // The types of non-type template parameters must agree.
2066 NonTypeTemplateParmDecl *NewNTTP
2067 = cast<NonTypeTemplateParmDecl>(*NewParm);
2068 if (Context.getCanonicalType(OldNTTP->getType()) !=
2069 Context.getCanonicalType(NewNTTP->getType())) {
2070 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002071 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2072 if (TemplateArgLoc.isValid()) {
2073 Diag(TemplateArgLoc,
2074 diag::err_template_arg_template_params_mismatch);
2075 NextDiag = diag::note_template_nontype_parm_different_type;
2076 }
2077 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002078 << NewNTTP->getType()
2079 << IsTemplateTemplateParm;
2080 Diag(OldNTTP->getLocation(),
2081 diag::note_template_nontype_parm_prev_declaration)
2082 << OldNTTP->getType();
2083 }
2084 return false;
2085 }
2086 } else {
2087 // The template parameter lists of template template
2088 // parameters must agree.
2089 // FIXME: Could we perform a faster "type" comparison here?
2090 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2091 "Only template template parameters handled here");
2092 TemplateTemplateParmDecl *OldTTP
2093 = cast<TemplateTemplateParmDecl>(*OldParm);
2094 TemplateTemplateParmDecl *NewTTP
2095 = cast<TemplateTemplateParmDecl>(*NewParm);
2096 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2097 OldTTP->getTemplateParameters(),
2098 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002099 /*IsTemplateTemplateParm=*/true,
2100 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002101 return false;
2102 }
2103 }
2104
2105 return true;
2106}
2107
2108/// \brief Check whether a template can be declared within this scope.
2109///
2110/// If the template declaration is valid in this scope, returns
2111/// false. Otherwise, issues a diagnostic and returns true.
2112bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002113Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002114 // Find the nearest enclosing declaration scope.
2115 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2116 (S->getFlags() & Scope::TemplateParamScope) != 0)
2117 S = S->getParent();
2118
Douglas Gregorddc29e12009-02-06 22:42:48 +00002119 // C++ [temp]p2:
2120 // A template-declaration can appear only as a namespace scope or
2121 // class scope declaration.
2122 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002123 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2124 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Douglas Gregor05396e22009-08-25 17:23:04 +00002125 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2126 << TemplateParams->getSourceRange();
Eli Friedman1503f772009-07-31 01:43:05 +00002127
2128 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002129 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002130
2131 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2132 return false;
2133
Douglas Gregor05396e22009-08-25 17:23:04 +00002134 return Diag(TemplateParams->getTemplateLoc(),
2135 diag::err_template_outside_namespace_or_class_scope)
2136 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002137}
Douglas Gregorcc636682009-02-17 23:15:12 +00002138
Douglas Gregorff668032009-05-13 18:28:20 +00002139/// \brief Check whether a class template specialization or explicit
2140/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002141///
Douglas Gregorff668032009-05-13 18:28:20 +00002142/// This routine determines whether a class template specialization or
2143/// explicit instantiation can be declared in the current context
2144/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2145/// appropriate diagnostics if there was an error. It returns true if
2146// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002147bool
2148Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2149 ClassTemplateSpecializationDecl *PrevDecl,
2150 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002151 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002152 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002153 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002154 // C++ [temp.expl.spec]p2:
2155 // An explicit specialization shall be declared in the namespace
2156 // of which the template is a member, or, for member templates, in
2157 // the namespace of which the enclosing class or enclosing class
2158 // template is a member. An explicit specialization of a member
2159 // function, member class or static data member of a class
2160 // template shall be declared in the namespace of which the class
2161 // template is a member. Such a declaration may also be a
2162 // definition. If the declaration is not a definition, the
2163 // specialization may be defined later in the name- space in which
2164 // the explicit specialization was declared, or in a namespace
2165 // that encloses the one in which the explicit specialization was
2166 // declared.
2167 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002168 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002169 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002170 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002171 return true;
2172 }
2173
2174 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2175 DeclContext *TemplateContext
2176 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002177 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2178 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002179 // There is no prior declaration of this entity, so this
2180 // specialization must be in the same context as the template
2181 // itself.
2182 if (DC != TemplateContext) {
2183 if (isa<TranslationUnitDecl>(TemplateContext))
2184 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002185 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002186 << ClassTemplate << ScopeSpecifierRange;
2187 else if (isa<NamespaceDecl>(TemplateContext))
2188 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002189 << PartialSpecialization << ClassTemplate
2190 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002191
2192 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2193 }
2194
2195 return false;
2196 }
2197
2198 // We have a previous declaration of this entity. Make sure that
2199 // this redeclaration (or definition) occurs in an enclosing namespace.
2200 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002201 // FIXME: In C++98, we would like to turn these errors into warnings,
2202 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002203 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002204 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002205 if (isa<TranslationUnitDecl>(TemplateContext)) {
2206 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2207 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002208 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002209 else
2210 SuppressedDiag = true;
2211 } else if (isa<NamespaceDecl>(TemplateContext)) {
2212 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2213 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002214 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002215 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2216 else
2217 SuppressedDiag = true;
2218 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002219
Douglas Gregorff668032009-05-13 18:28:20 +00002220 if (!SuppressedDiag)
2221 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002222 }
2223
2224 return false;
2225}
2226
Douglas Gregore94866f2009-06-12 21:21:02 +00002227/// \brief Check the non-type template arguments of a class template
2228/// partial specialization according to C++ [temp.class.spec]p9.
2229///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002230/// \param TemplateParams the template parameters of the primary class
2231/// template.
2232///
2233/// \param TemplateArg the template arguments of the class template
2234/// partial specialization.
2235///
2236/// \param MirrorsPrimaryTemplate will be set true if the class
2237/// template partial specialization arguments are identical to the
2238/// implicit template arguments of the primary template. This is not
2239/// necessarily an error (C++0x), and it is left to the caller to diagnose
2240/// this condition when it is an error.
2241///
Douglas Gregore94866f2009-06-12 21:21:02 +00002242/// \returns true if there was an error, false otherwise.
2243bool Sema::CheckClassTemplatePartialSpecializationArgs(
2244 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002245 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002246 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002247 // FIXME: the interface to this function will have to change to
2248 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002249 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002250
Anders Carlssonfb250522009-06-23 01:26:57 +00002251 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002252
Douglas Gregore94866f2009-06-12 21:21:02 +00002253 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002254 // Determine whether the template argument list of the partial
2255 // specialization is identical to the implicit argument list of
2256 // the primary template. The caller may need to diagnostic this as
2257 // an error per C++ [temp.class.spec]p9b3.
2258 if (MirrorsPrimaryTemplate) {
2259 if (TemplateTypeParmDecl *TTP
2260 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2261 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002262 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002263 MirrorsPrimaryTemplate = false;
2264 } else if (TemplateTemplateParmDecl *TTP
2265 = dyn_cast<TemplateTemplateParmDecl>(
2266 TemplateParams->getParam(I))) {
2267 // FIXME: We should settle on either Declaration storage or
2268 // Expression storage for template template parameters.
2269 TemplateTemplateParmDecl *ArgDecl
2270 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002271 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002272 if (!ArgDecl)
2273 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002274 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002275 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2276
2277 if (!ArgDecl ||
2278 ArgDecl->getIndex() != TTP->getIndex() ||
2279 ArgDecl->getDepth() != TTP->getDepth())
2280 MirrorsPrimaryTemplate = false;
2281 }
2282 }
2283
Douglas Gregore94866f2009-06-12 21:21:02 +00002284 NonTypeTemplateParmDecl *Param
2285 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002286 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002287 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002288 }
2289
Anders Carlsson6360be72009-06-13 18:20:51 +00002290 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002291 if (!ArgExpr) {
2292 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002293 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002294 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002295
2296 // C++ [temp.class.spec]p8:
2297 // A non-type argument is non-specialized if it is the name of a
2298 // non-type parameter. All other non-type arguments are
2299 // specialized.
2300 //
2301 // Below, we check the two conditions that only apply to
2302 // specialized non-type arguments, so skip any non-specialized
2303 // arguments.
2304 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002305 if (NonTypeTemplateParmDecl *NTTP
2306 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2307 if (MirrorsPrimaryTemplate &&
2308 (Param->getIndex() != NTTP->getIndex() ||
2309 Param->getDepth() != NTTP->getDepth()))
2310 MirrorsPrimaryTemplate = false;
2311
Douglas Gregore94866f2009-06-12 21:21:02 +00002312 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002313 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002314
2315 // C++ [temp.class.spec]p9:
2316 // Within the argument list of a class template partial
2317 // specialization, the following restrictions apply:
2318 // -- A partially specialized non-type argument expression
2319 // shall not involve a template parameter of the partial
2320 // specialization except when the argument expression is a
2321 // simple identifier.
2322 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2323 Diag(ArgExpr->getLocStart(),
2324 diag::err_dependent_non_type_arg_in_partial_spec)
2325 << ArgExpr->getSourceRange();
2326 return true;
2327 }
2328
2329 // -- The type of a template parameter corresponding to a
2330 // specialized non-type argument shall not be dependent on a
2331 // parameter of the specialization.
2332 if (Param->getType()->isDependentType()) {
2333 Diag(ArgExpr->getLocStart(),
2334 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2335 << Param->getType()
2336 << ArgExpr->getSourceRange();
2337 Diag(Param->getLocation(), diag::note_template_param_here);
2338 return true;
2339 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002340
2341 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002342 }
2343
2344 return false;
2345}
2346
Douglas Gregor212e81c2009-03-25 00:13:59 +00002347Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002348Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2349 TagUseKind TUK,
Douglas Gregorcc636682009-02-17 23:15:12 +00002350 SourceLocation KWLoc,
2351 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002352 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002353 SourceLocation TemplateNameLoc,
2354 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002355 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002356 SourceLocation *TemplateArgLocs,
2357 SourceLocation RAngleLoc,
2358 AttributeList *Attr,
2359 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002360 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002361 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002362 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002363 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002364
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002365 bool isPartialSpecialization = false;
2366
Douglas Gregor88b70942009-02-25 22:02:03 +00002367 // Check the validity of the template headers that introduce this
2368 // template.
Douglas Gregor05396e22009-08-25 17:23:04 +00002369 TemplateParameterList *TemplateParams
2370 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2371 (TemplateParameterList**)TemplateParameterLists.get(),
2372 TemplateParameterLists.size());
2373 if (TemplateParams && TemplateParams->size() > 0) {
2374 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002375
Douglas Gregor05396e22009-08-25 17:23:04 +00002376 // C++ [temp.class.spec]p10:
2377 // The template parameter list of a specialization shall not
2378 // contain default template argument values.
2379 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2380 Decl *Param = TemplateParams->getParam(I);
2381 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2382 if (TTP->hasDefaultArgument()) {
2383 Diag(TTP->getDefaultArgumentLoc(),
2384 diag::err_default_arg_in_partial_spec);
2385 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2386 }
2387 } else if (NonTypeTemplateParmDecl *NTTP
2388 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2389 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2390 Diag(NTTP->getDefaultArgumentLoc(),
2391 diag::err_default_arg_in_partial_spec)
2392 << DefArg->getSourceRange();
2393 NTTP->setDefaultArgument(0);
2394 DefArg->Destroy(Context);
2395 }
2396 } else {
2397 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2398 if (Expr *DefArg = TTP->getDefaultArgument()) {
2399 Diag(TTP->getDefaultArgumentLoc(),
2400 diag::err_default_arg_in_partial_spec)
2401 << DefArg->getSourceRange();
2402 TTP->setDefaultArgument(0);
2403 DefArg->Destroy(Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002404 }
2405 }
2406 }
Douglas Gregor05396e22009-08-25 17:23:04 +00002407 } else if (!TemplateParams)
2408 Diag(KWLoc, diag::err_template_spec_needs_header)
2409 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor88b70942009-02-25 22:02:03 +00002410
Douglas Gregorcc636682009-02-17 23:15:12 +00002411 // Check that the specialization uses the same tag kind as the
2412 // original template.
2413 TagDecl::TagKind Kind;
2414 switch (TagSpec) {
2415 default: assert(0 && "Unknown tag type!");
2416 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2417 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2418 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2419 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002420 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2421 Kind, KWLoc,
2422 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002423 Diag(KWLoc, diag::err_use_with_wrong_tag)
2424 << ClassTemplate
2425 << CodeModificationHint::CreateReplacement(KWLoc,
2426 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002427 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2428 diag::note_previous_use);
2429 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2430 }
2431
Douglas Gregor40808ce2009-03-09 23:48:35 +00002432 // Translate the parser's template argument list in our AST format.
2433 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2434 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2435
Douglas Gregorcc636682009-02-17 23:15:12 +00002436 // Check that the template argument list is well-formed for this
2437 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002438 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2439 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002440 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002441 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002442 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002443 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002444
Anders Carlssonfb250522009-06-23 01:26:57 +00002445 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002446 ClassTemplate->getTemplateParameters()->size()) &&
2447 "Converted template argument list is too short!");
2448
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002449 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002450 // corresponds to these arguments.
2451 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002452 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002453 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002454 if (CheckClassTemplatePartialSpecializationArgs(
2455 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002456 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002457 return true;
2458
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002459 if (MirrorsPrimaryTemplate) {
2460 // C++ [temp.class.spec]p9b3:
2461 //
2462 // -- The argument list of the specialization shall not be identical
2463 // to the implicit argument list of the primary template.
2464 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00002465 << (TUK == TUK_Definition)
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002466 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2467 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00002468 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002469 ClassTemplate->getIdentifier(),
2470 TemplateNameLoc,
2471 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00002472 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002473 AS_none);
2474 }
2475
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002476 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002477 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002478 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002479 Converted.flatSize(),
2480 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002481 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002482 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002483 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002484 Converted.flatSize(),
2485 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002486 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002487 ClassTemplateSpecializationDecl *PrevDecl = 0;
2488
2489 if (isPartialSpecialization)
2490 PrevDecl
2491 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2492 InsertPos);
2493 else
2494 PrevDecl
2495 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002496
2497 ClassTemplateSpecializationDecl *Specialization = 0;
2498
Douglas Gregor88b70942009-02-25 22:02:03 +00002499 // Check whether we can declare a class template specialization in
2500 // the current scope.
2501 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2502 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002503 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002504 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002505 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002506 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002507
Douglas Gregorb88e8882009-07-30 17:40:51 +00002508 // The canonical type
2509 QualType CanonType;
Douglas Gregorcc636682009-02-17 23:15:12 +00002510 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2511 // Since the only prior class template specialization with these
2512 // arguments was referenced but not declared, reuse that
2513 // declaration node as our own, updating its source location to
2514 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002515 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002516 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002517 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00002518 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002519 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002520 // Build the canonical type that describes the converted template
2521 // arguments of the class template partial specialization.
2522 CanonType = Context.getTemplateSpecializationType(
2523 TemplateName(ClassTemplate),
2524 Converted.getFlatArguments(),
2525 Converted.flatSize());
2526
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002527 // Create a new class template partial specialization declaration node.
2528 TemplateParameterList *TemplateParams
2529 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2530 ClassTemplatePartialSpecializationDecl *PrevPartial
2531 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2532 ClassTemplatePartialSpecializationDecl *Partial
2533 = ClassTemplatePartialSpecializationDecl::Create(Context,
2534 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002535 TemplateNameLoc,
2536 TemplateParams,
2537 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002538 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002539 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002540
2541 if (PrevPartial) {
2542 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2543 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2544 } else {
2545 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2546 }
2547 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002548
2549 // Check that all of the template parameters of the class template
2550 // partial specialization are deducible from the template
2551 // arguments. If not, this class template partial specialization
2552 // will never be used.
2553 llvm::SmallVector<bool, 8> DeducibleParams;
2554 DeducibleParams.resize(TemplateParams->size());
2555 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2556 unsigned NumNonDeducible = 0;
2557 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2558 if (!DeducibleParams[I])
2559 ++NumNonDeducible;
2560
2561 if (NumNonDeducible) {
2562 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2563 << (NumNonDeducible > 1)
2564 << SourceRange(TemplateNameLoc, RAngleLoc);
2565 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2566 if (!DeducibleParams[I]) {
2567 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2568 if (Param->getDeclName())
2569 Diag(Param->getLocation(),
2570 diag::note_partial_spec_unused_parameter)
2571 << Param->getDeclName();
2572 else
2573 Diag(Param->getLocation(),
2574 diag::note_partial_spec_unused_parameter)
2575 << std::string("<anonymous>");
2576 }
2577 }
2578 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002579 } else {
2580 // Create a new class template specialization declaration node for
2581 // this explicit specialization.
2582 Specialization
2583 = ClassTemplateSpecializationDecl::Create(Context,
2584 ClassTemplate->getDeclContext(),
2585 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002586 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002587 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002588 PrevDecl);
2589
2590 if (PrevDecl) {
2591 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2592 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2593 } else {
2594 ClassTemplate->getSpecializations().InsertNode(Specialization,
2595 InsertPos);
2596 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00002597
2598 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002599 }
2600
2601 // Note that this is an explicit specialization.
2602 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2603
2604 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002605 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002606 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002607 // FIXME: Should also handle explicit specialization after implicit
2608 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002609 SourceRange Range(TemplateNameLoc, RAngleLoc);
2610 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002611 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002612 Diag(Def->getLocation(), diag::note_previous_definition);
2613 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002614 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002615 }
2616 }
2617
Douglas Gregorfc705b82009-02-26 22:19:44 +00002618 // Build the fully-sugared type for this class template
2619 // specialization as the user wrote in the specialization
2620 // itself. This means that we'll pretty-print the type retrieved
2621 // from the specialization's declaration the way that the user
2622 // actually wrote the specialization, rather than formatting the
2623 // name based on the "canonical" representation used to store the
2624 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002625 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002626 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002627 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002628 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00002629 CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +00002630 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002631 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002632
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002633 // C++ [temp.expl.spec]p9:
2634 // A template explicit specialization is in the scope of the
2635 // namespace in which the template was defined.
2636 //
2637 // We actually implement this paragraph where we set the semantic
2638 // context (in the creation of the ClassTemplateSpecializationDecl),
2639 // but we also maintain the lexical context where the actual
2640 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002641 Specialization->setLexicalDeclContext(CurContext);
2642
2643 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002644 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00002645 Specialization->startDefinition();
2646
2647 // Add the specialization into its lexical context, so that it can
2648 // be seen when iterating through the list of declarations in that
2649 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002650 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002651 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002652}
Douglas Gregord57959a2009-03-27 23:10:48 +00002653
Douglas Gregore542c862009-06-23 23:11:28 +00002654Sema::DeclPtrTy
2655Sema::ActOnTemplateDeclarator(Scope *S,
2656 MultiTemplateParamsArg TemplateParameterLists,
2657 Declarator &D) {
2658 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2659}
2660
Douglas Gregor52591bf2009-06-24 00:54:41 +00002661Sema::DeclPtrTy
2662Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2663 MultiTemplateParamsArg TemplateParameterLists,
2664 Declarator &D) {
2665 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2666 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2667 "Not a function declarator!");
2668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2669
2670 if (FTI.hasPrototype) {
2671 // FIXME: Diagnose arguments without names in C.
2672 }
2673
2674 Scope *ParentScope = FnBodyScope->getParent();
2675
2676 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2677 move(TemplateParameterLists),
2678 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002679 if (FunctionTemplateDecl *FunctionTemplate
2680 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002681 return ActOnStartOfFunctionDef(FnBodyScope,
2682 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002683 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2684 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002685 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002686}
2687
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002688// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002689Sema::DeclResult
2690Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2691 unsigned TagSpec,
2692 SourceLocation KWLoc,
2693 const CXXScopeSpec &SS,
2694 TemplateTy TemplateD,
2695 SourceLocation TemplateNameLoc,
2696 SourceLocation LAngleLoc,
2697 ASTTemplateArgsPtr TemplateArgsIn,
2698 SourceLocation *TemplateArgLocs,
2699 SourceLocation RAngleLoc,
2700 AttributeList *Attr) {
2701 // Find the class template we're specializing
2702 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2703 ClassTemplateDecl *ClassTemplate
2704 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2705
2706 // Check that the specialization uses the same tag kind as the
2707 // original template.
2708 TagDecl::TagKind Kind;
2709 switch (TagSpec) {
2710 default: assert(0 && "Unknown tag type!");
2711 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2712 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2713 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2714 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002715 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2716 Kind, KWLoc,
2717 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002718 Diag(KWLoc, diag::err_use_with_wrong_tag)
2719 << ClassTemplate
2720 << CodeModificationHint::CreateReplacement(KWLoc,
2721 ClassTemplate->getTemplatedDecl()->getKindName());
2722 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2723 diag::note_previous_use);
2724 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2725 }
2726
Douglas Gregorff668032009-05-13 18:28:20 +00002727 // C++0x [temp.explicit]p2:
2728 // [...] An explicit instantiation shall appear in an enclosing
2729 // namespace of its template. [...]
2730 //
2731 // This is C++ DR 275.
2732 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2733 TemplateNameLoc,
2734 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002735 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002736 /*ExplicitInstantiation=*/true))
2737 return true;
2738
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002739 // Translate the parser's template argument list in our AST format.
2740 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2741 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2742
2743 // Check that the template argument list is well-formed for this
2744 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002745 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2746 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002747 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002748 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002749 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002750 return true;
2751
Anders Carlssonfb250522009-06-23 01:26:57 +00002752 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002753 ClassTemplate->getTemplateParameters()->size()) &&
2754 "Converted template argument list is too short!");
2755
2756 // Find the class template specialization declaration that
2757 // corresponds to these arguments.
2758 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002759 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002760 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002761 Converted.flatSize(),
2762 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002763 void *InsertPos = 0;
2764 ClassTemplateSpecializationDecl *PrevDecl
2765 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2766
2767 ClassTemplateSpecializationDecl *Specialization = 0;
2768
Douglas Gregorff668032009-05-13 18:28:20 +00002769 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002770 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002771 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002772 // This particular specialization has already been declared or
2773 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002774 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2775 << Context.getTypeDeclType(PrevDecl);
2776 Diag(PrevDecl->getLocation(),
2777 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002778 return DeclPtrTy::make(PrevDecl);
2779 }
2780
Douglas Gregorff668032009-05-13 18:28:20 +00002781 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002782 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002783 // For a given set of template parameters, if an explicit
2784 // instantiation of a template appears after a declaration of
2785 // an explicit specialization for that template, the explicit
2786 // instantiation has no effect.
2787 if (!getLangOptions().CPlusPlus0x) {
2788 Diag(TemplateNameLoc,
2789 diag::ext_explicit_instantiation_after_specialization)
2790 << Context.getTypeDeclType(PrevDecl);
2791 Diag(PrevDecl->getLocation(),
2792 diag::note_previous_template_specialization);
2793 }
2794
2795 // Create a new class template specialization declaration node
2796 // for this explicit specialization. This node is only used to
2797 // record the existence of this explicit instantiation for
2798 // accurate reproduction of the source code; we don't actually
2799 // use it for anything, since it is semantically irrelevant.
2800 Specialization
2801 = ClassTemplateSpecializationDecl::Create(Context,
2802 ClassTemplate->getDeclContext(),
2803 TemplateNameLoc,
2804 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002805 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002806 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002807 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002808 return DeclPtrTy::make(Specialization);
2809 }
2810
2811 // If we have already (implicitly) instantiated this
2812 // specialization, there is less work to do.
2813 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2814 SpecializationRequiresInstantiation = false;
2815
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002816 // Since the only prior class template specialization with these
2817 // arguments was referenced but not declared, reuse that
2818 // declaration node as our own, updating its source location to
2819 // reflect our new declaration.
2820 Specialization = PrevDecl;
2821 Specialization->setLocation(TemplateNameLoc);
2822 PrevDecl = 0;
2823 } else {
2824 // Create a new class template specialization declaration node for
2825 // this explicit specialization.
2826 Specialization
2827 = ClassTemplateSpecializationDecl::Create(Context,
2828 ClassTemplate->getDeclContext(),
2829 TemplateNameLoc,
2830 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002831 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002832
2833 ClassTemplate->getSpecializations().InsertNode(Specialization,
2834 InsertPos);
2835 }
2836
2837 // Build the fully-sugared type for this explicit instantiation as
2838 // the user wrote in the explicit instantiation itself. This means
2839 // that we'll pretty-print the type retrieved from the
2840 // specialization's declaration the way that the user actually wrote
2841 // the explicit instantiation, rather than formatting the name based
2842 // on the "canonical" representation used to store the template
2843 // arguments in the specialization.
2844 QualType WrittenTy
2845 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002846 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002847 TemplateArgs.size(),
2848 Context.getTypeDeclType(Specialization));
2849 Specialization->setTypeAsWritten(WrittenTy);
2850 TemplateArgsIn.release();
2851
2852 // Add the explicit instantiation into its lexical context. However,
2853 // since explicit instantiations are never found by name lookup, we
2854 // just put it into the declaration context directly.
2855 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002856 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002857
2858 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002859 // A definition of a class template or class member template
2860 // shall be in scope at the point of the explicit instantiation of
2861 // the class template or class member template.
2862 //
2863 // This check comes when we actually try to perform the
2864 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002865 if (SpecializationRequiresInstantiation)
2866 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002867 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002868 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002869
2870 return DeclPtrTy::make(Specialization);
2871}
2872
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002873// Explicit instantiation of a member class of a class template.
2874Sema::DeclResult
2875Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2876 unsigned TagSpec,
2877 SourceLocation KWLoc,
2878 const CXXScopeSpec &SS,
2879 IdentifierInfo *Name,
2880 SourceLocation NameLoc,
2881 AttributeList *Attr) {
2882
Douglas Gregor402abb52009-05-28 23:31:59 +00002883 bool Owned = false;
John McCall0f434ec2009-07-31 02:45:11 +00002884 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002885 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2886 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002887 if (!TagD)
2888 return true;
2889
2890 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2891 if (Tag->isEnum()) {
2892 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2893 << Context.getTypeDeclType(Tag);
2894 return true;
2895 }
2896
Douglas Gregord0c87372009-05-27 17:30:49 +00002897 if (Tag->isInvalidDecl())
2898 return true;
2899
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002900 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2901 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2902 if (!Pattern) {
2903 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2904 << Context.getTypeDeclType(Record);
2905 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2906 return true;
2907 }
2908
2909 // C++0x [temp.explicit]p2:
2910 // [...] An explicit instantiation shall appear in an enclosing
2911 // namespace of its template. [...]
2912 //
2913 // This is C++ DR 275.
2914 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002915 // FIXME: In C++98, we would like to turn these errors into warnings,
2916 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002917 DeclContext *PatternContext
2918 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2919 if (!CurContext->Encloses(PatternContext)) {
2920 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2921 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2922 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2923 }
2924 }
2925
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002926 if (!Record->getDefinition(Context)) {
2927 // If the class has a definition, instantiate it (and all of its
2928 // members, recursively).
2929 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2930 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002931 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002932 /*ExplicitInstantiation=*/true))
2933 return true;
John McCallce3ff2b2009-08-25 22:02:44 +00002934 } else // Instantiate all of the members of the class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002935 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002936 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002937
Mike Stump390b4cc2009-05-16 07:39:55 +00002938 // FIXME: We don't have any representation for explicit instantiations of
2939 // member classes. Such a representation is not needed for compilation, but it
2940 // should be available for clients that want to see all of the declarations in
2941 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002942 return TagD;
2943}
2944
Douglas Gregord57959a2009-03-27 23:10:48 +00002945Sema::TypeResult
2946Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2947 const IdentifierInfo &II, SourceLocation IdLoc) {
2948 NestedNameSpecifier *NNS
2949 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2950 if (!NNS)
2951 return true;
2952
2953 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002954 if (T.isNull())
2955 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002956 return T.getAsOpaquePtr();
2957}
2958
Douglas Gregor17343172009-04-01 00:28:59 +00002959Sema::TypeResult
2960Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2961 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002962 QualType T = GetTypeFromParser(Ty);
Douglas Gregor17343172009-04-01 00:28:59 +00002963 NestedNameSpecifier *NNS
2964 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2965 const TemplateSpecializationType *TemplateId
2966 = T->getAsTemplateSpecializationType();
2967 assert(TemplateId && "Expected a template specialization type");
2968
2969 if (NNS->isDependent())
2970 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2971
2972 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2973}
2974
Douglas Gregord57959a2009-03-27 23:10:48 +00002975/// \brief Build the type that describes a C++ typename specifier,
2976/// e.g., "typename T::type".
2977QualType
2978Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2979 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002980 CXXRecordDecl *CurrentInstantiation = 0;
2981 if (NNS->isDependent()) {
2982 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002983
Douglas Gregor42af25f2009-05-11 19:58:34 +00002984 // If the nested-name-specifier does not refer to the current
2985 // instantiation, then build a typename type.
2986 if (!CurrentInstantiation)
2987 return Context.getTypenameType(NNS, &II);
2988 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002989
Douglas Gregor42af25f2009-05-11 19:58:34 +00002990 DeclContext *Ctx = 0;
2991
2992 if (CurrentInstantiation)
2993 Ctx = CurrentInstantiation;
2994 else {
2995 CXXScopeSpec SS;
2996 SS.setScopeRep(NNS);
2997 SS.setRange(Range);
2998 if (RequireCompleteDeclContext(SS))
2999 return QualType();
3000
3001 Ctx = computeDeclContext(SS);
3002 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003003 assert(Ctx && "No declaration context?");
3004
3005 DeclarationName Name(&II);
3006 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3007 false);
3008 unsigned DiagID = 0;
3009 Decl *Referenced = 0;
3010 switch (Result.getKind()) {
3011 case LookupResult::NotFound:
3012 if (Ctx->isTranslationUnit())
3013 DiagID = diag::err_typename_nested_not_found_global;
3014 else
3015 DiagID = diag::err_typename_nested_not_found;
3016 break;
3017
3018 case LookupResult::Found:
3019 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3020 // We found a type. Build a QualifiedNameType, since the
3021 // typename-specifier was just sugar. FIXME: Tell
3022 // QualifiedNameType that it has a "typename" prefix.
3023 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3024 }
3025
3026 DiagID = diag::err_typename_nested_not_type;
3027 Referenced = Result.getAsDecl();
3028 break;
3029
3030 case LookupResult::FoundOverloaded:
3031 DiagID = diag::err_typename_nested_not_type;
3032 Referenced = *Result.begin();
3033 break;
3034
3035 case LookupResult::AmbiguousBaseSubobjectTypes:
3036 case LookupResult::AmbiguousBaseSubobjects:
3037 case LookupResult::AmbiguousReference:
3038 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3039 return QualType();
3040 }
3041
3042 // If we get here, it's because name lookup did not find a
3043 // type. Emit an appropriate diagnostic and return an error.
3044 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3045 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3046 else
3047 Diag(Range.getEnd(), DiagID) << Range << Name;
3048 if (Referenced)
3049 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3050 << Name;
3051 return QualType();
3052}
Douglas Gregor4a959d82009-08-06 16:20:37 +00003053
3054namespace {
3055 // See Sema::RebuildTypeInCurrentInstantiation
3056 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3057 : public TreeTransform<CurrentInstantiationRebuilder>
3058 {
3059 SourceLocation Loc;
3060 DeclarationName Entity;
3061
3062 public:
3063 CurrentInstantiationRebuilder(Sema &SemaRef,
3064 SourceLocation Loc,
3065 DeclarationName Entity)
3066 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3067 Loc(Loc), Entity(Entity) { }
3068
3069 /// \brief Determine whether the given type \p T has already been
3070 /// transformed.
3071 ///
3072 /// For the purposes of type reconstruction, a type has already been
3073 /// transformed if it is NULL or if it is not dependent.
3074 bool AlreadyTransformed(QualType T) {
3075 return T.isNull() || !T->isDependentType();
3076 }
3077
3078 /// \brief Returns the location of the entity whose type is being
3079 /// rebuilt.
3080 SourceLocation getBaseLocation() { return Loc; }
3081
3082 /// \brief Returns the name of the entity whose type is being rebuilt.
3083 DeclarationName getBaseEntity() { return Entity; }
3084
3085 /// \brief Transforms an expression by returning the expression itself
3086 /// (an identity function).
3087 ///
3088 /// FIXME: This is completely unsafe; we will need to actually clone the
3089 /// expressions.
3090 Sema::OwningExprResult TransformExpr(Expr *E) {
3091 return getSema().Owned(E);
3092 }
3093
3094 /// \brief Transforms a typename type by determining whether the type now
3095 /// refers to a member of the current instantiation, and then
3096 /// type-checking and building a QualifiedNameType (when possible).
3097 QualType TransformTypenameType(const TypenameType *T);
3098 };
3099}
3100
3101QualType
3102CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3103 NestedNameSpecifier *NNS
3104 = TransformNestedNameSpecifier(T->getQualifier(),
3105 /*FIXME:*/SourceRange(getBaseLocation()));
3106 if (!NNS)
3107 return QualType();
3108
3109 // If the nested-name-specifier did not change, and we cannot compute the
3110 // context corresponding to the nested-name-specifier, then this
3111 // typename type will not change; exit early.
3112 CXXScopeSpec SS;
3113 SS.setRange(SourceRange(getBaseLocation()));
3114 SS.setScopeRep(NNS);
3115 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3116 return QualType(T, 0);
3117
3118 // Rebuild the typename type, which will probably turn into a
3119 // QualifiedNameType.
3120 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3121 QualType NewTemplateId
3122 = TransformType(QualType(TemplateId, 0));
3123 if (NewTemplateId.isNull())
3124 return QualType();
3125
3126 if (NNS == T->getQualifier() &&
3127 NewTemplateId == QualType(TemplateId, 0))
3128 return QualType(T, 0);
3129
3130 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3131 }
3132
3133 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3134}
3135
3136/// \brief Rebuilds a type within the context of the current instantiation.
3137///
3138/// The type \p T is part of the type of an out-of-line member definition of
3139/// a class template (or class template partial specialization) that was parsed
3140/// and constructed before we entered the scope of the class template (or
3141/// partial specialization thereof). This routine will rebuild that type now
3142/// that we have entered the declarator's scope, which may produce different
3143/// canonical types, e.g.,
3144///
3145/// \code
3146/// template<typename T>
3147/// struct X {
3148/// typedef T* pointer;
3149/// pointer data();
3150/// };
3151///
3152/// template<typename T>
3153/// typename X<T>::pointer X<T>::data() { ... }
3154/// \endcode
3155///
3156/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3157/// since we do not know that we can look into X<T> when we parsed the type.
3158/// This function will rebuild the type, performing the lookup of "pointer"
3159/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3160/// as the canonical type of T*, allowing the return types of the out-of-line
3161/// definition and the declaration to match.
3162QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3163 DeclarationName Name) {
3164 if (T.isNull() || !T->isDependentType())
3165 return T;
3166
3167 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3168 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00003169}