blob: 4dad3730bbf1bad8e92ea8e6784ae6bb589b3ad3 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregordd861062008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor3f220e82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregord406b032009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor3f220e82009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregordd861062008-12-05 18:15:24 +000021
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregord6ea07d2009-07-29 16:56:42 +000068 } else if (OverloadedFunctionDecl *Ovl
69 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregor2fa10442008-12-18 19:37:40 +000070 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
71 FEnd = Ovl->function_end();
72 F != FEnd; ++F) {
Douglas Gregord6ea07d2009-07-29 16:56:42 +000073 if (FunctionTemplateDecl *FuncTmpl
74 = dyn_cast<FunctionTemplateDecl>(*F)) {
75 // We've found a function template. Determine whether there are
76 // any other function templates we need to bundle together in an
77 // OverloadedFunctionDecl
78 for (++F; F != FEnd; ++F) {
79 if (isa<FunctionTemplateDecl>(*F))
80 break;
81 }
82
83 if (F != FEnd) {
84 // Build an overloaded function decl containing only the
85 // function templates in Ovl.
86 OverloadedFunctionDecl *OvlTemplate
87 = OverloadedFunctionDecl::Create(Context,
88 Ovl->getDeclContext(),
89 Ovl->getDeclName());
90 OvlTemplate->addOverload(FuncTmpl);
91 OvlTemplate->addOverload(*F);
92 for (++F; F != FEnd; ++F) {
93 if (isa<FunctionTemplateDecl>(*F))
94 OvlTemplate->addOverload(*F);
95 }
Douglas Gregor6631cb42009-07-29 18:26:50 +000096
97 // Form the resulting TemplateName
98 if (SS && SS->isSet() && !SS->isInvalid()) {
99 NestedNameSpecifier *Qualifier
100 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
101 TemplateResult
102 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
103 false,
104 OvlTemplate));
105 } else {
106 TemplateResult = TemplateTy::make(TemplateName(OvlTemplate));
107 }
Douglas Gregord6ea07d2009-07-29 16:56:42 +0000108 return TNK_Function_template;
109 }
110
111 TNK = TNK_Function_template;
112 Template = FuncTmpl;
113 break;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000114 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000115 }
116 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000117
118 if (TNK != TNK_Non_template) {
119 if (SS && SS->isSet() && !SS->isInvalid()) {
120 NestedNameSpecifier *Qualifier
121 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
122 TemplateResult
123 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
124 false,
125 Template));
126 } else
127 TemplateResult = TemplateTy::make(TemplateName(Template));
128 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000129 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000130 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000131}
132
Douglas Gregordd861062008-12-05 18:15:24 +0000133/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
134/// that the template parameter 'PrevDecl' is being shadowed by a new
135/// declaration at location Loc. Returns true to indicate that this is
136/// an error, and false otherwise.
137bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000138 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000139
140 // Microsoft Visual C++ permits template parameters to be shadowed.
141 if (getLangOptions().Microsoft)
142 return false;
143
144 // C++ [temp.local]p4:
145 // A template-parameter shall not be redeclared within its
146 // scope (including nested scopes).
147 Diag(Loc, diag::err_template_param_shadow)
148 << cast<NamedDecl>(PrevDecl)->getDeclName();
149 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
150 return true;
151}
152
Douglas Gregored3a3982009-03-03 04:44:36 +0000153/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000154/// the parameter D to reference the templated declaration and return a pointer
155/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000156TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
157 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
158 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000159 return Temp;
160 }
161 return 0;
162}
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164/// ActOnTypeParameter - Called when a C++ template type parameter
165/// (e.g., "typename T") has been parsed. Typename specifies whether
166/// the keyword "typename" was used to declare the type parameter
167/// (otherwise, "class" was used), and KeyLoc is the location of the
168/// "class" or "typename" keyword. ParamName is the name of the
169/// parameter (NULL indicates an unnamed template parameter) and
170/// ParamName is the location of the parameter name (if any).
171/// If the type parameter has a default argument, it will be added
172/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000173Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
174 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000175 SourceLocation KeyLoc,
176 IdentifierInfo *ParamName,
177 SourceLocation ParamNameLoc,
178 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000179 assert(S->isTemplateParamScope() &&
180 "Template type parameter not in template parameter scope!");
181 bool Invalid = false;
182
183 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000184 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000185 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000186 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
187 PrevDecl);
188 }
189
Douglas Gregord406b032009-02-06 22:42:48 +0000190 SourceLocation Loc = ParamNameLoc;
191 if (!ParamName)
192 Loc = KeyLoc;
193
Douglas Gregordd861062008-12-05 18:15:24 +0000194 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000195 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000196 Depth, Position, ParamName, Typename,
197 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000198 if (Invalid)
199 Param->setInvalidDecl();
200
201 if (ParamName) {
202 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000203 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000204 IdResolver.AddDecl(Param);
205 }
206
Chris Lattner5261d0c2009-03-28 19:18:32 +0000207 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000208}
209
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000210/// ActOnTypeParameterDefault - Adds a default argument (the type
211/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000212void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000213 SourceLocation EqualLoc,
214 SourceLocation DefaultLoc,
215 TypeTy *DefaultT) {
216 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000217 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000218 QualType Default = QualType::getFromOpaquePtr(DefaultT);
219
Anders Carlssona2333782009-06-12 22:30:13 +0000220 // C++0x [temp.param]p9:
221 // A default template-argument may be specified for any kind of
222 // template-parameter that is not a template parameter pack.
223 if (Parm->isParameterPack()) {
224 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000225 return;
226 }
227
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000228 // C++ [temp.param]p14:
229 // A template-parameter shall not be used in its own default argument.
230 // FIXME: Implement this check! Needs a recursive walk over the types.
231
232 // Check the template argument itself.
233 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
234 Parm->setInvalidDecl();
235 return;
236 }
237
238 Parm->setDefaultArgument(Default, DefaultLoc, false);
239}
240
Douglas Gregored3a3982009-03-03 04:44:36 +0000241/// \brief Check that the type of a non-type template parameter is
242/// well-formed.
243///
244/// \returns the (possibly-promoted) parameter type if valid;
245/// otherwise, produces a diagnostic and returns a NULL type.
246QualType
247Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
248 // C++ [temp.param]p4:
249 //
250 // A non-type template-parameter shall have one of the following
251 // (optionally cv-qualified) types:
252 //
253 // -- integral or enumeration type,
254 if (T->isIntegralType() || T->isEnumeralType() ||
255 // -- pointer to object or pointer to function,
256 (T->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000257 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
258 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregored3a3982009-03-03 04:44:36 +0000259 // -- reference to object or reference to function,
260 T->isReferenceType() ||
261 // -- pointer to member.
262 T->isMemberPointerType() ||
263 // If T is a dependent type, we can't do the check now, so we
264 // assume that it is well-formed.
265 T->isDependentType())
266 return T;
267 // C++ [temp.param]p8:
268 //
269 // A non-type template-parameter of type "array of T" or
270 // "function returning T" is adjusted to be of type "pointer to
271 // T" or "pointer to function returning T", respectively.
272 else if (T->isArrayType())
273 // FIXME: Keep the type prior to promotion?
274 return Context.getArrayDecayedType(T);
275 else if (T->isFunctionType())
276 // FIXME: Keep the type prior to promotion?
277 return Context.getPointerType(T);
278
279 Diag(Loc, diag::err_template_nontype_parm_bad_type)
280 << T;
281
282 return QualType();
283}
284
Douglas Gregordd861062008-12-05 18:15:24 +0000285/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
286/// template parameter (e.g., "int Size" in "template<int Size>
287/// class Array") has been parsed. S is the current scope and D is
288/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000289Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
290 unsigned Depth,
291 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000292 QualType T = GetTypeForDeclarator(D, S);
293
Douglas Gregor279272e2009-02-04 19:02:06 +0000294 assert(S->isTemplateParamScope() &&
295 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000296 bool Invalid = false;
297
298 IdentifierInfo *ParamName = D.getIdentifier();
299 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000300 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000301 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000302 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000303 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000304 }
305
Douglas Gregored3a3982009-03-03 04:44:36 +0000306 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000307 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000308 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000309 Invalid = true;
310 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000311
Douglas Gregordd861062008-12-05 18:15:24 +0000312 NonTypeTemplateParmDecl *Param
313 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000314 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000315 if (Invalid)
316 Param->setInvalidDecl();
317
318 if (D.getIdentifier()) {
319 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000320 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000321 IdResolver.AddDecl(Param);
322 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000323 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000324}
Douglas Gregor52473432008-12-24 02:52:09 +0000325
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000326/// \brief Adds a default argument to the given non-type template
327/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000328void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000329 SourceLocation EqualLoc,
330 ExprArg DefaultE) {
331 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000332 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000333 Expr *Default = static_cast<Expr *>(DefaultE.get());
334
335 // C++ [temp.param]p14:
336 // A template-parameter shall not be used in its own default argument.
337 // FIXME: Implement this check! Needs a recursive walk over the types.
338
339 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000340 TemplateArgument Converted;
341 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
342 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000343 TemplateParm->setInvalidDecl();
344 return;
345 }
346
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000347 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000348}
349
Douglas Gregor279272e2009-02-04 19:02:06 +0000350
351/// ActOnTemplateTemplateParameter - Called when a C++ template template
352/// parameter (e.g. T in template <template <typename> class T> class array)
353/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
355 SourceLocation TmpLoc,
356 TemplateParamsTy *Params,
357 IdentifierInfo *Name,
358 SourceLocation NameLoc,
359 unsigned Depth,
360 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000361{
362 assert(S->isTemplateParamScope() &&
363 "Template template parameter not in template parameter scope!");
364
365 // Construct the parameter object.
366 TemplateTemplateParmDecl *Param =
367 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
368 Position, Name,
369 (TemplateParameterList*)Params);
370
371 // Make sure the parameter is valid.
372 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
373 // do anything yet. However, if the template parameter list or (eventual)
374 // default value is ever invalidated, that will propagate here.
375 bool Invalid = false;
376 if (Invalid) {
377 Param->setInvalidDecl();
378 }
379
380 // If the tt-param has a name, then link the identifier into the scope
381 // and lookup mechanisms.
382 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000383 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000384 IdResolver.AddDecl(Param);
385 }
386
Chris Lattner5261d0c2009-03-28 19:18:32 +0000387 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000388}
389
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000390/// \brief Adds a default argument to the given template template
391/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000392void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000393 SourceLocation EqualLoc,
394 ExprArg DefaultE) {
395 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000396 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000397
398 // Since a template-template parameter's default argument is an
399 // id-expression, it must be a DeclRefExpr.
400 DeclRefExpr *Default
401 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
402
403 // C++ [temp.param]p14:
404 // A template-parameter shall not be used in its own default argument.
405 // FIXME: Implement this check! Needs a recursive walk over the types.
406
407 // Check the well-formedness of the template argument.
408 if (!isa<TemplateDecl>(Default->getDecl())) {
409 Diag(Default->getSourceRange().getBegin(),
410 diag::err_template_arg_must_be_template)
411 << Default->getSourceRange();
412 TemplateParm->setInvalidDecl();
413 return;
414 }
415 if (CheckTemplateArgument(TemplateParm, Default)) {
416 TemplateParm->setInvalidDecl();
417 return;
418 }
419
420 DefaultE.release();
421 TemplateParm->setDefaultArgument(Default);
422}
423
Douglas Gregor52473432008-12-24 02:52:09 +0000424/// ActOnTemplateParameterList - Builds a TemplateParameterList that
425/// contains the template parameters in Params/NumParams.
426Sema::TemplateParamsTy *
427Sema::ActOnTemplateParameterList(unsigned Depth,
428 SourceLocation ExportLoc,
429 SourceLocation TemplateLoc,
430 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000431 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000432 SourceLocation RAngleLoc) {
433 if (ExportLoc.isValid())
434 Diag(ExportLoc, diag::note_template_export_unsupported);
435
Douglas Gregord406b032009-02-06 22:42:48 +0000436 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
437 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000438}
Douglas Gregor279272e2009-02-04 19:02:06 +0000439
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000440Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +0000441Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregord406b032009-02-06 22:42:48 +0000442 SourceLocation KWLoc, const CXXScopeSpec &SS,
443 IdentifierInfo *Name, SourceLocation NameLoc,
444 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000445 MultiTemplateParamsArg TemplateParameterLists,
446 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000447 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
John McCall069c23a2009-07-31 02:45:11 +0000448 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000449 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000450
451 // Check that we can declare a template here.
452 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000453 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000454
455 TagDecl::TagKind Kind;
456 switch (TagSpec) {
457 default: assert(0 && "Unknown tag type!");
458 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
459 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
460 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
461 }
462
463 // There is no such thing as an unnamed class template.
464 if (!Name) {
465 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000466 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000467 }
468
469 // Find any previous declaration with this name.
470 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
471 true);
472 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
473 NamedDecl *PrevDecl = 0;
474 if (Previous.begin() != Previous.end())
475 PrevDecl = *Previous.begin();
476
Douglas Gregor23521802009-06-17 23:37:01 +0000477 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
478 PrevDecl = 0;
479
Douglas Gregord406b032009-02-06 22:42:48 +0000480 DeclContext *SemanticContext = CurContext;
481 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000482 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000483
Mike Stumpe127ae32009-05-16 07:39:55 +0000484 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000485 }
486
487 // FIXME: member templates!
488 TemplateParameterList *TemplateParams
489 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
490
491 // If there is a previous declaration with the same name, check
492 // whether this is a valid redeclaration.
493 ClassTemplateDecl *PrevClassTemplate
494 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
495 if (PrevClassTemplate) {
496 // Ensure that the template parameter lists are compatible.
497 if (!TemplateParameterListsAreEqual(TemplateParams,
498 PrevClassTemplate->getTemplateParameters(),
499 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000500 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000501
502 // C++ [temp.class]p4:
503 // In a redeclaration, partial specialization, explicit
504 // specialization or explicit instantiation of a class template,
505 // the class-key shall agree in kind with the original class
506 // template declaration (7.1.5.3).
507 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000508 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000509 Diag(KWLoc, diag::err_use_with_wrong_tag)
510 << Name
511 << CodeModificationHint::CreateReplacement(KWLoc,
512 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000513 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000514 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000515 }
516
Douglas Gregord406b032009-02-06 22:42:48 +0000517 // Check for redefinition of this class template.
John McCall069c23a2009-07-31 02:45:11 +0000518 if (TUK == TUK_Definition) {
Douglas Gregord406b032009-02-06 22:42:48 +0000519 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
520 Diag(NameLoc, diag::err_redefinition) << Name;
521 Diag(Def->getLocation(), diag::note_previous_definition);
522 // FIXME: Would it make sense to try to "forget" the previous
523 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000524 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000525 }
526 }
527 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
528 // Maybe we will complain about the shadowed template parameter.
529 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
530 // Just pretend that we didn't see the previous declaration.
531 PrevDecl = 0;
532 } else if (PrevDecl) {
533 // C++ [temp]p5:
534 // A class template shall not have the same name as any other
535 // template, class, function, object, enumeration, enumerator,
536 // namespace, or type in the same scope (3.3), except as specified
537 // in (14.5.4).
538 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
539 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000540 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000541 }
542
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000543 // Check the template parameter list of this declaration, possibly
544 // merging in the template parameter list from the previous class
545 // template declaration.
546 if (CheckTemplateParameterList(TemplateParams,
547 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
548 Invalid = true;
549
Douglas Gregor9054f982009-05-10 22:57:19 +0000550 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000551 // declaration!
552
Douglas Gregor55216ac2009-03-26 00:10:35 +0000553 CXXRecordDecl *NewClass =
Douglas Gregor9060d0e2009-07-21 14:46:17 +0000554 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregord406b032009-02-06 22:42:48 +0000555 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000556 PrevClassTemplate->getTemplatedDecl() : 0,
557 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000558
559 ClassTemplateDecl *NewTemplate
560 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
561 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000562 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000563 NewClass->setDescribedClassTemplate(NewTemplate);
564
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000565 // Build the type for the class template declaration now.
566 QualType T =
567 Context.getTypeDeclType(NewClass,
568 PrevClassTemplate?
569 PrevClassTemplate->getTemplatedDecl() : 0);
570 assert(T->isDependentType() && "Class template type is not dependent?");
571 (void)T;
572
Anders Carlsson4ca43492009-03-26 01:24:28 +0000573 // Set the access specifier.
574 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
575
Douglas Gregord406b032009-02-06 22:42:48 +0000576 // Set the lexical context of these templates
577 NewClass->setLexicalDeclContext(CurContext);
578 NewTemplate->setLexicalDeclContext(CurContext);
579
John McCall069c23a2009-07-31 02:45:11 +0000580 if (TUK == TUK_Definition)
Douglas Gregord406b032009-02-06 22:42:48 +0000581 NewClass->startDefinition();
582
583 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000584 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000585
586 PushOnScopeChains(NewTemplate, S);
587
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000588 if (Invalid) {
589 NewTemplate->setInvalidDecl();
590 NewClass->setInvalidDecl();
591 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000592 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000593}
594
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000595/// \brief Checks the validity of a template parameter list, possibly
596/// considering the template parameter list from a previous
597/// declaration.
598///
599/// If an "old" template parameter list is provided, it must be
600/// equivalent (per TemplateParameterListsAreEqual) to the "new"
601/// template parameter list.
602///
603/// \param NewParams Template parameter list for a new template
604/// declaration. This template parameter list will be updated with any
605/// default arguments that are carried through from the previous
606/// template parameter list.
607///
608/// \param OldParams If provided, template parameter list from a
609/// previous declaration of the same template. Default template
610/// arguments will be merged from the old template parameter list to
611/// the new template parameter list.
612///
613/// \returns true if an error occurred, false otherwise.
614bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
615 TemplateParameterList *OldParams) {
616 bool Invalid = false;
617
618 // C++ [temp.param]p10:
619 // The set of default template-arguments available for use with a
620 // template declaration or definition is obtained by merging the
621 // default arguments from the definition (if in scope) and all
622 // declarations in scope in the same way default function
623 // arguments are (8.3.6).
624 bool SawDefaultArgument = false;
625 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000626
Anders Carlssonb1929502009-06-12 23:20:15 +0000627 bool SawParameterPack = false;
628 SourceLocation ParameterPackLoc;
629
Mike Stumpe0b7e032009-02-11 23:03:27 +0000630 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000631 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000632 if (OldParams)
633 OldParam = OldParams->begin();
634
635 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
636 NewParamEnd = NewParams->end();
637 NewParam != NewParamEnd; ++NewParam) {
638 // Variables used to diagnose redundant default arguments
639 bool RedundantDefaultArg = false;
640 SourceLocation OldDefaultLoc;
641 SourceLocation NewDefaultLoc;
642
643 // Variables used to diagnose missing default arguments
644 bool MissingDefaultArg = false;
645
Anders Carlssonb1929502009-06-12 23:20:15 +0000646 // C++0x [temp.param]p11:
647 // If a template parameter of a class template is a template parameter pack,
648 // it must be the last template parameter.
649 if (SawParameterPack) {
650 Diag(ParameterPackLoc,
651 diag::err_template_param_pack_must_be_last_template_parameter);
652 Invalid = true;
653 }
654
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000655 // Merge default arguments for template type parameters.
656 if (TemplateTypeParmDecl *NewTypeParm
657 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
658 TemplateTypeParmDecl *OldTypeParm
659 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
660
Anders Carlssonb1929502009-06-12 23:20:15 +0000661 if (NewTypeParm->isParameterPack()) {
662 assert(!NewTypeParm->hasDefaultArgument() &&
663 "Parameter packs can't have a default argument!");
664 SawParameterPack = true;
665 ParameterPackLoc = NewTypeParm->getLocation();
666 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000667 NewTypeParm->hasDefaultArgument()) {
668 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
669 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
670 SawDefaultArgument = true;
671 RedundantDefaultArg = true;
672 PreviousDefaultArgLoc = NewDefaultLoc;
673 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
674 // Merge the default argument from the old declaration to the
675 // new declaration.
676 SawDefaultArgument = true;
677 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
678 OldTypeParm->getDefaultArgumentLoc(),
679 true);
680 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
681 } else if (NewTypeParm->hasDefaultArgument()) {
682 SawDefaultArgument = true;
683 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
684 } else if (SawDefaultArgument)
685 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000686 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000687 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000688 // Merge default arguments for non-type template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000689 NonTypeTemplateParmDecl *OldNonTypeParm
690 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
691 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
692 NewNonTypeParm->hasDefaultArgument()) {
693 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
694 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
695 SawDefaultArgument = true;
696 RedundantDefaultArg = true;
697 PreviousDefaultArgLoc = NewDefaultLoc;
698 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
699 // Merge the default argument from the old declaration to the
700 // new declaration.
701 SawDefaultArgument = true;
702 // FIXME: We need to create a new kind of "default argument"
703 // expression that points to a previous template template
704 // parameter.
705 NewNonTypeParm->setDefaultArgument(
706 OldNonTypeParm->getDefaultArgument());
707 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
708 } else if (NewNonTypeParm->hasDefaultArgument()) {
709 SawDefaultArgument = true;
710 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
711 } else if (SawDefaultArgument)
712 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000713 } else {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000714 // Merge default arguments for template template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000715 TemplateTemplateParmDecl *NewTemplateParm
716 = cast<TemplateTemplateParmDecl>(*NewParam);
717 TemplateTemplateParmDecl *OldTemplateParm
718 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
719 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
720 NewTemplateParm->hasDefaultArgument()) {
721 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
722 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
723 SawDefaultArgument = true;
724 RedundantDefaultArg = true;
725 PreviousDefaultArgLoc = NewDefaultLoc;
726 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
727 // Merge the default argument from the old declaration to the
728 // new declaration.
729 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000730 // FIXME: We need to create a new kind of "default argument" expression
731 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000732 NewTemplateParm->setDefaultArgument(
733 OldTemplateParm->getDefaultArgument());
734 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
735 } else if (NewTemplateParm->hasDefaultArgument()) {
736 SawDefaultArgument = true;
737 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
738 } else if (SawDefaultArgument)
739 MissingDefaultArg = true;
740 }
741
742 if (RedundantDefaultArg) {
743 // C++ [temp.param]p12:
744 // A template-parameter shall not be given default arguments
745 // by two different declarations in the same scope.
746 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
747 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
748 Invalid = true;
749 } else if (MissingDefaultArg) {
750 // C++ [temp.param]p11:
751 // If a template-parameter has a default template-argument,
752 // all subsequent template-parameters shall have a default
753 // template-argument supplied.
754 Diag((*NewParam)->getLocation(),
755 diag::err_template_param_default_arg_missing);
756 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
757 Invalid = true;
758 }
759
760 // If we have an old template parameter list that we're merging
761 // in, move on to the next parameter.
762 if (OldParams)
763 ++OldParam;
764 }
765
766 return Invalid;
767}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000768
Douglas Gregorb462c322009-07-21 23:53:31 +0000769/// \brief Match the given template parameter lists to the given scope
770/// specifier, returning the template parameter list that applies to the
771/// name.
772///
773/// \param DeclStartLoc the start of the declaration that has a scope
774/// specifier or a template parameter list.
775///
776/// \param SS the scope specifier that will be matched to the given template
777/// parameter lists. This scope specifier precedes a qualified name that is
778/// being declared.
779///
780/// \param ParamLists the template parameter lists, from the outermost to the
781/// innermost template parameter lists.
782///
783/// \param NumParamLists the number of template parameter lists in ParamLists.
784///
785/// \returns the template parameter list, if any, that corresponds to the
786/// name that is preceded by the scope specifier @p SS. This template
787/// parameter list may be have template parameters (if we're declaring a
788/// template) or may have no template parameters (if we're declaring a
789/// template specialization), or may be NULL (if we were's declaring isn't
790/// itself a template).
791TemplateParameterList *
792Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
793 const CXXScopeSpec &SS,
794 TemplateParameterList **ParamLists,
795 unsigned NumParamLists) {
796 // FIXME: This routine will need a lot more testing once we have support for
797 // member templates.
798
799 // Find the template-ids that occur within the nested-name-specifier. These
800 // template-ids will match up with the template parameter lists.
801 llvm::SmallVector<const TemplateSpecializationType *, 4>
802 TemplateIdsInSpecifier;
803 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
804 NNS; NNS = NNS->getPrefix()) {
805 if (const TemplateSpecializationType *SpecType
806 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
807 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
808 if (!Template)
809 continue; // FIXME: should this be an error? probably...
810
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000811 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorb462c322009-07-21 23:53:31 +0000812 ClassTemplateSpecializationDecl *SpecDecl
813 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
814 // If the nested name specifier refers to an explicit specialization,
815 // we don't need a template<> header.
Douglas Gregor1930d202009-07-30 17:40:51 +0000816 // FIXME: revisit this approach once we cope with specialization
817 // properly.
Douglas Gregorb462c322009-07-21 23:53:31 +0000818 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
819 continue;
820 }
821
822 TemplateIdsInSpecifier.push_back(SpecType);
823 }
824 }
825
826 // Reverse the list of template-ids in the scope specifier, so that we can
827 // more easily match up the template-ids and the template parameter lists.
828 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
829
830 SourceLocation FirstTemplateLoc = DeclStartLoc;
831 if (NumParamLists)
832 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
833
834 // Match the template-ids found in the specifier to the template parameter
835 // lists.
836 unsigned Idx = 0;
837 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
838 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor1930d202009-07-30 17:40:51 +0000839 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
840 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorb462c322009-07-21 23:53:31 +0000841 if (Idx >= NumParamLists) {
842 // We have a template-id without a corresponding template parameter
843 // list.
844 if (DependentTemplateId) {
845 // FIXME: the location information here isn't great.
846 Diag(SS.getRange().getBegin(),
847 diag::err_template_spec_needs_template_parameters)
Douglas Gregor1930d202009-07-30 17:40:51 +0000848 << TemplateId
Douglas Gregorb462c322009-07-21 23:53:31 +0000849 << SS.getRange();
850 } else {
851 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
852 << SS.getRange()
853 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
854 "template<> ");
855 }
856 return 0;
857 }
858
859 // Check the template parameter list against its corresponding template-id.
Douglas Gregor1930d202009-07-30 17:40:51 +0000860 if (DependentTemplateId) {
861 TemplateDecl *Template
862 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
863
864 if (ClassTemplateDecl *ClassTemplate
865 = dyn_cast<ClassTemplateDecl>(Template)) {
866 TemplateParameterList *ExpectedTemplateParams = 0;
867 // Is this template-id naming the primary template?
868 if (Context.hasSameType(TemplateId,
869 ClassTemplate->getInjectedClassNameType(Context)))
870 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
871 // ... or a partial specialization?
872 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
873 = ClassTemplate->findPartialSpecialization(TemplateId))
874 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
875
876 if (ExpectedTemplateParams)
877 TemplateParameterListsAreEqual(ParamLists[Idx],
878 ExpectedTemplateParams,
879 true);
880 }
881 } else if (ParamLists[Idx]->size() > 0)
882 Diag(ParamLists[Idx]->getTemplateLoc(),
883 diag::err_template_param_list_matches_nontemplate)
884 << TemplateId
885 << ParamLists[Idx]->getSourceRange();
Douglas Gregorb462c322009-07-21 23:53:31 +0000886 }
887
888 // If there were at least as many template-ids as there were template
889 // parameter lists, then there are no template parameter lists remaining for
890 // the declaration itself.
891 if (Idx >= NumParamLists)
892 return 0;
893
894 // If there were too many template parameter lists, complain about that now.
895 if (Idx != NumParamLists - 1) {
896 while (Idx < NumParamLists - 1) {
897 Diag(ParamLists[Idx]->getTemplateLoc(),
898 diag::err_template_spec_extra_headers)
899 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
900 ParamLists[Idx]->getRAngleLoc());
901 ++Idx;
902 }
903 }
904
905 // Return the last template parameter list, which corresponds to the
906 // entity being declared.
907 return ParamLists[NumParamLists - 1];
908}
909
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000910/// \brief Translates template arguments as provided by the parser
911/// into template arguments used by semantic analysis.
912static void
913translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
914 SourceLocation *TemplateArgLocs,
915 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
916 TemplateArgs.reserve(TemplateArgsIn.size());
917
918 void **Args = TemplateArgsIn.getArgs();
919 bool *ArgIsType = TemplateArgsIn.getArgIsType();
920 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
921 TemplateArgs.push_back(
922 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
923 QualType::getFromOpaquePtr(Args[Arg]))
924 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
925 }
926}
927
Douglas Gregordd13e842009-03-30 22:58:21 +0000928QualType Sema::CheckTemplateIdType(TemplateName Name,
929 SourceLocation TemplateLoc,
930 SourceLocation LAngleLoc,
931 const TemplateArgument *TemplateArgs,
932 unsigned NumTemplateArgs,
933 SourceLocation RAngleLoc) {
934 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000935 if (!Template) {
936 // The template name does not resolve to a template, so we just
937 // build a dependent template-id type.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000938 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor4262bc92009-07-28 23:00:59 +0000939 NumTemplateArgs);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000940 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000941
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000942 // Check that the template argument list is well-formed for this
943 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000944 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
945 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +0000946 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000947 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +0000948 false, Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000949 return QualType();
950
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000951 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000952 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000953 "Converted template argument list is too short!");
954
955 QualType CanonType;
956
Douglas Gregordd13e842009-03-30 22:58:21 +0000957 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000958 TemplateArgs,
959 NumTemplateArgs)) {
960 // This class template specialization is a dependent
961 // type. Therefore, its canonical type is another class template
962 // specialization type that contains all of the converted
963 // arguments in canonical form. This ensures that, e.g., A<T> and
964 // A<T, T> have identical types when A is declared as:
965 //
966 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000967 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
968 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000969 Converted.getFlatArguments(),
970 Converted.flatSize());
Douglas Gregor4262bc92009-07-28 23:00:59 +0000971
972 // FIXME: CanonType is not actually the canonical type, and unfortunately
973 // it is a TemplateTypeSpecializationType that we will never use again.
974 // In the future, we need to teach getTemplateSpecializationType to only
975 // build the canonical type and return that to us.
976 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +0000977 } else if (ClassTemplateDecl *ClassTemplate
978 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000979 // Find the class template specialization declaration that
980 // corresponds to these arguments.
981 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000982 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000983 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +0000984 Converted.flatSize(),
985 Context);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000986 void *InsertPos = 0;
987 ClassTemplateSpecializationDecl *Decl
988 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
989 if (!Decl) {
990 // This is the first time we have referenced this class template
991 // specialization. Create the canonical declaration and add it to
992 // the set of specializations.
993 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000994 ClassTemplate->getDeclContext(),
995 TemplateLoc,
996 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000997 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000998 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
999 Decl->setLexicalDeclContext(CurContext);
1000 }
1001
1002 CanonType = Context.getTypeDeclType(Decl);
1003 }
1004
1005 // Build the fully-sugared type for this class template
1006 // specialization, which refers back to the class template
1007 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +00001008 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1009 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001010}
1011
Douglas Gregora08b6c72009-02-17 23:15:12 +00001012Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +00001013Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1014 SourceLocation LAngleLoc,
1015 ASTTemplateArgsPtr TemplateArgsIn,
1016 SourceLocation *TemplateArgLocs,
1017 SourceLocation RAngleLoc) {
1018 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001019
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001020 // Translate the parser's template argument list in our AST format.
1021 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1022 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001023
Douglas Gregordd13e842009-03-30 22:58:21 +00001024 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +00001025 TemplateArgs.data(),
1026 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +00001027 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001028 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +00001029
1030 if (Result.isNull())
1031 return true;
1032
Douglas Gregor6f37b582009-02-09 19:34:22 +00001033 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001034}
1035
Douglas Gregor28857752009-06-30 22:34:41 +00001036Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1037 SourceLocation TemplateNameLoc,
1038 SourceLocation LAngleLoc,
1039 const TemplateArgument *TemplateArgs,
1040 unsigned NumTemplateArgs,
1041 SourceLocation RAngleLoc) {
1042 // FIXME: Can we do any checking at this point? I guess we could check the
1043 // template arguments that we have against the template name, if the template
1044 // name refers to a single template. That's not a terribly common case,
1045 // though.
1046 return Owned(TemplateIdRefExpr::Create(Context,
1047 /*FIXME: New type?*/Context.OverloadTy,
1048 /*FIXME: Necessary?*/0,
1049 /*FIXME: Necessary?*/SourceRange(),
1050 Template, TemplateNameLoc, LAngleLoc,
1051 TemplateArgs,
1052 NumTemplateArgs, RAngleLoc));
1053}
1054
1055Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1056 SourceLocation TemplateNameLoc,
1057 SourceLocation LAngleLoc,
1058 ASTTemplateArgsPtr TemplateArgsIn,
1059 SourceLocation *TemplateArgLocs,
1060 SourceLocation RAngleLoc) {
1061 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1062
1063 // Translate the parser's template argument list in our AST format.
1064 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1065 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorf2fedc62009-07-22 20:55:49 +00001066 TemplateArgsIn.release();
Douglas Gregor28857752009-06-30 22:34:41 +00001067
1068 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1069 TemplateArgs.data(), TemplateArgs.size(),
1070 RAngleLoc);
1071}
1072
Douglas Gregoraabb8502009-03-31 00:43:58 +00001073/// \brief Form a dependent template name.
1074///
1075/// This action forms a dependent template name given the template
1076/// name and its (presumably dependent) scope specifier. For
1077/// example, given "MetaFun::template apply", the scope specifier \p
1078/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1079/// of the "template" keyword, and "apply" is the \p Name.
1080Sema::TemplateTy
1081Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1082 const IdentifierInfo &Name,
1083 SourceLocation NameLoc,
1084 const CXXScopeSpec &SS) {
1085 if (!SS.isSet() || SS.isInvalid())
1086 return TemplateTy();
1087
1088 NestedNameSpecifier *Qualifier
1089 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1090
1091 // FIXME: member of the current instantiation
1092
1093 if (!Qualifier->isDependent()) {
1094 // C++0x [temp.names]p5:
1095 // If a name prefixed by the keyword template is not the name of
1096 // a template, the program is ill-formed. [Note: the keyword
1097 // template may not be applied to non-template members of class
1098 // templates. -end note ] [ Note: as is the case with the
1099 // typename prefix, the template prefix is allowed in cases
1100 // where it is not strictly necessary; i.e., when the
1101 // nested-name-specifier or the expression on the left of the ->
1102 // or . is not dependent on a template-parameter, or the use
1103 // does not appear in the scope of a template. -end note]
1104 //
1105 // Note: C++03 was more strict here, because it banned the use of
1106 // the "template" keyword prior to a template-name that was not a
1107 // dependent name. C++ DR468 relaxed this requirement (the
1108 // "template" keyword is now permitted). We follow the C++0x
1109 // rules, even in C++03 mode, retroactively applying the DR.
1110 TemplateTy Template;
1111 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1112 if (TNK == TNK_Non_template) {
1113 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1114 << &Name;
1115 return TemplateTy();
1116 }
1117
1118 return Template;
1119 }
1120
1121 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1122}
1123
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001124bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1125 const TemplateArgument &Arg,
1126 TemplateArgumentListBuilder &Converted) {
1127 // Check template type parameter.
1128 if (Arg.getKind() != TemplateArgument::Type) {
1129 // C++ [temp.arg.type]p1:
1130 // A template-argument for a template-parameter which is a
1131 // type shall be a type-id.
1132
1133 // We have a template type parameter but the template argument
1134 // is not a type.
1135 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1136 Diag(Param->getLocation(), diag::note_template_param_here);
1137
1138 return true;
1139 }
1140
1141 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1142 return true;
1143
1144 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001145 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001146 TemplateArgument(Arg.getLocation(),
1147 Context.getCanonicalType(Arg.getAsType())));
1148 return false;
1149}
1150
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001151/// \brief Check that the given template argument list is well-formed
1152/// for specializing the given template.
1153bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1154 SourceLocation TemplateLoc,
1155 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001156 const TemplateArgument *TemplateArgs,
1157 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001158 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001159 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001160 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001161 TemplateParameterList *Params = Template->getTemplateParameters();
1162 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001163 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001164 bool Invalid = false;
1165
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001166 bool HasParameterPack =
1167 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1168
1169 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001170 (NumArgs < Params->getMinRequiredArguments() &&
1171 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001172 // FIXME: point at either the first arg beyond what we can handle,
1173 // or the '>', depending on whether we have too many or too few
1174 // arguments.
1175 SourceRange Range;
1176 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001177 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001178 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1179 << (NumArgs > NumParams)
1180 << (isa<ClassTemplateDecl>(Template)? 0 :
1181 isa<FunctionTemplateDecl>(Template)? 1 :
1182 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1183 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001184 Diag(Template->getLocation(), diag::note_template_decl_here)
1185 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001186 Invalid = true;
1187 }
1188
1189 // C++ [temp.arg]p1:
1190 // [...] The type and form of each template-argument specified in
1191 // a template-id shall match the type and form specified for the
1192 // corresponding parameter declared by the template in its
1193 // template-parameter-list.
1194 unsigned ArgIdx = 0;
1195 for (TemplateParameterList::iterator Param = Params->begin(),
1196 ParamEnd = Params->end();
1197 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001198 if (ArgIdx > NumArgs && PartialTemplateArgs)
1199 break;
1200
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001201 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001202 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001203 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001204 // Retrieve the default template argument from the template
1205 // parameter.
1206 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001207 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001208 // We have an empty argument pack.
1209 Converted.BeginPack();
1210 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001211 break;
1212 }
1213
Douglas Gregorad964b32009-02-17 01:05:43 +00001214 if (!TTP->hasDefaultArgument())
1215 break;
1216
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001217 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001218
1219 // If the argument type is dependent, instantiate it now based
1220 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001221 if (ArgType->isDependentType()) {
1222 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001223 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001224 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001225 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001226
Anders Carlsson0233eb62009-06-05 04:47:51 +00001227 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001228 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001229 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001230 TTP->getDefaultArgumentLoc(),
1231 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001232 }
Douglas Gregor74296542009-02-27 19:31:52 +00001233
1234 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001235 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001236
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001237 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001238 } else if (NonTypeTemplateParmDecl *NTTP
1239 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1240 if (!NTTP->hasDefaultArgument())
1241 break;
1242
Anders Carlsson0297caf2009-06-11 16:06:49 +00001243 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001244 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001245 Converted.flatSize(),
1246 SourceRange(TemplateLoc, RAngleLoc));
1247
1248 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001249 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001250
1251 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1252 TemplateArgs);
1253 if (E.isInvalid())
1254 return true;
1255
1256 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001257 } else {
1258 TemplateTemplateParmDecl *TempParm
1259 = cast<TemplateTemplateParmDecl>(*Param);
1260
1261 if (!TempParm->hasDefaultArgument())
1262 break;
1263
Douglas Gregored3a3982009-03-03 04:44:36 +00001264 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001265 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001266 }
1267 } else {
1268 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001269 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001270 }
1271
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001272
1273 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001274 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001275 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001276 // Check all the remaining arguments (if any).
1277 for (; ArgIdx < NumArgs; ++ArgIdx) {
1278 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1279 Invalid = true;
1280 }
1281
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001282 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001283 } else {
1284 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1285 Invalid = true;
1286 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001287 } else if (NonTypeTemplateParmDecl *NTTP
1288 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1289 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001290
1291 // Instantiate the type of the non-type template parameter with
1292 // the template arguments we've seen thus far.
1293 QualType NTTPType = NTTP->getType();
1294 if (NTTPType->isDependentType()) {
1295 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001296 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001297 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001298 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001299 SourceRange(TemplateLoc, RAngleLoc));
1300
Anders Carlsson0233eb62009-06-05 04:47:51 +00001301 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001302 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001303 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001304 NTTP->getLocation(),
1305 NTTP->getDeclName());
1306 // If that worked, check the non-type template parameter type
1307 // for validity.
1308 if (!NTTPType.isNull())
1309 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1310 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001311 if (NTTPType.isNull()) {
1312 Invalid = true;
1313 break;
1314 }
1315 }
1316
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001317 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001318 case TemplateArgument::Null:
1319 assert(false && "Should never see a NULL template argument here");
1320 break;
1321
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001322 case TemplateArgument::Expression: {
1323 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001324 TemplateArgument Result;
1325 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001326 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001327 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001328 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001329 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001330 }
1331
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001332 case TemplateArgument::Declaration:
1333 case TemplateArgument::Integral:
1334 // We've already checked this template argument, so just copy
1335 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001336 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001337 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001338
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001339 case TemplateArgument::Type:
1340 // We have a non-type template parameter but the template
1341 // argument is a type.
1342
1343 // C++ [temp.arg]p2:
1344 // In a template-argument, an ambiguity between a type-id and
1345 // an expression is resolved to a type-id, regardless of the
1346 // form of the corresponding template-parameter.
1347 //
1348 // We warn specifically about this case, since it can be rather
1349 // confusing for users.
1350 if (Arg.getAsType()->isFunctionType())
1351 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1352 << Arg.getAsType();
1353 else
1354 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1355 Diag((*Param)->getLocation(), diag::note_template_param_here);
1356 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001357 break;
1358
1359 case TemplateArgument::Pack:
1360 assert(0 && "FIXME: Implement!");
1361 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001362 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001363 } else {
1364 // Check template template parameters.
1365 TemplateTemplateParmDecl *TempParm
1366 = cast<TemplateTemplateParmDecl>(*Param);
1367
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001368 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001369 case TemplateArgument::Null:
1370 assert(false && "Should never see a NULL template argument here");
1371 break;
1372
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001373 case TemplateArgument::Expression: {
1374 Expr *ArgExpr = Arg.getAsExpr();
1375 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1376 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1377 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1378 Invalid = true;
1379
1380 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001381 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001382 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001383 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001384 continue;
1385 }
1386 }
1387 // fall through
1388
1389 case TemplateArgument::Type: {
1390 // We have a template template parameter but the template
1391 // argument does not refer to a template.
1392 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1393 Invalid = true;
1394 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001395 }
1396
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001397 case TemplateArgument::Declaration:
1398 // We've already checked this template argument, so just copy
1399 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001400 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001401 break;
1402
1403 case TemplateArgument::Integral:
1404 assert(false && "Integral argument with template template parameter");
1405 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001406
1407 case TemplateArgument::Pack:
1408 assert(0 && "FIXME: Implement!");
1409 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001410 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001411 }
1412 }
1413
1414 return Invalid;
1415}
1416
1417/// \brief Check a template argument against its corresponding
1418/// template type parameter.
1419///
1420/// This routine implements the semantics of C++ [temp.arg.type]. It
1421/// returns true if an error occurred, and false otherwise.
1422bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1423 QualType Arg, SourceLocation ArgLoc) {
1424 // C++ [temp.arg.type]p2:
1425 // A local type, a type with no linkage, an unnamed type or a type
1426 // compounded from any of these types shall not be used as a
1427 // template-argument for a template type-parameter.
1428 //
1429 // FIXME: Perform the recursive and no-linkage type checks.
1430 const TagType *Tag = 0;
1431 if (const EnumType *EnumT = Arg->getAsEnumType())
1432 Tag = EnumT;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001433 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001434 Tag = RecordT;
1435 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1436 return Diag(ArgLoc, diag::err_template_arg_local_type)
1437 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001438 else if (Tag && !Tag->getDecl()->getDeclName() &&
1439 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001440 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1441 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1442 return true;
1443 }
1444
1445 return false;
1446}
1447
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001448/// \brief Checks whether the given template argument is the address
1449/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001450bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1451 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001452 bool Invalid = false;
1453
1454 // See through any implicit casts we added to fix the type.
1455 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1456 Arg = Cast->getSubExpr();
1457
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001458 // C++0x allows nullptr, and there's no further checking to be done for that.
1459 if (Arg->getType()->isNullPtrType())
1460 return false;
1461
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001462 // C++ [temp.arg.nontype]p1:
1463 //
1464 // A template-argument for a non-type, non-template
1465 // template-parameter shall be one of: [...]
1466 //
1467 // -- the address of an object or function with external
1468 // linkage, including function templates and function
1469 // template-ids but excluding non-static class members,
1470 // expressed as & id-expression where the & is optional if
1471 // the name refers to a function or array, or if the
1472 // corresponding template-parameter is a reference; or
1473 DeclRefExpr *DRE = 0;
1474
1475 // Ignore (and complain about) any excess parentheses.
1476 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1477 if (!Invalid) {
1478 Diag(Arg->getSourceRange().getBegin(),
1479 diag::err_template_arg_extra_parens)
1480 << Arg->getSourceRange();
1481 Invalid = true;
1482 }
1483
1484 Arg = Parens->getSubExpr();
1485 }
1486
1487 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1488 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1489 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1490 } else
1491 DRE = dyn_cast<DeclRefExpr>(Arg);
1492
1493 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1494 return Diag(Arg->getSourceRange().getBegin(),
1495 diag::err_template_arg_not_object_or_func_form)
1496 << Arg->getSourceRange();
1497
1498 // Cannot refer to non-static data members
1499 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1500 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1501 << Field << Arg->getSourceRange();
1502
1503 // Cannot refer to non-static member functions
1504 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1505 if (!Method->isStatic())
1506 return Diag(Arg->getSourceRange().getBegin(),
1507 diag::err_template_arg_method)
1508 << Method << Arg->getSourceRange();
1509
1510 // Functions must have external linkage.
1511 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1512 if (Func->getStorageClass() == FunctionDecl::Static) {
1513 Diag(Arg->getSourceRange().getBegin(),
1514 diag::err_template_arg_function_not_extern)
1515 << Func << Arg->getSourceRange();
1516 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1517 << true;
1518 return true;
1519 }
1520
1521 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001522 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001523 return Invalid;
1524 }
1525
1526 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1527 if (!Var->hasGlobalStorage()) {
1528 Diag(Arg->getSourceRange().getBegin(),
1529 diag::err_template_arg_object_not_extern)
1530 << Var << Arg->getSourceRange();
1531 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1532 << true;
1533 return true;
1534 }
1535
1536 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001537 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001538 return Invalid;
1539 }
1540
1541 // We found something else, but we don't know specifically what it is.
1542 Diag(Arg->getSourceRange().getBegin(),
1543 diag::err_template_arg_not_object_or_func)
1544 << Arg->getSourceRange();
1545 Diag(DRE->getDecl()->getLocation(),
1546 diag::note_template_arg_refers_here);
1547 return true;
1548}
1549
1550/// \brief Checks whether the given template argument is a pointer to
1551/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001552bool
1553Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001554 bool Invalid = false;
1555
1556 // See through any implicit casts we added to fix the type.
1557 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1558 Arg = Cast->getSubExpr();
1559
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001560 // C++0x allows nullptr, and there's no further checking to be done for that.
1561 if (Arg->getType()->isNullPtrType())
1562 return false;
1563
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001564 // C++ [temp.arg.nontype]p1:
1565 //
1566 // A template-argument for a non-type, non-template
1567 // template-parameter shall be one of: [...]
1568 //
1569 // -- a pointer to member expressed as described in 5.3.1.
1570 QualifiedDeclRefExpr *DRE = 0;
1571
1572 // Ignore (and complain about) any excess parentheses.
1573 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1574 if (!Invalid) {
1575 Diag(Arg->getSourceRange().getBegin(),
1576 diag::err_template_arg_extra_parens)
1577 << Arg->getSourceRange();
1578 Invalid = true;
1579 }
1580
1581 Arg = Parens->getSubExpr();
1582 }
1583
1584 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1585 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1586 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1587
1588 if (!DRE)
1589 return Diag(Arg->getSourceRange().getBegin(),
1590 diag::err_template_arg_not_pointer_to_member_form)
1591 << Arg->getSourceRange();
1592
1593 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1594 assert((isa<FieldDecl>(DRE->getDecl()) ||
1595 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1596 "Only non-static member pointers can make it here");
1597
1598 // Okay: this is the address of a non-static member, and therefore
1599 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001600 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001601 return Invalid;
1602 }
1603
1604 // We found something else, but we don't know specifically what it is.
1605 Diag(Arg->getSourceRange().getBegin(),
1606 diag::err_template_arg_not_pointer_to_member_form)
1607 << Arg->getSourceRange();
1608 Diag(DRE->getDecl()->getLocation(),
1609 diag::note_template_arg_refers_here);
1610 return true;
1611}
1612
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001613/// \brief Check a template argument against its corresponding
1614/// non-type template parameter.
1615///
Douglas Gregored3a3982009-03-03 04:44:36 +00001616/// This routine implements the semantics of C++ [temp.arg.nontype].
1617/// It returns true if an error occurred, and false otherwise. \p
1618/// InstantiatedParamType is the type of the non-type template
1619/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001620///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001621/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001622bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001623 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001624 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001625 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1626
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001627 // If either the parameter has a dependent type or the argument is
1628 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001629 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001630 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1631 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001632 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001633 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001634 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001635
1636 // C++ [temp.arg.nontype]p5:
1637 // The following conversions are performed on each expression used
1638 // as a non-type template-argument. If a non-type
1639 // template-argument cannot be converted to the type of the
1640 // corresponding template-parameter then the program is
1641 // ill-formed.
1642 //
1643 // -- for a non-type template-parameter of integral or
1644 // enumeration type, integral promotions (4.5) and integral
1645 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001646 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001647 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001648 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001649 // C++ [temp.arg.nontype]p1:
1650 // A template-argument for a non-type, non-template
1651 // template-parameter shall be one of:
1652 //
1653 // -- an integral constant-expression of integral or enumeration
1654 // type; or
1655 // -- the name of a non-type template-parameter; or
1656 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001657 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001658 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1659 Diag(Arg->getSourceRange().getBegin(),
1660 diag::err_template_arg_not_integral_or_enumeral)
1661 << ArgType << Arg->getSourceRange();
1662 Diag(Param->getLocation(), diag::note_template_param_here);
1663 return true;
1664 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001665 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001666 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1667 << ArgType << Arg->getSourceRange();
1668 return true;
1669 }
1670
1671 // FIXME: We need some way to more easily get the unqualified form
1672 // of the types without going all the way to the
1673 // canonical type.
1674 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1675 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1676 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1677 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1678
1679 // Try to convert the argument to the parameter's type.
1680 if (ParamType == ArgType) {
1681 // Okay: no conversion necessary
1682 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1683 !ParamType->isEnumeralType()) {
1684 // This is an integral promotion or conversion.
1685 ImpCastExprToType(Arg, ParamType);
1686 } else {
1687 // We can't perform this conversion.
1688 Diag(Arg->getSourceRange().getBegin(),
1689 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001690 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001691 Diag(Param->getLocation(), diag::note_template_param_here);
1692 return true;
1693 }
1694
Douglas Gregorafc86942009-03-14 00:20:21 +00001695 QualType IntegerType = Context.getCanonicalType(ParamType);
1696 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001697 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001698
1699 if (!Arg->isValueDependent()) {
1700 // Check that an unsigned parameter does not receive a negative
1701 // value.
1702 if (IntegerType->isUnsignedIntegerType()
1703 && (Value.isSigned() && Value.isNegative())) {
1704 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1705 << Value.toString(10) << Param->getType()
1706 << Arg->getSourceRange();
1707 Diag(Param->getLocation(), diag::note_template_param_here);
1708 return true;
1709 }
1710
1711 // Check that we don't overflow the template parameter type.
1712 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1713 if (Value.getActiveBits() > AllowedBits) {
1714 Diag(Arg->getSourceRange().getBegin(),
1715 diag::err_template_arg_too_large)
1716 << Value.toString(10) << Param->getType()
1717 << Arg->getSourceRange();
1718 Diag(Param->getLocation(), diag::note_template_param_here);
1719 return true;
1720 }
1721
1722 if (Value.getBitWidth() != AllowedBits)
1723 Value.extOrTrunc(AllowedBits);
1724 Value.setIsSigned(IntegerType->isSignedIntegerType());
1725 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001726
Douglas Gregor8f378a92009-06-11 18:10:32 +00001727 // Add the value of this argument to the list of converted
1728 // arguments. We use the bitwidth and signedness of the template
1729 // parameter.
1730 if (Arg->isValueDependent()) {
1731 // The argument is value-dependent. Create a new
1732 // TemplateArgument with the converted expression.
1733 Converted = TemplateArgument(Arg);
1734 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001735 }
1736
Douglas Gregor8f378a92009-06-11 18:10:32 +00001737 Converted = TemplateArgument(StartLoc, Value,
1738 ParamType->isEnumeralType() ? ParamType
1739 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001740 return false;
1741 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001742
Douglas Gregor3f411962009-02-11 01:18:59 +00001743 // Handle pointer-to-function, reference-to-function, and
1744 // pointer-to-member-function all in (roughly) the same way.
1745 if (// -- For a non-type template-parameter of type pointer to
1746 // function, only the function-to-pointer conversion (4.3) is
1747 // applied. If the template-argument represents a set of
1748 // overloaded functions (or a pointer to such), the matching
1749 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001750 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001751 (ParamType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001752 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001753 // -- For a non-type template-parameter of type reference to
1754 // function, no conversions apply. If the template-argument
1755 // represents a set of overloaded functions, the matching
1756 // function is selected from the set (13.4).
1757 (ParamType->isReferenceType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001758 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001759 // -- For a non-type template-parameter of type pointer to
1760 // member function, no conversions apply. If the
1761 // template-argument represents a set of overloaded member
1762 // functions, the matching member function is selected from
1763 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001764 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001765 (ParamType->isMemberPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001766 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001767 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001768 if (Context.hasSameUnqualifiedType(ArgType,
1769 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001770 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001771 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1772 ParamType->isMemberPointerType())) {
1773 ArgType = ParamType;
1774 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001775 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001776 ArgType = Context.getPointerType(ArgType);
1777 ImpCastExprToType(Arg, ArgType);
1778 } else if (FunctionDecl *Fn
1779 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001780 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1781 return true;
1782
Douglas Gregor2eedd992009-02-11 00:19:33 +00001783 FixOverloadedFunctionReference(Arg, Fn);
1784 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001785 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001786 ArgType = Context.getPointerType(Arg->getType());
1787 ImpCastExprToType(Arg, ArgType);
1788 }
1789 }
1790
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001791 if (!Context.hasSameUnqualifiedType(ArgType,
1792 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001793 // We can't perform this conversion.
1794 Diag(Arg->getSourceRange().getBegin(),
1795 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001796 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001797 Diag(Param->getLocation(), diag::note_template_param_here);
1798 return true;
1799 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001800
Douglas Gregorad964b32009-02-17 01:05:43 +00001801 if (ParamType->isMemberPointerType()) {
1802 NamedDecl *Member = 0;
1803 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1804 return true;
1805
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001806 if (Member)
1807 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001808 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001809 return false;
1810 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001811
Douglas Gregorad964b32009-02-17 01:05:43 +00001812 NamedDecl *Entity = 0;
1813 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1814 return true;
1815
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001816 if (Entity)
1817 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001818 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001819 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001820 }
1821
Chris Lattner320dff22009-02-20 21:37:53 +00001822 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001823 // -- for a non-type template-parameter of type pointer to
1824 // object, qualification conversions (4.4) and the
1825 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001826 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001827 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001828 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001829
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001830 if (ArgType->isNullPtrType()) {
1831 ArgType = ParamType;
1832 ImpCastExprToType(Arg, ParamType);
1833 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001834 ArgType = Context.getArrayDecayedType(ArgType);
1835 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001836 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001837
Douglas Gregor3f411962009-02-11 01:18:59 +00001838 if (IsQualificationConversion(ArgType, ParamType)) {
1839 ArgType = ParamType;
1840 ImpCastExprToType(Arg, ParamType);
1841 }
1842
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001843 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001844 // We can't perform this conversion.
1845 Diag(Arg->getSourceRange().getBegin(),
1846 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001847 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001848 Diag(Param->getLocation(), diag::note_template_param_here);
1849 return true;
1850 }
1851
Douglas Gregorad964b32009-02-17 01:05:43 +00001852 NamedDecl *Entity = 0;
1853 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1854 return true;
1855
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001856 if (Entity)
1857 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001858 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001859 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001860 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001861
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001862 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001863 // -- For a non-type template-parameter of type reference to
1864 // object, no conversions apply. The type referred to by the
1865 // reference may be more cv-qualified than the (otherwise
1866 // identical) type of the template-argument. The
1867 // template-parameter is bound directly to the
1868 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001869 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001870 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001871
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001872 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001873 Diag(Arg->getSourceRange().getBegin(),
1874 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001875 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001876 << Arg->getSourceRange();
1877 Diag(Param->getLocation(), diag::note_template_param_here);
1878 return true;
1879 }
1880
1881 unsigned ParamQuals
1882 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1883 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1884
1885 if ((ParamQuals | ArgQuals) != ParamQuals) {
1886 Diag(Arg->getSourceRange().getBegin(),
1887 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001888 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001889 << Arg->getSourceRange();
1890 Diag(Param->getLocation(), diag::note_template_param_here);
1891 return true;
1892 }
1893
Douglas Gregorad964b32009-02-17 01:05:43 +00001894 NamedDecl *Entity = 0;
1895 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1896 return true;
1897
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001898 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001899 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001900 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001901 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001902
1903 // -- For a non-type template-parameter of type pointer to data
1904 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001905 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001906 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1907
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001908 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001909 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001910 } else if (ArgType->isNullPtrType()) {
1911 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001912 } else if (IsQualificationConversion(ArgType, ParamType)) {
1913 ImpCastExprToType(Arg, ParamType);
1914 } else {
1915 // We can't perform this conversion.
1916 Diag(Arg->getSourceRange().getBegin(),
1917 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001918 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001919 Diag(Param->getLocation(), diag::note_template_param_here);
1920 return true;
1921 }
1922
Douglas Gregorad964b32009-02-17 01:05:43 +00001923 NamedDecl *Member = 0;
1924 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1925 return true;
1926
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001927 if (Member)
1928 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001929 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001930 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001931}
1932
1933/// \brief Check a template argument against its corresponding
1934/// template template parameter.
1935///
1936/// This routine implements the semantics of C++ [temp.arg.template].
1937/// It returns true if an error occurred, and false otherwise.
1938bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1939 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001940 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1941 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1942
1943 // C++ [temp.arg.template]p1:
1944 // A template-argument for a template template-parameter shall be
1945 // the name of a class template, expressed as id-expression. Only
1946 // primary class templates are considered when matching the
1947 // template template argument with the corresponding parameter;
1948 // partial specializations are not considered even if their
1949 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001950 //
1951 // Note that we also allow template template parameters here, which
1952 // will happen when we are dealing with, e.g., class template
1953 // partial specializations.
1954 if (!isa<ClassTemplateDecl>(Template) &&
1955 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001956 assert(isa<FunctionTemplateDecl>(Template) &&
1957 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001958 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1959 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001960 << Template;
1961 }
1962
1963 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1964 Param->getTemplateParameters(),
1965 true, true,
1966 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001967}
1968
Douglas Gregord406b032009-02-06 22:42:48 +00001969/// \brief Determine whether the given template parameter lists are
1970/// equivalent.
1971///
1972/// \param New The new template parameter list, typically written in the
1973/// source code as part of a new template declaration.
1974///
1975/// \param Old The old template parameter list, typically found via
1976/// name lookup of the template declared with this template parameter
1977/// list.
1978///
1979/// \param Complain If true, this routine will produce a diagnostic if
1980/// the template parameter lists are not equivalent.
1981///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001982/// \param IsTemplateTemplateParm If true, this routine is being
1983/// called to compare the template parameter lists of a template
1984/// template parameter.
1985///
1986/// \param TemplateArgLoc If this source location is valid, then we
1987/// are actually checking the template parameter list of a template
1988/// argument (New) against the template parameter list of its
1989/// corresponding template template parameter (Old). We produce
1990/// slightly different diagnostics in this scenario.
1991///
Douglas Gregord406b032009-02-06 22:42:48 +00001992/// \returns True if the template parameter lists are equal, false
1993/// otherwise.
1994bool
1995Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1996 TemplateParameterList *Old,
1997 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001998 bool IsTemplateTemplateParm,
1999 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00002000 if (Old->size() != New->size()) {
2001 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002002 unsigned NextDiag = diag::err_template_param_list_different_arity;
2003 if (TemplateArgLoc.isValid()) {
2004 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2005 NextDiag = diag::note_template_param_list_different_arity;
2006 }
2007 Diag(New->getTemplateLoc(), NextDiag)
2008 << (New->size() > Old->size())
2009 << IsTemplateTemplateParm
2010 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00002011 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2012 << IsTemplateTemplateParm
2013 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2014 }
2015
2016 return false;
2017 }
2018
2019 for (TemplateParameterList::iterator OldParm = Old->begin(),
2020 OldParmEnd = Old->end(), NewParm = New->begin();
2021 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2022 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00002023 if (Complain) {
2024 unsigned NextDiag = diag::err_template_param_different_kind;
2025 if (TemplateArgLoc.isValid()) {
2026 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2027 NextDiag = diag::note_template_param_different_kind;
2028 }
2029 Diag((*NewParm)->getLocation(), NextDiag)
2030 << IsTemplateTemplateParm;
2031 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2032 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00002033 }
Douglas Gregord406b032009-02-06 22:42:48 +00002034 return false;
2035 }
2036
2037 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2038 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00002039 // know we're at the same index).
2040#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00002041 // FIXME: Enable this code in debug mode *after* we properly go through
2042 // and "instantiate" the template parameter lists of template template
2043 // parameters. It's only after this instantiation that (1) any dependent
2044 // types within the template parameter list of the template template
2045 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00002046 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00002047 QualType OldParmType
2048 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2049 QualType NewParmType
2050 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2051 assert(Context.getCanonicalType(OldParmType) ==
2052 Context.getCanonicalType(NewParmType) &&
2053 "type parameter mismatch?");
2054#endif
2055 } else if (NonTypeTemplateParmDecl *OldNTTP
2056 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2057 // The types of non-type template parameters must agree.
2058 NonTypeTemplateParmDecl *NewNTTP
2059 = cast<NonTypeTemplateParmDecl>(*NewParm);
2060 if (Context.getCanonicalType(OldNTTP->getType()) !=
2061 Context.getCanonicalType(NewNTTP->getType())) {
2062 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002063 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2064 if (TemplateArgLoc.isValid()) {
2065 Diag(TemplateArgLoc,
2066 diag::err_template_arg_template_params_mismatch);
2067 NextDiag = diag::note_template_nontype_parm_different_type;
2068 }
2069 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002070 << NewNTTP->getType()
2071 << IsTemplateTemplateParm;
2072 Diag(OldNTTP->getLocation(),
2073 diag::note_template_nontype_parm_prev_declaration)
2074 << OldNTTP->getType();
2075 }
2076 return false;
2077 }
2078 } else {
2079 // The template parameter lists of template template
2080 // parameters must agree.
2081 // FIXME: Could we perform a faster "type" comparison here?
2082 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2083 "Only template template parameters handled here");
2084 TemplateTemplateParmDecl *OldTTP
2085 = cast<TemplateTemplateParmDecl>(*OldParm);
2086 TemplateTemplateParmDecl *NewTTP
2087 = cast<TemplateTemplateParmDecl>(*NewParm);
2088 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2089 OldTTP->getTemplateParameters(),
2090 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002091 /*IsTemplateTemplateParm=*/true,
2092 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002093 return false;
2094 }
2095 }
2096
2097 return true;
2098}
2099
2100/// \brief Check whether a template can be declared within this scope.
2101///
2102/// If the template declaration is valid in this scope, returns
2103/// false. Otherwise, issues a diagnostic and returns true.
2104bool
2105Sema::CheckTemplateDeclScope(Scope *S,
2106 MultiTemplateParamsArg &TemplateParameterLists) {
2107 assert(TemplateParameterLists.size() > 0 && "Not a template");
2108
2109 // Find the nearest enclosing declaration scope.
2110 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2111 (S->getFlags() & Scope::TemplateParamScope) != 0)
2112 S = S->getParent();
2113
2114 TemplateParameterList *TemplateParams =
2115 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2116 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2117 SourceRange TemplateRange
2118 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2119
2120 // C++ [temp]p2:
2121 // A template-declaration can appear only as a namespace scope or
2122 // class scope declaration.
2123 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandda81522009-07-31 01:43:05 +00002124 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2125 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2126 return Diag(TemplateLoc, diag::err_template_linkage) << TemplateRange;
2127
2128 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregord406b032009-02-06 22:42:48 +00002129 Ctx = Ctx->getParent();
Douglas Gregord406b032009-02-06 22:42:48 +00002130
2131 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2132 return false;
2133
2134 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2135 << TemplateRange;
2136}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002137
Douglas Gregor90177912009-05-13 18:28:20 +00002138/// \brief Check whether a class template specialization or explicit
2139/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002140///
Douglas Gregor90177912009-05-13 18:28:20 +00002141/// This routine determines whether a class template specialization or
2142/// explicit instantiation can be declared in the current context
2143/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2144/// appropriate diagnostics if there was an error. It returns true if
2145// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002146bool
2147Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2148 ClassTemplateSpecializationDecl *PrevDecl,
2149 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002150 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002151 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002152 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002153 // C++ [temp.expl.spec]p2:
2154 // An explicit specialization shall be declared in the namespace
2155 // of which the template is a member, or, for member templates, in
2156 // the namespace of which the enclosing class or enclosing class
2157 // template is a member. An explicit specialization of a member
2158 // function, member class or static data member of a class
2159 // template shall be declared in the namespace of which the class
2160 // template is a member. Such a declaration may also be a
2161 // definition. If the declaration is not a definition, the
2162 // specialization may be defined later in the name- space in which
2163 // the explicit specialization was declared, or in a namespace
2164 // that encloses the one in which the explicit specialization was
2165 // declared.
2166 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002167 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002168 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002169 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002170 return true;
2171 }
2172
2173 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2174 DeclContext *TemplateContext
2175 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002176 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2177 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002178 // There is no prior declaration of this entity, so this
2179 // specialization must be in the same context as the template
2180 // itself.
2181 if (DC != TemplateContext) {
2182 if (isa<TranslationUnitDecl>(TemplateContext))
2183 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002184 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002185 << ClassTemplate << ScopeSpecifierRange;
2186 else if (isa<NamespaceDecl>(TemplateContext))
2187 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002188 << PartialSpecialization << ClassTemplate
2189 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002190
2191 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2192 }
2193
2194 return false;
2195 }
2196
2197 // We have a previous declaration of this entity. Make sure that
2198 // this redeclaration (or definition) occurs in an enclosing namespace.
2199 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002200 // FIXME: In C++98, we would like to turn these errors into warnings,
2201 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002202 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002203 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002204 if (isa<TranslationUnitDecl>(TemplateContext)) {
2205 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2206 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002207 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002208 else
2209 SuppressedDiag = true;
2210 } else if (isa<NamespaceDecl>(TemplateContext)) {
2211 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2212 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002213 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002214 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2215 else
2216 SuppressedDiag = true;
2217 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002218
Douglas Gregor90177912009-05-13 18:28:20 +00002219 if (!SuppressedDiag)
2220 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002221 }
2222
2223 return false;
2224}
2225
Douglas Gregor76e79952009-06-12 21:21:02 +00002226/// \brief Check the non-type template arguments of a class template
2227/// partial specialization according to C++ [temp.class.spec]p9.
2228///
Douglas Gregor42476442009-06-12 22:08:06 +00002229/// \param TemplateParams the template parameters of the primary class
2230/// template.
2231///
2232/// \param TemplateArg the template arguments of the class template
2233/// partial specialization.
2234///
2235/// \param MirrorsPrimaryTemplate will be set true if the class
2236/// template partial specialization arguments are identical to the
2237/// implicit template arguments of the primary template. This is not
2238/// necessarily an error (C++0x), and it is left to the caller to diagnose
2239/// this condition when it is an error.
2240///
Douglas Gregor76e79952009-06-12 21:21:02 +00002241/// \returns true if there was an error, false otherwise.
2242bool Sema::CheckClassTemplatePartialSpecializationArgs(
2243 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002244 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002245 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002246 // FIXME: the interface to this function will have to change to
2247 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002248 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002249
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002250 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002251
Douglas Gregor76e79952009-06-12 21:21:02 +00002252 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002253 // Determine whether the template argument list of the partial
2254 // specialization is identical to the implicit argument list of
2255 // the primary template. The caller may need to diagnostic this as
2256 // an error per C++ [temp.class.spec]p9b3.
2257 if (MirrorsPrimaryTemplate) {
2258 if (TemplateTypeParmDecl *TTP
2259 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2260 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002261 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002262 MirrorsPrimaryTemplate = false;
2263 } else if (TemplateTemplateParmDecl *TTP
2264 = dyn_cast<TemplateTemplateParmDecl>(
2265 TemplateParams->getParam(I))) {
2266 // FIXME: We should settle on either Declaration storage or
2267 // Expression storage for template template parameters.
2268 TemplateTemplateParmDecl *ArgDecl
2269 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002270 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002271 if (!ArgDecl)
2272 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002273 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002274 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2275
2276 if (!ArgDecl ||
2277 ArgDecl->getIndex() != TTP->getIndex() ||
2278 ArgDecl->getDepth() != TTP->getDepth())
2279 MirrorsPrimaryTemplate = false;
2280 }
2281 }
2282
Douglas Gregor76e79952009-06-12 21:21:02 +00002283 NonTypeTemplateParmDecl *Param
2284 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002285 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002286 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002287 }
2288
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002289 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002290 if (!ArgExpr) {
2291 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002292 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002293 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002294
2295 // C++ [temp.class.spec]p8:
2296 // A non-type argument is non-specialized if it is the name of a
2297 // non-type parameter. All other non-type arguments are
2298 // specialized.
2299 //
2300 // Below, we check the two conditions that only apply to
2301 // specialized non-type arguments, so skip any non-specialized
2302 // arguments.
2303 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002304 if (NonTypeTemplateParmDecl *NTTP
2305 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2306 if (MirrorsPrimaryTemplate &&
2307 (Param->getIndex() != NTTP->getIndex() ||
2308 Param->getDepth() != NTTP->getDepth()))
2309 MirrorsPrimaryTemplate = false;
2310
Douglas Gregor76e79952009-06-12 21:21:02 +00002311 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002312 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002313
2314 // C++ [temp.class.spec]p9:
2315 // Within the argument list of a class template partial
2316 // specialization, the following restrictions apply:
2317 // -- A partially specialized non-type argument expression
2318 // shall not involve a template parameter of the partial
2319 // specialization except when the argument expression is a
2320 // simple identifier.
2321 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2322 Diag(ArgExpr->getLocStart(),
2323 diag::err_dependent_non_type_arg_in_partial_spec)
2324 << ArgExpr->getSourceRange();
2325 return true;
2326 }
2327
2328 // -- The type of a template parameter corresponding to a
2329 // specialized non-type argument shall not be dependent on a
2330 // parameter of the specialization.
2331 if (Param->getType()->isDependentType()) {
2332 Diag(ArgExpr->getLocStart(),
2333 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2334 << Param->getType()
2335 << ArgExpr->getSourceRange();
2336 Diag(Param->getLocation(), diag::note_template_param_here);
2337 return true;
2338 }
Douglas Gregor42476442009-06-12 22:08:06 +00002339
2340 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002341 }
2342
2343 return false;
2344}
2345
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002346Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +00002347Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2348 TagUseKind TUK,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002349 SourceLocation KWLoc,
2350 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002351 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002352 SourceLocation TemplateNameLoc,
2353 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002354 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002355 SourceLocation *TemplateArgLocs,
2356 SourceLocation RAngleLoc,
2357 AttributeList *Attr,
2358 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002359 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002360 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002361 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002362 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002363
Douglas Gregor58944ac2009-05-31 09:31:02 +00002364 bool isPartialSpecialization = false;
2365
Douglas Gregor0d93f692009-02-25 22:02:03 +00002366 // Check the validity of the template headers that introduce this
2367 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002368 // FIXME: Once we have member templates, we'll need to check
2369 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2370 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002371 if (TemplateParameterLists.size() == 0)
2372 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002373 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002374 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002375 TemplateParameterList *TemplateParams
2376 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002377 if (TemplateParameterLists.size() > 1) {
2378 Diag(TemplateParams->getTemplateLoc(),
2379 diag::err_template_spec_extra_headers);
2380 return true;
2381 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002382
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002383 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002384 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002385
2386 // C++ [temp.class.spec]p10:
2387 // The template parameter list of a specialization shall not
2388 // contain default template argument values.
2389 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2390 Decl *Param = TemplateParams->getParam(I);
2391 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2392 if (TTP->hasDefaultArgument()) {
2393 Diag(TTP->getDefaultArgumentLoc(),
2394 diag::err_default_arg_in_partial_spec);
2395 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2396 }
2397 } else if (NonTypeTemplateParmDecl *NTTP
2398 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2399 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2400 Diag(NTTP->getDefaultArgumentLoc(),
2401 diag::err_default_arg_in_partial_spec)
2402 << DefArg->getSourceRange();
2403 NTTP->setDefaultArgument(0);
2404 DefArg->Destroy(Context);
2405 }
2406 } else {
2407 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2408 if (Expr *DefArg = TTP->getDefaultArgument()) {
2409 Diag(TTP->getDefaultArgumentLoc(),
2410 diag::err_default_arg_in_partial_spec)
2411 << DefArg->getSourceRange();
2412 TTP->setDefaultArgument(0);
2413 DefArg->Destroy(Context);
2414 }
2415 }
2416 }
2417 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002418 }
2419
Douglas Gregora08b6c72009-02-17 23:15:12 +00002420 // Check that the specialization uses the same tag kind as the
2421 // original template.
2422 TagDecl::TagKind Kind;
2423 switch (TagSpec) {
2424 default: assert(0 && "Unknown tag type!");
2425 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2426 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2427 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2428 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002429 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2430 Kind, KWLoc,
2431 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002432 Diag(KWLoc, diag::err_use_with_wrong_tag)
2433 << ClassTemplate
2434 << CodeModificationHint::CreateReplacement(KWLoc,
2435 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002436 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2437 diag::note_previous_use);
2438 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2439 }
2440
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002441 // Translate the parser's template argument list in our AST format.
2442 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2443 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2444
Douglas Gregora08b6c72009-02-17 23:15:12 +00002445 // Check that the template argument list is well-formed for this
2446 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002447 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2448 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002449 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002450 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002451 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002452 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002453
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002454 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002455 ClassTemplate->getTemplateParameters()->size()) &&
2456 "Converted template argument list is too short!");
2457
Douglas Gregor58944ac2009-05-31 09:31:02 +00002458 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002459 // corresponds to these arguments.
2460 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002461 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002462 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002463 if (CheckClassTemplatePartialSpecializationArgs(
2464 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002465 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002466 return true;
2467
Douglas Gregor42476442009-06-12 22:08:06 +00002468 if (MirrorsPrimaryTemplate) {
2469 // C++ [temp.class.spec]p9b3:
2470 //
2471 // -- The argument list of the specialization shall not be identical
2472 // to the implicit argument list of the primary template.
2473 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall069c23a2009-07-31 02:45:11 +00002474 << (TUK == TUK_Definition)
Douglas Gregor42476442009-06-12 22:08:06 +00002475 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2476 RAngleLoc));
John McCall069c23a2009-07-31 02:45:11 +00002477 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor42476442009-06-12 22:08:06 +00002478 ClassTemplate->getIdentifier(),
2479 TemplateNameLoc,
2480 Attr,
2481 move(TemplateParameterLists),
2482 AS_none);
2483 }
2484
Douglas Gregor58944ac2009-05-31 09:31:02 +00002485 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002486 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002487 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002488 Converted.flatSize(),
2489 Context);
Mike Stump90fc78e2009-08-04 21:02:39 +00002490 } else
Anders Carlssona35faf92009-06-05 03:43:12 +00002491 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002492 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002493 Converted.flatSize(),
2494 Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002495 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002496 ClassTemplateSpecializationDecl *PrevDecl = 0;
2497
2498 if (isPartialSpecialization)
2499 PrevDecl
2500 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2501 InsertPos);
2502 else
2503 PrevDecl
2504 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002505
2506 ClassTemplateSpecializationDecl *Specialization = 0;
2507
Douglas Gregor0d93f692009-02-25 22:02:03 +00002508 // Check whether we can declare a class template specialization in
2509 // the current scope.
2510 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2511 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002512 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002513 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002514 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002515 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002516
Douglas Gregor1930d202009-07-30 17:40:51 +00002517 // The canonical type
2518 QualType CanonType;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002519 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2520 // Since the only prior class template specialization with these
2521 // arguments was referenced but not declared, reuse that
2522 // declaration node as our own, updating its source location to
2523 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002524 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002525 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002526 PrevDecl = 0;
Douglas Gregor1930d202009-07-30 17:40:51 +00002527 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002528 } else if (isPartialSpecialization) {
Douglas Gregor1930d202009-07-30 17:40:51 +00002529 // Build the canonical type that describes the converted template
2530 // arguments of the class template partial specialization.
2531 CanonType = Context.getTemplateSpecializationType(
2532 TemplateName(ClassTemplate),
2533 Converted.getFlatArguments(),
2534 Converted.flatSize());
2535
Douglas Gregor58944ac2009-05-31 09:31:02 +00002536 // Create a new class template partial specialization declaration node.
2537 TemplateParameterList *TemplateParams
2538 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2539 ClassTemplatePartialSpecializationDecl *PrevPartial
2540 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2541 ClassTemplatePartialSpecializationDecl *Partial
2542 = ClassTemplatePartialSpecializationDecl::Create(Context,
2543 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002544 TemplateNameLoc,
2545 TemplateParams,
2546 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002547 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002548 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002549
2550 if (PrevPartial) {
2551 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2552 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2553 } else {
2554 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2555 }
2556 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002557
2558 // Check that all of the template parameters of the class template
2559 // partial specialization are deducible from the template
2560 // arguments. If not, this class template partial specialization
2561 // will never be used.
2562 llvm::SmallVector<bool, 8> DeducibleParams;
2563 DeducibleParams.resize(TemplateParams->size());
2564 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2565 unsigned NumNonDeducible = 0;
2566 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2567 if (!DeducibleParams[I])
2568 ++NumNonDeducible;
2569
2570 if (NumNonDeducible) {
2571 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2572 << (NumNonDeducible > 1)
2573 << SourceRange(TemplateNameLoc, RAngleLoc);
2574 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2575 if (!DeducibleParams[I]) {
2576 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2577 if (Param->getDeclName())
2578 Diag(Param->getLocation(),
2579 diag::note_partial_spec_unused_parameter)
2580 << Param->getDeclName();
2581 else
2582 Diag(Param->getLocation(),
2583 diag::note_partial_spec_unused_parameter)
2584 << std::string("<anonymous>");
2585 }
2586 }
2587 }
Douglas Gregora08b6c72009-02-17 23:15:12 +00002588 } else {
2589 // Create a new class template specialization declaration node for
2590 // this explicit specialization.
2591 Specialization
2592 = ClassTemplateSpecializationDecl::Create(Context,
2593 ClassTemplate->getDeclContext(),
2594 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002595 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002596 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002597 PrevDecl);
2598
2599 if (PrevDecl) {
2600 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2601 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2602 } else {
2603 ClassTemplate->getSpecializations().InsertNode(Specialization,
2604 InsertPos);
2605 }
Douglas Gregor1930d202009-07-30 17:40:51 +00002606
2607 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002608 }
2609
2610 // Note that this is an explicit specialization.
2611 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2612
2613 // Check that this isn't a redefinition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002614 if (TUK == TUK_Definition) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002615 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002616 // FIXME: Should also handle explicit specialization after implicit
2617 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002618 SourceRange Range(TemplateNameLoc, RAngleLoc);
2619 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002620 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002621 Diag(Def->getLocation(), diag::note_previous_definition);
2622 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002623 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002624 }
2625 }
2626
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002627 // Build the fully-sugared type for this class template
2628 // specialization as the user wrote in the specialization
2629 // itself. This means that we'll pretty-print the type retrieved
2630 // from the specialization's declaration the way that the user
2631 // actually wrote the specialization, rather than formatting the
2632 // name based on the "canonical" representation used to store the
2633 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002634 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002635 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002636 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002637 TemplateArgs.size(),
Douglas Gregor1930d202009-07-30 17:40:51 +00002638 CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +00002639 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002640 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002641
Douglas Gregor50113ca2009-02-25 22:18:32 +00002642 // C++ [temp.expl.spec]p9:
2643 // A template explicit specialization is in the scope of the
2644 // namespace in which the template was defined.
2645 //
2646 // We actually implement this paragraph where we set the semantic
2647 // context (in the creation of the ClassTemplateSpecializationDecl),
2648 // but we also maintain the lexical context where the actual
2649 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002650 Specialization->setLexicalDeclContext(CurContext);
2651
2652 // We may be starting the definition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002653 if (TUK == TUK_Definition)
Douglas Gregora08b6c72009-02-17 23:15:12 +00002654 Specialization->startDefinition();
2655
2656 // Add the specialization into its lexical context, so that it can
2657 // be seen when iterating through the list of declarations in that
2658 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002659 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002660 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002661}
Douglas Gregord3022602009-03-27 23:10:48 +00002662
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002663Sema::DeclPtrTy
2664Sema::ActOnTemplateDeclarator(Scope *S,
2665 MultiTemplateParamsArg TemplateParameterLists,
2666 Declarator &D) {
2667 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2668}
2669
Douglas Gregor19d10652009-06-24 00:54:41 +00002670Sema::DeclPtrTy
2671Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2672 MultiTemplateParamsArg TemplateParameterLists,
2673 Declarator &D) {
2674 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2675 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2676 "Not a function declarator!");
2677 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2678
2679 if (FTI.hasPrototype) {
2680 // FIXME: Diagnose arguments without names in C.
2681 }
2682
2683 Scope *ParentScope = FnBodyScope->getParent();
2684
2685 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2686 move(TemplateParameterLists),
2687 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002688 if (FunctionTemplateDecl *FunctionTemplate
2689 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002690 return ActOnStartOfFunctionDef(FnBodyScope,
2691 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002692 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2693 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002694 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002695}
2696
Douglas Gregor96b6df92009-05-14 00:28:11 +00002697// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002698Sema::DeclResult
2699Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2700 unsigned TagSpec,
2701 SourceLocation KWLoc,
2702 const CXXScopeSpec &SS,
2703 TemplateTy TemplateD,
2704 SourceLocation TemplateNameLoc,
2705 SourceLocation LAngleLoc,
2706 ASTTemplateArgsPtr TemplateArgsIn,
2707 SourceLocation *TemplateArgLocs,
2708 SourceLocation RAngleLoc,
2709 AttributeList *Attr) {
2710 // Find the class template we're specializing
2711 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2712 ClassTemplateDecl *ClassTemplate
2713 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2714
2715 // Check that the specialization uses the same tag kind as the
2716 // original template.
2717 TagDecl::TagKind Kind;
2718 switch (TagSpec) {
2719 default: assert(0 && "Unknown tag type!");
2720 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2721 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2722 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2723 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002724 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2725 Kind, KWLoc,
2726 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002727 Diag(KWLoc, diag::err_use_with_wrong_tag)
2728 << ClassTemplate
2729 << CodeModificationHint::CreateReplacement(KWLoc,
2730 ClassTemplate->getTemplatedDecl()->getKindName());
2731 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2732 diag::note_previous_use);
2733 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2734 }
2735
Douglas Gregor90177912009-05-13 18:28:20 +00002736 // C++0x [temp.explicit]p2:
2737 // [...] An explicit instantiation shall appear in an enclosing
2738 // namespace of its template. [...]
2739 //
2740 // This is C++ DR 275.
2741 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2742 TemplateNameLoc,
2743 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002744 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002745 /*ExplicitInstantiation=*/true))
2746 return true;
2747
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002748 // Translate the parser's template argument list in our AST format.
2749 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2750 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2751
2752 // Check that the template argument list is well-formed for this
2753 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002754 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2755 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002756 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002757 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002758 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002759 return true;
2760
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002761 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002762 ClassTemplate->getTemplateParameters()->size()) &&
2763 "Converted template argument list is too short!");
2764
2765 // Find the class template specialization declaration that
2766 // corresponds to these arguments.
2767 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002768 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002769 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002770 Converted.flatSize(),
2771 Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002772 void *InsertPos = 0;
2773 ClassTemplateSpecializationDecl *PrevDecl
2774 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2775
2776 ClassTemplateSpecializationDecl *Specialization = 0;
2777
Douglas Gregor90177912009-05-13 18:28:20 +00002778 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002779 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002780 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002781 // This particular specialization has already been declared or
2782 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002783 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2784 << Context.getTypeDeclType(PrevDecl);
2785 Diag(PrevDecl->getLocation(),
2786 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002787 return DeclPtrTy::make(PrevDecl);
2788 }
2789
Douglas Gregor90177912009-05-13 18:28:20 +00002790 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002791 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002792 // For a given set of template parameters, if an explicit
2793 // instantiation of a template appears after a declaration of
2794 // an explicit specialization for that template, the explicit
2795 // instantiation has no effect.
2796 if (!getLangOptions().CPlusPlus0x) {
2797 Diag(TemplateNameLoc,
2798 diag::ext_explicit_instantiation_after_specialization)
2799 << Context.getTypeDeclType(PrevDecl);
2800 Diag(PrevDecl->getLocation(),
2801 diag::note_previous_template_specialization);
2802 }
2803
2804 // Create a new class template specialization declaration node
2805 // for this explicit specialization. This node is only used to
2806 // record the existence of this explicit instantiation for
2807 // accurate reproduction of the source code; we don't actually
2808 // use it for anything, since it is semantically irrelevant.
2809 Specialization
2810 = ClassTemplateSpecializationDecl::Create(Context,
2811 ClassTemplate->getDeclContext(),
2812 TemplateNameLoc,
2813 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002814 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002815 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002816 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002817 return DeclPtrTy::make(Specialization);
2818 }
2819
2820 // If we have already (implicitly) instantiated this
2821 // specialization, there is less work to do.
2822 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2823 SpecializationRequiresInstantiation = false;
2824
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002825 // Since the only prior class template specialization with these
2826 // arguments was referenced but not declared, reuse that
2827 // declaration node as our own, updating its source location to
2828 // reflect our new declaration.
2829 Specialization = PrevDecl;
2830 Specialization->setLocation(TemplateNameLoc);
2831 PrevDecl = 0;
2832 } else {
2833 // Create a new class template specialization declaration node for
2834 // this explicit specialization.
2835 Specialization
2836 = ClassTemplateSpecializationDecl::Create(Context,
2837 ClassTemplate->getDeclContext(),
2838 TemplateNameLoc,
2839 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002840 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002841
2842 ClassTemplate->getSpecializations().InsertNode(Specialization,
2843 InsertPos);
2844 }
2845
2846 // Build the fully-sugared type for this explicit instantiation as
2847 // the user wrote in the explicit instantiation itself. This means
2848 // that we'll pretty-print the type retrieved from the
2849 // specialization's declaration the way that the user actually wrote
2850 // the explicit instantiation, rather than formatting the name based
2851 // on the "canonical" representation used to store the template
2852 // arguments in the specialization.
2853 QualType WrittenTy
2854 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002855 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002856 TemplateArgs.size(),
2857 Context.getTypeDeclType(Specialization));
2858 Specialization->setTypeAsWritten(WrittenTy);
2859 TemplateArgsIn.release();
2860
2861 // Add the explicit instantiation into its lexical context. However,
2862 // since explicit instantiations are never found by name lookup, we
2863 // just put it into the declaration context directly.
2864 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002865 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002866
2867 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002868 // A definition of a class template or class member template
2869 // shall be in scope at the point of the explicit instantiation of
2870 // the class template or class member template.
2871 //
2872 // This check comes when we actually try to perform the
2873 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002874 if (SpecializationRequiresInstantiation)
2875 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002876 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002877 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002878
2879 return DeclPtrTy::make(Specialization);
2880}
2881
Douglas Gregor96b6df92009-05-14 00:28:11 +00002882// Explicit instantiation of a member class of a class template.
2883Sema::DeclResult
2884Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2885 unsigned TagSpec,
2886 SourceLocation KWLoc,
2887 const CXXScopeSpec &SS,
2888 IdentifierInfo *Name,
2889 SourceLocation NameLoc,
2890 AttributeList *Attr) {
2891
Douglas Gregor71f06032009-05-28 23:31:59 +00002892 bool Owned = false;
John McCall069c23a2009-07-31 02:45:11 +00002893 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor84a20812009-07-22 23:48:44 +00002894 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2895 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002896 if (!TagD)
2897 return true;
2898
2899 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2900 if (Tag->isEnum()) {
2901 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2902 << Context.getTypeDeclType(Tag);
2903 return true;
2904 }
2905
Douglas Gregord769bfa2009-05-27 17:30:49 +00002906 if (Tag->isInvalidDecl())
2907 return true;
2908
Douglas Gregor96b6df92009-05-14 00:28:11 +00002909 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2910 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2911 if (!Pattern) {
2912 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2913 << Context.getTypeDeclType(Record);
2914 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2915 return true;
2916 }
2917
2918 // C++0x [temp.explicit]p2:
2919 // [...] An explicit instantiation shall appear in an enclosing
2920 // namespace of its template. [...]
2921 //
2922 // This is C++ DR 275.
2923 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002924 // FIXME: In C++98, we would like to turn these errors into warnings,
2925 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002926 DeclContext *PatternContext
2927 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2928 if (!CurContext->Encloses(PatternContext)) {
2929 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2930 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2931 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2932 }
2933 }
2934
Douglas Gregor96b6df92009-05-14 00:28:11 +00002935 if (!Record->getDefinition(Context)) {
2936 // If the class has a definition, instantiate it (and all of its
2937 // members, recursively).
2938 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2939 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002940 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002941 /*ExplicitInstantiation=*/true))
2942 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002943 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002944 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002945 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002946
Mike Stumpe127ae32009-05-16 07:39:55 +00002947 // FIXME: We don't have any representation for explicit instantiations of
2948 // member classes. Such a representation is not needed for compilation, but it
2949 // should be available for clients that want to see all of the declarations in
2950 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002951 return TagD;
2952}
2953
Douglas Gregord3022602009-03-27 23:10:48 +00002954Sema::TypeResult
2955Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2956 const IdentifierInfo &II, SourceLocation IdLoc) {
2957 NestedNameSpecifier *NNS
2958 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2959 if (!NNS)
2960 return true;
2961
2962 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002963 if (T.isNull())
2964 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002965 return T.getAsOpaquePtr();
2966}
2967
Douglas Gregor77da5802009-04-01 00:28:59 +00002968Sema::TypeResult
2969Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2970 SourceLocation TemplateLoc, TypeTy *Ty) {
2971 QualType T = QualType::getFromOpaquePtr(Ty);
2972 NestedNameSpecifier *NNS
2973 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2974 const TemplateSpecializationType *TemplateId
2975 = T->getAsTemplateSpecializationType();
2976 assert(TemplateId && "Expected a template specialization type");
2977
2978 if (NNS->isDependent())
2979 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2980
2981 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2982}
2983
Douglas Gregord3022602009-03-27 23:10:48 +00002984/// \brief Build the type that describes a C++ typename specifier,
2985/// e.g., "typename T::type".
2986QualType
2987Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2988 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002989 CXXRecordDecl *CurrentInstantiation = 0;
2990 if (NNS->isDependent()) {
2991 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002992
Douglas Gregor3eb20702009-05-11 19:58:34 +00002993 // If the nested-name-specifier does not refer to the current
2994 // instantiation, then build a typename type.
2995 if (!CurrentInstantiation)
2996 return Context.getTypenameType(NNS, &II);
2997 }
Douglas Gregord3022602009-03-27 23:10:48 +00002998
Douglas Gregor3eb20702009-05-11 19:58:34 +00002999 DeclContext *Ctx = 0;
3000
3001 if (CurrentInstantiation)
3002 Ctx = CurrentInstantiation;
3003 else {
3004 CXXScopeSpec SS;
3005 SS.setScopeRep(NNS);
3006 SS.setRange(Range);
3007 if (RequireCompleteDeclContext(SS))
3008 return QualType();
3009
3010 Ctx = computeDeclContext(SS);
3011 }
Douglas Gregord3022602009-03-27 23:10:48 +00003012 assert(Ctx && "No declaration context?");
3013
3014 DeclarationName Name(&II);
3015 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3016 false);
3017 unsigned DiagID = 0;
3018 Decl *Referenced = 0;
3019 switch (Result.getKind()) {
3020 case LookupResult::NotFound:
3021 if (Ctx->isTranslationUnit())
3022 DiagID = diag::err_typename_nested_not_found_global;
3023 else
3024 DiagID = diag::err_typename_nested_not_found;
3025 break;
3026
3027 case LookupResult::Found:
3028 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3029 // We found a type. Build a QualifiedNameType, since the
3030 // typename-specifier was just sugar. FIXME: Tell
3031 // QualifiedNameType that it has a "typename" prefix.
3032 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3033 }
3034
3035 DiagID = diag::err_typename_nested_not_type;
3036 Referenced = Result.getAsDecl();
3037 break;
3038
3039 case LookupResult::FoundOverloaded:
3040 DiagID = diag::err_typename_nested_not_type;
3041 Referenced = *Result.begin();
3042 break;
3043
3044 case LookupResult::AmbiguousBaseSubobjectTypes:
3045 case LookupResult::AmbiguousBaseSubobjects:
3046 case LookupResult::AmbiguousReference:
3047 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3048 return QualType();
3049 }
3050
3051 // If we get here, it's because name lookup did not find a
3052 // type. Emit an appropriate diagnostic and return an error.
3053 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3054 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3055 else
3056 Diag(Range.getEnd(), DiagID) << Range << Name;
3057 if (Referenced)
3058 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3059 << Name;
3060 return QualType();
3061}
Douglas Gregor3f220e82009-08-06 16:20:37 +00003062
3063namespace {
3064 // See Sema::RebuildTypeInCurrentInstantiation
3065 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3066 : public TreeTransform<CurrentInstantiationRebuilder>
3067 {
3068 SourceLocation Loc;
3069 DeclarationName Entity;
3070
3071 public:
3072 CurrentInstantiationRebuilder(Sema &SemaRef,
3073 SourceLocation Loc,
3074 DeclarationName Entity)
3075 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3076 Loc(Loc), Entity(Entity) { }
3077
3078 /// \brief Determine whether the given type \p T has already been
3079 /// transformed.
3080 ///
3081 /// For the purposes of type reconstruction, a type has already been
3082 /// transformed if it is NULL or if it is not dependent.
3083 bool AlreadyTransformed(QualType T) {
3084 return T.isNull() || !T->isDependentType();
3085 }
3086
3087 /// \brief Returns the location of the entity whose type is being
3088 /// rebuilt.
3089 SourceLocation getBaseLocation() { return Loc; }
3090
3091 /// \brief Returns the name of the entity whose type is being rebuilt.
3092 DeclarationName getBaseEntity() { return Entity; }
3093
3094 /// \brief Transforms an expression by returning the expression itself
3095 /// (an identity function).
3096 ///
3097 /// FIXME: This is completely unsafe; we will need to actually clone the
3098 /// expressions.
3099 Sema::OwningExprResult TransformExpr(Expr *E) {
3100 return getSema().Owned(E);
3101 }
3102
3103 /// \brief Transforms a typename type by determining whether the type now
3104 /// refers to a member of the current instantiation, and then
3105 /// type-checking and building a QualifiedNameType (when possible).
3106 QualType TransformTypenameType(const TypenameType *T);
3107 };
3108}
3109
3110QualType
3111CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3112 NestedNameSpecifier *NNS
3113 = TransformNestedNameSpecifier(T->getQualifier(),
3114 /*FIXME:*/SourceRange(getBaseLocation()));
3115 if (!NNS)
3116 return QualType();
3117
3118 // If the nested-name-specifier did not change, and we cannot compute the
3119 // context corresponding to the nested-name-specifier, then this
3120 // typename type will not change; exit early.
3121 CXXScopeSpec SS;
3122 SS.setRange(SourceRange(getBaseLocation()));
3123 SS.setScopeRep(NNS);
3124 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3125 return QualType(T, 0);
3126
3127 // Rebuild the typename type, which will probably turn into a
3128 // QualifiedNameType.
3129 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3130 QualType NewTemplateId
3131 = TransformType(QualType(TemplateId, 0));
3132 if (NewTemplateId.isNull())
3133 return QualType();
3134
3135 if (NNS == T->getQualifier() &&
3136 NewTemplateId == QualType(TemplateId, 0))
3137 return QualType(T, 0);
3138
3139 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3140 }
3141
3142 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3143}
3144
3145/// \brief Rebuilds a type within the context of the current instantiation.
3146///
3147/// The type \p T is part of the type of an out-of-line member definition of
3148/// a class template (or class template partial specialization) that was parsed
3149/// and constructed before we entered the scope of the class template (or
3150/// partial specialization thereof). This routine will rebuild that type now
3151/// that we have entered the declarator's scope, which may produce different
3152/// canonical types, e.g.,
3153///
3154/// \code
3155/// template<typename T>
3156/// struct X {
3157/// typedef T* pointer;
3158/// pointer data();
3159/// };
3160///
3161/// template<typename T>
3162/// typename X<T>::pointer X<T>::data() { ... }
3163/// \endcode
3164///
3165/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3166/// since we do not know that we can look into X<T> when we parsed the type.
3167/// This function will rebuild the type, performing the lookup of "pointer"
3168/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3169/// as the canonical type of T*, allowing the return types of the out-of-line
3170/// definition and the declaration to match.
3171QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3172 DeclarationName Name) {
3173 if (T.isNull() || !T->isDependentType())
3174 return T;
3175
3176 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3177 return Rebuilder.TransformType(T);
3178}