blob: 1bcc8c37ecd7aff0799644f1bad4f32da449d0f4 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
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>());
Douglas Gregord684b002009-02-10 19:49:53 +0000218 QualType Default = QualType::getFromOpaquePtr(DefaultT);
219
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000220 // C++0x [temp.param]p9:
221 // A default template-argument may be specified for any kind of
222 // template-parameter that is not a template parameter pack.
223 if (Parm->isParameterPack()) {
224 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000225 return;
226 }
227
Douglas Gregord684b002009-02-10 19:49:53 +0000228 // C++ [temp.param]p14:
229 // A template-parameter shall not be used in its own default argument.
230 // FIXME: Implement this check! Needs a recursive walk over the types.
231
232 // Check the template argument itself.
233 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
234 Parm->setInvalidDecl();
235 return;
236 }
237
238 Parm->setDefaultArgument(Default, DefaultLoc, false);
239}
240
Douglas Gregor2943aed2009-03-03 04:44:36 +0000241/// \brief Check that the type of a non-type template parameter is
242/// well-formed.
243///
244/// \returns the (possibly-promoted) parameter type if valid;
245/// otherwise, produces a diagnostic and returns a NULL type.
246QualType
247Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
248 // C++ [temp.param]p4:
249 //
250 // A non-type template-parameter shall have one of the following
251 // (optionally cv-qualified) types:
252 //
253 // -- integral or enumeration type,
254 if (T->isIntegralType() || T->isEnumeralType() ||
255 // -- pointer to object or pointer to function,
256 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000257 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
258 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000259 // -- reference to object or reference to function,
260 T->isReferenceType() ||
261 // -- pointer to member.
262 T->isMemberPointerType() ||
263 // If T is a dependent type, we can't do the check now, so we
264 // assume that it is well-formed.
265 T->isDependentType())
266 return T;
267 // C++ [temp.param]p8:
268 //
269 // A non-type template-parameter of type "array of T" or
270 // "function returning T" is adjusted to be of type "pointer to
271 // T" or "pointer to function returning T", respectively.
272 else if (T->isArrayType())
273 // FIXME: Keep the type prior to promotion?
274 return Context.getArrayDecayedType(T);
275 else if (T->isFunctionType())
276 // FIXME: Keep the type prior to promotion?
277 return Context.getPointerType(T);
278
279 Diag(Loc, diag::err_template_nontype_parm_bad_type)
280 << T;
281
282 return QualType();
283}
284
Douglas Gregor72c3f312008-12-05 18:15:24 +0000285/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
286/// template parameter (e.g., "int Size" in "template<int Size>
287/// class Array") has been parsed. S is the current scope and D is
288/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000289Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
290 unsigned Depth,
291 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000292 QualType T = GetTypeForDeclarator(D, S);
293
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000294 assert(S->isTemplateParamScope() &&
295 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000296 bool Invalid = false;
297
298 IdentifierInfo *ParamName = D.getIdentifier();
299 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000300 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000301 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000302 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000303 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000304 }
305
Douglas Gregor2943aed2009-03-03 04:44:36 +0000306 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000307 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000308 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000309 Invalid = true;
310 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000311
Douglas Gregor72c3f312008-12-05 18:15:24 +0000312 NonTypeTemplateParmDecl *Param
313 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000314 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000315 if (Invalid)
316 Param->setInvalidDecl();
317
318 if (D.getIdentifier()) {
319 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000320 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000321 IdResolver.AddDecl(Param);
322 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000323 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000324}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000325
Douglas Gregord684b002009-02-10 19:49:53 +0000326/// \brief Adds a default argument to the given non-type template
327/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000328void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000329 SourceLocation EqualLoc,
330 ExprArg DefaultE) {
331 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000332 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000333 Expr *Default = static_cast<Expr *>(DefaultE.get());
334
335 // C++ [temp.param]p14:
336 // A template-parameter shall not be used in its own default argument.
337 // FIXME: Implement this check! Needs a recursive walk over the types.
338
339 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000340 TemplateArgument Converted;
341 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
342 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000343 TemplateParm->setInvalidDecl();
344 return;
345 }
346
Anders Carlssone9146f22009-05-01 19:49:17 +0000347 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000348}
349
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000350
351/// ActOnTemplateTemplateParameter - Called when a C++ template template
352/// parameter (e.g. T in template <template <typename> class T> class array)
353/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
355 SourceLocation TmpLoc,
356 TemplateParamsTy *Params,
357 IdentifierInfo *Name,
358 SourceLocation NameLoc,
359 unsigned Depth,
360 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000361{
362 assert(S->isTemplateParamScope() &&
363 "Template template parameter not in template parameter scope!");
364
365 // Construct the parameter object.
366 TemplateTemplateParmDecl *Param =
367 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
368 Position, Name,
369 (TemplateParameterList*)Params);
370
371 // Make sure the parameter is valid.
372 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
373 // do anything yet. However, if the template parameter list or (eventual)
374 // default value is ever invalidated, that will propagate here.
375 bool Invalid = false;
376 if (Invalid) {
377 Param->setInvalidDecl();
378 }
379
380 // If the tt-param has a name, then link the identifier into the scope
381 // and lookup mechanisms.
382 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000383 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000384 IdResolver.AddDecl(Param);
385 }
386
Chris Lattnerb28317a2009-03-28 19:18:32 +0000387 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000388}
389
Douglas Gregord684b002009-02-10 19:49:53 +0000390/// \brief Adds a default argument to the given template template
391/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000392void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000393 SourceLocation EqualLoc,
394 ExprArg DefaultE) {
395 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000396 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000397
398 // Since a template-template parameter's default argument is an
399 // id-expression, it must be a DeclRefExpr.
400 DeclRefExpr *Default
401 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
402
403 // C++ [temp.param]p14:
404 // A template-parameter shall not be used in its own default argument.
405 // FIXME: Implement this check! Needs a recursive walk over the types.
406
407 // Check the well-formedness of the template argument.
408 if (!isa<TemplateDecl>(Default->getDecl())) {
409 Diag(Default->getSourceRange().getBegin(),
410 diag::err_template_arg_must_be_template)
411 << Default->getSourceRange();
412 TemplateParm->setInvalidDecl();
413 return;
414 }
415 if (CheckTemplateArgument(TemplateParm, Default)) {
416 TemplateParm->setInvalidDecl();
417 return;
418 }
419
420 DefaultE.release();
421 TemplateParm->setDefaultArgument(Default);
422}
423
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000424/// ActOnTemplateParameterList - Builds a TemplateParameterList that
425/// contains the template parameters in Params/NumParams.
426Sema::TemplateParamsTy *
427Sema::ActOnTemplateParameterList(unsigned Depth,
428 SourceLocation ExportLoc,
429 SourceLocation TemplateLoc,
430 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000431 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000432 SourceLocation RAngleLoc) {
433 if (ExportLoc.isValid())
434 Diag(ExportLoc, diag::note_template_export_unsupported);
435
Douglas Gregorddc29e12009-02-06 22:42:48 +0000436 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
437 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000438}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000439
Douglas Gregor212e81c2009-03-25 00:13:59 +0000440Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000441Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000442 SourceLocation KWLoc, const CXXScopeSpec &SS,
443 IdentifierInfo *Name, SourceLocation NameLoc,
444 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000445 MultiTemplateParamsArg TemplateParameterLists,
446 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000447 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
John McCall0f434ec2009-07-31 02:45:11 +0000448 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000449 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000450
451 // Check that we can declare a template here.
452 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000453 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000454
455 TagDecl::TagKind Kind;
456 switch (TagSpec) {
457 default: assert(0 && "Unknown tag type!");
458 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
459 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
460 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
461 }
462
463 // There is no such thing as an unnamed class template.
464 if (!Name) {
465 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000466 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000467 }
468
469 // Find any previous declaration with this name.
470 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
471 true);
472 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
473 NamedDecl *PrevDecl = 0;
474 if (Previous.begin() != Previous.end())
475 PrevDecl = *Previous.begin();
476
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000477 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
478 PrevDecl = 0;
479
Douglas Gregorddc29e12009-02-06 22:42:48 +0000480 DeclContext *SemanticContext = CurContext;
481 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000482 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000483
Mike Stump390b4cc2009-05-16 07:39:55 +0000484 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000485 }
486
487 // FIXME: member templates!
488 TemplateParameterList *TemplateParams
489 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
490
491 // If there is a previous declaration with the same name, check
492 // whether this is a valid redeclaration.
493 ClassTemplateDecl *PrevClassTemplate
494 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
495 if (PrevClassTemplate) {
496 // Ensure that the template parameter lists are compatible.
497 if (!TemplateParameterListsAreEqual(TemplateParams,
498 PrevClassTemplate->getTemplateParameters(),
499 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000500 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000501
502 // C++ [temp.class]p4:
503 // In a redeclaration, partial specialization, explicit
504 // specialization or explicit instantiation of a class template,
505 // the class-key shall agree in kind with the original class
506 // template declaration (7.1.5.3).
507 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000508 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000509 Diag(KWLoc, diag::err_use_with_wrong_tag)
510 << Name
511 << CodeModificationHint::CreateReplacement(KWLoc,
512 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000513 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000514 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000515 }
516
Douglas Gregorddc29e12009-02-06 22:42:48 +0000517 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000518 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000519 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
520 Diag(NameLoc, diag::err_redefinition) << Name;
521 Diag(Def->getLocation(), diag::note_previous_definition);
522 // FIXME: Would it make sense to try to "forget" the previous
523 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000524 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000525 }
526 }
527 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
528 // Maybe we will complain about the shadowed template parameter.
529 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
530 // Just pretend that we didn't see the previous declaration.
531 PrevDecl = 0;
532 } else if (PrevDecl) {
533 // C++ [temp]p5:
534 // A class template shall not have the same name as any other
535 // template, class, function, object, enumeration, enumerator,
536 // namespace, or type in the same scope (3.3), except as specified
537 // in (14.5.4).
538 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
539 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000540 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000541 }
542
Douglas Gregord684b002009-02-10 19:49:53 +0000543 // Check the template parameter list of this declaration, possibly
544 // merging in the template parameter list from the previous class
545 // template declaration.
546 if (CheckTemplateParameterList(TemplateParams,
547 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
548 Invalid = true;
549
Douglas Gregor7da97d02009-05-10 22:57:19 +0000550 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000551 // declaration!
552
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000553 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000554 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000555 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000556 PrevClassTemplate->getTemplatedDecl() : 0,
557 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000558
559 ClassTemplateDecl *NewTemplate
560 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
561 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000562 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000563 NewClass->setDescribedClassTemplate(NewTemplate);
564
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000565 // Build the type for the class template declaration now.
566 QualType T =
567 Context.getTypeDeclType(NewClass,
568 PrevClassTemplate?
569 PrevClassTemplate->getTemplatedDecl() : 0);
570 assert(T->isDependentType() && "Class template type is not dependent?");
571 (void)T;
572
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000573 // Set the access specifier.
574 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
575
Douglas Gregorddc29e12009-02-06 22:42:48 +0000576 // Set the lexical context of these templates
577 NewClass->setLexicalDeclContext(CurContext);
578 NewTemplate->setLexicalDeclContext(CurContext);
579
John McCall0f434ec2009-07-31 02:45:11 +0000580 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000581 NewClass->startDefinition();
582
583 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000584 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000585
586 PushOnScopeChains(NewTemplate, S);
587
Douglas Gregord684b002009-02-10 19:49:53 +0000588 if (Invalid) {
589 NewTemplate->setInvalidDecl();
590 NewClass->setInvalidDecl();
591 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000592 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000593}
594
Douglas Gregord684b002009-02-10 19:49:53 +0000595/// \brief Checks the validity of a template parameter list, possibly
596/// considering the template parameter list from a previous
597/// declaration.
598///
599/// If an "old" template parameter list is provided, it must be
600/// equivalent (per TemplateParameterListsAreEqual) to the "new"
601/// template parameter list.
602///
603/// \param NewParams Template parameter list for a new template
604/// declaration. This template parameter list will be updated with any
605/// default arguments that are carried through from the previous
606/// template parameter list.
607///
608/// \param OldParams If provided, template parameter list from a
609/// previous declaration of the same template. Default template
610/// arguments will be merged from the old template parameter list to
611/// the new template parameter list.
612///
613/// \returns true if an error occurred, false otherwise.
614bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
615 TemplateParameterList *OldParams) {
616 bool Invalid = false;
617
618 // C++ [temp.param]p10:
619 // The set of default template-arguments available for use with a
620 // template declaration or definition is obtained by merging the
621 // default arguments from the definition (if in scope) and all
622 // declarations in scope in the same way default function
623 // arguments are (8.3.6).
624 bool SawDefaultArgument = false;
625 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000626
Anders Carlsson49d25572009-06-12 23:20:15 +0000627 bool SawParameterPack = false;
628 SourceLocation ParameterPackLoc;
629
Mike Stump1a35fde2009-02-11 23:03:27 +0000630 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000631 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000632 if (OldParams)
633 OldParam = OldParams->begin();
634
635 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
636 NewParamEnd = NewParams->end();
637 NewParam != NewParamEnd; ++NewParam) {
638 // Variables used to diagnose redundant default arguments
639 bool RedundantDefaultArg = false;
640 SourceLocation OldDefaultLoc;
641 SourceLocation NewDefaultLoc;
642
643 // Variables used to diagnose missing default arguments
644 bool MissingDefaultArg = false;
645
Anders Carlsson49d25572009-06-12 23:20:15 +0000646 // C++0x [temp.param]p11:
647 // If a template parameter of a class template is a template parameter pack,
648 // it must be the last template parameter.
649 if (SawParameterPack) {
650 Diag(ParameterPackLoc,
651 diag::err_template_param_pack_must_be_last_template_parameter);
652 Invalid = true;
653 }
654
Douglas Gregord684b002009-02-10 19:49:53 +0000655 // Merge default arguments for template type parameters.
656 if (TemplateTypeParmDecl *NewTypeParm
657 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
658 TemplateTypeParmDecl *OldTypeParm
659 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
660
Anders Carlsson49d25572009-06-12 23:20:15 +0000661 if (NewTypeParm->isParameterPack()) {
662 assert(!NewTypeParm->hasDefaultArgument() &&
663 "Parameter packs can't have a default argument!");
664 SawParameterPack = true;
665 ParameterPackLoc = NewTypeParm->getLocation();
666 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000667 NewTypeParm->hasDefaultArgument()) {
668 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
669 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
670 SawDefaultArgument = true;
671 RedundantDefaultArg = true;
672 PreviousDefaultArgLoc = NewDefaultLoc;
673 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
674 // Merge the default argument from the old declaration to the
675 // new declaration.
676 SawDefaultArgument = true;
677 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
678 OldTypeParm->getDefaultArgumentLoc(),
679 true);
680 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
681 } else if (NewTypeParm->hasDefaultArgument()) {
682 SawDefaultArgument = true;
683 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
684 } else if (SawDefaultArgument)
685 MissingDefaultArg = true;
686 }
687 // Merge default arguments for non-type template parameters
688 else if (NonTypeTemplateParmDecl *NewNonTypeParm
689 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
690 NonTypeTemplateParmDecl *OldNonTypeParm
691 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
692 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
693 NewNonTypeParm->hasDefaultArgument()) {
694 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
695 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
696 SawDefaultArgument = true;
697 RedundantDefaultArg = true;
698 PreviousDefaultArgLoc = NewDefaultLoc;
699 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
700 // Merge the default argument from the old declaration to the
701 // new declaration.
702 SawDefaultArgument = true;
703 // FIXME: We need to create a new kind of "default argument"
704 // expression that points to a previous template template
705 // parameter.
706 NewNonTypeParm->setDefaultArgument(
707 OldNonTypeParm->getDefaultArgument());
708 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
709 } else if (NewNonTypeParm->hasDefaultArgument()) {
710 SawDefaultArgument = true;
711 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
712 } else if (SawDefaultArgument)
713 MissingDefaultArg = true;
714 }
715 // Merge default arguments for template template parameters
716 else {
717 TemplateTemplateParmDecl *NewTemplateParm
718 = cast<TemplateTemplateParmDecl>(*NewParam);
719 TemplateTemplateParmDecl *OldTemplateParm
720 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
721 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
722 NewTemplateParm->hasDefaultArgument()) {
723 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
724 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
725 SawDefaultArgument = true;
726 RedundantDefaultArg = true;
727 PreviousDefaultArgLoc = NewDefaultLoc;
728 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
729 // Merge the default argument from the old declaration to the
730 // new declaration.
731 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000732 // FIXME: We need to create a new kind of "default argument" expression
733 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000734 NewTemplateParm->setDefaultArgument(
735 OldTemplateParm->getDefaultArgument());
736 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
737 } else if (NewTemplateParm->hasDefaultArgument()) {
738 SawDefaultArgument = true;
739 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
740 } else if (SawDefaultArgument)
741 MissingDefaultArg = true;
742 }
743
744 if (RedundantDefaultArg) {
745 // C++ [temp.param]p12:
746 // A template-parameter shall not be given default arguments
747 // by two different declarations in the same scope.
748 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
749 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
750 Invalid = true;
751 } else if (MissingDefaultArg) {
752 // C++ [temp.param]p11:
753 // If a template-parameter has a default template-argument,
754 // all subsequent template-parameters shall have a default
755 // template-argument supplied.
756 Diag((*NewParam)->getLocation(),
757 diag::err_template_param_default_arg_missing);
758 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
759 Invalid = true;
760 }
761
762 // If we have an old template parameter list that we're merging
763 // in, move on to the next parameter.
764 if (OldParams)
765 ++OldParam;
766 }
767
768 return Invalid;
769}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000770
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000771/// \brief Match the given template parameter lists to the given scope
772/// specifier, returning the template parameter list that applies to the
773/// name.
774///
775/// \param DeclStartLoc the start of the declaration that has a scope
776/// specifier or a template parameter list.
777///
778/// \param SS the scope specifier that will be matched to the given template
779/// parameter lists. This scope specifier precedes a qualified name that is
780/// being declared.
781///
782/// \param ParamLists the template parameter lists, from the outermost to the
783/// innermost template parameter lists.
784///
785/// \param NumParamLists the number of template parameter lists in ParamLists.
786///
787/// \returns the template parameter list, if any, that corresponds to the
788/// name that is preceded by the scope specifier @p SS. This template
789/// parameter list may be have template parameters (if we're declaring a
790/// template) or may have no template parameters (if we're declaring a
791/// template specialization), or may be NULL (if we were's declaring isn't
792/// itself a template).
793TemplateParameterList *
794Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
795 const CXXScopeSpec &SS,
796 TemplateParameterList **ParamLists,
797 unsigned NumParamLists) {
798 // FIXME: This routine will need a lot more testing once we have support for
799 // member templates.
800
801 // Find the template-ids that occur within the nested-name-specifier. These
802 // template-ids will match up with the template parameter lists.
803 llvm::SmallVector<const TemplateSpecializationType *, 4>
804 TemplateIdsInSpecifier;
805 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
806 NNS; NNS = NNS->getPrefix()) {
807 if (const TemplateSpecializationType *SpecType
808 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
809 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
810 if (!Template)
811 continue; // FIXME: should this be an error? probably...
812
Ted Kremenek6217b802009-07-29 21:53:49 +0000813 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000814 ClassTemplateSpecializationDecl *SpecDecl
815 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
816 // If the nested name specifier refers to an explicit specialization,
817 // we don't need a template<> header.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000818 // FIXME: revisit this approach once we cope with specialization
819 // properly.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000820 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
821 continue;
822 }
823
824 TemplateIdsInSpecifier.push_back(SpecType);
825 }
826 }
827
828 // Reverse the list of template-ids in the scope specifier, so that we can
829 // more easily match up the template-ids and the template parameter lists.
830 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
831
832 SourceLocation FirstTemplateLoc = DeclStartLoc;
833 if (NumParamLists)
834 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
835
836 // Match the template-ids found in the specifier to the template parameter
837 // lists.
838 unsigned Idx = 0;
839 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
840 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +0000841 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
842 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000843 if (Idx >= NumParamLists) {
844 // We have a template-id without a corresponding template parameter
845 // list.
846 if (DependentTemplateId) {
847 // FIXME: the location information here isn't great.
848 Diag(SS.getRange().getBegin(),
849 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +0000850 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000851 << SS.getRange();
852 } else {
853 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
854 << SS.getRange()
855 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
856 "template<> ");
857 }
858 return 0;
859 }
860
861 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +0000862 if (DependentTemplateId) {
863 TemplateDecl *Template
864 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
865
866 if (ClassTemplateDecl *ClassTemplate
867 = dyn_cast<ClassTemplateDecl>(Template)) {
868 TemplateParameterList *ExpectedTemplateParams = 0;
869 // Is this template-id naming the primary template?
870 if (Context.hasSameType(TemplateId,
871 ClassTemplate->getInjectedClassNameType(Context)))
872 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
873 // ... or a partial specialization?
874 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
875 = ClassTemplate->findPartialSpecialization(TemplateId))
876 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
877
878 if (ExpectedTemplateParams)
879 TemplateParameterListsAreEqual(ParamLists[Idx],
880 ExpectedTemplateParams,
881 true);
882 }
883 } else if (ParamLists[Idx]->size() > 0)
884 Diag(ParamLists[Idx]->getTemplateLoc(),
885 diag::err_template_param_list_matches_nontemplate)
886 << TemplateId
887 << ParamLists[Idx]->getSourceRange();
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000888 }
889
890 // If there were at least as many template-ids as there were template
891 // parameter lists, then there are no template parameter lists remaining for
892 // the declaration itself.
893 if (Idx >= NumParamLists)
894 return 0;
895
896 // If there were too many template parameter lists, complain about that now.
897 if (Idx != NumParamLists - 1) {
898 while (Idx < NumParamLists - 1) {
899 Diag(ParamLists[Idx]->getTemplateLoc(),
900 diag::err_template_spec_extra_headers)
901 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
902 ParamLists[Idx]->getRAngleLoc());
903 ++Idx;
904 }
905 }
906
907 // Return the last template parameter list, which corresponds to the
908 // entity being declared.
909 return ParamLists[NumParamLists - 1];
910}
911
Douglas Gregor40808ce2009-03-09 23:48:35 +0000912/// \brief Translates template arguments as provided by the parser
913/// into template arguments used by semantic analysis.
914static void
915translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
916 SourceLocation *TemplateArgLocs,
917 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
918 TemplateArgs.reserve(TemplateArgsIn.size());
919
920 void **Args = TemplateArgsIn.getArgs();
921 bool *ArgIsType = TemplateArgsIn.getArgIsType();
922 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
923 TemplateArgs.push_back(
924 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
925 QualType::getFromOpaquePtr(Args[Arg]))
926 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
927 }
928}
929
Douglas Gregor7532dc62009-03-30 22:58:21 +0000930QualType Sema::CheckTemplateIdType(TemplateName Name,
931 SourceLocation TemplateLoc,
932 SourceLocation LAngleLoc,
933 const TemplateArgument *TemplateArgs,
934 unsigned NumTemplateArgs,
935 SourceLocation RAngleLoc) {
936 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000937 if (!Template) {
938 // The template name does not resolve to a template, so we just
939 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000940 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000941 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000942 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000943
Douglas Gregor40808ce2009-03-09 23:48:35 +0000944 // Check that the template argument list is well-formed for this
945 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000946 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
947 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000948 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000949 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000950 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000951 return QualType();
952
Anders Carlssonfb250522009-06-23 01:26:57 +0000953 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000954 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000955 "Converted template argument list is too short!");
956
957 QualType CanonType;
958
Douglas Gregor7532dc62009-03-30 22:58:21 +0000959 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000960 TemplateArgs,
961 NumTemplateArgs)) {
962 // This class template specialization is a dependent
963 // type. Therefore, its canonical type is another class template
964 // specialization type that contains all of the converted
965 // arguments in canonical form. This ensures that, e.g., A<T> and
966 // A<T, T> have identical types when A is declared as:
967 //
968 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000969 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
970 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000971 Converted.getFlatArguments(),
972 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +0000973
974 // FIXME: CanonType is not actually the canonical type, and unfortunately
975 // it is a TemplateTypeSpecializationType that we will never use again.
976 // In the future, we need to teach getTemplateSpecializationType to only
977 // build the canonical type and return that to us.
978 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000979 } else if (ClassTemplateDecl *ClassTemplate
980 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000981 // Find the class template specialization declaration that
982 // corresponds to these arguments.
983 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000984 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000985 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000986 Converted.flatSize(),
987 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000988 void *InsertPos = 0;
989 ClassTemplateSpecializationDecl *Decl
990 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
991 if (!Decl) {
992 // This is the first time we have referenced this class template
993 // specialization. Create the canonical declaration and add it to
994 // the set of specializations.
995 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000996 ClassTemplate->getDeclContext(),
997 TemplateLoc,
998 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000999 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001000 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1001 Decl->setLexicalDeclContext(CurContext);
1002 }
1003
1004 CanonType = Context.getTypeDeclType(Decl);
1005 }
1006
1007 // Build the fully-sugared type for this class template
1008 // specialization, which refers back to the class template
1009 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001010 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1011 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001012}
1013
Douglas Gregorcc636682009-02-17 23:15:12 +00001014Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001015Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1016 SourceLocation LAngleLoc,
1017 ASTTemplateArgsPtr TemplateArgsIn,
1018 SourceLocation *TemplateArgLocs,
1019 SourceLocation RAngleLoc) {
1020 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001021
Douglas Gregor40808ce2009-03-09 23:48:35 +00001022 // Translate the parser's template argument list in our AST format.
1023 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1024 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001025
Douglas Gregor7532dc62009-03-30 22:58:21 +00001026 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001027 TemplateArgs.data(),
1028 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001029 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001030 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001031
1032 if (Result.isNull())
1033 return true;
1034
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001035 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001036}
1037
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001038Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1039 SourceLocation TemplateNameLoc,
1040 SourceLocation LAngleLoc,
1041 const TemplateArgument *TemplateArgs,
1042 unsigned NumTemplateArgs,
1043 SourceLocation RAngleLoc) {
1044 // FIXME: Can we do any checking at this point? I guess we could check the
1045 // template arguments that we have against the template name, if the template
1046 // name refers to a single template. That's not a terribly common case,
1047 // though.
1048 return Owned(TemplateIdRefExpr::Create(Context,
1049 /*FIXME: New type?*/Context.OverloadTy,
1050 /*FIXME: Necessary?*/0,
1051 /*FIXME: Necessary?*/SourceRange(),
1052 Template, TemplateNameLoc, LAngleLoc,
1053 TemplateArgs,
1054 NumTemplateArgs, RAngleLoc));
1055}
1056
1057Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1058 SourceLocation TemplateNameLoc,
1059 SourceLocation LAngleLoc,
1060 ASTTemplateArgsPtr TemplateArgsIn,
1061 SourceLocation *TemplateArgLocs,
1062 SourceLocation RAngleLoc) {
1063 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1064
1065 // Translate the parser's template argument list in our AST format.
1066 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1067 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001068 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001069
1070 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1071 TemplateArgs.data(), TemplateArgs.size(),
1072 RAngleLoc);
1073}
1074
Douglas Gregorc45c2322009-03-31 00:43:58 +00001075/// \brief Form a dependent template name.
1076///
1077/// This action forms a dependent template name given the template
1078/// name and its (presumably dependent) scope specifier. For
1079/// example, given "MetaFun::template apply", the scope specifier \p
1080/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1081/// of the "template" keyword, and "apply" is the \p Name.
1082Sema::TemplateTy
1083Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1084 const IdentifierInfo &Name,
1085 SourceLocation NameLoc,
1086 const CXXScopeSpec &SS) {
1087 if (!SS.isSet() || SS.isInvalid())
1088 return TemplateTy();
1089
1090 NestedNameSpecifier *Qualifier
1091 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1092
1093 // FIXME: member of the current instantiation
1094
1095 if (!Qualifier->isDependent()) {
1096 // C++0x [temp.names]p5:
1097 // If a name prefixed by the keyword template is not the name of
1098 // a template, the program is ill-formed. [Note: the keyword
1099 // template may not be applied to non-template members of class
1100 // templates. -end note ] [ Note: as is the case with the
1101 // typename prefix, the template prefix is allowed in cases
1102 // where it is not strictly necessary; i.e., when the
1103 // nested-name-specifier or the expression on the left of the ->
1104 // or . is not dependent on a template-parameter, or the use
1105 // does not appear in the scope of a template. -end note]
1106 //
1107 // Note: C++03 was more strict here, because it banned the use of
1108 // the "template" keyword prior to a template-name that was not a
1109 // dependent name. C++ DR468 relaxed this requirement (the
1110 // "template" keyword is now permitted). We follow the C++0x
1111 // rules, even in C++03 mode, retroactively applying the DR.
1112 TemplateTy Template;
1113 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1114 if (TNK == TNK_Non_template) {
1115 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1116 << &Name;
1117 return TemplateTy();
1118 }
1119
1120 return Template;
1121 }
1122
1123 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1124}
1125
Anders Carlsson436b1562009-06-13 00:33:33 +00001126bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1127 const TemplateArgument &Arg,
1128 TemplateArgumentListBuilder &Converted) {
1129 // Check template type parameter.
1130 if (Arg.getKind() != TemplateArgument::Type) {
1131 // C++ [temp.arg.type]p1:
1132 // A template-argument for a template-parameter which is a
1133 // type shall be a type-id.
1134
1135 // We have a template type parameter but the template argument
1136 // is not a type.
1137 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1138 Diag(Param->getLocation(), diag::note_template_param_here);
1139
1140 return true;
1141 }
1142
1143 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1144 return true;
1145
1146 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001147 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001148 TemplateArgument(Arg.getLocation(),
1149 Context.getCanonicalType(Arg.getAsType())));
1150 return false;
1151}
1152
Douglas Gregorc15cb382009-02-09 23:23:08 +00001153/// \brief Check that the given template argument list is well-formed
1154/// for specializing the given template.
1155bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1156 SourceLocation TemplateLoc,
1157 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001158 const TemplateArgument *TemplateArgs,
1159 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001160 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001161 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001162 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001163 TemplateParameterList *Params = Template->getTemplateParameters();
1164 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001165 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001166 bool Invalid = false;
1167
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001168 bool HasParameterPack =
1169 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1170
1171 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001172 (NumArgs < Params->getMinRequiredArguments() &&
1173 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001174 // FIXME: point at either the first arg beyond what we can handle,
1175 // or the '>', depending on whether we have too many or too few
1176 // arguments.
1177 SourceRange Range;
1178 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001179 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001180 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1181 << (NumArgs > NumParams)
1182 << (isa<ClassTemplateDecl>(Template)? 0 :
1183 isa<FunctionTemplateDecl>(Template)? 1 :
1184 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1185 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001186 Diag(Template->getLocation(), diag::note_template_decl_here)
1187 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001188 Invalid = true;
1189 }
1190
1191 // C++ [temp.arg]p1:
1192 // [...] The type and form of each template-argument specified in
1193 // a template-id shall match the type and form specified for the
1194 // corresponding parameter declared by the template in its
1195 // template-parameter-list.
1196 unsigned ArgIdx = 0;
1197 for (TemplateParameterList::iterator Param = Params->begin(),
1198 ParamEnd = Params->end();
1199 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001200 if (ArgIdx > NumArgs && PartialTemplateArgs)
1201 break;
1202
Douglas Gregorc15cb382009-02-09 23:23:08 +00001203 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001204 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001205 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001206 // Retrieve the default template argument from the template
1207 // parameter.
1208 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001209 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001210 // We have an empty argument pack.
1211 Converted.BeginPack();
1212 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001213 break;
1214 }
1215
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001216 if (!TTP->hasDefaultArgument())
1217 break;
1218
Douglas Gregor40808ce2009-03-09 23:48:35 +00001219 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001220
1221 // If the argument type is dependent, instantiate it now based
1222 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001223 if (ArgType->isDependentType()) {
1224 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001225 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001226 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001227 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001228
Anders Carlssone9c904b2009-06-05 04:47:51 +00001229 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001230 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001231 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001232 TTP->getDefaultArgumentLoc(),
1233 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001234 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001235
1236 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001237 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001238
Douglas Gregor40808ce2009-03-09 23:48:35 +00001239 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001240 } else if (NonTypeTemplateParmDecl *NTTP
1241 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1242 if (!NTTP->hasDefaultArgument())
1243 break;
1244
Anders Carlsson3b56c002009-06-11 16:06:49 +00001245 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001246 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001247 Converted.flatSize(),
1248 SourceRange(TemplateLoc, RAngleLoc));
1249
1250 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001251 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001252
1253 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1254 TemplateArgs);
1255 if (E.isInvalid())
1256 return true;
1257
1258 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001259 } else {
1260 TemplateTemplateParmDecl *TempParm
1261 = cast<TemplateTemplateParmDecl>(*Param);
1262
1263 if (!TempParm->hasDefaultArgument())
1264 break;
1265
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001267 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001268 }
1269 } else {
1270 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001271 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001272 }
1273
Douglas Gregorc15cb382009-02-09 23:23:08 +00001274
1275 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001276 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001277 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001278 // Check all the remaining arguments (if any).
1279 for (; ArgIdx < NumArgs; ++ArgIdx) {
1280 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1281 Invalid = true;
1282 }
1283
Anders Carlssonfb250522009-06-23 01:26:57 +00001284 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001285 } else {
1286 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1287 Invalid = true;
1288 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001289 } else if (NonTypeTemplateParmDecl *NTTP
1290 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1291 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001292
1293 // Instantiate the type of the non-type template parameter with
1294 // the template arguments we've seen thus far.
1295 QualType NTTPType = NTTP->getType();
1296 if (NTTPType->isDependentType()) {
1297 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001298 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001299 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001300 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001301 SourceRange(TemplateLoc, RAngleLoc));
1302
Anders Carlssone9c904b2009-06-05 04:47:51 +00001303 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001304 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001305 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001306 NTTP->getLocation(),
1307 NTTP->getDeclName());
1308 // If that worked, check the non-type template parameter type
1309 // for validity.
1310 if (!NTTPType.isNull())
1311 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1312 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001313 if (NTTPType.isNull()) {
1314 Invalid = true;
1315 break;
1316 }
1317 }
1318
Douglas Gregor40808ce2009-03-09 23:48:35 +00001319 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001320 case TemplateArgument::Null:
1321 assert(false && "Should never see a NULL template argument here");
1322 break;
1323
Douglas Gregor40808ce2009-03-09 23:48:35 +00001324 case TemplateArgument::Expression: {
1325 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001326 TemplateArgument Result;
1327 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001328 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001329 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001330 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001331 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001332 }
1333
Douglas Gregor40808ce2009-03-09 23:48:35 +00001334 case TemplateArgument::Declaration:
1335 case TemplateArgument::Integral:
1336 // We've already checked this template argument, so just copy
1337 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001338 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001339 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001340
Douglas Gregor40808ce2009-03-09 23:48:35 +00001341 case TemplateArgument::Type:
1342 // We have a non-type template parameter but the template
1343 // argument is a type.
1344
1345 // C++ [temp.arg]p2:
1346 // In a template-argument, an ambiguity between a type-id and
1347 // an expression is resolved to a type-id, regardless of the
1348 // form of the corresponding template-parameter.
1349 //
1350 // We warn specifically about this case, since it can be rather
1351 // confusing for users.
1352 if (Arg.getAsType()->isFunctionType())
1353 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1354 << Arg.getAsType();
1355 else
1356 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1357 Diag((*Param)->getLocation(), diag::note_template_param_here);
1358 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001359 break;
1360
1361 case TemplateArgument::Pack:
1362 assert(0 && "FIXME: Implement!");
1363 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001364 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001365 } else {
1366 // Check template template parameters.
1367 TemplateTemplateParmDecl *TempParm
1368 = cast<TemplateTemplateParmDecl>(*Param);
1369
Douglas Gregor40808ce2009-03-09 23:48:35 +00001370 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001371 case TemplateArgument::Null:
1372 assert(false && "Should never see a NULL template argument here");
1373 break;
1374
Douglas Gregor40808ce2009-03-09 23:48:35 +00001375 case TemplateArgument::Expression: {
1376 Expr *ArgExpr = Arg.getAsExpr();
1377 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1378 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1379 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1380 Invalid = true;
1381
1382 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001383 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001384 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001385 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001386 continue;
1387 }
1388 }
1389 // fall through
1390
1391 case TemplateArgument::Type: {
1392 // We have a template template parameter but the template
1393 // argument does not refer to a template.
1394 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1395 Invalid = true;
1396 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001397 }
1398
Douglas Gregor40808ce2009-03-09 23:48:35 +00001399 case TemplateArgument::Declaration:
1400 // We've already checked this template argument, so just copy
1401 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001402 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001403 break;
1404
1405 case TemplateArgument::Integral:
1406 assert(false && "Integral argument with template template parameter");
1407 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001408
1409 case TemplateArgument::Pack:
1410 assert(0 && "FIXME: Implement!");
1411 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001412 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001413 }
1414 }
1415
1416 return Invalid;
1417}
1418
1419/// \brief Check a template argument against its corresponding
1420/// template type parameter.
1421///
1422/// This routine implements the semantics of C++ [temp.arg.type]. It
1423/// returns true if an error occurred, and false otherwise.
1424bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1425 QualType Arg, SourceLocation ArgLoc) {
1426 // C++ [temp.arg.type]p2:
1427 // A local type, a type with no linkage, an unnamed type or a type
1428 // compounded from any of these types shall not be used as a
1429 // template-argument for a template type-parameter.
1430 //
1431 // FIXME: Perform the recursive and no-linkage type checks.
1432 const TagType *Tag = 0;
1433 if (const EnumType *EnumT = Arg->getAsEnumType())
1434 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001435 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001436 Tag = RecordT;
1437 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1438 return Diag(ArgLoc, diag::err_template_arg_local_type)
1439 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001440 else if (Tag && !Tag->getDecl()->getDeclName() &&
1441 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001442 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1443 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1444 return true;
1445 }
1446
1447 return false;
1448}
1449
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001450/// \brief Checks whether the given template argument is the address
1451/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001452bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1453 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001454 bool Invalid = false;
1455
1456 // See through any implicit casts we added to fix the type.
1457 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1458 Arg = Cast->getSubExpr();
1459
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001460 // C++0x allows nullptr, and there's no further checking to be done for that.
1461 if (Arg->getType()->isNullPtrType())
1462 return false;
1463
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001464 // C++ [temp.arg.nontype]p1:
1465 //
1466 // A template-argument for a non-type, non-template
1467 // template-parameter shall be one of: [...]
1468 //
1469 // -- the address of an object or function with external
1470 // linkage, including function templates and function
1471 // template-ids but excluding non-static class members,
1472 // expressed as & id-expression where the & is optional if
1473 // the name refers to a function or array, or if the
1474 // corresponding template-parameter is a reference; or
1475 DeclRefExpr *DRE = 0;
1476
1477 // Ignore (and complain about) any excess parentheses.
1478 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1479 if (!Invalid) {
1480 Diag(Arg->getSourceRange().getBegin(),
1481 diag::err_template_arg_extra_parens)
1482 << Arg->getSourceRange();
1483 Invalid = true;
1484 }
1485
1486 Arg = Parens->getSubExpr();
1487 }
1488
1489 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1490 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1491 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1492 } else
1493 DRE = dyn_cast<DeclRefExpr>(Arg);
1494
1495 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1496 return Diag(Arg->getSourceRange().getBegin(),
1497 diag::err_template_arg_not_object_or_func_form)
1498 << Arg->getSourceRange();
1499
1500 // Cannot refer to non-static data members
1501 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1502 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1503 << Field << Arg->getSourceRange();
1504
1505 // Cannot refer to non-static member functions
1506 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1507 if (!Method->isStatic())
1508 return Diag(Arg->getSourceRange().getBegin(),
1509 diag::err_template_arg_method)
1510 << Method << Arg->getSourceRange();
1511
1512 // Functions must have external linkage.
1513 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1514 if (Func->getStorageClass() == FunctionDecl::Static) {
1515 Diag(Arg->getSourceRange().getBegin(),
1516 diag::err_template_arg_function_not_extern)
1517 << Func << Arg->getSourceRange();
1518 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1519 << true;
1520 return true;
1521 }
1522
1523 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001524 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001525 return Invalid;
1526 }
1527
1528 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1529 if (!Var->hasGlobalStorage()) {
1530 Diag(Arg->getSourceRange().getBegin(),
1531 diag::err_template_arg_object_not_extern)
1532 << Var << Arg->getSourceRange();
1533 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1534 << true;
1535 return true;
1536 }
1537
1538 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001539 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001540 return Invalid;
1541 }
1542
1543 // We found something else, but we don't know specifically what it is.
1544 Diag(Arg->getSourceRange().getBegin(),
1545 diag::err_template_arg_not_object_or_func)
1546 << Arg->getSourceRange();
1547 Diag(DRE->getDecl()->getLocation(),
1548 diag::note_template_arg_refers_here);
1549 return true;
1550}
1551
1552/// \brief Checks whether the given template argument is a pointer to
1553/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001554bool
1555Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001556 bool Invalid = false;
1557
1558 // See through any implicit casts we added to fix the type.
1559 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1560 Arg = Cast->getSubExpr();
1561
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001562 // C++0x allows nullptr, and there's no further checking to be done for that.
1563 if (Arg->getType()->isNullPtrType())
1564 return false;
1565
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001566 // C++ [temp.arg.nontype]p1:
1567 //
1568 // A template-argument for a non-type, non-template
1569 // template-parameter shall be one of: [...]
1570 //
1571 // -- a pointer to member expressed as described in 5.3.1.
1572 QualifiedDeclRefExpr *DRE = 0;
1573
1574 // Ignore (and complain about) any excess parentheses.
1575 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1576 if (!Invalid) {
1577 Diag(Arg->getSourceRange().getBegin(),
1578 diag::err_template_arg_extra_parens)
1579 << Arg->getSourceRange();
1580 Invalid = true;
1581 }
1582
1583 Arg = Parens->getSubExpr();
1584 }
1585
1586 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1587 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1588 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1589
1590 if (!DRE)
1591 return Diag(Arg->getSourceRange().getBegin(),
1592 diag::err_template_arg_not_pointer_to_member_form)
1593 << Arg->getSourceRange();
1594
1595 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1596 assert((isa<FieldDecl>(DRE->getDecl()) ||
1597 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1598 "Only non-static member pointers can make it here");
1599
1600 // Okay: this is the address of a non-static member, and therefore
1601 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001602 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001603 return Invalid;
1604 }
1605
1606 // We found something else, but we don't know specifically what it is.
1607 Diag(Arg->getSourceRange().getBegin(),
1608 diag::err_template_arg_not_pointer_to_member_form)
1609 << Arg->getSourceRange();
1610 Diag(DRE->getDecl()->getLocation(),
1611 diag::note_template_arg_refers_here);
1612 return true;
1613}
1614
Douglas Gregorc15cb382009-02-09 23:23:08 +00001615/// \brief Check a template argument against its corresponding
1616/// non-type template parameter.
1617///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001618/// This routine implements the semantics of C++ [temp.arg.nontype].
1619/// It returns true if an error occurred, and false otherwise. \p
1620/// InstantiatedParamType is the type of the non-type template
1621/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001622///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001623/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001624bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001625 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001626 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001627 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1628
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001629 // If either the parameter has a dependent type or the argument is
1630 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001631 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001632 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1633 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001634 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001635 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001636 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001637
1638 // C++ [temp.arg.nontype]p5:
1639 // The following conversions are performed on each expression used
1640 // as a non-type template-argument. If a non-type
1641 // template-argument cannot be converted to the type of the
1642 // corresponding template-parameter then the program is
1643 // ill-formed.
1644 //
1645 // -- for a non-type template-parameter of integral or
1646 // enumeration type, integral promotions (4.5) and integral
1647 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001648 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001649 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001650 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001651 // C++ [temp.arg.nontype]p1:
1652 // A template-argument for a non-type, non-template
1653 // template-parameter shall be one of:
1654 //
1655 // -- an integral constant-expression of integral or enumeration
1656 // type; or
1657 // -- the name of a non-type template-parameter; or
1658 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001659 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001660 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1661 Diag(Arg->getSourceRange().getBegin(),
1662 diag::err_template_arg_not_integral_or_enumeral)
1663 << ArgType << Arg->getSourceRange();
1664 Diag(Param->getLocation(), diag::note_template_param_here);
1665 return true;
1666 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001667 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001668 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1669 << ArgType << Arg->getSourceRange();
1670 return true;
1671 }
1672
1673 // FIXME: We need some way to more easily get the unqualified form
1674 // of the types without going all the way to the
1675 // canonical type.
1676 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1677 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1678 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1679 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1680
1681 // Try to convert the argument to the parameter's type.
1682 if (ParamType == ArgType) {
1683 // Okay: no conversion necessary
1684 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1685 !ParamType->isEnumeralType()) {
1686 // This is an integral promotion or conversion.
1687 ImpCastExprToType(Arg, ParamType);
1688 } else {
1689 // We can't perform this conversion.
1690 Diag(Arg->getSourceRange().getBegin(),
1691 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001692 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001693 Diag(Param->getLocation(), diag::note_template_param_here);
1694 return true;
1695 }
1696
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001697 QualType IntegerType = Context.getCanonicalType(ParamType);
1698 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001699 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001700
1701 if (!Arg->isValueDependent()) {
1702 // Check that an unsigned parameter does not receive a negative
1703 // value.
1704 if (IntegerType->isUnsignedIntegerType()
1705 && (Value.isSigned() && Value.isNegative())) {
1706 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1707 << Value.toString(10) << Param->getType()
1708 << Arg->getSourceRange();
1709 Diag(Param->getLocation(), diag::note_template_param_here);
1710 return true;
1711 }
1712
1713 // Check that we don't overflow the template parameter type.
1714 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1715 if (Value.getActiveBits() > AllowedBits) {
1716 Diag(Arg->getSourceRange().getBegin(),
1717 diag::err_template_arg_too_large)
1718 << Value.toString(10) << Param->getType()
1719 << Arg->getSourceRange();
1720 Diag(Param->getLocation(), diag::note_template_param_here);
1721 return true;
1722 }
1723
1724 if (Value.getBitWidth() != AllowedBits)
1725 Value.extOrTrunc(AllowedBits);
1726 Value.setIsSigned(IntegerType->isSignedIntegerType());
1727 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001728
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001729 // Add the value of this argument to the list of converted
1730 // arguments. We use the bitwidth and signedness of the template
1731 // parameter.
1732 if (Arg->isValueDependent()) {
1733 // The argument is value-dependent. Create a new
1734 // TemplateArgument with the converted expression.
1735 Converted = TemplateArgument(Arg);
1736 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001737 }
1738
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001739 Converted = TemplateArgument(StartLoc, Value,
1740 ParamType->isEnumeralType() ? ParamType
1741 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001742 return false;
1743 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001744
Douglas Gregorb86b0572009-02-11 01:18:59 +00001745 // Handle pointer-to-function, reference-to-function, and
1746 // pointer-to-member-function all in (roughly) the same way.
1747 if (// -- For a non-type template-parameter of type pointer to
1748 // function, only the function-to-pointer conversion (4.3) is
1749 // applied. If the template-argument represents a set of
1750 // overloaded functions (or a pointer to such), the matching
1751 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001752 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001753 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001754 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001755 // -- For a non-type template-parameter of type reference to
1756 // function, no conversions apply. If the template-argument
1757 // represents a set of overloaded functions, the matching
1758 // function is selected from the set (13.4).
1759 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001760 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001761 // -- For a non-type template-parameter of type pointer to
1762 // member function, no conversions apply. If the
1763 // template-argument represents a set of overloaded member
1764 // functions, the matching member function is selected from
1765 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001766 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001767 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001768 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001769 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001770 if (Context.hasSameUnqualifiedType(ArgType,
1771 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001772 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001773 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1774 ParamType->isMemberPointerType())) {
1775 ArgType = ParamType;
1776 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001777 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001778 ArgType = Context.getPointerType(ArgType);
1779 ImpCastExprToType(Arg, ArgType);
1780 } else if (FunctionDecl *Fn
1781 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001782 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1783 return true;
1784
Douglas Gregora35284b2009-02-11 00:19:33 +00001785 FixOverloadedFunctionReference(Arg, Fn);
1786 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001787 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001788 ArgType = Context.getPointerType(Arg->getType());
1789 ImpCastExprToType(Arg, ArgType);
1790 }
1791 }
1792
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001793 if (!Context.hasSameUnqualifiedType(ArgType,
1794 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001795 // We can't perform this conversion.
1796 Diag(Arg->getSourceRange().getBegin(),
1797 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001798 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001799 Diag(Param->getLocation(), diag::note_template_param_here);
1800 return true;
1801 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001802
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001803 if (ParamType->isMemberPointerType()) {
1804 NamedDecl *Member = 0;
1805 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1806 return true;
1807
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001808 if (Member)
1809 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001810 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001811 return false;
1812 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001813
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001814 NamedDecl *Entity = 0;
1815 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1816 return true;
1817
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001818 if (Entity)
1819 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001820 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001821 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001822 }
1823
Chris Lattnerfe90de72009-02-20 21:37:53 +00001824 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001825 // -- for a non-type template-parameter of type pointer to
1826 // object, qualification conversions (4.4) and the
1827 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001828 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00001829 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001830 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001831
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001832 if (ArgType->isNullPtrType()) {
1833 ArgType = ParamType;
1834 ImpCastExprToType(Arg, ParamType);
1835 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001836 ArgType = Context.getArrayDecayedType(ArgType);
1837 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001838 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001839
Douglas Gregorb86b0572009-02-11 01:18:59 +00001840 if (IsQualificationConversion(ArgType, ParamType)) {
1841 ArgType = ParamType;
1842 ImpCastExprToType(Arg, ParamType);
1843 }
1844
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001845 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001846 // We can't perform this conversion.
1847 Diag(Arg->getSourceRange().getBegin(),
1848 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001849 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001850 Diag(Param->getLocation(), diag::note_template_param_here);
1851 return true;
1852 }
1853
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001854 NamedDecl *Entity = 0;
1855 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1856 return true;
1857
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001858 if (Entity)
1859 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001860 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001861 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001862 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001863
Ted Kremenek6217b802009-07-29 21:53:49 +00001864 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001865 // -- For a non-type template-parameter of type reference to
1866 // object, no conversions apply. The type referred to by the
1867 // reference may be more cv-qualified than the (otherwise
1868 // identical) type of the template-argument. The
1869 // template-parameter is bound directly to the
1870 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001871 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001872 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001873
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001874 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001875 Diag(Arg->getSourceRange().getBegin(),
1876 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001877 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001878 << Arg->getSourceRange();
1879 Diag(Param->getLocation(), diag::note_template_param_here);
1880 return true;
1881 }
1882
1883 unsigned ParamQuals
1884 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1885 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1886
1887 if ((ParamQuals | ArgQuals) != ParamQuals) {
1888 Diag(Arg->getSourceRange().getBegin(),
1889 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001890 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001891 << Arg->getSourceRange();
1892 Diag(Param->getLocation(), diag::note_template_param_here);
1893 return true;
1894 }
1895
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001896 NamedDecl *Entity = 0;
1897 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1898 return true;
1899
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001900 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001901 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001902 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001903 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001904
1905 // -- For a non-type template-parameter of type pointer to data
1906 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001907 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001908 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1909
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001910 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001911 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001912 } else if (ArgType->isNullPtrType()) {
1913 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001914 } else if (IsQualificationConversion(ArgType, ParamType)) {
1915 ImpCastExprToType(Arg, ParamType);
1916 } else {
1917 // We can't perform this conversion.
1918 Diag(Arg->getSourceRange().getBegin(),
1919 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001920 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001921 Diag(Param->getLocation(), diag::note_template_param_here);
1922 return true;
1923 }
1924
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001925 NamedDecl *Member = 0;
1926 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1927 return true;
1928
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001929 if (Member)
1930 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001931 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001932 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001933}
1934
1935/// \brief Check a template argument against its corresponding
1936/// template template parameter.
1937///
1938/// This routine implements the semantics of C++ [temp.arg.template].
1939/// It returns true if an error occurred, and false otherwise.
1940bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1941 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001942 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1943 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1944
1945 // C++ [temp.arg.template]p1:
1946 // A template-argument for a template template-parameter shall be
1947 // the name of a class template, expressed as id-expression. Only
1948 // primary class templates are considered when matching the
1949 // template template argument with the corresponding parameter;
1950 // partial specializations are not considered even if their
1951 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001952 //
1953 // Note that we also allow template template parameters here, which
1954 // will happen when we are dealing with, e.g., class template
1955 // partial specializations.
1956 if (!isa<ClassTemplateDecl>(Template) &&
1957 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001958 assert(isa<FunctionTemplateDecl>(Template) &&
1959 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001960 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1961 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001962 << Template;
1963 }
1964
1965 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1966 Param->getTemplateParameters(),
1967 true, true,
1968 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001969}
1970
Douglas Gregorddc29e12009-02-06 22:42:48 +00001971/// \brief Determine whether the given template parameter lists are
1972/// equivalent.
1973///
1974/// \param New The new template parameter list, typically written in the
1975/// source code as part of a new template declaration.
1976///
1977/// \param Old The old template parameter list, typically found via
1978/// name lookup of the template declared with this template parameter
1979/// list.
1980///
1981/// \param Complain If true, this routine will produce a diagnostic if
1982/// the template parameter lists are not equivalent.
1983///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001984/// \param IsTemplateTemplateParm If true, this routine is being
1985/// called to compare the template parameter lists of a template
1986/// template parameter.
1987///
1988/// \param TemplateArgLoc If this source location is valid, then we
1989/// are actually checking the template parameter list of a template
1990/// argument (New) against the template parameter list of its
1991/// corresponding template template parameter (Old). We produce
1992/// slightly different diagnostics in this scenario.
1993///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001994/// \returns True if the template parameter lists are equal, false
1995/// otherwise.
1996bool
1997Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1998 TemplateParameterList *Old,
1999 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002000 bool IsTemplateTemplateParm,
2001 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002002 if (Old->size() != New->size()) {
2003 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002004 unsigned NextDiag = diag::err_template_param_list_different_arity;
2005 if (TemplateArgLoc.isValid()) {
2006 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2007 NextDiag = diag::note_template_param_list_different_arity;
2008 }
2009 Diag(New->getTemplateLoc(), NextDiag)
2010 << (New->size() > Old->size())
2011 << IsTemplateTemplateParm
2012 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002013 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2014 << IsTemplateTemplateParm
2015 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2016 }
2017
2018 return false;
2019 }
2020
2021 for (TemplateParameterList::iterator OldParm = Old->begin(),
2022 OldParmEnd = Old->end(), NewParm = New->begin();
2023 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2024 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002025 if (Complain) {
2026 unsigned NextDiag = diag::err_template_param_different_kind;
2027 if (TemplateArgLoc.isValid()) {
2028 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2029 NextDiag = diag::note_template_param_different_kind;
2030 }
2031 Diag((*NewParm)->getLocation(), NextDiag)
2032 << IsTemplateTemplateParm;
2033 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2034 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002035 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002036 return false;
2037 }
2038
2039 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2040 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002041 // know we're at the same index).
2042#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002043 // FIXME: Enable this code in debug mode *after* we properly go through
2044 // and "instantiate" the template parameter lists of template template
2045 // parameters. It's only after this instantiation that (1) any dependent
2046 // types within the template parameter list of the template template
2047 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002048 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00002049 QualType OldParmType
2050 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2051 QualType NewParmType
2052 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2053 assert(Context.getCanonicalType(OldParmType) ==
2054 Context.getCanonicalType(NewParmType) &&
2055 "type parameter mismatch?");
2056#endif
2057 } else if (NonTypeTemplateParmDecl *OldNTTP
2058 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2059 // The types of non-type template parameters must agree.
2060 NonTypeTemplateParmDecl *NewNTTP
2061 = cast<NonTypeTemplateParmDecl>(*NewParm);
2062 if (Context.getCanonicalType(OldNTTP->getType()) !=
2063 Context.getCanonicalType(NewNTTP->getType())) {
2064 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002065 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2066 if (TemplateArgLoc.isValid()) {
2067 Diag(TemplateArgLoc,
2068 diag::err_template_arg_template_params_mismatch);
2069 NextDiag = diag::note_template_nontype_parm_different_type;
2070 }
2071 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002072 << NewNTTP->getType()
2073 << IsTemplateTemplateParm;
2074 Diag(OldNTTP->getLocation(),
2075 diag::note_template_nontype_parm_prev_declaration)
2076 << OldNTTP->getType();
2077 }
2078 return false;
2079 }
2080 } else {
2081 // The template parameter lists of template template
2082 // parameters must agree.
2083 // FIXME: Could we perform a faster "type" comparison here?
2084 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2085 "Only template template parameters handled here");
2086 TemplateTemplateParmDecl *OldTTP
2087 = cast<TemplateTemplateParmDecl>(*OldParm);
2088 TemplateTemplateParmDecl *NewTTP
2089 = cast<TemplateTemplateParmDecl>(*NewParm);
2090 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2091 OldTTP->getTemplateParameters(),
2092 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002093 /*IsTemplateTemplateParm=*/true,
2094 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002095 return false;
2096 }
2097 }
2098
2099 return true;
2100}
2101
2102/// \brief Check whether a template can be declared within this scope.
2103///
2104/// If the template declaration is valid in this scope, returns
2105/// false. Otherwise, issues a diagnostic and returns true.
2106bool
2107Sema::CheckTemplateDeclScope(Scope *S,
2108 MultiTemplateParamsArg &TemplateParameterLists) {
2109 assert(TemplateParameterLists.size() > 0 && "Not a template");
2110
2111 // Find the nearest enclosing declaration scope.
2112 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2113 (S->getFlags() & Scope::TemplateParamScope) != 0)
2114 S = S->getParent();
2115
2116 TemplateParameterList *TemplateParams =
2117 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2118 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2119 SourceRange TemplateRange
2120 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2121
2122 // C++ [temp]p2:
2123 // A template-declaration can appear only as a namespace scope or
2124 // class scope declaration.
2125 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002126 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2127 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2128 return Diag(TemplateLoc, diag::err_template_linkage) << TemplateRange;
2129
2130 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002131 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002132
2133 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2134 return false;
2135
2136 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2137 << TemplateRange;
2138}
Douglas Gregorcc636682009-02-17 23:15:12 +00002139
Douglas Gregorff668032009-05-13 18:28:20 +00002140/// \brief Check whether a class template specialization or explicit
2141/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002142///
Douglas Gregorff668032009-05-13 18:28:20 +00002143/// This routine determines whether a class template specialization or
2144/// explicit instantiation can be declared in the current context
2145/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2146/// appropriate diagnostics if there was an error. It returns true if
2147// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002148bool
2149Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2150 ClassTemplateSpecializationDecl *PrevDecl,
2151 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002152 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002153 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002154 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002155 // C++ [temp.expl.spec]p2:
2156 // An explicit specialization shall be declared in the namespace
2157 // of which the template is a member, or, for member templates, in
2158 // the namespace of which the enclosing class or enclosing class
2159 // template is a member. An explicit specialization of a member
2160 // function, member class or static data member of a class
2161 // template shall be declared in the namespace of which the class
2162 // template is a member. Such a declaration may also be a
2163 // definition. If the declaration is not a definition, the
2164 // specialization may be defined later in the name- space in which
2165 // the explicit specialization was declared, or in a namespace
2166 // that encloses the one in which the explicit specialization was
2167 // declared.
2168 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002169 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002170 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002171 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002172 return true;
2173 }
2174
2175 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2176 DeclContext *TemplateContext
2177 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002178 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2179 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002180 // There is no prior declaration of this entity, so this
2181 // specialization must be in the same context as the template
2182 // itself.
2183 if (DC != TemplateContext) {
2184 if (isa<TranslationUnitDecl>(TemplateContext))
2185 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002186 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002187 << ClassTemplate << ScopeSpecifierRange;
2188 else if (isa<NamespaceDecl>(TemplateContext))
2189 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002190 << PartialSpecialization << ClassTemplate
2191 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002192
2193 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2194 }
2195
2196 return false;
2197 }
2198
2199 // We have a previous declaration of this entity. Make sure that
2200 // this redeclaration (or definition) occurs in an enclosing namespace.
2201 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002202 // FIXME: In C++98, we would like to turn these errors into warnings,
2203 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002204 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002205 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002206 if (isa<TranslationUnitDecl>(TemplateContext)) {
2207 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2208 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002209 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002210 else
2211 SuppressedDiag = true;
2212 } else if (isa<NamespaceDecl>(TemplateContext)) {
2213 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2214 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002215 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002216 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2217 else
2218 SuppressedDiag = true;
2219 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002220
Douglas Gregorff668032009-05-13 18:28:20 +00002221 if (!SuppressedDiag)
2222 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002223 }
2224
2225 return false;
2226}
2227
Douglas Gregore94866f2009-06-12 21:21:02 +00002228/// \brief Check the non-type template arguments of a class template
2229/// partial specialization according to C++ [temp.class.spec]p9.
2230///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002231/// \param TemplateParams the template parameters of the primary class
2232/// template.
2233///
2234/// \param TemplateArg the template arguments of the class template
2235/// partial specialization.
2236///
2237/// \param MirrorsPrimaryTemplate will be set true if the class
2238/// template partial specialization arguments are identical to the
2239/// implicit template arguments of the primary template. This is not
2240/// necessarily an error (C++0x), and it is left to the caller to diagnose
2241/// this condition when it is an error.
2242///
Douglas Gregore94866f2009-06-12 21:21:02 +00002243/// \returns true if there was an error, false otherwise.
2244bool Sema::CheckClassTemplatePartialSpecializationArgs(
2245 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002246 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002247 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002248 // FIXME: the interface to this function will have to change to
2249 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002250 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002251
Anders Carlssonfb250522009-06-23 01:26:57 +00002252 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002253
Douglas Gregore94866f2009-06-12 21:21:02 +00002254 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002255 // Determine whether the template argument list of the partial
2256 // specialization is identical to the implicit argument list of
2257 // the primary template. The caller may need to diagnostic this as
2258 // an error per C++ [temp.class.spec]p9b3.
2259 if (MirrorsPrimaryTemplate) {
2260 if (TemplateTypeParmDecl *TTP
2261 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2262 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002263 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002264 MirrorsPrimaryTemplate = false;
2265 } else if (TemplateTemplateParmDecl *TTP
2266 = dyn_cast<TemplateTemplateParmDecl>(
2267 TemplateParams->getParam(I))) {
2268 // FIXME: We should settle on either Declaration storage or
2269 // Expression storage for template template parameters.
2270 TemplateTemplateParmDecl *ArgDecl
2271 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002272 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002273 if (!ArgDecl)
2274 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002275 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002276 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2277
2278 if (!ArgDecl ||
2279 ArgDecl->getIndex() != TTP->getIndex() ||
2280 ArgDecl->getDepth() != TTP->getDepth())
2281 MirrorsPrimaryTemplate = false;
2282 }
2283 }
2284
Douglas Gregore94866f2009-06-12 21:21:02 +00002285 NonTypeTemplateParmDecl *Param
2286 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002287 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002288 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002289 }
2290
Anders Carlsson6360be72009-06-13 18:20:51 +00002291 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002292 if (!ArgExpr) {
2293 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002294 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002295 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002296
2297 // C++ [temp.class.spec]p8:
2298 // A non-type argument is non-specialized if it is the name of a
2299 // non-type parameter. All other non-type arguments are
2300 // specialized.
2301 //
2302 // Below, we check the two conditions that only apply to
2303 // specialized non-type arguments, so skip any non-specialized
2304 // arguments.
2305 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002306 if (NonTypeTemplateParmDecl *NTTP
2307 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2308 if (MirrorsPrimaryTemplate &&
2309 (Param->getIndex() != NTTP->getIndex() ||
2310 Param->getDepth() != NTTP->getDepth()))
2311 MirrorsPrimaryTemplate = false;
2312
Douglas Gregore94866f2009-06-12 21:21:02 +00002313 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002314 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002315
2316 // C++ [temp.class.spec]p9:
2317 // Within the argument list of a class template partial
2318 // specialization, the following restrictions apply:
2319 // -- A partially specialized non-type argument expression
2320 // shall not involve a template parameter of the partial
2321 // specialization except when the argument expression is a
2322 // simple identifier.
2323 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2324 Diag(ArgExpr->getLocStart(),
2325 diag::err_dependent_non_type_arg_in_partial_spec)
2326 << ArgExpr->getSourceRange();
2327 return true;
2328 }
2329
2330 // -- The type of a template parameter corresponding to a
2331 // specialized non-type argument shall not be dependent on a
2332 // parameter of the specialization.
2333 if (Param->getType()->isDependentType()) {
2334 Diag(ArgExpr->getLocStart(),
2335 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2336 << Param->getType()
2337 << ArgExpr->getSourceRange();
2338 Diag(Param->getLocation(), diag::note_template_param_here);
2339 return true;
2340 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002341
2342 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002343 }
2344
2345 return false;
2346}
2347
Douglas Gregor212e81c2009-03-25 00:13:59 +00002348Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00002349Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2350 TagUseKind TUK,
Douglas Gregorcc636682009-02-17 23:15:12 +00002351 SourceLocation KWLoc,
2352 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002353 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002354 SourceLocation TemplateNameLoc,
2355 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002356 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002357 SourceLocation *TemplateArgLocs,
2358 SourceLocation RAngleLoc,
2359 AttributeList *Attr,
2360 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002361 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002362 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002363 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002364 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002365
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002366 bool isPartialSpecialization = false;
2367
Douglas Gregor88b70942009-02-25 22:02:03 +00002368 // Check the validity of the template headers that introduce this
2369 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002370 // FIXME: Once we have member templates, we'll need to check
2371 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2372 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002373 if (TemplateParameterLists.size() == 0)
2374 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002375 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002376 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002377 TemplateParameterList *TemplateParams
2378 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002379 if (TemplateParameterLists.size() > 1) {
2380 Diag(TemplateParams->getTemplateLoc(),
2381 diag::err_template_spec_extra_headers);
2382 return true;
2383 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002384
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002385 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002386 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002387
2388 // C++ [temp.class.spec]p10:
2389 // The template parameter list of a specialization shall not
2390 // contain default template argument values.
2391 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2392 Decl *Param = TemplateParams->getParam(I);
2393 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2394 if (TTP->hasDefaultArgument()) {
2395 Diag(TTP->getDefaultArgumentLoc(),
2396 diag::err_default_arg_in_partial_spec);
2397 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2398 }
2399 } else if (NonTypeTemplateParmDecl *NTTP
2400 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2401 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2402 Diag(NTTP->getDefaultArgumentLoc(),
2403 diag::err_default_arg_in_partial_spec)
2404 << DefArg->getSourceRange();
2405 NTTP->setDefaultArgument(0);
2406 DefArg->Destroy(Context);
2407 }
2408 } else {
2409 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2410 if (Expr *DefArg = TTP->getDefaultArgument()) {
2411 Diag(TTP->getDefaultArgumentLoc(),
2412 diag::err_default_arg_in_partial_spec)
2413 << DefArg->getSourceRange();
2414 TTP->setDefaultArgument(0);
2415 DefArg->Destroy(Context);
2416 }
2417 }
2418 }
2419 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002420 }
2421
Douglas Gregorcc636682009-02-17 23:15:12 +00002422 // Check that the specialization uses the same tag kind as the
2423 // original template.
2424 TagDecl::TagKind Kind;
2425 switch (TagSpec) {
2426 default: assert(0 && "Unknown tag type!");
2427 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2428 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2429 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2430 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002431 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2432 Kind, KWLoc,
2433 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002434 Diag(KWLoc, diag::err_use_with_wrong_tag)
2435 << ClassTemplate
2436 << CodeModificationHint::CreateReplacement(KWLoc,
2437 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002438 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2439 diag::note_previous_use);
2440 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2441 }
2442
Douglas Gregor40808ce2009-03-09 23:48:35 +00002443 // Translate the parser's template argument list in our AST format.
2444 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2445 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2446
Douglas Gregorcc636682009-02-17 23:15:12 +00002447 // Check that the template argument list is well-formed for this
2448 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002449 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2450 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002451 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002452 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002453 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002454 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002455
Anders Carlssonfb250522009-06-23 01:26:57 +00002456 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002457 ClassTemplate->getTemplateParameters()->size()) &&
2458 "Converted template argument list is too short!");
2459
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002460 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002461 // corresponds to these arguments.
2462 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002463 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002464 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002465 if (CheckClassTemplatePartialSpecializationArgs(
2466 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002467 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002468 return true;
2469
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002470 if (MirrorsPrimaryTemplate) {
2471 // C++ [temp.class.spec]p9b3:
2472 //
2473 // -- The argument list of the specialization shall not be identical
2474 // to the implicit argument list of the primary template.
2475 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00002476 << (TUK == TUK_Definition)
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002477 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2478 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00002479 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002480 ClassTemplate->getIdentifier(),
2481 TemplateNameLoc,
2482 Attr,
2483 move(TemplateParameterLists),
2484 AS_none);
2485 }
2486
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002487 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002488 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002489 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002490 Converted.flatSize(),
2491 Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002492 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002493 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002494 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002495 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002496 Converted.flatSize(),
2497 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002498 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002499 ClassTemplateSpecializationDecl *PrevDecl = 0;
2500
2501 if (isPartialSpecialization)
2502 PrevDecl
2503 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2504 InsertPos);
2505 else
2506 PrevDecl
2507 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002508
2509 ClassTemplateSpecializationDecl *Specialization = 0;
2510
Douglas Gregor88b70942009-02-25 22:02:03 +00002511 // Check whether we can declare a class template specialization in
2512 // the current scope.
2513 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2514 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002515 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002516 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002517 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002518 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002519
Douglas Gregorb88e8882009-07-30 17:40:51 +00002520 // The canonical type
2521 QualType CanonType;
Douglas Gregorcc636682009-02-17 23:15:12 +00002522 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2523 // Since the only prior class template specialization with these
2524 // arguments was referenced but not declared, reuse that
2525 // declaration node as our own, updating its source location to
2526 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002527 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002528 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002529 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00002530 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002531 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002532 // Build the canonical type that describes the converted template
2533 // arguments of the class template partial specialization.
2534 CanonType = Context.getTemplateSpecializationType(
2535 TemplateName(ClassTemplate),
2536 Converted.getFlatArguments(),
2537 Converted.flatSize());
2538
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002539 // Create a new class template partial specialization declaration node.
2540 TemplateParameterList *TemplateParams
2541 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2542 ClassTemplatePartialSpecializationDecl *PrevPartial
2543 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2544 ClassTemplatePartialSpecializationDecl *Partial
2545 = ClassTemplatePartialSpecializationDecl::Create(Context,
2546 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002547 TemplateNameLoc,
2548 TemplateParams,
2549 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002550 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002551 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002552
2553 if (PrevPartial) {
2554 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2555 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2556 } else {
2557 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2558 }
2559 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002560
2561 // Check that all of the template parameters of the class template
2562 // partial specialization are deducible from the template
2563 // arguments. If not, this class template partial specialization
2564 // will never be used.
2565 llvm::SmallVector<bool, 8> DeducibleParams;
2566 DeducibleParams.resize(TemplateParams->size());
2567 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2568 unsigned NumNonDeducible = 0;
2569 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2570 if (!DeducibleParams[I])
2571 ++NumNonDeducible;
2572
2573 if (NumNonDeducible) {
2574 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2575 << (NumNonDeducible > 1)
2576 << SourceRange(TemplateNameLoc, RAngleLoc);
2577 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2578 if (!DeducibleParams[I]) {
2579 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2580 if (Param->getDeclName())
2581 Diag(Param->getLocation(),
2582 diag::note_partial_spec_unused_parameter)
2583 << Param->getDeclName();
2584 else
2585 Diag(Param->getLocation(),
2586 diag::note_partial_spec_unused_parameter)
2587 << std::string("<anonymous>");
2588 }
2589 }
2590 }
Douglas Gregorcc636682009-02-17 23:15:12 +00002591 } else {
2592 // Create a new class template specialization declaration node for
2593 // this explicit specialization.
2594 Specialization
2595 = ClassTemplateSpecializationDecl::Create(Context,
2596 ClassTemplate->getDeclContext(),
2597 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002598 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002599 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002600 PrevDecl);
2601
2602 if (PrevDecl) {
2603 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2604 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2605 } else {
2606 ClassTemplate->getSpecializations().InsertNode(Specialization,
2607 InsertPos);
2608 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00002609
2610 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002611 }
2612
2613 // Note that this is an explicit specialization.
2614 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2615
2616 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002617 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002618 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002619 // FIXME: Should also handle explicit specialization after implicit
2620 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002621 SourceRange Range(TemplateNameLoc, RAngleLoc);
2622 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002623 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002624 Diag(Def->getLocation(), diag::note_previous_definition);
2625 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002626 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002627 }
2628 }
2629
Douglas Gregorfc705b82009-02-26 22:19:44 +00002630 // Build the fully-sugared type for this class template
2631 // specialization as the user wrote in the specialization
2632 // itself. This means that we'll pretty-print the type retrieved
2633 // from the specialization's declaration the way that the user
2634 // actually wrote the specialization, rather than formatting the
2635 // name based on the "canonical" representation used to store the
2636 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002637 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002638 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002639 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002640 TemplateArgs.size(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00002641 CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +00002642 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002643 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002644
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002645 // C++ [temp.expl.spec]p9:
2646 // A template explicit specialization is in the scope of the
2647 // namespace in which the template was defined.
2648 //
2649 // We actually implement this paragraph where we set the semantic
2650 // context (in the creation of the ClassTemplateSpecializationDecl),
2651 // but we also maintain the lexical context where the actual
2652 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002653 Specialization->setLexicalDeclContext(CurContext);
2654
2655 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00002656 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00002657 Specialization->startDefinition();
2658
2659 // Add the specialization into its lexical context, so that it can
2660 // be seen when iterating through the list of declarations in that
2661 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002662 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002663 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002664}
Douglas Gregord57959a2009-03-27 23:10:48 +00002665
Douglas Gregore542c862009-06-23 23:11:28 +00002666Sema::DeclPtrTy
2667Sema::ActOnTemplateDeclarator(Scope *S,
2668 MultiTemplateParamsArg TemplateParameterLists,
2669 Declarator &D) {
2670 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2671}
2672
Douglas Gregor52591bf2009-06-24 00:54:41 +00002673Sema::DeclPtrTy
2674Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2675 MultiTemplateParamsArg TemplateParameterLists,
2676 Declarator &D) {
2677 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2678 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2679 "Not a function declarator!");
2680 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2681
2682 if (FTI.hasPrototype) {
2683 // FIXME: Diagnose arguments without names in C.
2684 }
2685
2686 Scope *ParentScope = FnBodyScope->getParent();
2687
2688 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2689 move(TemplateParameterLists),
2690 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002691 if (FunctionTemplateDecl *FunctionTemplate
2692 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002693 return ActOnStartOfFunctionDef(FnBodyScope,
2694 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002695 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2696 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002697 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002698}
2699
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002700// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002701Sema::DeclResult
2702Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2703 unsigned TagSpec,
2704 SourceLocation KWLoc,
2705 const CXXScopeSpec &SS,
2706 TemplateTy TemplateD,
2707 SourceLocation TemplateNameLoc,
2708 SourceLocation LAngleLoc,
2709 ASTTemplateArgsPtr TemplateArgsIn,
2710 SourceLocation *TemplateArgLocs,
2711 SourceLocation RAngleLoc,
2712 AttributeList *Attr) {
2713 // Find the class template we're specializing
2714 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2715 ClassTemplateDecl *ClassTemplate
2716 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2717
2718 // Check that the specialization uses the same tag kind as the
2719 // original template.
2720 TagDecl::TagKind Kind;
2721 switch (TagSpec) {
2722 default: assert(0 && "Unknown tag type!");
2723 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2724 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2725 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2726 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002727 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2728 Kind, KWLoc,
2729 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002730 Diag(KWLoc, diag::err_use_with_wrong_tag)
2731 << ClassTemplate
2732 << CodeModificationHint::CreateReplacement(KWLoc,
2733 ClassTemplate->getTemplatedDecl()->getKindName());
2734 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2735 diag::note_previous_use);
2736 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2737 }
2738
Douglas Gregorff668032009-05-13 18:28:20 +00002739 // C++0x [temp.explicit]p2:
2740 // [...] An explicit instantiation shall appear in an enclosing
2741 // namespace of its template. [...]
2742 //
2743 // This is C++ DR 275.
2744 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2745 TemplateNameLoc,
2746 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002747 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002748 /*ExplicitInstantiation=*/true))
2749 return true;
2750
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002751 // Translate the parser's template argument list in our AST format.
2752 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2753 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2754
2755 // Check that the template argument list is well-formed for this
2756 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002757 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2758 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002759 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002760 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002761 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002762 return true;
2763
Anders Carlssonfb250522009-06-23 01:26:57 +00002764 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002765 ClassTemplate->getTemplateParameters()->size()) &&
2766 "Converted template argument list is too short!");
2767
2768 // Find the class template specialization declaration that
2769 // corresponds to these arguments.
2770 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002771 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002772 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002773 Converted.flatSize(),
2774 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002775 void *InsertPos = 0;
2776 ClassTemplateSpecializationDecl *PrevDecl
2777 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2778
2779 ClassTemplateSpecializationDecl *Specialization = 0;
2780
Douglas Gregorff668032009-05-13 18:28:20 +00002781 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002782 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002783 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002784 // This particular specialization has already been declared or
2785 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002786 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2787 << Context.getTypeDeclType(PrevDecl);
2788 Diag(PrevDecl->getLocation(),
2789 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002790 return DeclPtrTy::make(PrevDecl);
2791 }
2792
Douglas Gregorff668032009-05-13 18:28:20 +00002793 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002794 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002795 // For a given set of template parameters, if an explicit
2796 // instantiation of a template appears after a declaration of
2797 // an explicit specialization for that template, the explicit
2798 // instantiation has no effect.
2799 if (!getLangOptions().CPlusPlus0x) {
2800 Diag(TemplateNameLoc,
2801 diag::ext_explicit_instantiation_after_specialization)
2802 << Context.getTypeDeclType(PrevDecl);
2803 Diag(PrevDecl->getLocation(),
2804 diag::note_previous_template_specialization);
2805 }
2806
2807 // Create a new class template specialization declaration node
2808 // for this explicit specialization. This node is only used to
2809 // record the existence of this explicit instantiation for
2810 // accurate reproduction of the source code; we don't actually
2811 // use it for anything, since it is semantically irrelevant.
2812 Specialization
2813 = ClassTemplateSpecializationDecl::Create(Context,
2814 ClassTemplate->getDeclContext(),
2815 TemplateNameLoc,
2816 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002817 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002818 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002819 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002820 return DeclPtrTy::make(Specialization);
2821 }
2822
2823 // If we have already (implicitly) instantiated this
2824 // specialization, there is less work to do.
2825 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2826 SpecializationRequiresInstantiation = false;
2827
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002828 // Since the only prior class template specialization with these
2829 // arguments was referenced but not declared, reuse that
2830 // declaration node as our own, updating its source location to
2831 // reflect our new declaration.
2832 Specialization = PrevDecl;
2833 Specialization->setLocation(TemplateNameLoc);
2834 PrevDecl = 0;
2835 } else {
2836 // Create a new class template specialization declaration node for
2837 // this explicit specialization.
2838 Specialization
2839 = ClassTemplateSpecializationDecl::Create(Context,
2840 ClassTemplate->getDeclContext(),
2841 TemplateNameLoc,
2842 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002843 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002844
2845 ClassTemplate->getSpecializations().InsertNode(Specialization,
2846 InsertPos);
2847 }
2848
2849 // Build the fully-sugared type for this explicit instantiation as
2850 // the user wrote in the explicit instantiation itself. This means
2851 // that we'll pretty-print the type retrieved from the
2852 // specialization's declaration the way that the user actually wrote
2853 // the explicit instantiation, rather than formatting the name based
2854 // on the "canonical" representation used to store the template
2855 // arguments in the specialization.
2856 QualType WrittenTy
2857 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002858 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002859 TemplateArgs.size(),
2860 Context.getTypeDeclType(Specialization));
2861 Specialization->setTypeAsWritten(WrittenTy);
2862 TemplateArgsIn.release();
2863
2864 // Add the explicit instantiation into its lexical context. However,
2865 // since explicit instantiations are never found by name lookup, we
2866 // just put it into the declaration context directly.
2867 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002868 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002869
2870 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002871 // A definition of a class template or class member template
2872 // shall be in scope at the point of the explicit instantiation of
2873 // the class template or class member template.
2874 //
2875 // This check comes when we actually try to perform the
2876 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002877 if (SpecializationRequiresInstantiation)
2878 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002879 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002880 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002881
2882 return DeclPtrTy::make(Specialization);
2883}
2884
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002885// Explicit instantiation of a member class of a class template.
2886Sema::DeclResult
2887Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2888 unsigned TagSpec,
2889 SourceLocation KWLoc,
2890 const CXXScopeSpec &SS,
2891 IdentifierInfo *Name,
2892 SourceLocation NameLoc,
2893 AttributeList *Attr) {
2894
Douglas Gregor402abb52009-05-28 23:31:59 +00002895 bool Owned = false;
John McCall0f434ec2009-07-31 02:45:11 +00002896 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002897 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2898 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002899 if (!TagD)
2900 return true;
2901
2902 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2903 if (Tag->isEnum()) {
2904 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2905 << Context.getTypeDeclType(Tag);
2906 return true;
2907 }
2908
Douglas Gregord0c87372009-05-27 17:30:49 +00002909 if (Tag->isInvalidDecl())
2910 return true;
2911
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002912 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2913 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2914 if (!Pattern) {
2915 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2916 << Context.getTypeDeclType(Record);
2917 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2918 return true;
2919 }
2920
2921 // C++0x [temp.explicit]p2:
2922 // [...] An explicit instantiation shall appear in an enclosing
2923 // namespace of its template. [...]
2924 //
2925 // This is C++ DR 275.
2926 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002927 // FIXME: In C++98, we would like to turn these errors into warnings,
2928 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002929 DeclContext *PatternContext
2930 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2931 if (!CurContext->Encloses(PatternContext)) {
2932 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2933 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2934 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2935 }
2936 }
2937
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002938 if (!Record->getDefinition(Context)) {
2939 // If the class has a definition, instantiate it (and all of its
2940 // members, recursively).
2941 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2942 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002943 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002944 /*ExplicitInstantiation=*/true))
2945 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002946 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002947 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002948 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002949
Mike Stump390b4cc2009-05-16 07:39:55 +00002950 // FIXME: We don't have any representation for explicit instantiations of
2951 // member classes. Such a representation is not needed for compilation, but it
2952 // should be available for clients that want to see all of the declarations in
2953 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002954 return TagD;
2955}
2956
Douglas Gregord57959a2009-03-27 23:10:48 +00002957Sema::TypeResult
2958Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2959 const IdentifierInfo &II, SourceLocation IdLoc) {
2960 NestedNameSpecifier *NNS
2961 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2962 if (!NNS)
2963 return true;
2964
2965 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002966 if (T.isNull())
2967 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002968 return T.getAsOpaquePtr();
2969}
2970
Douglas Gregor17343172009-04-01 00:28:59 +00002971Sema::TypeResult
2972Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2973 SourceLocation TemplateLoc, TypeTy *Ty) {
2974 QualType T = QualType::getFromOpaquePtr(Ty);
2975 NestedNameSpecifier *NNS
2976 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2977 const TemplateSpecializationType *TemplateId
2978 = T->getAsTemplateSpecializationType();
2979 assert(TemplateId && "Expected a template specialization type");
2980
2981 if (NNS->isDependent())
2982 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2983
2984 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2985}
2986
Douglas Gregord57959a2009-03-27 23:10:48 +00002987/// \brief Build the type that describes a C++ typename specifier,
2988/// e.g., "typename T::type".
2989QualType
2990Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2991 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002992 CXXRecordDecl *CurrentInstantiation = 0;
2993 if (NNS->isDependent()) {
2994 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002995
Douglas Gregor42af25f2009-05-11 19:58:34 +00002996 // If the nested-name-specifier does not refer to the current
2997 // instantiation, then build a typename type.
2998 if (!CurrentInstantiation)
2999 return Context.getTypenameType(NNS, &II);
3000 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003001
Douglas Gregor42af25f2009-05-11 19:58:34 +00003002 DeclContext *Ctx = 0;
3003
3004 if (CurrentInstantiation)
3005 Ctx = CurrentInstantiation;
3006 else {
3007 CXXScopeSpec SS;
3008 SS.setScopeRep(NNS);
3009 SS.setRange(Range);
3010 if (RequireCompleteDeclContext(SS))
3011 return QualType();
3012
3013 Ctx = computeDeclContext(SS);
3014 }
Douglas Gregord57959a2009-03-27 23:10:48 +00003015 assert(Ctx && "No declaration context?");
3016
3017 DeclarationName Name(&II);
3018 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3019 false);
3020 unsigned DiagID = 0;
3021 Decl *Referenced = 0;
3022 switch (Result.getKind()) {
3023 case LookupResult::NotFound:
3024 if (Ctx->isTranslationUnit())
3025 DiagID = diag::err_typename_nested_not_found_global;
3026 else
3027 DiagID = diag::err_typename_nested_not_found;
3028 break;
3029
3030 case LookupResult::Found:
3031 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3032 // We found a type. Build a QualifiedNameType, since the
3033 // typename-specifier was just sugar. FIXME: Tell
3034 // QualifiedNameType that it has a "typename" prefix.
3035 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3036 }
3037
3038 DiagID = diag::err_typename_nested_not_type;
3039 Referenced = Result.getAsDecl();
3040 break;
3041
3042 case LookupResult::FoundOverloaded:
3043 DiagID = diag::err_typename_nested_not_type;
3044 Referenced = *Result.begin();
3045 break;
3046
3047 case LookupResult::AmbiguousBaseSubobjectTypes:
3048 case LookupResult::AmbiguousBaseSubobjects:
3049 case LookupResult::AmbiguousReference:
3050 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3051 return QualType();
3052 }
3053
3054 // If we get here, it's because name lookup did not find a
3055 // type. Emit an appropriate diagnostic and return an error.
3056 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3057 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3058 else
3059 Diag(Range.getEnd(), DiagID) << Range << Name;
3060 if (Referenced)
3061 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3062 << Name;
3063 return QualType();
3064}