blob: 2b2272d9995ba14d318e3f4b82049b3bdf2f7b5a [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()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
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 Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregor55f6b142009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000085 }
86 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000099 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000101}
102
Douglas Gregor72c3f312008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregor2943aed2009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregor72c3f312008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregorddc29e12009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregor72c3f312008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000166 Depth, Position, ParamName, Typename,
167 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000168 if (Invalid)
169 Param->setInvalidDecl();
170
171 if (ParamName) {
172 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000173 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000174 IdResolver.AddDecl(Param);
175 }
176
Chris Lattnerb28317a2009-03-28 19:18:32 +0000177 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000178}
179
Douglas Gregord684b002009-02-10 19:49:53 +0000180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000183 SourceLocation EqualLoc,
184 SourceLocation DefaultLoc,
185 TypeTy *DefaultT) {
186 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000187 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000188 QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000190 // C++0x [temp.param]p9:
191 // A default template-argument may be specified for any kind of
192 // template-parameter that is not a template parameter pack.
193 if (Parm->isParameterPack()) {
194 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000195 return;
196 }
197
Douglas Gregord684b002009-02-10 19:49:53 +0000198 // C++ [temp.param]p14:
199 // A template-parameter shall not be used in its own default argument.
200 // FIXME: Implement this check! Needs a recursive walk over the types.
201
202 // Check the template argument itself.
203 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
204 Parm->setInvalidDecl();
205 return;
206 }
207
208 Parm->setDefaultArgument(Default, DefaultLoc, false);
209}
210
Douglas Gregor2943aed2009-03-03 04:44:36 +0000211/// \brief Check that the type of a non-type template parameter is
212/// well-formed.
213///
214/// \returns the (possibly-promoted) parameter type if valid;
215/// otherwise, produces a diagnostic and returns a NULL type.
216QualType
217Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
218 // C++ [temp.param]p4:
219 //
220 // A non-type template-parameter shall have one of the following
221 // (optionally cv-qualified) types:
222 //
223 // -- integral or enumeration type,
224 if (T->isIntegralType() || T->isEnumeralType() ||
225 // -- pointer to object or pointer to function,
226 (T->isPointerType() &&
227 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
228 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
229 // -- reference to object or reference to function,
230 T->isReferenceType() ||
231 // -- pointer to member.
232 T->isMemberPointerType() ||
233 // If T is a dependent type, we can't do the check now, so we
234 // assume that it is well-formed.
235 T->isDependentType())
236 return T;
237 // C++ [temp.param]p8:
238 //
239 // A non-type template-parameter of type "array of T" or
240 // "function returning T" is adjusted to be of type "pointer to
241 // T" or "pointer to function returning T", respectively.
242 else if (T->isArrayType())
243 // FIXME: Keep the type prior to promotion?
244 return Context.getArrayDecayedType(T);
245 else if (T->isFunctionType())
246 // FIXME: Keep the type prior to promotion?
247 return Context.getPointerType(T);
248
249 Diag(Loc, diag::err_template_nontype_parm_bad_type)
250 << T;
251
252 return QualType();
253}
254
Douglas Gregor72c3f312008-12-05 18:15:24 +0000255/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
256/// template parameter (e.g., "int Size" in "template<int Size>
257/// class Array") has been parsed. S is the current scope and D is
258/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000259Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
260 unsigned Depth,
261 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 QualType T = GetTypeForDeclarator(D, S);
263
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000264 assert(S->isTemplateParamScope() &&
265 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000266 bool Invalid = false;
267
268 IdentifierInfo *ParamName = D.getIdentifier();
269 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000270 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000271 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000273 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000274 }
275
Douglas Gregor2943aed2009-03-03 04:44:36 +0000276 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000277 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000278 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000279 Invalid = true;
280 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000281
Douglas Gregor72c3f312008-12-05 18:15:24 +0000282 NonTypeTemplateParmDecl *Param
283 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000284 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000285 if (Invalid)
286 Param->setInvalidDecl();
287
288 if (D.getIdentifier()) {
289 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000290 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000291 IdResolver.AddDecl(Param);
292 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000293 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000294}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000295
Douglas Gregord684b002009-02-10 19:49:53 +0000296/// \brief Adds a default argument to the given non-type template
297/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000298void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000299 SourceLocation EqualLoc,
300 ExprArg DefaultE) {
301 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000302 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000303 Expr *Default = static_cast<Expr *>(DefaultE.get());
304
305 // C++ [temp.param]p14:
306 // A template-parameter shall not be used in its own default argument.
307 // FIXME: Implement this check! Needs a recursive walk over the types.
308
309 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000310 TemplateArgument Converted;
311 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
312 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000313 TemplateParm->setInvalidDecl();
314 return;
315 }
316
Anders Carlssone9146f22009-05-01 19:49:17 +0000317 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000318}
319
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000320
321/// ActOnTemplateTemplateParameter - Called when a C++ template template
322/// parameter (e.g. T in template <template <typename> class T> class array)
323/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000324Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
325 SourceLocation TmpLoc,
326 TemplateParamsTy *Params,
327 IdentifierInfo *Name,
328 SourceLocation NameLoc,
329 unsigned Depth,
330 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000331{
332 assert(S->isTemplateParamScope() &&
333 "Template template parameter not in template parameter scope!");
334
335 // Construct the parameter object.
336 TemplateTemplateParmDecl *Param =
337 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
338 Position, Name,
339 (TemplateParameterList*)Params);
340
341 // Make sure the parameter is valid.
342 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
343 // do anything yet. However, if the template parameter list or (eventual)
344 // default value is ever invalidated, that will propagate here.
345 bool Invalid = false;
346 if (Invalid) {
347 Param->setInvalidDecl();
348 }
349
350 // If the tt-param has a name, then link the identifier into the scope
351 // and lookup mechanisms.
352 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000354 IdResolver.AddDecl(Param);
355 }
356
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000358}
359
Douglas Gregord684b002009-02-10 19:49:53 +0000360/// \brief Adds a default argument to the given template template
361/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000362void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000363 SourceLocation EqualLoc,
364 ExprArg DefaultE) {
365 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000367
368 // Since a template-template parameter's default argument is an
369 // id-expression, it must be a DeclRefExpr.
370 DeclRefExpr *Default
371 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
372
373 // C++ [temp.param]p14:
374 // A template-parameter shall not be used in its own default argument.
375 // FIXME: Implement this check! Needs a recursive walk over the types.
376
377 // Check the well-formedness of the template argument.
378 if (!isa<TemplateDecl>(Default->getDecl())) {
379 Diag(Default->getSourceRange().getBegin(),
380 diag::err_template_arg_must_be_template)
381 << Default->getSourceRange();
382 TemplateParm->setInvalidDecl();
383 return;
384 }
385 if (CheckTemplateArgument(TemplateParm, Default)) {
386 TemplateParm->setInvalidDecl();
387 return;
388 }
389
390 DefaultE.release();
391 TemplateParm->setDefaultArgument(Default);
392}
393
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000394/// ActOnTemplateParameterList - Builds a TemplateParameterList that
395/// contains the template parameters in Params/NumParams.
396Sema::TemplateParamsTy *
397Sema::ActOnTemplateParameterList(unsigned Depth,
398 SourceLocation ExportLoc,
399 SourceLocation TemplateLoc,
400 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000401 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000402 SourceLocation RAngleLoc) {
403 if (ExportLoc.isValid())
404 Diag(ExportLoc, diag::note_template_export_unsupported);
405
Douglas Gregorddc29e12009-02-06 22:42:48 +0000406 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
407 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000408}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000409
Douglas Gregor212e81c2009-03-25 00:13:59 +0000410Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000411Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
412 SourceLocation KWLoc, const CXXScopeSpec &SS,
413 IdentifierInfo *Name, SourceLocation NameLoc,
414 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000415 MultiTemplateParamsArg TemplateParameterLists,
416 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000417 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
418 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000419 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000420
421 // Check that we can declare a template here.
422 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000423 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000424
425 TagDecl::TagKind Kind;
426 switch (TagSpec) {
427 default: assert(0 && "Unknown tag type!");
428 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
429 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
430 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
431 }
432
433 // There is no such thing as an unnamed class template.
434 if (!Name) {
435 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000436 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000437 }
438
439 // Find any previous declaration with this name.
440 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
441 true);
442 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
443 NamedDecl *PrevDecl = 0;
444 if (Previous.begin() != Previous.end())
445 PrevDecl = *Previous.begin();
446
447 DeclContext *SemanticContext = CurContext;
448 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000449 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000450
Mike Stump390b4cc2009-05-16 07:39:55 +0000451 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000452 }
453
454 // FIXME: member templates!
455 TemplateParameterList *TemplateParams
456 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
457
458 // If there is a previous declaration with the same name, check
459 // whether this is a valid redeclaration.
460 ClassTemplateDecl *PrevClassTemplate
461 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
462 if (PrevClassTemplate) {
463 // Ensure that the template parameter lists are compatible.
464 if (!TemplateParameterListsAreEqual(TemplateParams,
465 PrevClassTemplate->getTemplateParameters(),
466 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000467 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000468
469 // C++ [temp.class]p4:
470 // In a redeclaration, partial specialization, explicit
471 // specialization or explicit instantiation of a class template,
472 // the class-key shall agree in kind with the original class
473 // template declaration (7.1.5.3).
474 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000475 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000476 Diag(KWLoc, diag::err_use_with_wrong_tag)
477 << Name
478 << CodeModificationHint::CreateReplacement(KWLoc,
479 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000480 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000481 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000482 }
483
Douglas Gregorddc29e12009-02-06 22:42:48 +0000484 // Check for redefinition of this class template.
485 if (TK == TK_Definition) {
486 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
487 Diag(NameLoc, diag::err_redefinition) << Name;
488 Diag(Def->getLocation(), diag::note_previous_definition);
489 // FIXME: Would it make sense to try to "forget" the previous
490 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000491 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000492 }
493 }
494 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
495 // Maybe we will complain about the shadowed template parameter.
496 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
497 // Just pretend that we didn't see the previous declaration.
498 PrevDecl = 0;
499 } else if (PrevDecl) {
500 // C++ [temp]p5:
501 // A class template shall not have the same name as any other
502 // template, class, function, object, enumeration, enumerator,
503 // namespace, or type in the same scope (3.3), except as specified
504 // in (14.5.4).
505 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
506 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000507 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000508 }
509
Douglas Gregord684b002009-02-10 19:49:53 +0000510 // Check the template parameter list of this declaration, possibly
511 // merging in the template parameter list from the previous class
512 // template declaration.
513 if (CheckTemplateParameterList(TemplateParams,
514 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
515 Invalid = true;
516
Douglas Gregor7da97d02009-05-10 22:57:19 +0000517 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000518 // declaration!
519
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000520 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000521 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
522 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000523 PrevClassTemplate->getTemplatedDecl() : 0,
524 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000525
526 ClassTemplateDecl *NewTemplate
527 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
528 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000529 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000530 NewClass->setDescribedClassTemplate(NewTemplate);
531
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000532 // Build the type for the class template declaration now.
533 QualType T =
534 Context.getTypeDeclType(NewClass,
535 PrevClassTemplate?
536 PrevClassTemplate->getTemplatedDecl() : 0);
537 assert(T->isDependentType() && "Class template type is not dependent?");
538 (void)T;
539
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000540 // Set the access specifier.
541 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
542
Douglas Gregorddc29e12009-02-06 22:42:48 +0000543 // Set the lexical context of these templates
544 NewClass->setLexicalDeclContext(CurContext);
545 NewTemplate->setLexicalDeclContext(CurContext);
546
547 if (TK == TK_Definition)
548 NewClass->startDefinition();
549
550 if (Attr)
551 ProcessDeclAttributeList(NewClass, Attr);
552
553 PushOnScopeChains(NewTemplate, S);
554
Douglas Gregord684b002009-02-10 19:49:53 +0000555 if (Invalid) {
556 NewTemplate->setInvalidDecl();
557 NewClass->setInvalidDecl();
558 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000559 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000560}
561
Douglas Gregord684b002009-02-10 19:49:53 +0000562/// \brief Checks the validity of a template parameter list, possibly
563/// considering the template parameter list from a previous
564/// declaration.
565///
566/// If an "old" template parameter list is provided, it must be
567/// equivalent (per TemplateParameterListsAreEqual) to the "new"
568/// template parameter list.
569///
570/// \param NewParams Template parameter list for a new template
571/// declaration. This template parameter list will be updated with any
572/// default arguments that are carried through from the previous
573/// template parameter list.
574///
575/// \param OldParams If provided, template parameter list from a
576/// previous declaration of the same template. Default template
577/// arguments will be merged from the old template parameter list to
578/// the new template parameter list.
579///
580/// \returns true if an error occurred, false otherwise.
581bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
582 TemplateParameterList *OldParams) {
583 bool Invalid = false;
584
585 // C++ [temp.param]p10:
586 // The set of default template-arguments available for use with a
587 // template declaration or definition is obtained by merging the
588 // default arguments from the definition (if in scope) and all
589 // declarations in scope in the same way default function
590 // arguments are (8.3.6).
591 bool SawDefaultArgument = false;
592 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000593
Anders Carlsson49d25572009-06-12 23:20:15 +0000594 bool SawParameterPack = false;
595 SourceLocation ParameterPackLoc;
596
Mike Stump1a35fde2009-02-11 23:03:27 +0000597 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000598 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000599 if (OldParams)
600 OldParam = OldParams->begin();
601
602 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
603 NewParamEnd = NewParams->end();
604 NewParam != NewParamEnd; ++NewParam) {
605 // Variables used to diagnose redundant default arguments
606 bool RedundantDefaultArg = false;
607 SourceLocation OldDefaultLoc;
608 SourceLocation NewDefaultLoc;
609
610 // Variables used to diagnose missing default arguments
611 bool MissingDefaultArg = false;
612
Anders Carlsson49d25572009-06-12 23:20:15 +0000613 // C++0x [temp.param]p11:
614 // If a template parameter of a class template is a template parameter pack,
615 // it must be the last template parameter.
616 if (SawParameterPack) {
617 Diag(ParameterPackLoc,
618 diag::err_template_param_pack_must_be_last_template_parameter);
619 Invalid = true;
620 }
621
Douglas Gregord684b002009-02-10 19:49:53 +0000622 // Merge default arguments for template type parameters.
623 if (TemplateTypeParmDecl *NewTypeParm
624 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
625 TemplateTypeParmDecl *OldTypeParm
626 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
627
Anders Carlsson49d25572009-06-12 23:20:15 +0000628 if (NewTypeParm->isParameterPack()) {
629 assert(!NewTypeParm->hasDefaultArgument() &&
630 "Parameter packs can't have a default argument!");
631 SawParameterPack = true;
632 ParameterPackLoc = NewTypeParm->getLocation();
633 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000634 NewTypeParm->hasDefaultArgument()) {
635 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
636 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
637 SawDefaultArgument = true;
638 RedundantDefaultArg = true;
639 PreviousDefaultArgLoc = NewDefaultLoc;
640 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
641 // Merge the default argument from the old declaration to the
642 // new declaration.
643 SawDefaultArgument = true;
644 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
645 OldTypeParm->getDefaultArgumentLoc(),
646 true);
647 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
648 } else if (NewTypeParm->hasDefaultArgument()) {
649 SawDefaultArgument = true;
650 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
651 } else if (SawDefaultArgument)
652 MissingDefaultArg = true;
653 }
654 // Merge default arguments for non-type template parameters
655 else if (NonTypeTemplateParmDecl *NewNonTypeParm
656 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
657 NonTypeTemplateParmDecl *OldNonTypeParm
658 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
659 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
660 NewNonTypeParm->hasDefaultArgument()) {
661 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
662 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
663 SawDefaultArgument = true;
664 RedundantDefaultArg = true;
665 PreviousDefaultArgLoc = NewDefaultLoc;
666 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
667 // Merge the default argument from the old declaration to the
668 // new declaration.
669 SawDefaultArgument = true;
670 // FIXME: We need to create a new kind of "default argument"
671 // expression that points to a previous template template
672 // parameter.
673 NewNonTypeParm->setDefaultArgument(
674 OldNonTypeParm->getDefaultArgument());
675 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
676 } else if (NewNonTypeParm->hasDefaultArgument()) {
677 SawDefaultArgument = true;
678 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
679 } else if (SawDefaultArgument)
680 MissingDefaultArg = true;
681 }
682 // Merge default arguments for template template parameters
683 else {
684 TemplateTemplateParmDecl *NewTemplateParm
685 = cast<TemplateTemplateParmDecl>(*NewParam);
686 TemplateTemplateParmDecl *OldTemplateParm
687 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
688 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
689 NewTemplateParm->hasDefaultArgument()) {
690 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
691 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
692 SawDefaultArgument = true;
693 RedundantDefaultArg = true;
694 PreviousDefaultArgLoc = NewDefaultLoc;
695 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
696 // Merge the default argument from the old declaration to the
697 // new declaration.
698 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000699 // FIXME: We need to create a new kind of "default argument" expression
700 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000701 NewTemplateParm->setDefaultArgument(
702 OldTemplateParm->getDefaultArgument());
703 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
704 } else if (NewTemplateParm->hasDefaultArgument()) {
705 SawDefaultArgument = true;
706 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
707 } else if (SawDefaultArgument)
708 MissingDefaultArg = true;
709 }
710
711 if (RedundantDefaultArg) {
712 // C++ [temp.param]p12:
713 // A template-parameter shall not be given default arguments
714 // by two different declarations in the same scope.
715 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
716 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
717 Invalid = true;
718 } else if (MissingDefaultArg) {
719 // C++ [temp.param]p11:
720 // If a template-parameter has a default template-argument,
721 // all subsequent template-parameters shall have a default
722 // template-argument supplied.
723 Diag((*NewParam)->getLocation(),
724 diag::err_template_param_default_arg_missing);
725 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
726 Invalid = true;
727 }
728
729 // If we have an old template parameter list that we're merging
730 // in, move on to the next parameter.
731 if (OldParams)
732 ++OldParam;
733 }
734
735 return Invalid;
736}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000737
Douglas Gregor40808ce2009-03-09 23:48:35 +0000738/// \brief Translates template arguments as provided by the parser
739/// into template arguments used by semantic analysis.
740static void
741translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
742 SourceLocation *TemplateArgLocs,
743 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
744 TemplateArgs.reserve(TemplateArgsIn.size());
745
746 void **Args = TemplateArgsIn.getArgs();
747 bool *ArgIsType = TemplateArgsIn.getArgIsType();
748 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
749 TemplateArgs.push_back(
750 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
751 QualType::getFromOpaquePtr(Args[Arg]))
752 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
753 }
754}
755
Douglas Gregorc45c2322009-03-31 00:43:58 +0000756/// \brief Build a canonical version of a template argument list.
757///
758/// This function builds a canonical version of the given template
759/// argument list, where each of the template arguments has been
760/// converted into its canonical form. This routine is typically used
761/// to canonicalize a template argument list when the template name
762/// itself is dependent. When the template name refers to an actual
763/// template declaration, Sema::CheckTemplateArgumentList should be
764/// used to check and canonicalize the template arguments.
765///
766/// \param TemplateArgs The incoming template arguments.
767///
768/// \param NumTemplateArgs The number of template arguments in \p
769/// TemplateArgs.
770///
771/// \param Canonical A vector to be filled with the canonical versions
772/// of the template arguments.
773///
774/// \param Context The ASTContext in which the template arguments live.
775static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
776 unsigned NumTemplateArgs,
777 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
778 ASTContext &Context) {
779 Canonical.reserve(NumTemplateArgs);
780 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
781 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000782 case TemplateArgument::Null:
783 assert(false && "Should never see a NULL template argument here");
784 break;
785
Douglas Gregorc45c2322009-03-31 00:43:58 +0000786 case TemplateArgument::Expression:
787 // FIXME: Build canonical expression (!)
788 Canonical.push_back(TemplateArgs[Idx]);
789 break;
790
791 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000792 Canonical.push_back(
793 TemplateArgument(SourceLocation(),
794 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000795 break;
796
797 case TemplateArgument::Integral:
798 Canonical.push_back(TemplateArgument(SourceLocation(),
799 *TemplateArgs[Idx].getAsIntegral(),
800 TemplateArgs[Idx].getIntegralType()));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000801 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000802
803 case TemplateArgument::Type: {
804 QualType CanonType
805 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
806 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000807 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000808 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000809
810 case TemplateArgument::Pack:
811 assert(0 && "FIXME: Implement!");
812 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000813 }
814 }
815}
816
Douglas Gregor7532dc62009-03-30 22:58:21 +0000817QualType Sema::CheckTemplateIdType(TemplateName Name,
818 SourceLocation TemplateLoc,
819 SourceLocation LAngleLoc,
820 const TemplateArgument *TemplateArgs,
821 unsigned NumTemplateArgs,
822 SourceLocation RAngleLoc) {
823 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000824 if (!Template) {
825 // The template name does not resolve to a template, so we just
826 // build a dependent template-id type.
827
828 // Canonicalize the template arguments to build the canonical
829 // template-id type.
830 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
831 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
832 CanonicalTemplateArgs, Context);
833
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000834 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000835 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000836 = Context.getTemplateSpecializationType(CanonName,
837 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000838 CanonicalTemplateArgs.size());
839
840 // Build the dependent template-id type.
841 return Context.getTemplateSpecializationType(Name, TemplateArgs,
842 NumTemplateArgs, CanonType);
843 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000844
Douglas Gregor40808ce2009-03-09 23:48:35 +0000845 // Check that the template argument list is well-formed for this
846 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +0000847 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000848 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000849 TemplateArgs, NumTemplateArgs, RAngleLoc,
850 ConvertedTemplateArgs))
851 return QualType();
852
853 assert((ConvertedTemplateArgs.size() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000854 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000855 "Converted template argument list is too short!");
856
857 QualType CanonType;
858
Douglas Gregor7532dc62009-03-30 22:58:21 +0000859 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000860 TemplateArgs,
861 NumTemplateArgs)) {
862 // This class template specialization is a dependent
863 // type. Therefore, its canonical type is another class template
864 // specialization type that contains all of the converted
865 // arguments in canonical form. This ensures that, e.g., A<T> and
866 // A<T, T> have identical types when A is declared as:
867 //
868 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000869 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
870 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000871 ConvertedTemplateArgs.getFlatArgumentList(),
872 ConvertedTemplateArgs.flatSize());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000873 } else if (ClassTemplateDecl *ClassTemplate
874 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000875 // Find the class template specialization declaration that
876 // corresponds to these arguments.
877 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000878 ClassTemplateSpecializationDecl::Profile(ID,
879 ConvertedTemplateArgs.getFlatArgumentList(),
880 ConvertedTemplateArgs.flatSize());
Douglas Gregor40808ce2009-03-09 23:48:35 +0000881 void *InsertPos = 0;
882 ClassTemplateSpecializationDecl *Decl
883 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
884 if (!Decl) {
885 // This is the first time we have referenced this class template
886 // specialization. Create the canonical declaration and add it to
887 // the set of specializations.
888 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000889 ClassTemplate->getDeclContext(),
890 TemplateLoc,
891 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +0000892 ConvertedTemplateArgs, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000893 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
894 Decl->setLexicalDeclContext(CurContext);
895 }
896
897 CanonType = Context.getTypeDeclType(Decl);
898 }
899
900 // Build the fully-sugared type for this class template
901 // specialization, which refers back to the class template
902 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000903 return Context.getTemplateSpecializationType(Name, TemplateArgs,
904 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000905}
906
Douglas Gregorcc636682009-02-17 23:15:12 +0000907Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000908Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
909 SourceLocation LAngleLoc,
910 ASTTemplateArgsPtr TemplateArgsIn,
911 SourceLocation *TemplateArgLocs,
912 SourceLocation RAngleLoc) {
913 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000914
Douglas Gregor40808ce2009-03-09 23:48:35 +0000915 // Translate the parser's template argument list in our AST format.
916 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
917 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000918
Douglas Gregor7532dc62009-03-30 22:58:21 +0000919 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000920 TemplateArgs.data(),
921 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000922 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000923 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000924
925 if (Result.isNull())
926 return true;
927
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000928 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000929}
930
Douglas Gregorc45c2322009-03-31 00:43:58 +0000931/// \brief Form a dependent template name.
932///
933/// This action forms a dependent template name given the template
934/// name and its (presumably dependent) scope specifier. For
935/// example, given "MetaFun::template apply", the scope specifier \p
936/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
937/// of the "template" keyword, and "apply" is the \p Name.
938Sema::TemplateTy
939Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
940 const IdentifierInfo &Name,
941 SourceLocation NameLoc,
942 const CXXScopeSpec &SS) {
943 if (!SS.isSet() || SS.isInvalid())
944 return TemplateTy();
945
946 NestedNameSpecifier *Qualifier
947 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
948
949 // FIXME: member of the current instantiation
950
951 if (!Qualifier->isDependent()) {
952 // C++0x [temp.names]p5:
953 // If a name prefixed by the keyword template is not the name of
954 // a template, the program is ill-formed. [Note: the keyword
955 // template may not be applied to non-template members of class
956 // templates. -end note ] [ Note: as is the case with the
957 // typename prefix, the template prefix is allowed in cases
958 // where it is not strictly necessary; i.e., when the
959 // nested-name-specifier or the expression on the left of the ->
960 // or . is not dependent on a template-parameter, or the use
961 // does not appear in the scope of a template. -end note]
962 //
963 // Note: C++03 was more strict here, because it banned the use of
964 // the "template" keyword prior to a template-name that was not a
965 // dependent name. C++ DR468 relaxed this requirement (the
966 // "template" keyword is now permitted). We follow the C++0x
967 // rules, even in C++03 mode, retroactively applying the DR.
968 TemplateTy Template;
969 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
970 if (TNK == TNK_Non_template) {
971 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
972 << &Name;
973 return TemplateTy();
974 }
975
976 return Template;
977 }
978
979 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
980}
981
Anders Carlsson436b1562009-06-13 00:33:33 +0000982bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
983 const TemplateArgument &Arg,
984 TemplateArgumentListBuilder &Converted) {
985 // Check template type parameter.
986 if (Arg.getKind() != TemplateArgument::Type) {
987 // C++ [temp.arg.type]p1:
988 // A template-argument for a template-parameter which is a
989 // type shall be a type-id.
990
991 // We have a template type parameter but the template argument
992 // is not a type.
993 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
994 Diag(Param->getLocation(), diag::note_template_param_here);
995
996 return true;
997 }
998
999 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1000 return true;
1001
1002 // Add the converted template type argument.
1003 Converted.push_back(
1004 TemplateArgument(Arg.getLocation(),
1005 Context.getCanonicalType(Arg.getAsType())));
1006 return false;
1007}
1008
Douglas Gregorc15cb382009-02-09 23:23:08 +00001009/// \brief Check that the given template argument list is well-formed
1010/// for specializing the given template.
1011bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1012 SourceLocation TemplateLoc,
1013 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001014 const TemplateArgument *TemplateArgs,
1015 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001016 SourceLocation RAngleLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001017 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001018 TemplateParameterList *Params = Template->getTemplateParameters();
1019 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001020 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001021 bool Invalid = false;
1022
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001023 bool HasParameterPack =
1024 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1025
1026 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001027 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001028 // FIXME: point at either the first arg beyond what we can handle,
1029 // or the '>', depending on whether we have too many or too few
1030 // arguments.
1031 SourceRange Range;
1032 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001033 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001034 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1035 << (NumArgs > NumParams)
1036 << (isa<ClassTemplateDecl>(Template)? 0 :
1037 isa<FunctionTemplateDecl>(Template)? 1 :
1038 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1039 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001040 Diag(Template->getLocation(), diag::note_template_decl_here)
1041 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001042 Invalid = true;
1043 }
1044
1045 // C++ [temp.arg]p1:
1046 // [...] The type and form of each template-argument specified in
1047 // a template-id shall match the type and form specified for the
1048 // corresponding parameter declared by the template in its
1049 // template-parameter-list.
1050 unsigned ArgIdx = 0;
1051 for (TemplateParameterList::iterator Param = Params->begin(),
1052 ParamEnd = Params->end();
1053 Param != ParamEnd; ++Param, ++ArgIdx) {
1054 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001055 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001056 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001057 // Retrieve the default template argument from the template
1058 // parameter.
1059 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001060 if (TTP->isParameterPack()) {
1061 // We have an empty parameter pack.
1062 Converted.BeginParameterPack();
1063 Converted.EndParameterPack();
1064 break;
1065 }
1066
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001067 if (!TTP->hasDefaultArgument())
1068 break;
1069
Douglas Gregor40808ce2009-03-09 23:48:35 +00001070 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001071
1072 // If the argument type is dependent, instantiate it now based
1073 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001074 if (ArgType->isDependentType()) {
1075 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001076 Template, Converted.getFlatArgumentList(),
1077 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001078 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001079
Anders Carlssone9c904b2009-06-05 04:47:51 +00001080 TemplateArgumentList TemplateArgs(Context, Converted,
1081 /*CopyArgs=*/false,
1082 /*FlattenArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001083 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001084 TTP->getDefaultArgumentLoc(),
1085 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001086 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001087
1088 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001089 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001090
Douglas Gregor40808ce2009-03-09 23:48:35 +00001091 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001092 } else if (NonTypeTemplateParmDecl *NTTP
1093 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1094 if (!NTTP->hasDefaultArgument())
1095 break;
1096
Anders Carlsson3b56c002009-06-11 16:06:49 +00001097 InstantiatingTemplate Inst(*this, TemplateLoc,
1098 Template, Converted.getFlatArgumentList(),
1099 Converted.flatSize(),
1100 SourceRange(TemplateLoc, RAngleLoc));
1101
1102 TemplateArgumentList TemplateArgs(Context, Converted,
1103 /*CopyArgs=*/false,
1104 /*FlattenArgs=*/false);
1105
1106 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1107 TemplateArgs);
1108 if (E.isInvalid())
1109 return true;
1110
1111 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001112 } else {
1113 TemplateTemplateParmDecl *TempParm
1114 = cast<TemplateTemplateParmDecl>(*Param);
1115
1116 if (!TempParm->hasDefaultArgument())
1117 break;
1118
Douglas Gregor2943aed2009-03-03 04:44:36 +00001119 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001120 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001121 }
1122 } else {
1123 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001124 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001125 }
1126
Douglas Gregorc15cb382009-02-09 23:23:08 +00001127
1128 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001129 if (TTP->isParameterPack()) {
1130 Converted.BeginParameterPack();
1131 // Check all the remaining arguments (if any).
1132 for (; ArgIdx < NumArgs; ++ArgIdx) {
1133 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1134 Invalid = true;
1135 }
1136
1137 Converted.EndParameterPack();
1138 } else {
1139 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1140 Invalid = true;
1141 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001142 } else if (NonTypeTemplateParmDecl *NTTP
1143 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1144 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145
1146 // Instantiate the type of the non-type template parameter with
1147 // the template arguments we've seen thus far.
1148 QualType NTTPType = NTTP->getType();
1149 if (NTTPType->isDependentType()) {
1150 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001151 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001152 Template, Converted.getFlatArgumentList(),
1153 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001154 SourceRange(TemplateLoc, RAngleLoc));
1155
Anders Carlssone9c904b2009-06-05 04:47:51 +00001156 TemplateArgumentList TemplateArgs(Context, Converted,
1157 /*CopyArgs=*/false,
1158 /*FlattenArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001159 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160 NTTP->getLocation(),
1161 NTTP->getDeclName());
1162 // If that worked, check the non-type template parameter type
1163 // for validity.
1164 if (!NTTPType.isNull())
1165 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1166 NTTP->getLocation());
1167
1168 if (NTTPType.isNull()) {
1169 Invalid = true;
1170 break;
1171 }
1172 }
1173
Douglas Gregor40808ce2009-03-09 23:48:35 +00001174 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001175 case TemplateArgument::Null:
1176 assert(false && "Should never see a NULL template argument here");
1177 break;
1178
Douglas Gregor40808ce2009-03-09 23:48:35 +00001179 case TemplateArgument::Expression: {
1180 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001181 TemplateArgument Result;
1182 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001183 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001184 else
1185 Converted.push_back(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001186 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001187 }
1188
Douglas Gregor40808ce2009-03-09 23:48:35 +00001189 case TemplateArgument::Declaration:
1190 case TemplateArgument::Integral:
1191 // We've already checked this template argument, so just copy
1192 // it to the list of converted arguments.
1193 Converted.push_back(Arg);
1194 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001195
Douglas Gregor40808ce2009-03-09 23:48:35 +00001196 case TemplateArgument::Type:
1197 // We have a non-type template parameter but the template
1198 // argument is a type.
1199
1200 // C++ [temp.arg]p2:
1201 // In a template-argument, an ambiguity between a type-id and
1202 // an expression is resolved to a type-id, regardless of the
1203 // form of the corresponding template-parameter.
1204 //
1205 // We warn specifically about this case, since it can be rather
1206 // confusing for users.
1207 if (Arg.getAsType()->isFunctionType())
1208 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1209 << Arg.getAsType();
1210 else
1211 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1212 Diag((*Param)->getLocation(), diag::note_template_param_here);
1213 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001214 break;
1215
1216 case TemplateArgument::Pack:
1217 assert(0 && "FIXME: Implement!");
1218 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001219 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001220 } else {
1221 // Check template template parameters.
1222 TemplateTemplateParmDecl *TempParm
1223 = cast<TemplateTemplateParmDecl>(*Param);
1224
Douglas Gregor40808ce2009-03-09 23:48:35 +00001225 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001226 case TemplateArgument::Null:
1227 assert(false && "Should never see a NULL template argument here");
1228 break;
1229
Douglas Gregor40808ce2009-03-09 23:48:35 +00001230 case TemplateArgument::Expression: {
1231 Expr *ArgExpr = Arg.getAsExpr();
1232 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1233 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1234 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1235 Invalid = true;
1236
1237 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001238 Decl *D
1239 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1240 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001241 continue;
1242 }
1243 }
1244 // fall through
1245
1246 case TemplateArgument::Type: {
1247 // We have a template template parameter but the template
1248 // argument does not refer to a template.
1249 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1250 Invalid = true;
1251 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001252 }
1253
Douglas Gregor40808ce2009-03-09 23:48:35 +00001254 case TemplateArgument::Declaration:
1255 // We've already checked this template argument, so just copy
1256 // it to the list of converted arguments.
1257 Converted.push_back(Arg);
1258 break;
1259
1260 case TemplateArgument::Integral:
1261 assert(false && "Integral argument with template template parameter");
1262 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001263
1264 case TemplateArgument::Pack:
1265 assert(0 && "FIXME: Implement!");
1266 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001267 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001268 }
1269 }
1270
1271 return Invalid;
1272}
1273
1274/// \brief Check a template argument against its corresponding
1275/// template type parameter.
1276///
1277/// This routine implements the semantics of C++ [temp.arg.type]. It
1278/// returns true if an error occurred, and false otherwise.
1279bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1280 QualType Arg, SourceLocation ArgLoc) {
1281 // C++ [temp.arg.type]p2:
1282 // A local type, a type with no linkage, an unnamed type or a type
1283 // compounded from any of these types shall not be used as a
1284 // template-argument for a template type-parameter.
1285 //
1286 // FIXME: Perform the recursive and no-linkage type checks.
1287 const TagType *Tag = 0;
1288 if (const EnumType *EnumT = Arg->getAsEnumType())
1289 Tag = EnumT;
1290 else if (const RecordType *RecordT = Arg->getAsRecordType())
1291 Tag = RecordT;
1292 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1293 return Diag(ArgLoc, diag::err_template_arg_local_type)
1294 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001295 else if (Tag && !Tag->getDecl()->getDeclName() &&
1296 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001297 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1298 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1299 return true;
1300 }
1301
1302 return false;
1303}
1304
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001305/// \brief Checks whether the given template argument is the address
1306/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001307bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1308 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001309 bool Invalid = false;
1310
1311 // See through any implicit casts we added to fix the type.
1312 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1313 Arg = Cast->getSubExpr();
1314
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001315 // C++0x allows nullptr, and there's no further checking to be done for that.
1316 if (Arg->getType()->isNullPtrType())
1317 return false;
1318
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001319 // C++ [temp.arg.nontype]p1:
1320 //
1321 // A template-argument for a non-type, non-template
1322 // template-parameter shall be one of: [...]
1323 //
1324 // -- the address of an object or function with external
1325 // linkage, including function templates and function
1326 // template-ids but excluding non-static class members,
1327 // expressed as & id-expression where the & is optional if
1328 // the name refers to a function or array, or if the
1329 // corresponding template-parameter is a reference; or
1330 DeclRefExpr *DRE = 0;
1331
1332 // Ignore (and complain about) any excess parentheses.
1333 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1334 if (!Invalid) {
1335 Diag(Arg->getSourceRange().getBegin(),
1336 diag::err_template_arg_extra_parens)
1337 << Arg->getSourceRange();
1338 Invalid = true;
1339 }
1340
1341 Arg = Parens->getSubExpr();
1342 }
1343
1344 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1345 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1346 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1347 } else
1348 DRE = dyn_cast<DeclRefExpr>(Arg);
1349
1350 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1351 return Diag(Arg->getSourceRange().getBegin(),
1352 diag::err_template_arg_not_object_or_func_form)
1353 << Arg->getSourceRange();
1354
1355 // Cannot refer to non-static data members
1356 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1357 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1358 << Field << Arg->getSourceRange();
1359
1360 // Cannot refer to non-static member functions
1361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1362 if (!Method->isStatic())
1363 return Diag(Arg->getSourceRange().getBegin(),
1364 diag::err_template_arg_method)
1365 << Method << Arg->getSourceRange();
1366
1367 // Functions must have external linkage.
1368 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1369 if (Func->getStorageClass() == FunctionDecl::Static) {
1370 Diag(Arg->getSourceRange().getBegin(),
1371 diag::err_template_arg_function_not_extern)
1372 << Func << Arg->getSourceRange();
1373 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1374 << true;
1375 return true;
1376 }
1377
1378 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001379 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001380 return Invalid;
1381 }
1382
1383 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1384 if (!Var->hasGlobalStorage()) {
1385 Diag(Arg->getSourceRange().getBegin(),
1386 diag::err_template_arg_object_not_extern)
1387 << Var << Arg->getSourceRange();
1388 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1389 << true;
1390 return true;
1391 }
1392
1393 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001394 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001395 return Invalid;
1396 }
1397
1398 // We found something else, but we don't know specifically what it is.
1399 Diag(Arg->getSourceRange().getBegin(),
1400 diag::err_template_arg_not_object_or_func)
1401 << Arg->getSourceRange();
1402 Diag(DRE->getDecl()->getLocation(),
1403 diag::note_template_arg_refers_here);
1404 return true;
1405}
1406
1407/// \brief Checks whether the given template argument is a pointer to
1408/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001409bool
1410Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001411 bool Invalid = false;
1412
1413 // See through any implicit casts we added to fix the type.
1414 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1415 Arg = Cast->getSubExpr();
1416
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001417 // C++0x allows nullptr, and there's no further checking to be done for that.
1418 if (Arg->getType()->isNullPtrType())
1419 return false;
1420
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001421 // C++ [temp.arg.nontype]p1:
1422 //
1423 // A template-argument for a non-type, non-template
1424 // template-parameter shall be one of: [...]
1425 //
1426 // -- a pointer to member expressed as described in 5.3.1.
1427 QualifiedDeclRefExpr *DRE = 0;
1428
1429 // Ignore (and complain about) any excess parentheses.
1430 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1431 if (!Invalid) {
1432 Diag(Arg->getSourceRange().getBegin(),
1433 diag::err_template_arg_extra_parens)
1434 << Arg->getSourceRange();
1435 Invalid = true;
1436 }
1437
1438 Arg = Parens->getSubExpr();
1439 }
1440
1441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1442 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1443 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1444
1445 if (!DRE)
1446 return Diag(Arg->getSourceRange().getBegin(),
1447 diag::err_template_arg_not_pointer_to_member_form)
1448 << Arg->getSourceRange();
1449
1450 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1451 assert((isa<FieldDecl>(DRE->getDecl()) ||
1452 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1453 "Only non-static member pointers can make it here");
1454
1455 // Okay: this is the address of a non-static member, and therefore
1456 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001457 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001458 return Invalid;
1459 }
1460
1461 // We found something else, but we don't know specifically what it is.
1462 Diag(Arg->getSourceRange().getBegin(),
1463 diag::err_template_arg_not_pointer_to_member_form)
1464 << Arg->getSourceRange();
1465 Diag(DRE->getDecl()->getLocation(),
1466 diag::note_template_arg_refers_here);
1467 return true;
1468}
1469
Douglas Gregorc15cb382009-02-09 23:23:08 +00001470/// \brief Check a template argument against its corresponding
1471/// non-type template parameter.
1472///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001473/// This routine implements the semantics of C++ [temp.arg.nontype].
1474/// It returns true if an error occurred, and false otherwise. \p
1475/// InstantiatedParamType is the type of the non-type template
1476/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001477///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001478/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001479bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001481 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001482 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1483
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001484 // If either the parameter has a dependent type or the argument is
1485 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001486 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001487 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1488 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001489 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001490 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001491 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001492
1493 // C++ [temp.arg.nontype]p5:
1494 // The following conversions are performed on each expression used
1495 // as a non-type template-argument. If a non-type
1496 // template-argument cannot be converted to the type of the
1497 // corresponding template-parameter then the program is
1498 // ill-formed.
1499 //
1500 // -- for a non-type template-parameter of integral or
1501 // enumeration type, integral promotions (4.5) and integral
1502 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001503 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001504 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001505 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001506 // C++ [temp.arg.nontype]p1:
1507 // A template-argument for a non-type, non-template
1508 // template-parameter shall be one of:
1509 //
1510 // -- an integral constant-expression of integral or enumeration
1511 // type; or
1512 // -- the name of a non-type template-parameter; or
1513 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001514 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001515 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1516 Diag(Arg->getSourceRange().getBegin(),
1517 diag::err_template_arg_not_integral_or_enumeral)
1518 << ArgType << Arg->getSourceRange();
1519 Diag(Param->getLocation(), diag::note_template_param_here);
1520 return true;
1521 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001522 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001523 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1524 << ArgType << Arg->getSourceRange();
1525 return true;
1526 }
1527
1528 // FIXME: We need some way to more easily get the unqualified form
1529 // of the types without going all the way to the
1530 // canonical type.
1531 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1532 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1533 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1534 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1535
1536 // Try to convert the argument to the parameter's type.
1537 if (ParamType == ArgType) {
1538 // Okay: no conversion necessary
1539 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1540 !ParamType->isEnumeralType()) {
1541 // This is an integral promotion or conversion.
1542 ImpCastExprToType(Arg, ParamType);
1543 } else {
1544 // We can't perform this conversion.
1545 Diag(Arg->getSourceRange().getBegin(),
1546 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001547 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001548 Diag(Param->getLocation(), diag::note_template_param_here);
1549 return true;
1550 }
1551
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001552 QualType IntegerType = Context.getCanonicalType(ParamType);
1553 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001554 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001555
1556 if (!Arg->isValueDependent()) {
1557 // Check that an unsigned parameter does not receive a negative
1558 // value.
1559 if (IntegerType->isUnsignedIntegerType()
1560 && (Value.isSigned() && Value.isNegative())) {
1561 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1562 << Value.toString(10) << Param->getType()
1563 << Arg->getSourceRange();
1564 Diag(Param->getLocation(), diag::note_template_param_here);
1565 return true;
1566 }
1567
1568 // Check that we don't overflow the template parameter type.
1569 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1570 if (Value.getActiveBits() > AllowedBits) {
1571 Diag(Arg->getSourceRange().getBegin(),
1572 diag::err_template_arg_too_large)
1573 << Value.toString(10) << Param->getType()
1574 << Arg->getSourceRange();
1575 Diag(Param->getLocation(), diag::note_template_param_here);
1576 return true;
1577 }
1578
1579 if (Value.getBitWidth() != AllowedBits)
1580 Value.extOrTrunc(AllowedBits);
1581 Value.setIsSigned(IntegerType->isSignedIntegerType());
1582 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001583
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001584 // Add the value of this argument to the list of converted
1585 // arguments. We use the bitwidth and signedness of the template
1586 // parameter.
1587 if (Arg->isValueDependent()) {
1588 // The argument is value-dependent. Create a new
1589 // TemplateArgument with the converted expression.
1590 Converted = TemplateArgument(Arg);
1591 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001592 }
1593
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001594 Converted = TemplateArgument(StartLoc, Value,
1595 ParamType->isEnumeralType() ? ParamType
1596 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001597 return false;
1598 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001599
Douglas Gregorb86b0572009-02-11 01:18:59 +00001600 // Handle pointer-to-function, reference-to-function, and
1601 // pointer-to-member-function all in (roughly) the same way.
1602 if (// -- For a non-type template-parameter of type pointer to
1603 // function, only the function-to-pointer conversion (4.3) is
1604 // applied. If the template-argument represents a set of
1605 // overloaded functions (or a pointer to such), the matching
1606 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001607 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001608 (ParamType->isPointerType() &&
1609 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1610 // -- For a non-type template-parameter of type reference to
1611 // function, no conversions apply. If the template-argument
1612 // represents a set of overloaded functions, the matching
1613 // function is selected from the set (13.4).
1614 (ParamType->isReferenceType() &&
1615 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1616 // -- For a non-type template-parameter of type pointer to
1617 // member function, no conversions apply. If the
1618 // template-argument represents a set of overloaded member
1619 // functions, the matching member function is selected from
1620 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001621 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001622 (ParamType->isMemberPointerType() &&
1623 ParamType->getAsMemberPointerType()->getPointeeType()
1624 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001625 if (Context.hasSameUnqualifiedType(ArgType,
1626 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001627 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001628 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1629 ParamType->isMemberPointerType())) {
1630 ArgType = ParamType;
1631 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001632 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001633 ArgType = Context.getPointerType(ArgType);
1634 ImpCastExprToType(Arg, ArgType);
1635 } else if (FunctionDecl *Fn
1636 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001637 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1638 return true;
1639
Douglas Gregora35284b2009-02-11 00:19:33 +00001640 FixOverloadedFunctionReference(Arg, Fn);
1641 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001642 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001643 ArgType = Context.getPointerType(Arg->getType());
1644 ImpCastExprToType(Arg, ArgType);
1645 }
1646 }
1647
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001648 if (!Context.hasSameUnqualifiedType(ArgType,
1649 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001650 // We can't perform this conversion.
1651 Diag(Arg->getSourceRange().getBegin(),
1652 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001653 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001654 Diag(Param->getLocation(), diag::note_template_param_here);
1655 return true;
1656 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001657
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001658 if (ParamType->isMemberPointerType()) {
1659 NamedDecl *Member = 0;
1660 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1661 return true;
1662
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001663 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1664 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001665 return false;
1666 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001667
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001668 NamedDecl *Entity = 0;
1669 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1670 return true;
1671
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001672 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1673 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001674 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001675 }
1676
Chris Lattnerfe90de72009-02-20 21:37:53 +00001677 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001678 // -- for a non-type template-parameter of type pointer to
1679 // object, qualification conversions (4.4) and the
1680 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001681 // C++0x also allows a value of std::nullptr_t.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001682 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001683 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001684
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001685 if (ArgType->isNullPtrType()) {
1686 ArgType = ParamType;
1687 ImpCastExprToType(Arg, ParamType);
1688 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001689 ArgType = Context.getArrayDecayedType(ArgType);
1690 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001691 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001692
Douglas Gregorb86b0572009-02-11 01:18:59 +00001693 if (IsQualificationConversion(ArgType, ParamType)) {
1694 ArgType = ParamType;
1695 ImpCastExprToType(Arg, ParamType);
1696 }
1697
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001698 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001699 // We can't perform this conversion.
1700 Diag(Arg->getSourceRange().getBegin(),
1701 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001702 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001703 Diag(Param->getLocation(), diag::note_template_param_here);
1704 return true;
1705 }
1706
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001707 NamedDecl *Entity = 0;
1708 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1709 return true;
1710
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001711 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1712 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001713 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001714 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001715
1716 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1717 // -- For a non-type template-parameter of type reference to
1718 // object, no conversions apply. The type referred to by the
1719 // reference may be more cv-qualified than the (otherwise
1720 // identical) type of the template-argument. The
1721 // template-parameter is bound directly to the
1722 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001723 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001724 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001725
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001726 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001727 Diag(Arg->getSourceRange().getBegin(),
1728 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001729 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001730 << Arg->getSourceRange();
1731 Diag(Param->getLocation(), diag::note_template_param_here);
1732 return true;
1733 }
1734
1735 unsigned ParamQuals
1736 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1737 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1738
1739 if ((ParamQuals | ArgQuals) != ParamQuals) {
1740 Diag(Arg->getSourceRange().getBegin(),
1741 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001742 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001743 << Arg->getSourceRange();
1744 Diag(Param->getLocation(), diag::note_template_param_here);
1745 return true;
1746 }
1747
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001748 NamedDecl *Entity = 0;
1749 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1750 return true;
1751
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001752 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1753 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001754 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001755 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001756
1757 // -- For a non-type template-parameter of type pointer to data
1758 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001759 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001760 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1761
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001762 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001763 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001764 } else if (ArgType->isNullPtrType()) {
1765 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001766 } else if (IsQualificationConversion(ArgType, ParamType)) {
1767 ImpCastExprToType(Arg, ParamType);
1768 } else {
1769 // We can't perform this conversion.
1770 Diag(Arg->getSourceRange().getBegin(),
1771 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001772 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001773 Diag(Param->getLocation(), diag::note_template_param_here);
1774 return true;
1775 }
1776
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001777 NamedDecl *Member = 0;
1778 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1779 return true;
1780
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001781 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1782 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001783 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001784}
1785
1786/// \brief Check a template argument against its corresponding
1787/// template template parameter.
1788///
1789/// This routine implements the semantics of C++ [temp.arg.template].
1790/// It returns true if an error occurred, and false otherwise.
1791bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1792 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001793 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1794 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1795
1796 // C++ [temp.arg.template]p1:
1797 // A template-argument for a template template-parameter shall be
1798 // the name of a class template, expressed as id-expression. Only
1799 // primary class templates are considered when matching the
1800 // template template argument with the corresponding parameter;
1801 // partial specializations are not considered even if their
1802 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001803 //
1804 // Note that we also allow template template parameters here, which
1805 // will happen when we are dealing with, e.g., class template
1806 // partial specializations.
1807 if (!isa<ClassTemplateDecl>(Template) &&
1808 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001809 assert(isa<FunctionTemplateDecl>(Template) &&
1810 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001811 Diag(Arg->getSourceRange().getBegin(),
1812 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001813 << Template;
1814 }
1815
1816 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1817 Param->getTemplateParameters(),
1818 true, true,
1819 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001820}
1821
Douglas Gregorddc29e12009-02-06 22:42:48 +00001822/// \brief Determine whether the given template parameter lists are
1823/// equivalent.
1824///
1825/// \param New The new template parameter list, typically written in the
1826/// source code as part of a new template declaration.
1827///
1828/// \param Old The old template parameter list, typically found via
1829/// name lookup of the template declared with this template parameter
1830/// list.
1831///
1832/// \param Complain If true, this routine will produce a diagnostic if
1833/// the template parameter lists are not equivalent.
1834///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001835/// \param IsTemplateTemplateParm If true, this routine is being
1836/// called to compare the template parameter lists of a template
1837/// template parameter.
1838///
1839/// \param TemplateArgLoc If this source location is valid, then we
1840/// are actually checking the template parameter list of a template
1841/// argument (New) against the template parameter list of its
1842/// corresponding template template parameter (Old). We produce
1843/// slightly different diagnostics in this scenario.
1844///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001845/// \returns True if the template parameter lists are equal, false
1846/// otherwise.
1847bool
1848Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1849 TemplateParameterList *Old,
1850 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001851 bool IsTemplateTemplateParm,
1852 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001853 if (Old->size() != New->size()) {
1854 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001855 unsigned NextDiag = diag::err_template_param_list_different_arity;
1856 if (TemplateArgLoc.isValid()) {
1857 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1858 NextDiag = diag::note_template_param_list_different_arity;
1859 }
1860 Diag(New->getTemplateLoc(), NextDiag)
1861 << (New->size() > Old->size())
1862 << IsTemplateTemplateParm
1863 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001864 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1865 << IsTemplateTemplateParm
1866 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1867 }
1868
1869 return false;
1870 }
1871
1872 for (TemplateParameterList::iterator OldParm = Old->begin(),
1873 OldParmEnd = Old->end(), NewParm = New->begin();
1874 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1875 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001876 unsigned NextDiag = diag::err_template_param_different_kind;
1877 if (TemplateArgLoc.isValid()) {
1878 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1879 NextDiag = diag::note_template_param_different_kind;
1880 }
1881 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001882 << IsTemplateTemplateParm;
1883 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1884 << IsTemplateTemplateParm;
1885 return false;
1886 }
1887
1888 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1889 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001890 // know we're at the same index).
1891#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001892 // FIXME: Enable this code in debug mode *after* we properly go through
1893 // and "instantiate" the template parameter lists of template template
1894 // parameters. It's only after this instantiation that (1) any dependent
1895 // types within the template parameter list of the template template
1896 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001897 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001898 QualType OldParmType
1899 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1900 QualType NewParmType
1901 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1902 assert(Context.getCanonicalType(OldParmType) ==
1903 Context.getCanonicalType(NewParmType) &&
1904 "type parameter mismatch?");
1905#endif
1906 } else if (NonTypeTemplateParmDecl *OldNTTP
1907 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1908 // The types of non-type template parameters must agree.
1909 NonTypeTemplateParmDecl *NewNTTP
1910 = cast<NonTypeTemplateParmDecl>(*NewParm);
1911 if (Context.getCanonicalType(OldNTTP->getType()) !=
1912 Context.getCanonicalType(NewNTTP->getType())) {
1913 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001914 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1915 if (TemplateArgLoc.isValid()) {
1916 Diag(TemplateArgLoc,
1917 diag::err_template_arg_template_params_mismatch);
1918 NextDiag = diag::note_template_nontype_parm_different_type;
1919 }
1920 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001921 << NewNTTP->getType()
1922 << IsTemplateTemplateParm;
1923 Diag(OldNTTP->getLocation(),
1924 diag::note_template_nontype_parm_prev_declaration)
1925 << OldNTTP->getType();
1926 }
1927 return false;
1928 }
1929 } else {
1930 // The template parameter lists of template template
1931 // parameters must agree.
1932 // FIXME: Could we perform a faster "type" comparison here?
1933 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1934 "Only template template parameters handled here");
1935 TemplateTemplateParmDecl *OldTTP
1936 = cast<TemplateTemplateParmDecl>(*OldParm);
1937 TemplateTemplateParmDecl *NewTTP
1938 = cast<TemplateTemplateParmDecl>(*NewParm);
1939 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1940 OldTTP->getTemplateParameters(),
1941 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001942 /*IsTemplateTemplateParm=*/true,
1943 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001944 return false;
1945 }
1946 }
1947
1948 return true;
1949}
1950
1951/// \brief Check whether a template can be declared within this scope.
1952///
1953/// If the template declaration is valid in this scope, returns
1954/// false. Otherwise, issues a diagnostic and returns true.
1955bool
1956Sema::CheckTemplateDeclScope(Scope *S,
1957 MultiTemplateParamsArg &TemplateParameterLists) {
1958 assert(TemplateParameterLists.size() > 0 && "Not a template");
1959
1960 // Find the nearest enclosing declaration scope.
1961 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1962 (S->getFlags() & Scope::TemplateParamScope) != 0)
1963 S = S->getParent();
1964
1965 TemplateParameterList *TemplateParams =
1966 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1967 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1968 SourceRange TemplateRange
1969 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1970
1971 // C++ [temp]p2:
1972 // A template-declaration can appear only as a namespace scope or
1973 // class scope declaration.
1974 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1975 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1976 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1977 return Diag(TemplateLoc, diag::err_template_linkage)
1978 << TemplateRange;
1979
1980 Ctx = Ctx->getParent();
1981 }
1982
1983 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1984 return false;
1985
1986 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1987 << TemplateRange;
1988}
Douglas Gregorcc636682009-02-17 23:15:12 +00001989
Douglas Gregorff668032009-05-13 18:28:20 +00001990/// \brief Check whether a class template specialization or explicit
1991/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00001992///
Douglas Gregorff668032009-05-13 18:28:20 +00001993/// This routine determines whether a class template specialization or
1994/// explicit instantiation can be declared in the current context
1995/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1996/// appropriate diagnostics if there was an error. It returns true if
1997// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00001998bool
1999Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2000 ClassTemplateSpecializationDecl *PrevDecl,
2001 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002002 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002003 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002004 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002005 // C++ [temp.expl.spec]p2:
2006 // An explicit specialization shall be declared in the namespace
2007 // of which the template is a member, or, for member templates, in
2008 // the namespace of which the enclosing class or enclosing class
2009 // template is a member. An explicit specialization of a member
2010 // function, member class or static data member of a class
2011 // template shall be declared in the namespace of which the class
2012 // template is a member. Such a declaration may also be a
2013 // definition. If the declaration is not a definition, the
2014 // specialization may be defined later in the name- space in which
2015 // the explicit specialization was declared, or in a namespace
2016 // that encloses the one in which the explicit specialization was
2017 // declared.
2018 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002019 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002020 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002021 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002022 return true;
2023 }
2024
2025 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2026 DeclContext *TemplateContext
2027 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002028 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2029 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002030 // There is no prior declaration of this entity, so this
2031 // specialization must be in the same context as the template
2032 // itself.
2033 if (DC != TemplateContext) {
2034 if (isa<TranslationUnitDecl>(TemplateContext))
2035 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002036 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002037 << ClassTemplate << ScopeSpecifierRange;
2038 else if (isa<NamespaceDecl>(TemplateContext))
2039 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002040 << PartialSpecialization << ClassTemplate
2041 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002042
2043 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2044 }
2045
2046 return false;
2047 }
2048
2049 // We have a previous declaration of this entity. Make sure that
2050 // this redeclaration (or definition) occurs in an enclosing namespace.
2051 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002052 // FIXME: In C++98, we would like to turn these errors into warnings,
2053 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002054 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002055 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002056 if (isa<TranslationUnitDecl>(TemplateContext)) {
2057 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2058 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002059 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002060 else
2061 SuppressedDiag = true;
2062 } else if (isa<NamespaceDecl>(TemplateContext)) {
2063 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2064 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002065 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002066 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2067 else
2068 SuppressedDiag = true;
2069 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002070
Douglas Gregorff668032009-05-13 18:28:20 +00002071 if (!SuppressedDiag)
2072 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002073 }
2074
2075 return false;
2076}
2077
Douglas Gregore94866f2009-06-12 21:21:02 +00002078/// \brief Check the non-type template arguments of a class template
2079/// partial specialization according to C++ [temp.class.spec]p9.
2080///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002081/// \param TemplateParams the template parameters of the primary class
2082/// template.
2083///
2084/// \param TemplateArg the template arguments of the class template
2085/// partial specialization.
2086///
2087/// \param MirrorsPrimaryTemplate will be set true if the class
2088/// template partial specialization arguments are identical to the
2089/// implicit template arguments of the primary template. This is not
2090/// necessarily an error (C++0x), and it is left to the caller to diagnose
2091/// this condition when it is an error.
2092///
Douglas Gregore94866f2009-06-12 21:21:02 +00002093/// \returns true if there was an error, false otherwise.
2094bool Sema::CheckClassTemplatePartialSpecializationArgs(
2095 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002096 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002097 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002098 // FIXME: the interface to this function will have to change to
2099 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002100 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002101
2102 const TemplateArgument *ArgList = TemplateArgs.getFlatArgumentList();
2103
Douglas Gregore94866f2009-06-12 21:21:02 +00002104 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002105 // Determine whether the template argument list of the partial
2106 // specialization is identical to the implicit argument list of
2107 // the primary template. The caller may need to diagnostic this as
2108 // an error per C++ [temp.class.spec]p9b3.
2109 if (MirrorsPrimaryTemplate) {
2110 if (TemplateTypeParmDecl *TTP
2111 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2112 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002113 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002114 MirrorsPrimaryTemplate = false;
2115 } else if (TemplateTemplateParmDecl *TTP
2116 = dyn_cast<TemplateTemplateParmDecl>(
2117 TemplateParams->getParam(I))) {
2118 // FIXME: We should settle on either Declaration storage or
2119 // Expression storage for template template parameters.
2120 TemplateTemplateParmDecl *ArgDecl
2121 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002122 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002123 if (!ArgDecl)
2124 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002125 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002126 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2127
2128 if (!ArgDecl ||
2129 ArgDecl->getIndex() != TTP->getIndex() ||
2130 ArgDecl->getDepth() != TTP->getDepth())
2131 MirrorsPrimaryTemplate = false;
2132 }
2133 }
2134
Douglas Gregore94866f2009-06-12 21:21:02 +00002135 NonTypeTemplateParmDecl *Param
2136 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002137 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002138 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002139 }
2140
Anders Carlsson6360be72009-06-13 18:20:51 +00002141 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002142 if (!ArgExpr) {
2143 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002144 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002145 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002146
2147 // C++ [temp.class.spec]p8:
2148 // A non-type argument is non-specialized if it is the name of a
2149 // non-type parameter. All other non-type arguments are
2150 // specialized.
2151 //
2152 // Below, we check the two conditions that only apply to
2153 // specialized non-type arguments, so skip any non-specialized
2154 // arguments.
2155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002156 if (NonTypeTemplateParmDecl *NTTP
2157 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2158 if (MirrorsPrimaryTemplate &&
2159 (Param->getIndex() != NTTP->getIndex() ||
2160 Param->getDepth() != NTTP->getDepth()))
2161 MirrorsPrimaryTemplate = false;
2162
Douglas Gregore94866f2009-06-12 21:21:02 +00002163 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002164 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002165
2166 // C++ [temp.class.spec]p9:
2167 // Within the argument list of a class template partial
2168 // specialization, the following restrictions apply:
2169 // -- A partially specialized non-type argument expression
2170 // shall not involve a template parameter of the partial
2171 // specialization except when the argument expression is a
2172 // simple identifier.
2173 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2174 Diag(ArgExpr->getLocStart(),
2175 diag::err_dependent_non_type_arg_in_partial_spec)
2176 << ArgExpr->getSourceRange();
2177 return true;
2178 }
2179
2180 // -- The type of a template parameter corresponding to a
2181 // specialized non-type argument shall not be dependent on a
2182 // parameter of the specialization.
2183 if (Param->getType()->isDependentType()) {
2184 Diag(ArgExpr->getLocStart(),
2185 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2186 << Param->getType()
2187 << ArgExpr->getSourceRange();
2188 Diag(Param->getLocation(), diag::note_template_param_here);
2189 return true;
2190 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002191
2192 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002193 }
2194
2195 return false;
2196}
2197
Douglas Gregor212e81c2009-03-25 00:13:59 +00002198Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002199Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2200 SourceLocation KWLoc,
2201 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002202 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002203 SourceLocation TemplateNameLoc,
2204 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002205 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002206 SourceLocation *TemplateArgLocs,
2207 SourceLocation RAngleLoc,
2208 AttributeList *Attr,
2209 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002210 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002211 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002212 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002213 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002214
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002215 bool isPartialSpecialization = false;
2216
Douglas Gregor88b70942009-02-25 22:02:03 +00002217 // Check the validity of the template headers that introduce this
2218 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002219 // FIXME: Once we have member templates, we'll need to check
2220 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2221 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002222 if (TemplateParameterLists.size() == 0)
2223 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002224 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002225 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002226 TemplateParameterList *TemplateParams
2227 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002228 if (TemplateParameterLists.size() > 1) {
2229 Diag(TemplateParams->getTemplateLoc(),
2230 diag::err_template_spec_extra_headers);
2231 return true;
2232 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002233
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002234 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002235 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002236
2237 // C++ [temp.class.spec]p10:
2238 // The template parameter list of a specialization shall not
2239 // contain default template argument values.
2240 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2241 Decl *Param = TemplateParams->getParam(I);
2242 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2243 if (TTP->hasDefaultArgument()) {
2244 Diag(TTP->getDefaultArgumentLoc(),
2245 diag::err_default_arg_in_partial_spec);
2246 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2247 }
2248 } else if (NonTypeTemplateParmDecl *NTTP
2249 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2250 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2251 Diag(NTTP->getDefaultArgumentLoc(),
2252 diag::err_default_arg_in_partial_spec)
2253 << DefArg->getSourceRange();
2254 NTTP->setDefaultArgument(0);
2255 DefArg->Destroy(Context);
2256 }
2257 } else {
2258 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2259 if (Expr *DefArg = TTP->getDefaultArgument()) {
2260 Diag(TTP->getDefaultArgumentLoc(),
2261 diag::err_default_arg_in_partial_spec)
2262 << DefArg->getSourceRange();
2263 TTP->setDefaultArgument(0);
2264 DefArg->Destroy(Context);
2265 }
2266 }
2267 }
2268 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002269 }
2270
Douglas Gregorcc636682009-02-17 23:15:12 +00002271 // Check that the specialization uses the same tag kind as the
2272 // original template.
2273 TagDecl::TagKind Kind;
2274 switch (TagSpec) {
2275 default: assert(0 && "Unknown tag type!");
2276 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2277 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2278 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2279 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002280 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2281 Kind, KWLoc,
2282 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002283 Diag(KWLoc, diag::err_use_with_wrong_tag)
2284 << ClassTemplate
2285 << CodeModificationHint::CreateReplacement(KWLoc,
2286 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002287 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2288 diag::note_previous_use);
2289 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2290 }
2291
Douglas Gregor40808ce2009-03-09 23:48:35 +00002292 // Translate the parser's template argument list in our AST format.
2293 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2294 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2295
Douglas Gregorcc636682009-02-17 23:15:12 +00002296 // Check that the template argument list is well-formed for this
2297 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +00002298 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002299 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002300 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor40808ce2009-03-09 23:48:35 +00002301 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002302 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002303
2304 assert((ConvertedTemplateArgs.size() ==
2305 ClassTemplate->getTemplateParameters()->size()) &&
2306 "Converted template argument list is too short!");
2307
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002308 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002309 // corresponds to these arguments.
2310 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002311 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002312 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002313 if (CheckClassTemplatePartialSpecializationArgs(
2314 ClassTemplate->getTemplateParameters(),
Anders Carlsson6360be72009-06-13 18:20:51 +00002315 ConvertedTemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002316 MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002317 return true;
2318
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002319 if (MirrorsPrimaryTemplate) {
2320 // C++ [temp.class.spec]p9b3:
2321 //
2322 // -- The argument list of the specialization shall not be identical
2323 // to the implicit argument list of the primary template.
2324 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2325 << (TK == TK_Definition)
2326 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2327 RAngleLoc));
2328 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2329 ClassTemplate->getIdentifier(),
2330 TemplateNameLoc,
2331 Attr,
2332 move(TemplateParameterLists),
2333 AS_none);
2334 }
2335
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002336 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002337 ClassTemplatePartialSpecializationDecl::Profile(ID,
2338 ConvertedTemplateArgs.getFlatArgumentList(),
2339 ConvertedTemplateArgs.flatSize());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002340 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002341 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002342 ClassTemplateSpecializationDecl::Profile(ID,
2343 ConvertedTemplateArgs.getFlatArgumentList(),
2344 ConvertedTemplateArgs.flatSize());
Douglas Gregorcc636682009-02-17 23:15:12 +00002345 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002346 ClassTemplateSpecializationDecl *PrevDecl = 0;
2347
2348 if (isPartialSpecialization)
2349 PrevDecl
2350 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2351 InsertPos);
2352 else
2353 PrevDecl
2354 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002355
2356 ClassTemplateSpecializationDecl *Specialization = 0;
2357
Douglas Gregor88b70942009-02-25 22:02:03 +00002358 // Check whether we can declare a class template specialization in
2359 // the current scope.
2360 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2361 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002362 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002363 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002364 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002365 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002366
Douglas Gregorcc636682009-02-17 23:15:12 +00002367 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2368 // Since the only prior class template specialization with these
2369 // arguments was referenced but not declared, reuse that
2370 // declaration node as our own, updating its source location to
2371 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002372 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002373 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002374 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002375 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002376 // Create a new class template partial specialization declaration node.
2377 TemplateParameterList *TemplateParams
2378 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2379 ClassTemplatePartialSpecializationDecl *PrevPartial
2380 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2381 ClassTemplatePartialSpecializationDecl *Partial
2382 = ClassTemplatePartialSpecializationDecl::Create(Context,
2383 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002384 TemplateNameLoc,
2385 TemplateParams,
2386 ClassTemplate,
2387 ConvertedTemplateArgs,
2388 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002389
2390 if (PrevPartial) {
2391 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2392 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2393 } else {
2394 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2395 }
2396 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002397
2398 // Check that all of the template parameters of the class template
2399 // partial specialization are deducible from the template
2400 // arguments. If not, this class template partial specialization
2401 // will never be used.
2402 llvm::SmallVector<bool, 8> DeducibleParams;
2403 DeducibleParams.resize(TemplateParams->size());
2404 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2405 unsigned NumNonDeducible = 0;
2406 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2407 if (!DeducibleParams[I])
2408 ++NumNonDeducible;
2409
2410 if (NumNonDeducible) {
2411 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2412 << (NumNonDeducible > 1)
2413 << SourceRange(TemplateNameLoc, RAngleLoc);
2414 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2415 if (!DeducibleParams[I]) {
2416 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2417 if (Param->getDeclName())
2418 Diag(Param->getLocation(),
2419 diag::note_partial_spec_unused_parameter)
2420 << Param->getDeclName();
2421 else
2422 Diag(Param->getLocation(),
2423 diag::note_partial_spec_unused_parameter)
2424 << std::string("<anonymous>");
2425 }
2426 }
2427 }
2428
Douglas Gregorcc636682009-02-17 23:15:12 +00002429 } else {
2430 // Create a new class template specialization declaration node for
2431 // this explicit specialization.
2432 Specialization
2433 = ClassTemplateSpecializationDecl::Create(Context,
2434 ClassTemplate->getDeclContext(),
2435 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002436 ClassTemplate,
2437 ConvertedTemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +00002438 PrevDecl);
2439
2440 if (PrevDecl) {
2441 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2442 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2443 } else {
2444 ClassTemplate->getSpecializations().InsertNode(Specialization,
2445 InsertPos);
2446 }
2447 }
2448
2449 // Note that this is an explicit specialization.
2450 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2451
2452 // Check that this isn't a redefinition of this specialization.
2453 if (TK == TK_Definition) {
2454 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002455 // FIXME: Should also handle explicit specialization after implicit
2456 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002457 SourceRange Range(TemplateNameLoc, RAngleLoc);
2458 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002459 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002460 Diag(Def->getLocation(), diag::note_previous_definition);
2461 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002462 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002463 }
2464 }
2465
Douglas Gregorfc705b82009-02-26 22:19:44 +00002466 // Build the fully-sugared type for this class template
2467 // specialization as the user wrote in the specialization
2468 // itself. This means that we'll pretty-print the type retrieved
2469 // from the specialization's declaration the way that the user
2470 // actually wrote the specialization, rather than formatting the
2471 // name based on the "canonical" representation used to store the
2472 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002473 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002474 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002475 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002476 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002477 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002478 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002479 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002480
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002481 // C++ [temp.expl.spec]p9:
2482 // A template explicit specialization is in the scope of the
2483 // namespace in which the template was defined.
2484 //
2485 // We actually implement this paragraph where we set the semantic
2486 // context (in the creation of the ClassTemplateSpecializationDecl),
2487 // but we also maintain the lexical context where the actual
2488 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002489 Specialization->setLexicalDeclContext(CurContext);
2490
2491 // We may be starting the definition of this specialization.
2492 if (TK == TK_Definition)
2493 Specialization->startDefinition();
2494
2495 // Add the specialization into its lexical context, so that it can
2496 // be seen when iterating through the list of declarations in that
2497 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002498 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002499 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002500}
Douglas Gregord57959a2009-03-27 23:10:48 +00002501
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002502// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002503Sema::DeclResult
2504Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2505 unsigned TagSpec,
2506 SourceLocation KWLoc,
2507 const CXXScopeSpec &SS,
2508 TemplateTy TemplateD,
2509 SourceLocation TemplateNameLoc,
2510 SourceLocation LAngleLoc,
2511 ASTTemplateArgsPtr TemplateArgsIn,
2512 SourceLocation *TemplateArgLocs,
2513 SourceLocation RAngleLoc,
2514 AttributeList *Attr) {
2515 // Find the class template we're specializing
2516 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2517 ClassTemplateDecl *ClassTemplate
2518 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2519
2520 // Check that the specialization uses the same tag kind as the
2521 // original template.
2522 TagDecl::TagKind Kind;
2523 switch (TagSpec) {
2524 default: assert(0 && "Unknown tag type!");
2525 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2526 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2527 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2528 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002529 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2530 Kind, KWLoc,
2531 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002532 Diag(KWLoc, diag::err_use_with_wrong_tag)
2533 << ClassTemplate
2534 << CodeModificationHint::CreateReplacement(KWLoc,
2535 ClassTemplate->getTemplatedDecl()->getKindName());
2536 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2537 diag::note_previous_use);
2538 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2539 }
2540
Douglas Gregorff668032009-05-13 18:28:20 +00002541 // C++0x [temp.explicit]p2:
2542 // [...] An explicit instantiation shall appear in an enclosing
2543 // namespace of its template. [...]
2544 //
2545 // This is C++ DR 275.
2546 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2547 TemplateNameLoc,
2548 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002549 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002550 /*ExplicitInstantiation=*/true))
2551 return true;
2552
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002553 // Translate the parser's template argument list in our AST format.
2554 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2555 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2556
2557 // Check that the template argument list is well-formed for this
2558 // template.
Anders Carlsson9ba41642009-06-05 05:31:27 +00002559 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002560 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002561 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002562 RAngleLoc, ConvertedTemplateArgs))
2563 return true;
2564
2565 assert((ConvertedTemplateArgs.size() ==
2566 ClassTemplate->getTemplateParameters()->size()) &&
2567 "Converted template argument list is too short!");
2568
2569 // Find the class template specialization declaration that
2570 // corresponds to these arguments.
2571 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002572 ClassTemplateSpecializationDecl::Profile(ID,
2573 ConvertedTemplateArgs.getFlatArgumentList(),
2574 ConvertedTemplateArgs.flatSize());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002575 void *InsertPos = 0;
2576 ClassTemplateSpecializationDecl *PrevDecl
2577 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2578
2579 ClassTemplateSpecializationDecl *Specialization = 0;
2580
Douglas Gregorff668032009-05-13 18:28:20 +00002581 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002582 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002583 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002584 // This particular specialization has already been declared or
2585 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002586 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2587 << Context.getTypeDeclType(PrevDecl);
2588 Diag(PrevDecl->getLocation(),
2589 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002590 return DeclPtrTy::make(PrevDecl);
2591 }
2592
Douglas Gregorff668032009-05-13 18:28:20 +00002593 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002594 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002595 // For a given set of template parameters, if an explicit
2596 // instantiation of a template appears after a declaration of
2597 // an explicit specialization for that template, the explicit
2598 // instantiation has no effect.
2599 if (!getLangOptions().CPlusPlus0x) {
2600 Diag(TemplateNameLoc,
2601 diag::ext_explicit_instantiation_after_specialization)
2602 << Context.getTypeDeclType(PrevDecl);
2603 Diag(PrevDecl->getLocation(),
2604 diag::note_previous_template_specialization);
2605 }
2606
2607 // Create a new class template specialization declaration node
2608 // for this explicit specialization. This node is only used to
2609 // record the existence of this explicit instantiation for
2610 // accurate reproduction of the source code; we don't actually
2611 // use it for anything, since it is semantically irrelevant.
2612 Specialization
2613 = ClassTemplateSpecializationDecl::Create(Context,
2614 ClassTemplate->getDeclContext(),
2615 TemplateNameLoc,
2616 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002617 ConvertedTemplateArgs, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002618 Specialization->setLexicalDeclContext(CurContext);
2619 CurContext->addDecl(Context, Specialization);
2620 return DeclPtrTy::make(Specialization);
2621 }
2622
2623 // If we have already (implicitly) instantiated this
2624 // specialization, there is less work to do.
2625 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2626 SpecializationRequiresInstantiation = false;
2627
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002628 // Since the only prior class template specialization with these
2629 // arguments was referenced but not declared, reuse that
2630 // declaration node as our own, updating its source location to
2631 // reflect our new declaration.
2632 Specialization = PrevDecl;
2633 Specialization->setLocation(TemplateNameLoc);
2634 PrevDecl = 0;
2635 } else {
2636 // Create a new class template specialization declaration node for
2637 // this explicit specialization.
2638 Specialization
2639 = ClassTemplateSpecializationDecl::Create(Context,
2640 ClassTemplate->getDeclContext(),
2641 TemplateNameLoc,
2642 ClassTemplate,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002643 ConvertedTemplateArgs, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002644
2645 ClassTemplate->getSpecializations().InsertNode(Specialization,
2646 InsertPos);
2647 }
2648
2649 // Build the fully-sugared type for this explicit instantiation as
2650 // the user wrote in the explicit instantiation itself. This means
2651 // that we'll pretty-print the type retrieved from the
2652 // specialization's declaration the way that the user actually wrote
2653 // the explicit instantiation, rather than formatting the name based
2654 // on the "canonical" representation used to store the template
2655 // arguments in the specialization.
2656 QualType WrittenTy
2657 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002658 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002659 TemplateArgs.size(),
2660 Context.getTypeDeclType(Specialization));
2661 Specialization->setTypeAsWritten(WrittenTy);
2662 TemplateArgsIn.release();
2663
2664 // Add the explicit instantiation into its lexical context. However,
2665 // since explicit instantiations are never found by name lookup, we
2666 // just put it into the declaration context directly.
2667 Specialization->setLexicalDeclContext(CurContext);
2668 CurContext->addDecl(Context, Specialization);
2669
2670 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002671 // A definition of a class template or class member template
2672 // shall be in scope at the point of the explicit instantiation of
2673 // the class template or class member template.
2674 //
2675 // This check comes when we actually try to perform the
2676 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002677 if (SpecializationRequiresInstantiation)
2678 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002679 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002680 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002681
2682 return DeclPtrTy::make(Specialization);
2683}
2684
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002685// Explicit instantiation of a member class of a class template.
2686Sema::DeclResult
2687Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2688 unsigned TagSpec,
2689 SourceLocation KWLoc,
2690 const CXXScopeSpec &SS,
2691 IdentifierInfo *Name,
2692 SourceLocation NameLoc,
2693 AttributeList *Attr) {
2694
Douglas Gregor402abb52009-05-28 23:31:59 +00002695 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002696 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor402abb52009-05-28 23:31:59 +00002697 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002698 if (!TagD)
2699 return true;
2700
2701 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2702 if (Tag->isEnum()) {
2703 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2704 << Context.getTypeDeclType(Tag);
2705 return true;
2706 }
2707
Douglas Gregord0c87372009-05-27 17:30:49 +00002708 if (Tag->isInvalidDecl())
2709 return true;
2710
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002711 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2712 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2713 if (!Pattern) {
2714 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2715 << Context.getTypeDeclType(Record);
2716 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2717 return true;
2718 }
2719
2720 // C++0x [temp.explicit]p2:
2721 // [...] An explicit instantiation shall appear in an enclosing
2722 // namespace of its template. [...]
2723 //
2724 // This is C++ DR 275.
2725 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002726 // FIXME: In C++98, we would like to turn these errors into warnings,
2727 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002728 DeclContext *PatternContext
2729 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2730 if (!CurContext->Encloses(PatternContext)) {
2731 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2732 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2733 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2734 }
2735 }
2736
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002737 if (!Record->getDefinition(Context)) {
2738 // If the class has a definition, instantiate it (and all of its
2739 // members, recursively).
2740 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2741 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002742 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002743 /*ExplicitInstantiation=*/true))
2744 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002745 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002746 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002747 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002748
Mike Stump390b4cc2009-05-16 07:39:55 +00002749 // FIXME: We don't have any representation for explicit instantiations of
2750 // member classes. Such a representation is not needed for compilation, but it
2751 // should be available for clients that want to see all of the declarations in
2752 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002753 return TagD;
2754}
2755
Douglas Gregord57959a2009-03-27 23:10:48 +00002756Sema::TypeResult
2757Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2758 const IdentifierInfo &II, SourceLocation IdLoc) {
2759 NestedNameSpecifier *NNS
2760 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2761 if (!NNS)
2762 return true;
2763
2764 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002765 if (T.isNull())
2766 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002767 return T.getAsOpaquePtr();
2768}
2769
Douglas Gregor17343172009-04-01 00:28:59 +00002770Sema::TypeResult
2771Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2772 SourceLocation TemplateLoc, TypeTy *Ty) {
2773 QualType T = QualType::getFromOpaquePtr(Ty);
2774 NestedNameSpecifier *NNS
2775 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2776 const TemplateSpecializationType *TemplateId
2777 = T->getAsTemplateSpecializationType();
2778 assert(TemplateId && "Expected a template specialization type");
2779
2780 if (NNS->isDependent())
2781 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2782
2783 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2784}
2785
Douglas Gregord57959a2009-03-27 23:10:48 +00002786/// \brief Build the type that describes a C++ typename specifier,
2787/// e.g., "typename T::type".
2788QualType
2789Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2790 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002791 CXXRecordDecl *CurrentInstantiation = 0;
2792 if (NNS->isDependent()) {
2793 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002794
Douglas Gregor42af25f2009-05-11 19:58:34 +00002795 // If the nested-name-specifier does not refer to the current
2796 // instantiation, then build a typename type.
2797 if (!CurrentInstantiation)
2798 return Context.getTypenameType(NNS, &II);
2799 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002800
Douglas Gregor42af25f2009-05-11 19:58:34 +00002801 DeclContext *Ctx = 0;
2802
2803 if (CurrentInstantiation)
2804 Ctx = CurrentInstantiation;
2805 else {
2806 CXXScopeSpec SS;
2807 SS.setScopeRep(NNS);
2808 SS.setRange(Range);
2809 if (RequireCompleteDeclContext(SS))
2810 return QualType();
2811
2812 Ctx = computeDeclContext(SS);
2813 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002814 assert(Ctx && "No declaration context?");
2815
2816 DeclarationName Name(&II);
2817 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2818 false);
2819 unsigned DiagID = 0;
2820 Decl *Referenced = 0;
2821 switch (Result.getKind()) {
2822 case LookupResult::NotFound:
2823 if (Ctx->isTranslationUnit())
2824 DiagID = diag::err_typename_nested_not_found_global;
2825 else
2826 DiagID = diag::err_typename_nested_not_found;
2827 break;
2828
2829 case LookupResult::Found:
2830 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2831 // We found a type. Build a QualifiedNameType, since the
2832 // typename-specifier was just sugar. FIXME: Tell
2833 // QualifiedNameType that it has a "typename" prefix.
2834 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2835 }
2836
2837 DiagID = diag::err_typename_nested_not_type;
2838 Referenced = Result.getAsDecl();
2839 break;
2840
2841 case LookupResult::FoundOverloaded:
2842 DiagID = diag::err_typename_nested_not_type;
2843 Referenced = *Result.begin();
2844 break;
2845
2846 case LookupResult::AmbiguousBaseSubobjectTypes:
2847 case LookupResult::AmbiguousBaseSubobjects:
2848 case LookupResult::AmbiguousReference:
2849 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2850 return QualType();
2851 }
2852
2853 // If we get here, it's because name lookup did not find a
2854 // type. Emit an appropriate diagnostic and return an error.
2855 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2856 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2857 else
2858 Diag(Range.getEnd(), DiagID) << Range << Name;
2859 if (Referenced)
2860 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2861 << Name;
2862 return QualType();
2863}