blob: 425b50263fe76fb0451cbf7dc14f8abdb54f5ce8 [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
Douglas Gregorbd1099e2009-07-23 16:36:45 +0000441Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
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?");
448 assert(TK != TK_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.
518 if (TK == TK_Definition) {
519 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
580 if (TK == TK_Definition)
581 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.
818 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
819 continue;
820 }
821
822 TemplateIdsInSpecifier.push_back(SpecType);
823 }
824 }
825
826 // Reverse the list of template-ids in the scope specifier, so that we can
827 // more easily match up the template-ids and the template parameter lists.
828 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
829
830 SourceLocation FirstTemplateLoc = DeclStartLoc;
831 if (NumParamLists)
832 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
833
834 // Match the template-ids found in the specifier to the template parameter
835 // lists.
836 unsigned Idx = 0;
837 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
838 Idx != NumTemplateIds; ++Idx) {
839 bool DependentTemplateId = TemplateIdsInSpecifier[Idx]->isDependentType();
840 if (Idx >= NumParamLists) {
841 // We have a template-id without a corresponding template parameter
842 // list.
843 if (DependentTemplateId) {
844 // FIXME: the location information here isn't great.
845 Diag(SS.getRange().getBegin(),
846 diag::err_template_spec_needs_template_parameters)
847 << QualType(TemplateIdsInSpecifier[Idx], 0)
848 << SS.getRange();
849 } else {
850 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
851 << SS.getRange()
852 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
853 "template<> ");
854 }
855 return 0;
856 }
857
858 // Check the template parameter list against its corresponding template-id.
859 TemplateDecl *Template
860 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
861 TemplateParameterListsAreEqual(ParamLists[Idx],
862 Template->getTemplateParameters(),
863 true);
864 }
865
866 // If there were at least as many template-ids as there were template
867 // parameter lists, then there are no template parameter lists remaining for
868 // the declaration itself.
869 if (Idx >= NumParamLists)
870 return 0;
871
872 // If there were too many template parameter lists, complain about that now.
873 if (Idx != NumParamLists - 1) {
874 while (Idx < NumParamLists - 1) {
875 Diag(ParamLists[Idx]->getTemplateLoc(),
876 diag::err_template_spec_extra_headers)
877 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
878 ParamLists[Idx]->getRAngleLoc());
879 ++Idx;
880 }
881 }
882
883 // Return the last template parameter list, which corresponds to the
884 // entity being declared.
885 return ParamLists[NumParamLists - 1];
886}
887
Douglas Gregor40808ce2009-03-09 23:48:35 +0000888/// \brief Translates template arguments as provided by the parser
889/// into template arguments used by semantic analysis.
890static void
891translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
892 SourceLocation *TemplateArgLocs,
893 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
894 TemplateArgs.reserve(TemplateArgsIn.size());
895
896 void **Args = TemplateArgsIn.getArgs();
897 bool *ArgIsType = TemplateArgsIn.getArgIsType();
898 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
899 TemplateArgs.push_back(
900 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
901 QualType::getFromOpaquePtr(Args[Arg]))
902 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
903 }
904}
905
Douglas Gregor7532dc62009-03-30 22:58:21 +0000906QualType Sema::CheckTemplateIdType(TemplateName Name,
907 SourceLocation TemplateLoc,
908 SourceLocation LAngleLoc,
909 const TemplateArgument *TemplateArgs,
910 unsigned NumTemplateArgs,
911 SourceLocation RAngleLoc) {
912 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000913 if (!Template) {
914 // The template name does not resolve to a template, so we just
915 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000916 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000917 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000918 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000919
Douglas Gregor40808ce2009-03-09 23:48:35 +0000920 // Check that the template argument list is well-formed for this
921 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000922 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
923 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000924 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000925 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000926 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000927 return QualType();
928
Anders Carlssonfb250522009-06-23 01:26:57 +0000929 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000930 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000931 "Converted template argument list is too short!");
932
933 QualType CanonType;
934
Douglas Gregor7532dc62009-03-30 22:58:21 +0000935 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000936 TemplateArgs,
937 NumTemplateArgs)) {
938 // This class template specialization is a dependent
939 // type. Therefore, its canonical type is another class template
940 // specialization type that contains all of the converted
941 // arguments in canonical form. This ensures that, e.g., A<T> and
942 // A<T, T> have identical types when A is declared as:
943 //
944 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000945 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
946 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000947 Converted.getFlatArguments(),
948 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +0000949
950 // FIXME: CanonType is not actually the canonical type, and unfortunately
951 // it is a TemplateTypeSpecializationType that we will never use again.
952 // In the future, we need to teach getTemplateSpecializationType to only
953 // build the canonical type and return that to us.
954 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000955 } else if (ClassTemplateDecl *ClassTemplate
956 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000957 // Find the class template specialization declaration that
958 // corresponds to these arguments.
959 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000960 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000961 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000962 Converted.flatSize(),
963 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000964 void *InsertPos = 0;
965 ClassTemplateSpecializationDecl *Decl
966 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
967 if (!Decl) {
968 // This is the first time we have referenced this class template
969 // specialization. Create the canonical declaration and add it to
970 // the set of specializations.
971 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000972 ClassTemplate->getDeclContext(),
973 TemplateLoc,
974 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000975 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000976 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
977 Decl->setLexicalDeclContext(CurContext);
978 }
979
980 CanonType = Context.getTypeDeclType(Decl);
981 }
982
983 // Build the fully-sugared type for this class template
984 // specialization, which refers back to the class template
985 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000986 return Context.getTemplateSpecializationType(Name, TemplateArgs,
987 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000988}
989
Douglas Gregorcc636682009-02-17 23:15:12 +0000990Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000991Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
992 SourceLocation LAngleLoc,
993 ASTTemplateArgsPtr TemplateArgsIn,
994 SourceLocation *TemplateArgLocs,
995 SourceLocation RAngleLoc) {
996 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000997
Douglas Gregor40808ce2009-03-09 23:48:35 +0000998 // Translate the parser's template argument list in our AST format.
999 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1000 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001001
Douglas Gregor7532dc62009-03-30 22:58:21 +00001002 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001003 TemplateArgs.data(),
1004 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00001005 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001006 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001007
1008 if (Result.isNull())
1009 return true;
1010
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001011 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001012}
1013
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001014Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1015 SourceLocation TemplateNameLoc,
1016 SourceLocation LAngleLoc,
1017 const TemplateArgument *TemplateArgs,
1018 unsigned NumTemplateArgs,
1019 SourceLocation RAngleLoc) {
1020 // FIXME: Can we do any checking at this point? I guess we could check the
1021 // template arguments that we have against the template name, if the template
1022 // name refers to a single template. That's not a terribly common case,
1023 // though.
1024 return Owned(TemplateIdRefExpr::Create(Context,
1025 /*FIXME: New type?*/Context.OverloadTy,
1026 /*FIXME: Necessary?*/0,
1027 /*FIXME: Necessary?*/SourceRange(),
1028 Template, TemplateNameLoc, LAngleLoc,
1029 TemplateArgs,
1030 NumTemplateArgs, RAngleLoc));
1031}
1032
1033Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1034 SourceLocation TemplateNameLoc,
1035 SourceLocation LAngleLoc,
1036 ASTTemplateArgsPtr TemplateArgsIn,
1037 SourceLocation *TemplateArgLocs,
1038 SourceLocation RAngleLoc) {
1039 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1040
1041 // Translate the parser's template argument list in our AST format.
1042 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1043 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001044 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001045
1046 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1047 TemplateArgs.data(), TemplateArgs.size(),
1048 RAngleLoc);
1049}
1050
Douglas Gregorc45c2322009-03-31 00:43:58 +00001051/// \brief Form a dependent template name.
1052///
1053/// This action forms a dependent template name given the template
1054/// name and its (presumably dependent) scope specifier. For
1055/// example, given "MetaFun::template apply", the scope specifier \p
1056/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1057/// of the "template" keyword, and "apply" is the \p Name.
1058Sema::TemplateTy
1059Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1060 const IdentifierInfo &Name,
1061 SourceLocation NameLoc,
1062 const CXXScopeSpec &SS) {
1063 if (!SS.isSet() || SS.isInvalid())
1064 return TemplateTy();
1065
1066 NestedNameSpecifier *Qualifier
1067 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1068
1069 // FIXME: member of the current instantiation
1070
1071 if (!Qualifier->isDependent()) {
1072 // C++0x [temp.names]p5:
1073 // If a name prefixed by the keyword template is not the name of
1074 // a template, the program is ill-formed. [Note: the keyword
1075 // template may not be applied to non-template members of class
1076 // templates. -end note ] [ Note: as is the case with the
1077 // typename prefix, the template prefix is allowed in cases
1078 // where it is not strictly necessary; i.e., when the
1079 // nested-name-specifier or the expression on the left of the ->
1080 // or . is not dependent on a template-parameter, or the use
1081 // does not appear in the scope of a template. -end note]
1082 //
1083 // Note: C++03 was more strict here, because it banned the use of
1084 // the "template" keyword prior to a template-name that was not a
1085 // dependent name. C++ DR468 relaxed this requirement (the
1086 // "template" keyword is now permitted). We follow the C++0x
1087 // rules, even in C++03 mode, retroactively applying the DR.
1088 TemplateTy Template;
1089 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1090 if (TNK == TNK_Non_template) {
1091 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1092 << &Name;
1093 return TemplateTy();
1094 }
1095
1096 return Template;
1097 }
1098
1099 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1100}
1101
Anders Carlsson436b1562009-06-13 00:33:33 +00001102bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1103 const TemplateArgument &Arg,
1104 TemplateArgumentListBuilder &Converted) {
1105 // Check template type parameter.
1106 if (Arg.getKind() != TemplateArgument::Type) {
1107 // C++ [temp.arg.type]p1:
1108 // A template-argument for a template-parameter which is a
1109 // type shall be a type-id.
1110
1111 // We have a template type parameter but the template argument
1112 // is not a type.
1113 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1114 Diag(Param->getLocation(), diag::note_template_param_here);
1115
1116 return true;
1117 }
1118
1119 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1120 return true;
1121
1122 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001123 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001124 TemplateArgument(Arg.getLocation(),
1125 Context.getCanonicalType(Arg.getAsType())));
1126 return false;
1127}
1128
Douglas Gregorc15cb382009-02-09 23:23:08 +00001129/// \brief Check that the given template argument list is well-formed
1130/// for specializing the given template.
1131bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1132 SourceLocation TemplateLoc,
1133 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001134 const TemplateArgument *TemplateArgs,
1135 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001136 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001137 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001138 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001139 TemplateParameterList *Params = Template->getTemplateParameters();
1140 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001141 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001142 bool Invalid = false;
1143
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001144 bool HasParameterPack =
1145 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1146
1147 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001148 (NumArgs < Params->getMinRequiredArguments() &&
1149 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001150 // FIXME: point at either the first arg beyond what we can handle,
1151 // or the '>', depending on whether we have too many or too few
1152 // arguments.
1153 SourceRange Range;
1154 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001155 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001156 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1157 << (NumArgs > NumParams)
1158 << (isa<ClassTemplateDecl>(Template)? 0 :
1159 isa<FunctionTemplateDecl>(Template)? 1 :
1160 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1161 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001162 Diag(Template->getLocation(), diag::note_template_decl_here)
1163 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001164 Invalid = true;
1165 }
1166
1167 // C++ [temp.arg]p1:
1168 // [...] The type and form of each template-argument specified in
1169 // a template-id shall match the type and form specified for the
1170 // corresponding parameter declared by the template in its
1171 // template-parameter-list.
1172 unsigned ArgIdx = 0;
1173 for (TemplateParameterList::iterator Param = Params->begin(),
1174 ParamEnd = Params->end();
1175 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001176 if (ArgIdx > NumArgs && PartialTemplateArgs)
1177 break;
1178
Douglas Gregorc15cb382009-02-09 23:23:08 +00001179 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001180 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001181 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001182 // Retrieve the default template argument from the template
1183 // parameter.
1184 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001185 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001186 // We have an empty argument pack.
1187 Converted.BeginPack();
1188 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001189 break;
1190 }
1191
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001192 if (!TTP->hasDefaultArgument())
1193 break;
1194
Douglas Gregor40808ce2009-03-09 23:48:35 +00001195 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001196
1197 // If the argument type is dependent, instantiate it now based
1198 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001199 if (ArgType->isDependentType()) {
1200 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001201 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001202 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001203 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001204
Anders Carlssone9c904b2009-06-05 04:47:51 +00001205 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001206 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001207 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001208 TTP->getDefaultArgumentLoc(),
1209 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001210 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001211
1212 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001213 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001214
Douglas Gregor40808ce2009-03-09 23:48:35 +00001215 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001216 } else if (NonTypeTemplateParmDecl *NTTP
1217 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1218 if (!NTTP->hasDefaultArgument())
1219 break;
1220
Anders Carlsson3b56c002009-06-11 16:06:49 +00001221 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001222 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001223 Converted.flatSize(),
1224 SourceRange(TemplateLoc, RAngleLoc));
1225
1226 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001227 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001228
1229 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1230 TemplateArgs);
1231 if (E.isInvalid())
1232 return true;
1233
1234 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001235 } else {
1236 TemplateTemplateParmDecl *TempParm
1237 = cast<TemplateTemplateParmDecl>(*Param);
1238
1239 if (!TempParm->hasDefaultArgument())
1240 break;
1241
Douglas Gregor2943aed2009-03-03 04:44:36 +00001242 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001243 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001244 }
1245 } else {
1246 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001247 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001248 }
1249
Douglas Gregorc15cb382009-02-09 23:23:08 +00001250
1251 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001252 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001253 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001254 // Check all the remaining arguments (if any).
1255 for (; ArgIdx < NumArgs; ++ArgIdx) {
1256 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1257 Invalid = true;
1258 }
1259
Anders Carlssonfb250522009-06-23 01:26:57 +00001260 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001261 } else {
1262 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1263 Invalid = true;
1264 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001265 } else if (NonTypeTemplateParmDecl *NTTP
1266 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1267 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001268
1269 // Instantiate the type of the non-type template parameter with
1270 // the template arguments we've seen thus far.
1271 QualType NTTPType = NTTP->getType();
1272 if (NTTPType->isDependentType()) {
1273 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001274 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001275 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001276 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001277 SourceRange(TemplateLoc, RAngleLoc));
1278
Anders Carlssone9c904b2009-06-05 04:47:51 +00001279 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001280 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001281 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001282 NTTP->getLocation(),
1283 NTTP->getDeclName());
1284 // If that worked, check the non-type template parameter type
1285 // for validity.
1286 if (!NTTPType.isNull())
1287 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1288 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001289 if (NTTPType.isNull()) {
1290 Invalid = true;
1291 break;
1292 }
1293 }
1294
Douglas Gregor40808ce2009-03-09 23:48:35 +00001295 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001296 case TemplateArgument::Null:
1297 assert(false && "Should never see a NULL template argument here");
1298 break;
1299
Douglas Gregor40808ce2009-03-09 23:48:35 +00001300 case TemplateArgument::Expression: {
1301 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001302 TemplateArgument Result;
1303 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001304 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001305 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001306 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001307 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001308 }
1309
Douglas Gregor40808ce2009-03-09 23:48:35 +00001310 case TemplateArgument::Declaration:
1311 case TemplateArgument::Integral:
1312 // We've already checked this template argument, so just copy
1313 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001314 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001315 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001316
Douglas Gregor40808ce2009-03-09 23:48:35 +00001317 case TemplateArgument::Type:
1318 // We have a non-type template parameter but the template
1319 // argument is a type.
1320
1321 // C++ [temp.arg]p2:
1322 // In a template-argument, an ambiguity between a type-id and
1323 // an expression is resolved to a type-id, regardless of the
1324 // form of the corresponding template-parameter.
1325 //
1326 // We warn specifically about this case, since it can be rather
1327 // confusing for users.
1328 if (Arg.getAsType()->isFunctionType())
1329 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1330 << Arg.getAsType();
1331 else
1332 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1333 Diag((*Param)->getLocation(), diag::note_template_param_here);
1334 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001335 break;
1336
1337 case TemplateArgument::Pack:
1338 assert(0 && "FIXME: Implement!");
1339 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001340 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001341 } else {
1342 // Check template template parameters.
1343 TemplateTemplateParmDecl *TempParm
1344 = cast<TemplateTemplateParmDecl>(*Param);
1345
Douglas Gregor40808ce2009-03-09 23:48:35 +00001346 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001347 case TemplateArgument::Null:
1348 assert(false && "Should never see a NULL template argument here");
1349 break;
1350
Douglas Gregor40808ce2009-03-09 23:48:35 +00001351 case TemplateArgument::Expression: {
1352 Expr *ArgExpr = Arg.getAsExpr();
1353 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1354 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1355 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1356 Invalid = true;
1357
1358 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001359 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001360 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001361 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001362 continue;
1363 }
1364 }
1365 // fall through
1366
1367 case TemplateArgument::Type: {
1368 // We have a template template parameter but the template
1369 // argument does not refer to a template.
1370 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1371 Invalid = true;
1372 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001373 }
1374
Douglas Gregor40808ce2009-03-09 23:48:35 +00001375 case TemplateArgument::Declaration:
1376 // We've already checked this template argument, so just copy
1377 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001378 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001379 break;
1380
1381 case TemplateArgument::Integral:
1382 assert(false && "Integral argument with template template parameter");
1383 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001384
1385 case TemplateArgument::Pack:
1386 assert(0 && "FIXME: Implement!");
1387 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001388 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001389 }
1390 }
1391
1392 return Invalid;
1393}
1394
1395/// \brief Check a template argument against its corresponding
1396/// template type parameter.
1397///
1398/// This routine implements the semantics of C++ [temp.arg.type]. It
1399/// returns true if an error occurred, and false otherwise.
1400bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1401 QualType Arg, SourceLocation ArgLoc) {
1402 // C++ [temp.arg.type]p2:
1403 // A local type, a type with no linkage, an unnamed type or a type
1404 // compounded from any of these types shall not be used as a
1405 // template-argument for a template type-parameter.
1406 //
1407 // FIXME: Perform the recursive and no-linkage type checks.
1408 const TagType *Tag = 0;
1409 if (const EnumType *EnumT = Arg->getAsEnumType())
1410 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00001411 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001412 Tag = RecordT;
1413 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1414 return Diag(ArgLoc, diag::err_template_arg_local_type)
1415 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001416 else if (Tag && !Tag->getDecl()->getDeclName() &&
1417 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001418 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1419 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1420 return true;
1421 }
1422
1423 return false;
1424}
1425
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001426/// \brief Checks whether the given template argument is the address
1427/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001428bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1429 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001430 bool Invalid = false;
1431
1432 // See through any implicit casts we added to fix the type.
1433 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1434 Arg = Cast->getSubExpr();
1435
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001436 // C++0x allows nullptr, and there's no further checking to be done for that.
1437 if (Arg->getType()->isNullPtrType())
1438 return false;
1439
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001440 // C++ [temp.arg.nontype]p1:
1441 //
1442 // A template-argument for a non-type, non-template
1443 // template-parameter shall be one of: [...]
1444 //
1445 // -- the address of an object or function with external
1446 // linkage, including function templates and function
1447 // template-ids but excluding non-static class members,
1448 // expressed as & id-expression where the & is optional if
1449 // the name refers to a function or array, or if the
1450 // corresponding template-parameter is a reference; or
1451 DeclRefExpr *DRE = 0;
1452
1453 // Ignore (and complain about) any excess parentheses.
1454 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1455 if (!Invalid) {
1456 Diag(Arg->getSourceRange().getBegin(),
1457 diag::err_template_arg_extra_parens)
1458 << Arg->getSourceRange();
1459 Invalid = true;
1460 }
1461
1462 Arg = Parens->getSubExpr();
1463 }
1464
1465 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1466 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1467 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1468 } else
1469 DRE = dyn_cast<DeclRefExpr>(Arg);
1470
1471 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1472 return Diag(Arg->getSourceRange().getBegin(),
1473 diag::err_template_arg_not_object_or_func_form)
1474 << Arg->getSourceRange();
1475
1476 // Cannot refer to non-static data members
1477 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1478 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1479 << Field << Arg->getSourceRange();
1480
1481 // Cannot refer to non-static member functions
1482 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1483 if (!Method->isStatic())
1484 return Diag(Arg->getSourceRange().getBegin(),
1485 diag::err_template_arg_method)
1486 << Method << Arg->getSourceRange();
1487
1488 // Functions must have external linkage.
1489 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1490 if (Func->getStorageClass() == FunctionDecl::Static) {
1491 Diag(Arg->getSourceRange().getBegin(),
1492 diag::err_template_arg_function_not_extern)
1493 << Func << Arg->getSourceRange();
1494 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1495 << true;
1496 return true;
1497 }
1498
1499 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001500 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001501 return Invalid;
1502 }
1503
1504 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1505 if (!Var->hasGlobalStorage()) {
1506 Diag(Arg->getSourceRange().getBegin(),
1507 diag::err_template_arg_object_not_extern)
1508 << Var << Arg->getSourceRange();
1509 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1510 << true;
1511 return true;
1512 }
1513
1514 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001515 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001516 return Invalid;
1517 }
1518
1519 // We found something else, but we don't know specifically what it is.
1520 Diag(Arg->getSourceRange().getBegin(),
1521 diag::err_template_arg_not_object_or_func)
1522 << Arg->getSourceRange();
1523 Diag(DRE->getDecl()->getLocation(),
1524 diag::note_template_arg_refers_here);
1525 return true;
1526}
1527
1528/// \brief Checks whether the given template argument is a pointer to
1529/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001530bool
1531Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001532 bool Invalid = false;
1533
1534 // See through any implicit casts we added to fix the type.
1535 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1536 Arg = Cast->getSubExpr();
1537
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001538 // C++0x allows nullptr, and there's no further checking to be done for that.
1539 if (Arg->getType()->isNullPtrType())
1540 return false;
1541
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001542 // C++ [temp.arg.nontype]p1:
1543 //
1544 // A template-argument for a non-type, non-template
1545 // template-parameter shall be one of: [...]
1546 //
1547 // -- a pointer to member expressed as described in 5.3.1.
1548 QualifiedDeclRefExpr *DRE = 0;
1549
1550 // Ignore (and complain about) any excess parentheses.
1551 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1552 if (!Invalid) {
1553 Diag(Arg->getSourceRange().getBegin(),
1554 diag::err_template_arg_extra_parens)
1555 << Arg->getSourceRange();
1556 Invalid = true;
1557 }
1558
1559 Arg = Parens->getSubExpr();
1560 }
1561
1562 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1563 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1564 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1565
1566 if (!DRE)
1567 return Diag(Arg->getSourceRange().getBegin(),
1568 diag::err_template_arg_not_pointer_to_member_form)
1569 << Arg->getSourceRange();
1570
1571 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1572 assert((isa<FieldDecl>(DRE->getDecl()) ||
1573 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1574 "Only non-static member pointers can make it here");
1575
1576 // Okay: this is the address of a non-static member, and therefore
1577 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001578 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001579 return Invalid;
1580 }
1581
1582 // We found something else, but we don't know specifically what it is.
1583 Diag(Arg->getSourceRange().getBegin(),
1584 diag::err_template_arg_not_pointer_to_member_form)
1585 << Arg->getSourceRange();
1586 Diag(DRE->getDecl()->getLocation(),
1587 diag::note_template_arg_refers_here);
1588 return true;
1589}
1590
Douglas Gregorc15cb382009-02-09 23:23:08 +00001591/// \brief Check a template argument against its corresponding
1592/// non-type template parameter.
1593///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001594/// This routine implements the semantics of C++ [temp.arg.nontype].
1595/// It returns true if an error occurred, and false otherwise. \p
1596/// InstantiatedParamType is the type of the non-type template
1597/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001598///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001599/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001600bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001601 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001602 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001603 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1604
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001605 // If either the parameter has a dependent type or the argument is
1606 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001607 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001608 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1609 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001610 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001611 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001612 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001613
1614 // C++ [temp.arg.nontype]p5:
1615 // The following conversions are performed on each expression used
1616 // as a non-type template-argument. If a non-type
1617 // template-argument cannot be converted to the type of the
1618 // corresponding template-parameter then the program is
1619 // ill-formed.
1620 //
1621 // -- for a non-type template-parameter of integral or
1622 // enumeration type, integral promotions (4.5) and integral
1623 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001624 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001625 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001626 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001627 // C++ [temp.arg.nontype]p1:
1628 // A template-argument for a non-type, non-template
1629 // template-parameter shall be one of:
1630 //
1631 // -- an integral constant-expression of integral or enumeration
1632 // type; or
1633 // -- the name of a non-type template-parameter; or
1634 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001635 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001636 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1637 Diag(Arg->getSourceRange().getBegin(),
1638 diag::err_template_arg_not_integral_or_enumeral)
1639 << ArgType << Arg->getSourceRange();
1640 Diag(Param->getLocation(), diag::note_template_param_here);
1641 return true;
1642 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001643 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001644 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1645 << ArgType << Arg->getSourceRange();
1646 return true;
1647 }
1648
1649 // FIXME: We need some way to more easily get the unqualified form
1650 // of the types without going all the way to the
1651 // canonical type.
1652 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1653 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1654 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1655 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1656
1657 // Try to convert the argument to the parameter's type.
1658 if (ParamType == ArgType) {
1659 // Okay: no conversion necessary
1660 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1661 !ParamType->isEnumeralType()) {
1662 // This is an integral promotion or conversion.
1663 ImpCastExprToType(Arg, ParamType);
1664 } else {
1665 // We can't perform this conversion.
1666 Diag(Arg->getSourceRange().getBegin(),
1667 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001668 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001669 Diag(Param->getLocation(), diag::note_template_param_here);
1670 return true;
1671 }
1672
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001673 QualType IntegerType = Context.getCanonicalType(ParamType);
1674 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001675 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001676
1677 if (!Arg->isValueDependent()) {
1678 // Check that an unsigned parameter does not receive a negative
1679 // value.
1680 if (IntegerType->isUnsignedIntegerType()
1681 && (Value.isSigned() && Value.isNegative())) {
1682 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1683 << Value.toString(10) << Param->getType()
1684 << Arg->getSourceRange();
1685 Diag(Param->getLocation(), diag::note_template_param_here);
1686 return true;
1687 }
1688
1689 // Check that we don't overflow the template parameter type.
1690 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1691 if (Value.getActiveBits() > AllowedBits) {
1692 Diag(Arg->getSourceRange().getBegin(),
1693 diag::err_template_arg_too_large)
1694 << Value.toString(10) << Param->getType()
1695 << Arg->getSourceRange();
1696 Diag(Param->getLocation(), diag::note_template_param_here);
1697 return true;
1698 }
1699
1700 if (Value.getBitWidth() != AllowedBits)
1701 Value.extOrTrunc(AllowedBits);
1702 Value.setIsSigned(IntegerType->isSignedIntegerType());
1703 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001704
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001705 // Add the value of this argument to the list of converted
1706 // arguments. We use the bitwidth and signedness of the template
1707 // parameter.
1708 if (Arg->isValueDependent()) {
1709 // The argument is value-dependent. Create a new
1710 // TemplateArgument with the converted expression.
1711 Converted = TemplateArgument(Arg);
1712 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001713 }
1714
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001715 Converted = TemplateArgument(StartLoc, Value,
1716 ParamType->isEnumeralType() ? ParamType
1717 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001718 return false;
1719 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001720
Douglas Gregorb86b0572009-02-11 01:18:59 +00001721 // Handle pointer-to-function, reference-to-function, and
1722 // pointer-to-member-function all in (roughly) the same way.
1723 if (// -- For a non-type template-parameter of type pointer to
1724 // function, only the function-to-pointer conversion (4.3) is
1725 // applied. If the template-argument represents a set of
1726 // overloaded functions (or a pointer to such), the matching
1727 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001728 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001729 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001730 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001731 // -- For a non-type template-parameter of type reference to
1732 // function, no conversions apply. If the template-argument
1733 // represents a set of overloaded functions, the matching
1734 // function is selected from the set (13.4).
1735 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001736 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001737 // -- For a non-type template-parameter of type pointer to
1738 // member function, no conversions apply. If the
1739 // template-argument represents a set of overloaded member
1740 // functions, the matching member function is selected from
1741 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001742 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001743 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001744 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001745 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001746 if (Context.hasSameUnqualifiedType(ArgType,
1747 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001748 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001749 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1750 ParamType->isMemberPointerType())) {
1751 ArgType = ParamType;
1752 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001753 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001754 ArgType = Context.getPointerType(ArgType);
1755 ImpCastExprToType(Arg, ArgType);
1756 } else if (FunctionDecl *Fn
1757 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001758 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1759 return true;
1760
Douglas Gregora35284b2009-02-11 00:19:33 +00001761 FixOverloadedFunctionReference(Arg, Fn);
1762 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001763 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001764 ArgType = Context.getPointerType(Arg->getType());
1765 ImpCastExprToType(Arg, ArgType);
1766 }
1767 }
1768
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001769 if (!Context.hasSameUnqualifiedType(ArgType,
1770 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001771 // We can't perform this conversion.
1772 Diag(Arg->getSourceRange().getBegin(),
1773 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001774 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001775 Diag(Param->getLocation(), diag::note_template_param_here);
1776 return true;
1777 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001778
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001779 if (ParamType->isMemberPointerType()) {
1780 NamedDecl *Member = 0;
1781 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1782 return true;
1783
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001784 if (Member)
1785 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001786 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001787 return false;
1788 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001789
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001790 NamedDecl *Entity = 0;
1791 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1792 return true;
1793
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001794 if (Entity)
1795 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001796 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001797 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001798 }
1799
Chris Lattnerfe90de72009-02-20 21:37:53 +00001800 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001801 // -- for a non-type template-parameter of type pointer to
1802 // object, qualification conversions (4.4) and the
1803 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001804 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00001805 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001806 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001807
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001808 if (ArgType->isNullPtrType()) {
1809 ArgType = ParamType;
1810 ImpCastExprToType(Arg, ParamType);
1811 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001812 ArgType = Context.getArrayDecayedType(ArgType);
1813 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001814 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001815
Douglas Gregorb86b0572009-02-11 01:18:59 +00001816 if (IsQualificationConversion(ArgType, ParamType)) {
1817 ArgType = ParamType;
1818 ImpCastExprToType(Arg, ParamType);
1819 }
1820
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001821 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001822 // We can't perform this conversion.
1823 Diag(Arg->getSourceRange().getBegin(),
1824 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001825 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001826 Diag(Param->getLocation(), diag::note_template_param_here);
1827 return true;
1828 }
1829
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001830 NamedDecl *Entity = 0;
1831 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1832 return true;
1833
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001834 if (Entity)
1835 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001836 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001837 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001838 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001839
Ted Kremenek6217b802009-07-29 21:53:49 +00001840 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001841 // -- For a non-type template-parameter of type reference to
1842 // object, no conversions apply. The type referred to by the
1843 // reference may be more cv-qualified than the (otherwise
1844 // identical) type of the template-argument. The
1845 // template-parameter is bound directly to the
1846 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001847 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001848 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001849
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001850 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001851 Diag(Arg->getSourceRange().getBegin(),
1852 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001853 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001854 << Arg->getSourceRange();
1855 Diag(Param->getLocation(), diag::note_template_param_here);
1856 return true;
1857 }
1858
1859 unsigned ParamQuals
1860 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1861 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1862
1863 if ((ParamQuals | ArgQuals) != ParamQuals) {
1864 Diag(Arg->getSourceRange().getBegin(),
1865 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001866 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001867 << Arg->getSourceRange();
1868 Diag(Param->getLocation(), diag::note_template_param_here);
1869 return true;
1870 }
1871
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001872 NamedDecl *Entity = 0;
1873 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1874 return true;
1875
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001876 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001877 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001878 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001879 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001880
1881 // -- For a non-type template-parameter of type pointer to data
1882 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001883 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001884 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1885
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001886 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001887 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001888 } else if (ArgType->isNullPtrType()) {
1889 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001890 } else if (IsQualificationConversion(ArgType, ParamType)) {
1891 ImpCastExprToType(Arg, ParamType);
1892 } else {
1893 // We can't perform this conversion.
1894 Diag(Arg->getSourceRange().getBegin(),
1895 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001896 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001897 Diag(Param->getLocation(), diag::note_template_param_here);
1898 return true;
1899 }
1900
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001901 NamedDecl *Member = 0;
1902 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1903 return true;
1904
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001905 if (Member)
1906 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001907 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001908 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001909}
1910
1911/// \brief Check a template argument against its corresponding
1912/// template template parameter.
1913///
1914/// This routine implements the semantics of C++ [temp.arg.template].
1915/// It returns true if an error occurred, and false otherwise.
1916bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1917 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001918 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1919 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1920
1921 // C++ [temp.arg.template]p1:
1922 // A template-argument for a template template-parameter shall be
1923 // the name of a class template, expressed as id-expression. Only
1924 // primary class templates are considered when matching the
1925 // template template argument with the corresponding parameter;
1926 // partial specializations are not considered even if their
1927 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001928 //
1929 // Note that we also allow template template parameters here, which
1930 // will happen when we are dealing with, e.g., class template
1931 // partial specializations.
1932 if (!isa<ClassTemplateDecl>(Template) &&
1933 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001934 assert(isa<FunctionTemplateDecl>(Template) &&
1935 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001936 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1937 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001938 << Template;
1939 }
1940
1941 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1942 Param->getTemplateParameters(),
1943 true, true,
1944 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001945}
1946
Douglas Gregorddc29e12009-02-06 22:42:48 +00001947/// \brief Determine whether the given template parameter lists are
1948/// equivalent.
1949///
1950/// \param New The new template parameter list, typically written in the
1951/// source code as part of a new template declaration.
1952///
1953/// \param Old The old template parameter list, typically found via
1954/// name lookup of the template declared with this template parameter
1955/// list.
1956///
1957/// \param Complain If true, this routine will produce a diagnostic if
1958/// the template parameter lists are not equivalent.
1959///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001960/// \param IsTemplateTemplateParm If true, this routine is being
1961/// called to compare the template parameter lists of a template
1962/// template parameter.
1963///
1964/// \param TemplateArgLoc If this source location is valid, then we
1965/// are actually checking the template parameter list of a template
1966/// argument (New) against the template parameter list of its
1967/// corresponding template template parameter (Old). We produce
1968/// slightly different diagnostics in this scenario.
1969///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001970/// \returns True if the template parameter lists are equal, false
1971/// otherwise.
1972bool
1973Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1974 TemplateParameterList *Old,
1975 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001976 bool IsTemplateTemplateParm,
1977 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001978 if (Old->size() != New->size()) {
1979 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001980 unsigned NextDiag = diag::err_template_param_list_different_arity;
1981 if (TemplateArgLoc.isValid()) {
1982 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1983 NextDiag = diag::note_template_param_list_different_arity;
1984 }
1985 Diag(New->getTemplateLoc(), NextDiag)
1986 << (New->size() > Old->size())
1987 << IsTemplateTemplateParm
1988 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001989 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1990 << IsTemplateTemplateParm
1991 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1992 }
1993
1994 return false;
1995 }
1996
1997 for (TemplateParameterList::iterator OldParm = Old->begin(),
1998 OldParmEnd = Old->end(), NewParm = New->begin();
1999 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2000 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002001 if (Complain) {
2002 unsigned NextDiag = diag::err_template_param_different_kind;
2003 if (TemplateArgLoc.isValid()) {
2004 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2005 NextDiag = diag::note_template_param_different_kind;
2006 }
2007 Diag((*NewParm)->getLocation(), NextDiag)
2008 << IsTemplateTemplateParm;
2009 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2010 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002011 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002012 return false;
2013 }
2014
2015 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2016 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002017 // know we're at the same index).
2018#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002019 // FIXME: Enable this code in debug mode *after* we properly go through
2020 // and "instantiate" the template parameter lists of template template
2021 // parameters. It's only after this instantiation that (1) any dependent
2022 // types within the template parameter list of the template template
2023 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002024 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00002025 QualType OldParmType
2026 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2027 QualType NewParmType
2028 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2029 assert(Context.getCanonicalType(OldParmType) ==
2030 Context.getCanonicalType(NewParmType) &&
2031 "type parameter mismatch?");
2032#endif
2033 } else if (NonTypeTemplateParmDecl *OldNTTP
2034 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2035 // The types of non-type template parameters must agree.
2036 NonTypeTemplateParmDecl *NewNTTP
2037 = cast<NonTypeTemplateParmDecl>(*NewParm);
2038 if (Context.getCanonicalType(OldNTTP->getType()) !=
2039 Context.getCanonicalType(NewNTTP->getType())) {
2040 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002041 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2042 if (TemplateArgLoc.isValid()) {
2043 Diag(TemplateArgLoc,
2044 diag::err_template_arg_template_params_mismatch);
2045 NextDiag = diag::note_template_nontype_parm_different_type;
2046 }
2047 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002048 << NewNTTP->getType()
2049 << IsTemplateTemplateParm;
2050 Diag(OldNTTP->getLocation(),
2051 diag::note_template_nontype_parm_prev_declaration)
2052 << OldNTTP->getType();
2053 }
2054 return false;
2055 }
2056 } else {
2057 // The template parameter lists of template template
2058 // parameters must agree.
2059 // FIXME: Could we perform a faster "type" comparison here?
2060 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2061 "Only template template parameters handled here");
2062 TemplateTemplateParmDecl *OldTTP
2063 = cast<TemplateTemplateParmDecl>(*OldParm);
2064 TemplateTemplateParmDecl *NewTTP
2065 = cast<TemplateTemplateParmDecl>(*NewParm);
2066 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2067 OldTTP->getTemplateParameters(),
2068 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002069 /*IsTemplateTemplateParm=*/true,
2070 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002071 return false;
2072 }
2073 }
2074
2075 return true;
2076}
2077
2078/// \brief Check whether a template can be declared within this scope.
2079///
2080/// If the template declaration is valid in this scope, returns
2081/// false. Otherwise, issues a diagnostic and returns true.
2082bool
2083Sema::CheckTemplateDeclScope(Scope *S,
2084 MultiTemplateParamsArg &TemplateParameterLists) {
2085 assert(TemplateParameterLists.size() > 0 && "Not a template");
2086
2087 // Find the nearest enclosing declaration scope.
2088 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2089 (S->getFlags() & Scope::TemplateParamScope) != 0)
2090 S = S->getParent();
2091
2092 TemplateParameterList *TemplateParams =
2093 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2094 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2095 SourceRange TemplateRange
2096 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2097
2098 // C++ [temp]p2:
2099 // A template-declaration can appear only as a namespace scope or
2100 // class scope declaration.
2101 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2102 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2103 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2104 return Diag(TemplateLoc, diag::err_template_linkage)
2105 << TemplateRange;
2106
2107 Ctx = Ctx->getParent();
2108 }
2109
2110 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2111 return false;
2112
2113 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2114 << TemplateRange;
2115}
Douglas Gregorcc636682009-02-17 23:15:12 +00002116
Douglas Gregorff668032009-05-13 18:28:20 +00002117/// \brief Check whether a class template specialization or explicit
2118/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002119///
Douglas Gregorff668032009-05-13 18:28:20 +00002120/// This routine determines whether a class template specialization or
2121/// explicit instantiation can be declared in the current context
2122/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2123/// appropriate diagnostics if there was an error. It returns true if
2124// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002125bool
2126Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2127 ClassTemplateSpecializationDecl *PrevDecl,
2128 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002129 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002130 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002131 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002132 // C++ [temp.expl.spec]p2:
2133 // An explicit specialization shall be declared in the namespace
2134 // of which the template is a member, or, for member templates, in
2135 // the namespace of which the enclosing class or enclosing class
2136 // template is a member. An explicit specialization of a member
2137 // function, member class or static data member of a class
2138 // template shall be declared in the namespace of which the class
2139 // template is a member. Such a declaration may also be a
2140 // definition. If the declaration is not a definition, the
2141 // specialization may be defined later in the name- space in which
2142 // the explicit specialization was declared, or in a namespace
2143 // that encloses the one in which the explicit specialization was
2144 // declared.
2145 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002146 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002147 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002148 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002149 return true;
2150 }
2151
2152 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2153 DeclContext *TemplateContext
2154 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002155 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2156 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002157 // There is no prior declaration of this entity, so this
2158 // specialization must be in the same context as the template
2159 // itself.
2160 if (DC != TemplateContext) {
2161 if (isa<TranslationUnitDecl>(TemplateContext))
2162 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002163 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002164 << ClassTemplate << ScopeSpecifierRange;
2165 else if (isa<NamespaceDecl>(TemplateContext))
2166 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002167 << PartialSpecialization << ClassTemplate
2168 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002169
2170 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2171 }
2172
2173 return false;
2174 }
2175
2176 // We have a previous declaration of this entity. Make sure that
2177 // this redeclaration (or definition) occurs in an enclosing namespace.
2178 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002179 // FIXME: In C++98, we would like to turn these errors into warnings,
2180 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002181 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002182 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002183 if (isa<TranslationUnitDecl>(TemplateContext)) {
2184 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2185 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002186 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002187 else
2188 SuppressedDiag = true;
2189 } else if (isa<NamespaceDecl>(TemplateContext)) {
2190 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2191 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002192 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002193 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2194 else
2195 SuppressedDiag = true;
2196 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002197
Douglas Gregorff668032009-05-13 18:28:20 +00002198 if (!SuppressedDiag)
2199 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002200 }
2201
2202 return false;
2203}
2204
Douglas Gregore94866f2009-06-12 21:21:02 +00002205/// \brief Check the non-type template arguments of a class template
2206/// partial specialization according to C++ [temp.class.spec]p9.
2207///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002208/// \param TemplateParams the template parameters of the primary class
2209/// template.
2210///
2211/// \param TemplateArg the template arguments of the class template
2212/// partial specialization.
2213///
2214/// \param MirrorsPrimaryTemplate will be set true if the class
2215/// template partial specialization arguments are identical to the
2216/// implicit template arguments of the primary template. This is not
2217/// necessarily an error (C++0x), and it is left to the caller to diagnose
2218/// this condition when it is an error.
2219///
Douglas Gregore94866f2009-06-12 21:21:02 +00002220/// \returns true if there was an error, false otherwise.
2221bool Sema::CheckClassTemplatePartialSpecializationArgs(
2222 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002223 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002224 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002225 // FIXME: the interface to this function will have to change to
2226 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002227 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002228
Anders Carlssonfb250522009-06-23 01:26:57 +00002229 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002230
Douglas Gregore94866f2009-06-12 21:21:02 +00002231 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002232 // Determine whether the template argument list of the partial
2233 // specialization is identical to the implicit argument list of
2234 // the primary template. The caller may need to diagnostic this as
2235 // an error per C++ [temp.class.spec]p9b3.
2236 if (MirrorsPrimaryTemplate) {
2237 if (TemplateTypeParmDecl *TTP
2238 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2239 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002240 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002241 MirrorsPrimaryTemplate = false;
2242 } else if (TemplateTemplateParmDecl *TTP
2243 = dyn_cast<TemplateTemplateParmDecl>(
2244 TemplateParams->getParam(I))) {
2245 // FIXME: We should settle on either Declaration storage or
2246 // Expression storage for template template parameters.
2247 TemplateTemplateParmDecl *ArgDecl
2248 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002249 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002250 if (!ArgDecl)
2251 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002252 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002253 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2254
2255 if (!ArgDecl ||
2256 ArgDecl->getIndex() != TTP->getIndex() ||
2257 ArgDecl->getDepth() != TTP->getDepth())
2258 MirrorsPrimaryTemplate = false;
2259 }
2260 }
2261
Douglas Gregore94866f2009-06-12 21:21:02 +00002262 NonTypeTemplateParmDecl *Param
2263 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002264 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002265 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002266 }
2267
Anders Carlsson6360be72009-06-13 18:20:51 +00002268 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002269 if (!ArgExpr) {
2270 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002271 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002272 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002273
2274 // C++ [temp.class.spec]p8:
2275 // A non-type argument is non-specialized if it is the name of a
2276 // non-type parameter. All other non-type arguments are
2277 // specialized.
2278 //
2279 // Below, we check the two conditions that only apply to
2280 // specialized non-type arguments, so skip any non-specialized
2281 // arguments.
2282 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002283 if (NonTypeTemplateParmDecl *NTTP
2284 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2285 if (MirrorsPrimaryTemplate &&
2286 (Param->getIndex() != NTTP->getIndex() ||
2287 Param->getDepth() != NTTP->getDepth()))
2288 MirrorsPrimaryTemplate = false;
2289
Douglas Gregore94866f2009-06-12 21:21:02 +00002290 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002291 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002292
2293 // C++ [temp.class.spec]p9:
2294 // Within the argument list of a class template partial
2295 // specialization, the following restrictions apply:
2296 // -- A partially specialized non-type argument expression
2297 // shall not involve a template parameter of the partial
2298 // specialization except when the argument expression is a
2299 // simple identifier.
2300 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2301 Diag(ArgExpr->getLocStart(),
2302 diag::err_dependent_non_type_arg_in_partial_spec)
2303 << ArgExpr->getSourceRange();
2304 return true;
2305 }
2306
2307 // -- The type of a template parameter corresponding to a
2308 // specialized non-type argument shall not be dependent on a
2309 // parameter of the specialization.
2310 if (Param->getType()->isDependentType()) {
2311 Diag(ArgExpr->getLocStart(),
2312 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2313 << Param->getType()
2314 << ArgExpr->getSourceRange();
2315 Diag(Param->getLocation(), diag::note_template_param_here);
2316 return true;
2317 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002318
2319 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002320 }
2321
2322 return false;
2323}
2324
Douglas Gregor212e81c2009-03-25 00:13:59 +00002325Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002326Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2327 SourceLocation KWLoc,
2328 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002329 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002330 SourceLocation TemplateNameLoc,
2331 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002332 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002333 SourceLocation *TemplateArgLocs,
2334 SourceLocation RAngleLoc,
2335 AttributeList *Attr,
2336 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002337 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002338 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002339 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002340 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002341
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002342 bool isPartialSpecialization = false;
2343
Douglas Gregor88b70942009-02-25 22:02:03 +00002344 // Check the validity of the template headers that introduce this
2345 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002346 // FIXME: Once we have member templates, we'll need to check
2347 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2348 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002349 if (TemplateParameterLists.size() == 0)
2350 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002351 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002352 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002353 TemplateParameterList *TemplateParams
2354 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002355 if (TemplateParameterLists.size() > 1) {
2356 Diag(TemplateParams->getTemplateLoc(),
2357 diag::err_template_spec_extra_headers);
2358 return true;
2359 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002360
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002361 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002362 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002363
2364 // C++ [temp.class.spec]p10:
2365 // The template parameter list of a specialization shall not
2366 // contain default template argument values.
2367 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2368 Decl *Param = TemplateParams->getParam(I);
2369 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2370 if (TTP->hasDefaultArgument()) {
2371 Diag(TTP->getDefaultArgumentLoc(),
2372 diag::err_default_arg_in_partial_spec);
2373 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2374 }
2375 } else if (NonTypeTemplateParmDecl *NTTP
2376 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2377 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2378 Diag(NTTP->getDefaultArgumentLoc(),
2379 diag::err_default_arg_in_partial_spec)
2380 << DefArg->getSourceRange();
2381 NTTP->setDefaultArgument(0);
2382 DefArg->Destroy(Context);
2383 }
2384 } else {
2385 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2386 if (Expr *DefArg = TTP->getDefaultArgument()) {
2387 Diag(TTP->getDefaultArgumentLoc(),
2388 diag::err_default_arg_in_partial_spec)
2389 << DefArg->getSourceRange();
2390 TTP->setDefaultArgument(0);
2391 DefArg->Destroy(Context);
2392 }
2393 }
2394 }
2395 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002396 }
2397
Douglas Gregorcc636682009-02-17 23:15:12 +00002398 // Check that the specialization uses the same tag kind as the
2399 // original template.
2400 TagDecl::TagKind Kind;
2401 switch (TagSpec) {
2402 default: assert(0 && "Unknown tag type!");
2403 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2404 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2405 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2406 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002407 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2408 Kind, KWLoc,
2409 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002410 Diag(KWLoc, diag::err_use_with_wrong_tag)
2411 << ClassTemplate
2412 << CodeModificationHint::CreateReplacement(KWLoc,
2413 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002414 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2415 diag::note_previous_use);
2416 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2417 }
2418
Douglas Gregor40808ce2009-03-09 23:48:35 +00002419 // Translate the parser's template argument list in our AST format.
2420 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2421 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2422
Douglas Gregorcc636682009-02-17 23:15:12 +00002423 // Check that the template argument list is well-formed for this
2424 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002425 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2426 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002427 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002428 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002429 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002430 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002431
Anders Carlssonfb250522009-06-23 01:26:57 +00002432 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002433 ClassTemplate->getTemplateParameters()->size()) &&
2434 "Converted template argument list is too short!");
2435
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002436 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002437 // corresponds to these arguments.
2438 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002439 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002440 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002441 if (CheckClassTemplatePartialSpecializationArgs(
2442 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002443 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002444 return true;
2445
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002446 if (MirrorsPrimaryTemplate) {
2447 // C++ [temp.class.spec]p9b3:
2448 //
2449 // -- The argument list of the specialization shall not be identical
2450 // to the implicit argument list of the primary template.
2451 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2452 << (TK == TK_Definition)
2453 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2454 RAngleLoc));
Douglas Gregorbd1099e2009-07-23 16:36:45 +00002455 return CheckClassTemplate(S, TagSpec, TK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002456 ClassTemplate->getIdentifier(),
2457 TemplateNameLoc,
2458 Attr,
2459 move(TemplateParameterLists),
2460 AS_none);
2461 }
2462
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002463 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002464 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002465 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002466 Converted.flatSize(),
2467 Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002468 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002469 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002470 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002471 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002472 Converted.flatSize(),
2473 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002474 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002475 ClassTemplateSpecializationDecl *PrevDecl = 0;
2476
2477 if (isPartialSpecialization)
2478 PrevDecl
2479 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2480 InsertPos);
2481 else
2482 PrevDecl
2483 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002484
2485 ClassTemplateSpecializationDecl *Specialization = 0;
2486
Douglas Gregor88b70942009-02-25 22:02:03 +00002487 // Check whether we can declare a class template specialization in
2488 // the current scope.
2489 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2490 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002491 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002492 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002493 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002494 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002495
Douglas Gregorcc636682009-02-17 23:15:12 +00002496 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2497 // Since the only prior class template specialization with these
2498 // arguments was referenced but not declared, reuse that
2499 // declaration node as our own, updating its source location to
2500 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002501 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002502 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002503 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002504 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002505 // Create a new class template partial specialization declaration node.
2506 TemplateParameterList *TemplateParams
2507 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2508 ClassTemplatePartialSpecializationDecl *PrevPartial
2509 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2510 ClassTemplatePartialSpecializationDecl *Partial
2511 = ClassTemplatePartialSpecializationDecl::Create(Context,
2512 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002513 TemplateNameLoc,
2514 TemplateParams,
2515 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002516 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002517 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002518
2519 if (PrevPartial) {
2520 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2521 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2522 } else {
2523 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2524 }
2525 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002526
2527 // Check that all of the template parameters of the class template
2528 // partial specialization are deducible from the template
2529 // arguments. If not, this class template partial specialization
2530 // will never be used.
2531 llvm::SmallVector<bool, 8> DeducibleParams;
2532 DeducibleParams.resize(TemplateParams->size());
2533 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2534 unsigned NumNonDeducible = 0;
2535 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2536 if (!DeducibleParams[I])
2537 ++NumNonDeducible;
2538
2539 if (NumNonDeducible) {
2540 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2541 << (NumNonDeducible > 1)
2542 << SourceRange(TemplateNameLoc, RAngleLoc);
2543 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2544 if (!DeducibleParams[I]) {
2545 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2546 if (Param->getDeclName())
2547 Diag(Param->getLocation(),
2548 diag::note_partial_spec_unused_parameter)
2549 << Param->getDeclName();
2550 else
2551 Diag(Param->getLocation(),
2552 diag::note_partial_spec_unused_parameter)
2553 << std::string("<anonymous>");
2554 }
2555 }
2556 }
2557
Douglas Gregorcc636682009-02-17 23:15:12 +00002558 } else {
2559 // Create a new class template specialization declaration node for
2560 // this explicit specialization.
2561 Specialization
2562 = ClassTemplateSpecializationDecl::Create(Context,
2563 ClassTemplate->getDeclContext(),
2564 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002565 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002566 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002567 PrevDecl);
2568
2569 if (PrevDecl) {
2570 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2571 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2572 } else {
2573 ClassTemplate->getSpecializations().InsertNode(Specialization,
2574 InsertPos);
2575 }
2576 }
2577
2578 // Note that this is an explicit specialization.
2579 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2580
2581 // Check that this isn't a redefinition of this specialization.
2582 if (TK == TK_Definition) {
2583 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002584 // FIXME: Should also handle explicit specialization after implicit
2585 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002586 SourceRange Range(TemplateNameLoc, RAngleLoc);
2587 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002588 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002589 Diag(Def->getLocation(), diag::note_previous_definition);
2590 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002591 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002592 }
2593 }
2594
Douglas Gregorfc705b82009-02-26 22:19:44 +00002595 // Build the fully-sugared type for this class template
2596 // specialization as the user wrote in the specialization
2597 // itself. This means that we'll pretty-print the type retrieved
2598 // from the specialization's declaration the way that the user
2599 // actually wrote the specialization, rather than formatting the
2600 // name based on the "canonical" representation used to store the
2601 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002602 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002603 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002604 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002605 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002606 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002607 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002608 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002609
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002610 // C++ [temp.expl.spec]p9:
2611 // A template explicit specialization is in the scope of the
2612 // namespace in which the template was defined.
2613 //
2614 // We actually implement this paragraph where we set the semantic
2615 // context (in the creation of the ClassTemplateSpecializationDecl),
2616 // but we also maintain the lexical context where the actual
2617 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002618 Specialization->setLexicalDeclContext(CurContext);
2619
2620 // We may be starting the definition of this specialization.
2621 if (TK == TK_Definition)
2622 Specialization->startDefinition();
2623
2624 // Add the specialization into its lexical context, so that it can
2625 // be seen when iterating through the list of declarations in that
2626 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002627 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002628 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002629}
Douglas Gregord57959a2009-03-27 23:10:48 +00002630
Douglas Gregore542c862009-06-23 23:11:28 +00002631Sema::DeclPtrTy
2632Sema::ActOnTemplateDeclarator(Scope *S,
2633 MultiTemplateParamsArg TemplateParameterLists,
2634 Declarator &D) {
2635 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2636}
2637
Douglas Gregor52591bf2009-06-24 00:54:41 +00002638Sema::DeclPtrTy
2639Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2640 MultiTemplateParamsArg TemplateParameterLists,
2641 Declarator &D) {
2642 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2643 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2644 "Not a function declarator!");
2645 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2646
2647 if (FTI.hasPrototype) {
2648 // FIXME: Diagnose arguments without names in C.
2649 }
2650
2651 Scope *ParentScope = FnBodyScope->getParent();
2652
2653 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2654 move(TemplateParameterLists),
2655 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002656 if (FunctionTemplateDecl *FunctionTemplate
2657 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002658 return ActOnStartOfFunctionDef(FnBodyScope,
2659 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002660 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2661 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002662 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002663}
2664
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002665// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002666Sema::DeclResult
2667Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2668 unsigned TagSpec,
2669 SourceLocation KWLoc,
2670 const CXXScopeSpec &SS,
2671 TemplateTy TemplateD,
2672 SourceLocation TemplateNameLoc,
2673 SourceLocation LAngleLoc,
2674 ASTTemplateArgsPtr TemplateArgsIn,
2675 SourceLocation *TemplateArgLocs,
2676 SourceLocation RAngleLoc,
2677 AttributeList *Attr) {
2678 // Find the class template we're specializing
2679 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2680 ClassTemplateDecl *ClassTemplate
2681 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2682
2683 // Check that the specialization uses the same tag kind as the
2684 // original template.
2685 TagDecl::TagKind Kind;
2686 switch (TagSpec) {
2687 default: assert(0 && "Unknown tag type!");
2688 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2689 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2690 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2691 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002692 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2693 Kind, KWLoc,
2694 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002695 Diag(KWLoc, diag::err_use_with_wrong_tag)
2696 << ClassTemplate
2697 << CodeModificationHint::CreateReplacement(KWLoc,
2698 ClassTemplate->getTemplatedDecl()->getKindName());
2699 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2700 diag::note_previous_use);
2701 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2702 }
2703
Douglas Gregorff668032009-05-13 18:28:20 +00002704 // C++0x [temp.explicit]p2:
2705 // [...] An explicit instantiation shall appear in an enclosing
2706 // namespace of its template. [...]
2707 //
2708 // This is C++ DR 275.
2709 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2710 TemplateNameLoc,
2711 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002712 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002713 /*ExplicitInstantiation=*/true))
2714 return true;
2715
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002716 // Translate the parser's template argument list in our AST format.
2717 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2718 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2719
2720 // Check that the template argument list is well-formed for this
2721 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002722 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2723 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002724 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002725 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002726 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002727 return true;
2728
Anders Carlssonfb250522009-06-23 01:26:57 +00002729 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002730 ClassTemplate->getTemplateParameters()->size()) &&
2731 "Converted template argument list is too short!");
2732
2733 // Find the class template specialization declaration that
2734 // corresponds to these arguments.
2735 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002736 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002737 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002738 Converted.flatSize(),
2739 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002740 void *InsertPos = 0;
2741 ClassTemplateSpecializationDecl *PrevDecl
2742 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2743
2744 ClassTemplateSpecializationDecl *Specialization = 0;
2745
Douglas Gregorff668032009-05-13 18:28:20 +00002746 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002747 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002748 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002749 // This particular specialization has already been declared or
2750 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002751 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2752 << Context.getTypeDeclType(PrevDecl);
2753 Diag(PrevDecl->getLocation(),
2754 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002755 return DeclPtrTy::make(PrevDecl);
2756 }
2757
Douglas Gregorff668032009-05-13 18:28:20 +00002758 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002759 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002760 // For a given set of template parameters, if an explicit
2761 // instantiation of a template appears after a declaration of
2762 // an explicit specialization for that template, the explicit
2763 // instantiation has no effect.
2764 if (!getLangOptions().CPlusPlus0x) {
2765 Diag(TemplateNameLoc,
2766 diag::ext_explicit_instantiation_after_specialization)
2767 << Context.getTypeDeclType(PrevDecl);
2768 Diag(PrevDecl->getLocation(),
2769 diag::note_previous_template_specialization);
2770 }
2771
2772 // Create a new class template specialization declaration node
2773 // for this explicit specialization. This node is only used to
2774 // record the existence of this explicit instantiation for
2775 // accurate reproduction of the source code; we don't actually
2776 // use it for anything, since it is semantically irrelevant.
2777 Specialization
2778 = ClassTemplateSpecializationDecl::Create(Context,
2779 ClassTemplate->getDeclContext(),
2780 TemplateNameLoc,
2781 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002782 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002783 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002784 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002785 return DeclPtrTy::make(Specialization);
2786 }
2787
2788 // If we have already (implicitly) instantiated this
2789 // specialization, there is less work to do.
2790 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2791 SpecializationRequiresInstantiation = false;
2792
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002793 // Since the only prior class template specialization with these
2794 // arguments was referenced but not declared, reuse that
2795 // declaration node as our own, updating its source location to
2796 // reflect our new declaration.
2797 Specialization = PrevDecl;
2798 Specialization->setLocation(TemplateNameLoc);
2799 PrevDecl = 0;
2800 } else {
2801 // Create a new class template specialization declaration node for
2802 // this explicit specialization.
2803 Specialization
2804 = ClassTemplateSpecializationDecl::Create(Context,
2805 ClassTemplate->getDeclContext(),
2806 TemplateNameLoc,
2807 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002808 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002809
2810 ClassTemplate->getSpecializations().InsertNode(Specialization,
2811 InsertPos);
2812 }
2813
2814 // Build the fully-sugared type for this explicit instantiation as
2815 // the user wrote in the explicit instantiation itself. This means
2816 // that we'll pretty-print the type retrieved from the
2817 // specialization's declaration the way that the user actually wrote
2818 // the explicit instantiation, rather than formatting the name based
2819 // on the "canonical" representation used to store the template
2820 // arguments in the specialization.
2821 QualType WrittenTy
2822 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002823 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002824 TemplateArgs.size(),
2825 Context.getTypeDeclType(Specialization));
2826 Specialization->setTypeAsWritten(WrittenTy);
2827 TemplateArgsIn.release();
2828
2829 // Add the explicit instantiation into its lexical context. However,
2830 // since explicit instantiations are never found by name lookup, we
2831 // just put it into the declaration context directly.
2832 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002833 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002834
2835 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002836 // A definition of a class template or class member template
2837 // shall be in scope at the point of the explicit instantiation of
2838 // the class template or class member template.
2839 //
2840 // This check comes when we actually try to perform the
2841 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002842 if (SpecializationRequiresInstantiation)
2843 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002844 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002845 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002846
2847 return DeclPtrTy::make(Specialization);
2848}
2849
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002850// Explicit instantiation of a member class of a class template.
2851Sema::DeclResult
2852Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2853 unsigned TagSpec,
2854 SourceLocation KWLoc,
2855 const CXXScopeSpec &SS,
2856 IdentifierInfo *Name,
2857 SourceLocation NameLoc,
2858 AttributeList *Attr) {
2859
Douglas Gregor402abb52009-05-28 23:31:59 +00002860 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002861 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002862 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2863 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002864 if (!TagD)
2865 return true;
2866
2867 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2868 if (Tag->isEnum()) {
2869 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2870 << Context.getTypeDeclType(Tag);
2871 return true;
2872 }
2873
Douglas Gregord0c87372009-05-27 17:30:49 +00002874 if (Tag->isInvalidDecl())
2875 return true;
2876
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002877 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2878 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2879 if (!Pattern) {
2880 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2881 << Context.getTypeDeclType(Record);
2882 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2883 return true;
2884 }
2885
2886 // C++0x [temp.explicit]p2:
2887 // [...] An explicit instantiation shall appear in an enclosing
2888 // namespace of its template. [...]
2889 //
2890 // This is C++ DR 275.
2891 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002892 // FIXME: In C++98, we would like to turn these errors into warnings,
2893 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002894 DeclContext *PatternContext
2895 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2896 if (!CurContext->Encloses(PatternContext)) {
2897 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2898 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2899 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2900 }
2901 }
2902
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002903 if (!Record->getDefinition(Context)) {
2904 // If the class has a definition, instantiate it (and all of its
2905 // members, recursively).
2906 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2907 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002908 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002909 /*ExplicitInstantiation=*/true))
2910 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002911 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002912 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002913 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002914
Mike Stump390b4cc2009-05-16 07:39:55 +00002915 // FIXME: We don't have any representation for explicit instantiations of
2916 // member classes. Such a representation is not needed for compilation, but it
2917 // should be available for clients that want to see all of the declarations in
2918 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002919 return TagD;
2920}
2921
Douglas Gregord57959a2009-03-27 23:10:48 +00002922Sema::TypeResult
2923Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2924 const IdentifierInfo &II, SourceLocation IdLoc) {
2925 NestedNameSpecifier *NNS
2926 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2927 if (!NNS)
2928 return true;
2929
2930 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002931 if (T.isNull())
2932 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002933 return T.getAsOpaquePtr();
2934}
2935
Douglas Gregor17343172009-04-01 00:28:59 +00002936Sema::TypeResult
2937Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2938 SourceLocation TemplateLoc, TypeTy *Ty) {
2939 QualType T = QualType::getFromOpaquePtr(Ty);
2940 NestedNameSpecifier *NNS
2941 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2942 const TemplateSpecializationType *TemplateId
2943 = T->getAsTemplateSpecializationType();
2944 assert(TemplateId && "Expected a template specialization type");
2945
2946 if (NNS->isDependent())
2947 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2948
2949 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2950}
2951
Douglas Gregord57959a2009-03-27 23:10:48 +00002952/// \brief Build the type that describes a C++ typename specifier,
2953/// e.g., "typename T::type".
2954QualType
2955Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2956 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002957 CXXRecordDecl *CurrentInstantiation = 0;
2958 if (NNS->isDependent()) {
2959 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002960
Douglas Gregor42af25f2009-05-11 19:58:34 +00002961 // If the nested-name-specifier does not refer to the current
2962 // instantiation, then build a typename type.
2963 if (!CurrentInstantiation)
2964 return Context.getTypenameType(NNS, &II);
2965 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002966
Douglas Gregor42af25f2009-05-11 19:58:34 +00002967 DeclContext *Ctx = 0;
2968
2969 if (CurrentInstantiation)
2970 Ctx = CurrentInstantiation;
2971 else {
2972 CXXScopeSpec SS;
2973 SS.setScopeRep(NNS);
2974 SS.setRange(Range);
2975 if (RequireCompleteDeclContext(SS))
2976 return QualType();
2977
2978 Ctx = computeDeclContext(SS);
2979 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002980 assert(Ctx && "No declaration context?");
2981
2982 DeclarationName Name(&II);
2983 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2984 false);
2985 unsigned DiagID = 0;
2986 Decl *Referenced = 0;
2987 switch (Result.getKind()) {
2988 case LookupResult::NotFound:
2989 if (Ctx->isTranslationUnit())
2990 DiagID = diag::err_typename_nested_not_found_global;
2991 else
2992 DiagID = diag::err_typename_nested_not_found;
2993 break;
2994
2995 case LookupResult::Found:
2996 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2997 // We found a type. Build a QualifiedNameType, since the
2998 // typename-specifier was just sugar. FIXME: Tell
2999 // QualifiedNameType that it has a "typename" prefix.
3000 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3001 }
3002
3003 DiagID = diag::err_typename_nested_not_type;
3004 Referenced = Result.getAsDecl();
3005 break;
3006
3007 case LookupResult::FoundOverloaded:
3008 DiagID = diag::err_typename_nested_not_type;
3009 Referenced = *Result.begin();
3010 break;
3011
3012 case LookupResult::AmbiguousBaseSubobjectTypes:
3013 case LookupResult::AmbiguousBaseSubobjects:
3014 case LookupResult::AmbiguousReference:
3015 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3016 return QualType();
3017 }
3018
3019 // If we get here, it's because name lookup did not find a
3020 // type. Emit an appropriate diagnostic and return an error.
3021 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3022 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3023 else
3024 Diag(Range.getEnd(), DiagID) << Range << Name;
3025 if (Referenced)
3026 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3027 << Name;
3028 return QualType();
3029}