blob: fb41b2b7536f22ad489fdfedd7cd2d3e1e9c05be [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
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()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
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 Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregord406b032009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000166 Depth, Position, ParamName, Typename,
167 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000168 if (Invalid)
169 Param->setInvalidDecl();
170
171 if (ParamName) {
172 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000173 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000174 IdResolver.AddDecl(Param);
175 }
176
Chris Lattner5261d0c2009-03-28 19:18:32 +0000177 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000178}
179
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000183 SourceLocation EqualLoc,
184 SourceLocation DefaultLoc,
185 TypeTy *DefaultT) {
186 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000187 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000188 QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
Anders Carlssona2333782009-06-12 22:30:13 +0000190 // C++0x [temp.param]p9:
191 // A default template-argument may be specified for any kind of
192 // template-parameter that is not a template parameter pack.
193 if (Parm->isParameterPack()) {
194 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000195 return;
196 }
197
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000198 // C++ [temp.param]p14:
199 // A template-parameter shall not be used in its own default argument.
200 // FIXME: Implement this check! Needs a recursive walk over the types.
201
202 // Check the template argument itself.
203 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
204 Parm->setInvalidDecl();
205 return;
206 }
207
208 Parm->setDefaultArgument(Default, DefaultLoc, false);
209}
210
Douglas Gregored3a3982009-03-03 04:44:36 +0000211/// \brief Check that the type of a non-type template parameter is
212/// well-formed.
213///
214/// \returns the (possibly-promoted) parameter type if valid;
215/// otherwise, produces a diagnostic and returns a NULL type.
216QualType
217Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
218 // C++ [temp.param]p4:
219 //
220 // A non-type template-parameter shall have one of the following
221 // (optionally cv-qualified) types:
222 //
223 // -- integral or enumeration type,
224 if (T->isIntegralType() || T->isEnumeralType() ||
225 // -- pointer to object or pointer to function,
226 (T->isPointerType() &&
227 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
228 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
229 // -- reference to object or reference to function,
230 T->isReferenceType() ||
231 // -- pointer to member.
232 T->isMemberPointerType() ||
233 // If T is a dependent type, we can't do the check now, so we
234 // assume that it is well-formed.
235 T->isDependentType())
236 return T;
237 // C++ [temp.param]p8:
238 //
239 // A non-type template-parameter of type "array of T" or
240 // "function returning T" is adjusted to be of type "pointer to
241 // T" or "pointer to function returning T", respectively.
242 else if (T->isArrayType())
243 // FIXME: Keep the type prior to promotion?
244 return Context.getArrayDecayedType(T);
245 else if (T->isFunctionType())
246 // FIXME: Keep the type prior to promotion?
247 return Context.getPointerType(T);
248
249 Diag(Loc, diag::err_template_nontype_parm_bad_type)
250 << T;
251
252 return QualType();
253}
254
Douglas Gregordd861062008-12-05 18:15:24 +0000255/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
256/// template parameter (e.g., "int Size" in "template<int Size>
257/// class Array") has been parsed. S is the current scope and D is
258/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000259Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
260 unsigned Depth,
261 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000262 QualType T = GetTypeForDeclarator(D, S);
263
Douglas Gregor279272e2009-02-04 19:02:06 +0000264 assert(S->isTemplateParamScope() &&
265 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000266 bool Invalid = false;
267
268 IdentifierInfo *ParamName = D.getIdentifier();
269 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000270 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000271 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000272 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000273 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000274 }
275
Douglas Gregored3a3982009-03-03 04:44:36 +0000276 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000277 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000278 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000279 Invalid = true;
280 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000281
Douglas Gregordd861062008-12-05 18:15:24 +0000282 NonTypeTemplateParmDecl *Param
283 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000284 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000285 if (Invalid)
286 Param->setInvalidDecl();
287
288 if (D.getIdentifier()) {
289 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000290 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000291 IdResolver.AddDecl(Param);
292 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000293 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000294}
Douglas Gregor52473432008-12-24 02:52:09 +0000295
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000296/// \brief Adds a default argument to the given non-type template
297/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000298void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000299 SourceLocation EqualLoc,
300 ExprArg DefaultE) {
301 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000302 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000303 Expr *Default = static_cast<Expr *>(DefaultE.get());
304
305 // C++ [temp.param]p14:
306 // A template-parameter shall not be used in its own default argument.
307 // FIXME: Implement this check! Needs a recursive walk over the types.
308
309 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000310 TemplateArgument Converted;
311 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
312 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000313 TemplateParm->setInvalidDecl();
314 return;
315 }
316
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000317 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000318}
319
Douglas Gregor279272e2009-02-04 19:02:06 +0000320
321/// ActOnTemplateTemplateParameter - Called when a C++ template template
322/// parameter (e.g. T in template <template <typename> class T> class array)
323/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000324Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
325 SourceLocation TmpLoc,
326 TemplateParamsTy *Params,
327 IdentifierInfo *Name,
328 SourceLocation NameLoc,
329 unsigned Depth,
330 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000331{
332 assert(S->isTemplateParamScope() &&
333 "Template template parameter not in template parameter scope!");
334
335 // Construct the parameter object.
336 TemplateTemplateParmDecl *Param =
337 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
338 Position, Name,
339 (TemplateParameterList*)Params);
340
341 // Make sure the parameter is valid.
342 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
343 // do anything yet. However, if the template parameter list or (eventual)
344 // default value is ever invalidated, that will propagate here.
345 bool Invalid = false;
346 if (Invalid) {
347 Param->setInvalidDecl();
348 }
349
350 // If the tt-param has a name, then link the identifier into the scope
351 // and lookup mechanisms.
352 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000353 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000354 IdResolver.AddDecl(Param);
355 }
356
Chris Lattner5261d0c2009-03-28 19:18:32 +0000357 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000358}
359
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000360/// \brief Adds a default argument to the given template template
361/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000362void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000363 SourceLocation EqualLoc,
364 ExprArg DefaultE) {
365 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000366 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000367
368 // Since a template-template parameter's default argument is an
369 // id-expression, it must be a DeclRefExpr.
370 DeclRefExpr *Default
371 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
372
373 // C++ [temp.param]p14:
374 // A template-parameter shall not be used in its own default argument.
375 // FIXME: Implement this check! Needs a recursive walk over the types.
376
377 // Check the well-formedness of the template argument.
378 if (!isa<TemplateDecl>(Default->getDecl())) {
379 Diag(Default->getSourceRange().getBegin(),
380 diag::err_template_arg_must_be_template)
381 << Default->getSourceRange();
382 TemplateParm->setInvalidDecl();
383 return;
384 }
385 if (CheckTemplateArgument(TemplateParm, Default)) {
386 TemplateParm->setInvalidDecl();
387 return;
388 }
389
390 DefaultE.release();
391 TemplateParm->setDefaultArgument(Default);
392}
393
Douglas Gregor52473432008-12-24 02:52:09 +0000394/// ActOnTemplateParameterList - Builds a TemplateParameterList that
395/// contains the template parameters in Params/NumParams.
396Sema::TemplateParamsTy *
397Sema::ActOnTemplateParameterList(unsigned Depth,
398 SourceLocation ExportLoc,
399 SourceLocation TemplateLoc,
400 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000401 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000402 SourceLocation RAngleLoc) {
403 if (ExportLoc.isValid())
404 Diag(ExportLoc, diag::note_template_export_unsupported);
405
Douglas Gregord406b032009-02-06 22:42:48 +0000406 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
407 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000408}
Douglas Gregor279272e2009-02-04 19:02:06 +0000409
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000410Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000411Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
412 SourceLocation KWLoc, const CXXScopeSpec &SS,
413 IdentifierInfo *Name, SourceLocation NameLoc,
414 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000415 MultiTemplateParamsArg TemplateParameterLists,
416 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000417 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
418 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000419 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000420
421 // Check that we can declare a template here.
422 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000423 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000424
425 TagDecl::TagKind Kind;
426 switch (TagSpec) {
427 default: assert(0 && "Unknown tag type!");
428 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
429 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
430 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
431 }
432
433 // There is no such thing as an unnamed class template.
434 if (!Name) {
435 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000436 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000437 }
438
439 // Find any previous declaration with this name.
440 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
441 true);
442 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
443 NamedDecl *PrevDecl = 0;
444 if (Previous.begin() != Previous.end())
445 PrevDecl = *Previous.begin();
446
Douglas Gregor23521802009-06-17 23:37:01 +0000447 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
448 PrevDecl = 0;
449
Douglas Gregord406b032009-02-06 22:42:48 +0000450 DeclContext *SemanticContext = CurContext;
451 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000452 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000453
Mike Stumpe127ae32009-05-16 07:39:55 +0000454 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000455 }
456
457 // FIXME: member templates!
458 TemplateParameterList *TemplateParams
459 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
460
461 // If there is a previous declaration with the same name, check
462 // whether this is a valid redeclaration.
463 ClassTemplateDecl *PrevClassTemplate
464 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
465 if (PrevClassTemplate) {
466 // Ensure that the template parameter lists are compatible.
467 if (!TemplateParameterListsAreEqual(TemplateParams,
468 PrevClassTemplate->getTemplateParameters(),
469 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000470 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000471
472 // C++ [temp.class]p4:
473 // In a redeclaration, partial specialization, explicit
474 // specialization or explicit instantiation of a class template,
475 // the class-key shall agree in kind with the original class
476 // template declaration (7.1.5.3).
477 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000478 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000479 Diag(KWLoc, diag::err_use_with_wrong_tag)
480 << Name
481 << CodeModificationHint::CreateReplacement(KWLoc,
482 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000483 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000484 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000485 }
486
Douglas Gregord406b032009-02-06 22:42:48 +0000487 // Check for redefinition of this class template.
488 if (TK == TK_Definition) {
489 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
490 Diag(NameLoc, diag::err_redefinition) << Name;
491 Diag(Def->getLocation(), diag::note_previous_definition);
492 // FIXME: Would it make sense to try to "forget" the previous
493 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000494 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000495 }
496 }
497 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
498 // Maybe we will complain about the shadowed template parameter.
499 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
500 // Just pretend that we didn't see the previous declaration.
501 PrevDecl = 0;
502 } else if (PrevDecl) {
503 // C++ [temp]p5:
504 // A class template shall not have the same name as any other
505 // template, class, function, object, enumeration, enumerator,
506 // namespace, or type in the same scope (3.3), except as specified
507 // in (14.5.4).
508 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
509 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000510 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000511 }
512
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000513 // Check the template parameter list of this declaration, possibly
514 // merging in the template parameter list from the previous class
515 // template declaration.
516 if (CheckTemplateParameterList(TemplateParams,
517 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
518 Invalid = true;
519
Douglas Gregor9054f982009-05-10 22:57:19 +0000520 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000521 // declaration!
522
Douglas Gregor55216ac2009-03-26 00:10:35 +0000523 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000524 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
525 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000526 PrevClassTemplate->getTemplatedDecl() : 0,
527 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000528
529 ClassTemplateDecl *NewTemplate
530 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
531 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000532 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000533 NewClass->setDescribedClassTemplate(NewTemplate);
534
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000535 // Build the type for the class template declaration now.
536 QualType T =
537 Context.getTypeDeclType(NewClass,
538 PrevClassTemplate?
539 PrevClassTemplate->getTemplatedDecl() : 0);
540 assert(T->isDependentType() && "Class template type is not dependent?");
541 (void)T;
542
Anders Carlsson4ca43492009-03-26 01:24:28 +0000543 // Set the access specifier.
544 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
545
Douglas Gregord406b032009-02-06 22:42:48 +0000546 // Set the lexical context of these templates
547 NewClass->setLexicalDeclContext(CurContext);
548 NewTemplate->setLexicalDeclContext(CurContext);
549
550 if (TK == TK_Definition)
551 NewClass->startDefinition();
552
553 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000554 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000555
556 PushOnScopeChains(NewTemplate, S);
557
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000558 if (Invalid) {
559 NewTemplate->setInvalidDecl();
560 NewClass->setInvalidDecl();
561 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000562 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000563}
564
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000565/// \brief Checks the validity of a template parameter list, possibly
566/// considering the template parameter list from a previous
567/// declaration.
568///
569/// If an "old" template parameter list is provided, it must be
570/// equivalent (per TemplateParameterListsAreEqual) to the "new"
571/// template parameter list.
572///
573/// \param NewParams Template parameter list for a new template
574/// declaration. This template parameter list will be updated with any
575/// default arguments that are carried through from the previous
576/// template parameter list.
577///
578/// \param OldParams If provided, template parameter list from a
579/// previous declaration of the same template. Default template
580/// arguments will be merged from the old template parameter list to
581/// the new template parameter list.
582///
583/// \returns true if an error occurred, false otherwise.
584bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
585 TemplateParameterList *OldParams) {
586 bool Invalid = false;
587
588 // C++ [temp.param]p10:
589 // The set of default template-arguments available for use with a
590 // template declaration or definition is obtained by merging the
591 // default arguments from the definition (if in scope) and all
592 // declarations in scope in the same way default function
593 // arguments are (8.3.6).
594 bool SawDefaultArgument = false;
595 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000596
Anders Carlssonb1929502009-06-12 23:20:15 +0000597 bool SawParameterPack = false;
598 SourceLocation ParameterPackLoc;
599
Mike Stumpe0b7e032009-02-11 23:03:27 +0000600 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000601 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000602 if (OldParams)
603 OldParam = OldParams->begin();
604
605 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
606 NewParamEnd = NewParams->end();
607 NewParam != NewParamEnd; ++NewParam) {
608 // Variables used to diagnose redundant default arguments
609 bool RedundantDefaultArg = false;
610 SourceLocation OldDefaultLoc;
611 SourceLocation NewDefaultLoc;
612
613 // Variables used to diagnose missing default arguments
614 bool MissingDefaultArg = false;
615
Anders Carlssonb1929502009-06-12 23:20:15 +0000616 // C++0x [temp.param]p11:
617 // If a template parameter of a class template is a template parameter pack,
618 // it must be the last template parameter.
619 if (SawParameterPack) {
620 Diag(ParameterPackLoc,
621 diag::err_template_param_pack_must_be_last_template_parameter);
622 Invalid = true;
623 }
624
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000625 // Merge default arguments for template type parameters.
626 if (TemplateTypeParmDecl *NewTypeParm
627 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
628 TemplateTypeParmDecl *OldTypeParm
629 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
630
Anders Carlssonb1929502009-06-12 23:20:15 +0000631 if (NewTypeParm->isParameterPack()) {
632 assert(!NewTypeParm->hasDefaultArgument() &&
633 "Parameter packs can't have a default argument!");
634 SawParameterPack = true;
635 ParameterPackLoc = NewTypeParm->getLocation();
636 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000637 NewTypeParm->hasDefaultArgument()) {
638 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
639 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
640 SawDefaultArgument = true;
641 RedundantDefaultArg = true;
642 PreviousDefaultArgLoc = NewDefaultLoc;
643 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
644 // Merge the default argument from the old declaration to the
645 // new declaration.
646 SawDefaultArgument = true;
647 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
648 OldTypeParm->getDefaultArgumentLoc(),
649 true);
650 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
651 } else if (NewTypeParm->hasDefaultArgument()) {
652 SawDefaultArgument = true;
653 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
654 } else if (SawDefaultArgument)
655 MissingDefaultArg = true;
656 }
657 // Merge default arguments for non-type template parameters
658 else if (NonTypeTemplateParmDecl *NewNonTypeParm
659 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
660 NonTypeTemplateParmDecl *OldNonTypeParm
661 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
662 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
663 NewNonTypeParm->hasDefaultArgument()) {
664 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
665 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
666 SawDefaultArgument = true;
667 RedundantDefaultArg = true;
668 PreviousDefaultArgLoc = NewDefaultLoc;
669 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
670 // Merge the default argument from the old declaration to the
671 // new declaration.
672 SawDefaultArgument = true;
673 // FIXME: We need to create a new kind of "default argument"
674 // expression that points to a previous template template
675 // parameter.
676 NewNonTypeParm->setDefaultArgument(
677 OldNonTypeParm->getDefaultArgument());
678 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
679 } else if (NewNonTypeParm->hasDefaultArgument()) {
680 SawDefaultArgument = true;
681 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
682 } else if (SawDefaultArgument)
683 MissingDefaultArg = true;
684 }
685 // Merge default arguments for template template parameters
686 else {
687 TemplateTemplateParmDecl *NewTemplateParm
688 = cast<TemplateTemplateParmDecl>(*NewParam);
689 TemplateTemplateParmDecl *OldTemplateParm
690 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
691 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
692 NewTemplateParm->hasDefaultArgument()) {
693 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
694 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
695 SawDefaultArgument = true;
696 RedundantDefaultArg = true;
697 PreviousDefaultArgLoc = NewDefaultLoc;
698 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
699 // Merge the default argument from the old declaration to the
700 // new declaration.
701 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000702 // FIXME: We need to create a new kind of "default argument" expression
703 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000704 NewTemplateParm->setDefaultArgument(
705 OldTemplateParm->getDefaultArgument());
706 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
707 } else if (NewTemplateParm->hasDefaultArgument()) {
708 SawDefaultArgument = true;
709 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
710 } else if (SawDefaultArgument)
711 MissingDefaultArg = true;
712 }
713
714 if (RedundantDefaultArg) {
715 // C++ [temp.param]p12:
716 // A template-parameter shall not be given default arguments
717 // by two different declarations in the same scope.
718 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
719 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
720 Invalid = true;
721 } else if (MissingDefaultArg) {
722 // C++ [temp.param]p11:
723 // If a template-parameter has a default template-argument,
724 // all subsequent template-parameters shall have a default
725 // template-argument supplied.
726 Diag((*NewParam)->getLocation(),
727 diag::err_template_param_default_arg_missing);
728 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
729 Invalid = true;
730 }
731
732 // If we have an old template parameter list that we're merging
733 // in, move on to the next parameter.
734 if (OldParams)
735 ++OldParam;
736 }
737
738 return Invalid;
739}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000740
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000741/// \brief Translates template arguments as provided by the parser
742/// into template arguments used by semantic analysis.
743static void
744translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
745 SourceLocation *TemplateArgLocs,
746 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
747 TemplateArgs.reserve(TemplateArgsIn.size());
748
749 void **Args = TemplateArgsIn.getArgs();
750 bool *ArgIsType = TemplateArgsIn.getArgIsType();
751 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
752 TemplateArgs.push_back(
753 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
754 QualType::getFromOpaquePtr(Args[Arg]))
755 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
756 }
757}
758
Douglas Gregoraabb8502009-03-31 00:43:58 +0000759/// \brief Build a canonical version of a template argument list.
760///
761/// This function builds a canonical version of the given template
762/// argument list, where each of the template arguments has been
763/// converted into its canonical form. This routine is typically used
764/// to canonicalize a template argument list when the template name
765/// itself is dependent. When the template name refers to an actual
766/// template declaration, Sema::CheckTemplateArgumentList should be
767/// used to check and canonicalize the template arguments.
768///
769/// \param TemplateArgs The incoming template arguments.
770///
771/// \param NumTemplateArgs The number of template arguments in \p
772/// TemplateArgs.
773///
774/// \param Canonical A vector to be filled with the canonical versions
775/// of the template arguments.
776///
777/// \param Context The ASTContext in which the template arguments live.
778static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
779 unsigned NumTemplateArgs,
780 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
781 ASTContext &Context) {
782 Canonical.reserve(NumTemplateArgs);
783 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
784 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000785 case TemplateArgument::Null:
786 assert(false && "Should never see a NULL template argument here");
787 break;
788
Douglas Gregoraabb8502009-03-31 00:43:58 +0000789 case TemplateArgument::Expression:
790 // FIXME: Build canonical expression (!)
791 Canonical.push_back(TemplateArgs[Idx]);
792 break;
793
794 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000795 Canonical.push_back(
796 TemplateArgument(SourceLocation(),
797 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000798 break;
799
800 case TemplateArgument::Integral:
801 Canonical.push_back(TemplateArgument(SourceLocation(),
802 *TemplateArgs[Idx].getAsIntegral(),
803 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000804 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000805
806 case TemplateArgument::Type: {
807 QualType CanonType
808 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
809 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000810 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000811 }
Anders Carlsson584b5062009-06-15 17:04:53 +0000812
813 case TemplateArgument::Pack:
814 assert(0 && "FIXME: Implement!");
815 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000816 }
817 }
818}
819
Douglas Gregordd13e842009-03-30 22:58:21 +0000820QualType Sema::CheckTemplateIdType(TemplateName Name,
821 SourceLocation TemplateLoc,
822 SourceLocation LAngleLoc,
823 const TemplateArgument *TemplateArgs,
824 unsigned NumTemplateArgs,
825 SourceLocation RAngleLoc) {
826 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000827 if (!Template) {
828 // The template name does not resolve to a template, so we just
829 // build a dependent template-id type.
830
831 // Canonicalize the template arguments to build the canonical
832 // template-id type.
833 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
834 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
835 CanonicalTemplateArgs, Context);
836
Douglas Gregor905406b2009-05-07 06:49:52 +0000837 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000838 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000839 = Context.getTemplateSpecializationType(CanonName,
840 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000841 CanonicalTemplateArgs.size());
842
843 // Build the dependent template-id type.
844 return Context.getTemplateSpecializationType(Name, TemplateArgs,
845 NumTemplateArgs, CanonType);
846 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000847
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000848 // Check that the template argument list is well-formed for this
849 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000850 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000851 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000852 TemplateArgs, NumTemplateArgs, RAngleLoc,
853 ConvertedTemplateArgs))
854 return QualType();
855
Anders Carlsson023cbac2009-06-15 17:56:45 +0000856 assert((ConvertedTemplateArgs.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000857 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000858 "Converted template argument list is too short!");
859
860 QualType CanonType;
861
Douglas Gregordd13e842009-03-30 22:58:21 +0000862 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000863 TemplateArgs,
864 NumTemplateArgs)) {
865 // This class template specialization is a dependent
866 // type. Therefore, its canonical type is another class template
867 // specialization type that contains all of the converted
868 // arguments in canonical form. This ensures that, e.g., A<T> and
869 // A<T, T> have identical types when A is declared as:
870 //
871 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000872 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
873 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000874 ConvertedTemplateArgs.getFlatArgumentList(),
875 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000876 } else if (ClassTemplateDecl *ClassTemplate
877 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000878 // Find the class template specialization declaration that
879 // corresponds to these arguments.
880 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000881 ClassTemplateSpecializationDecl::Profile(ID,
882 ConvertedTemplateArgs.getFlatArgumentList(),
883 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000884 void *InsertPos = 0;
885 ClassTemplateSpecializationDecl *Decl
886 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
887 if (!Decl) {
888 // This is the first time we have referenced this class template
889 // specialization. Create the canonical declaration and add it to
890 // the set of specializations.
891 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000892 ClassTemplate->getDeclContext(),
893 TemplateLoc,
894 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000895 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000896 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
897 Decl->setLexicalDeclContext(CurContext);
898 }
899
900 CanonType = Context.getTypeDeclType(Decl);
901 }
902
903 // Build the fully-sugared type for this class template
904 // specialization, which refers back to the class template
905 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000906 return Context.getTemplateSpecializationType(Name, TemplateArgs,
907 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000908}
909
Douglas Gregora08b6c72009-02-17 23:15:12 +0000910Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000911Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
912 SourceLocation LAngleLoc,
913 ASTTemplateArgsPtr TemplateArgsIn,
914 SourceLocation *TemplateArgLocs,
915 SourceLocation RAngleLoc) {
916 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000917
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000918 // Translate the parser's template argument list in our AST format.
919 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
920 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000921
Douglas Gregordd13e842009-03-30 22:58:21 +0000922 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000923 TemplateArgs.data(),
924 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000925 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000926 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000927
928 if (Result.isNull())
929 return true;
930
Douglas Gregor6f37b582009-02-09 19:34:22 +0000931 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000932}
933
Douglas Gregoraabb8502009-03-31 00:43:58 +0000934/// \brief Form a dependent template name.
935///
936/// This action forms a dependent template name given the template
937/// name and its (presumably dependent) scope specifier. For
938/// example, given "MetaFun::template apply", the scope specifier \p
939/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
940/// of the "template" keyword, and "apply" is the \p Name.
941Sema::TemplateTy
942Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
943 const IdentifierInfo &Name,
944 SourceLocation NameLoc,
945 const CXXScopeSpec &SS) {
946 if (!SS.isSet() || SS.isInvalid())
947 return TemplateTy();
948
949 NestedNameSpecifier *Qualifier
950 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
951
952 // FIXME: member of the current instantiation
953
954 if (!Qualifier->isDependent()) {
955 // C++0x [temp.names]p5:
956 // If a name prefixed by the keyword template is not the name of
957 // a template, the program is ill-formed. [Note: the keyword
958 // template may not be applied to non-template members of class
959 // templates. -end note ] [ Note: as is the case with the
960 // typename prefix, the template prefix is allowed in cases
961 // where it is not strictly necessary; i.e., when the
962 // nested-name-specifier or the expression on the left of the ->
963 // or . is not dependent on a template-parameter, or the use
964 // does not appear in the scope of a template. -end note]
965 //
966 // Note: C++03 was more strict here, because it banned the use of
967 // the "template" keyword prior to a template-name that was not a
968 // dependent name. C++ DR468 relaxed this requirement (the
969 // "template" keyword is now permitted). We follow the C++0x
970 // rules, even in C++03 mode, retroactively applying the DR.
971 TemplateTy Template;
972 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
973 if (TNK == TNK_Non_template) {
974 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
975 << &Name;
976 return TemplateTy();
977 }
978
979 return Template;
980 }
981
982 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
983}
984
Anders Carlssonfdd33cc2009-06-13 00:33:33 +0000985bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
986 const TemplateArgument &Arg,
987 TemplateArgumentListBuilder &Converted) {
988 // Check template type parameter.
989 if (Arg.getKind() != TemplateArgument::Type) {
990 // C++ [temp.arg.type]p1:
991 // A template-argument for a template-parameter which is a
992 // type shall be a type-id.
993
994 // We have a template type parameter but the template argument
995 // is not a type.
996 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
997 Diag(Param->getLocation(), diag::note_template_param_here);
998
999 return true;
1000 }
1001
1002 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1003 return true;
1004
1005 // Add the converted template type argument.
1006 Converted.push_back(
1007 TemplateArgument(Arg.getLocation(),
1008 Context.getCanonicalType(Arg.getAsType())));
1009 return false;
1010}
1011
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001012/// \brief Check that the given template argument list is well-formed
1013/// for specializing the given template.
1014bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1015 SourceLocation TemplateLoc,
1016 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001017 const TemplateArgument *TemplateArgs,
1018 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001019 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001020 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001021 TemplateParameterList *Params = Template->getTemplateParameters();
1022 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001023 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001024 bool Invalid = false;
1025
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001026 bool HasParameterPack =
1027 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1028
1029 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001030 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001031 // FIXME: point at either the first arg beyond what we can handle,
1032 // or the '>', depending on whether we have too many or too few
1033 // arguments.
1034 SourceRange Range;
1035 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001036 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001037 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1038 << (NumArgs > NumParams)
1039 << (isa<ClassTemplateDecl>(Template)? 0 :
1040 isa<FunctionTemplateDecl>(Template)? 1 :
1041 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1042 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001043 Diag(Template->getLocation(), diag::note_template_decl_here)
1044 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001045 Invalid = true;
1046 }
1047
1048 // C++ [temp.arg]p1:
1049 // [...] The type and form of each template-argument specified in
1050 // a template-id shall match the type and form specified for the
1051 // corresponding parameter declared by the template in its
1052 // template-parameter-list.
1053 unsigned ArgIdx = 0;
1054 for (TemplateParameterList::iterator Param = Params->begin(),
1055 ParamEnd = Params->end();
1056 Param != ParamEnd; ++Param, ++ArgIdx) {
1057 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001058 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001059 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001060 // Retrieve the default template argument from the template
1061 // parameter.
1062 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001063 if (TTP->isParameterPack()) {
1064 // We have an empty parameter pack.
1065 Converted.BeginParameterPack();
1066 Converted.EndParameterPack();
1067 break;
1068 }
1069
Douglas Gregorad964b32009-02-17 01:05:43 +00001070 if (!TTP->hasDefaultArgument())
1071 break;
1072
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001073 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001074
1075 // If the argument type is dependent, instantiate it now based
1076 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001077 if (ArgType->isDependentType()) {
1078 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001079 Template, Converted.getFlatArgumentList(),
1080 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001081 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001082
Anders Carlsson0233eb62009-06-05 04:47:51 +00001083 TemplateArgumentList TemplateArgs(Context, Converted,
1084 /*CopyArgs=*/false,
1085 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001086 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001087 TTP->getDefaultArgumentLoc(),
1088 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001089 }
Douglas Gregor74296542009-02-27 19:31:52 +00001090
1091 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001092 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001093
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001094 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001095 } else if (NonTypeTemplateParmDecl *NTTP
1096 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1097 if (!NTTP->hasDefaultArgument())
1098 break;
1099
Anders Carlsson0297caf2009-06-11 16:06:49 +00001100 InstantiatingTemplate Inst(*this, TemplateLoc,
1101 Template, Converted.getFlatArgumentList(),
1102 Converted.flatSize(),
1103 SourceRange(TemplateLoc, RAngleLoc));
1104
1105 TemplateArgumentList TemplateArgs(Context, Converted,
1106 /*CopyArgs=*/false,
1107 /*FlattenArgs=*/false);
1108
1109 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1110 TemplateArgs);
1111 if (E.isInvalid())
1112 return true;
1113
1114 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001115 } else {
1116 TemplateTemplateParmDecl *TempParm
1117 = cast<TemplateTemplateParmDecl>(*Param);
1118
1119 if (!TempParm->hasDefaultArgument())
1120 break;
1121
Douglas Gregored3a3982009-03-03 04:44:36 +00001122 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001123 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001124 }
1125 } else {
1126 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001127 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001128 }
1129
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001130
1131 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001132 if (TTP->isParameterPack()) {
1133 Converted.BeginParameterPack();
1134 // Check all the remaining arguments (if any).
1135 for (; ArgIdx < NumArgs; ++ArgIdx) {
1136 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1137 Invalid = true;
1138 }
1139
1140 Converted.EndParameterPack();
1141 } else {
1142 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1143 Invalid = true;
1144 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001145 } else if (NonTypeTemplateParmDecl *NTTP
1146 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1147 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001148
1149 // Instantiate the type of the non-type template parameter with
1150 // the template arguments we've seen thus far.
1151 QualType NTTPType = NTTP->getType();
1152 if (NTTPType->isDependentType()) {
1153 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001154 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001155 Template, Converted.getFlatArgumentList(),
1156 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001157 SourceRange(TemplateLoc, RAngleLoc));
1158
Anders Carlsson0233eb62009-06-05 04:47:51 +00001159 TemplateArgumentList TemplateArgs(Context, Converted,
1160 /*CopyArgs=*/false,
1161 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001162 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001163 NTTP->getLocation(),
1164 NTTP->getDeclName());
1165 // If that worked, check the non-type template parameter type
1166 // for validity.
1167 if (!NTTPType.isNull())
1168 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1169 NTTP->getLocation());
1170
1171 if (NTTPType.isNull()) {
1172 Invalid = true;
1173 break;
1174 }
1175 }
1176
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001177 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001178 case TemplateArgument::Null:
1179 assert(false && "Should never see a NULL template argument here");
1180 break;
1181
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001182 case TemplateArgument::Expression: {
1183 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001184 TemplateArgument Result;
1185 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001186 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001187 else
1188 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001189 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001190 }
1191
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001192 case TemplateArgument::Declaration:
1193 case TemplateArgument::Integral:
1194 // We've already checked this template argument, so just copy
1195 // it to the list of converted arguments.
1196 Converted.push_back(Arg);
1197 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001198
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001199 case TemplateArgument::Type:
1200 // We have a non-type template parameter but the template
1201 // argument is a type.
1202
1203 // C++ [temp.arg]p2:
1204 // In a template-argument, an ambiguity between a type-id and
1205 // an expression is resolved to a type-id, regardless of the
1206 // form of the corresponding template-parameter.
1207 //
1208 // We warn specifically about this case, since it can be rather
1209 // confusing for users.
1210 if (Arg.getAsType()->isFunctionType())
1211 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1212 << Arg.getAsType();
1213 else
1214 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1215 Diag((*Param)->getLocation(), diag::note_template_param_here);
1216 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001217 break;
1218
1219 case TemplateArgument::Pack:
1220 assert(0 && "FIXME: Implement!");
1221 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001222 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001223 } else {
1224 // Check template template parameters.
1225 TemplateTemplateParmDecl *TempParm
1226 = cast<TemplateTemplateParmDecl>(*Param);
1227
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001228 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001229 case TemplateArgument::Null:
1230 assert(false && "Should never see a NULL template argument here");
1231 break;
1232
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001233 case TemplateArgument::Expression: {
1234 Expr *ArgExpr = Arg.getAsExpr();
1235 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1236 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1237 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1238 Invalid = true;
1239
1240 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001241 Decl *D
1242 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1243 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001244 continue;
1245 }
1246 }
1247 // fall through
1248
1249 case TemplateArgument::Type: {
1250 // We have a template template parameter but the template
1251 // argument does not refer to a template.
1252 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1253 Invalid = true;
1254 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001255 }
1256
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001257 case TemplateArgument::Declaration:
1258 // We've already checked this template argument, so just copy
1259 // it to the list of converted arguments.
1260 Converted.push_back(Arg);
1261 break;
1262
1263 case TemplateArgument::Integral:
1264 assert(false && "Integral argument with template template parameter");
1265 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001266
1267 case TemplateArgument::Pack:
1268 assert(0 && "FIXME: Implement!");
1269 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001270 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001271 }
1272 }
1273
1274 return Invalid;
1275}
1276
1277/// \brief Check a template argument against its corresponding
1278/// template type parameter.
1279///
1280/// This routine implements the semantics of C++ [temp.arg.type]. It
1281/// returns true if an error occurred, and false otherwise.
1282bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1283 QualType Arg, SourceLocation ArgLoc) {
1284 // C++ [temp.arg.type]p2:
1285 // A local type, a type with no linkage, an unnamed type or a type
1286 // compounded from any of these types shall not be used as a
1287 // template-argument for a template type-parameter.
1288 //
1289 // FIXME: Perform the recursive and no-linkage type checks.
1290 const TagType *Tag = 0;
1291 if (const EnumType *EnumT = Arg->getAsEnumType())
1292 Tag = EnumT;
1293 else if (const RecordType *RecordT = Arg->getAsRecordType())
1294 Tag = RecordT;
1295 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1296 return Diag(ArgLoc, diag::err_template_arg_local_type)
1297 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001298 else if (Tag && !Tag->getDecl()->getDeclName() &&
1299 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001300 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1301 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1302 return true;
1303 }
1304
1305 return false;
1306}
1307
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001308/// \brief Checks whether the given template argument is the address
1309/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001310bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1311 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001312 bool Invalid = false;
1313
1314 // See through any implicit casts we added to fix the type.
1315 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1316 Arg = Cast->getSubExpr();
1317
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001318 // C++0x allows nullptr, and there's no further checking to be done for that.
1319 if (Arg->getType()->isNullPtrType())
1320 return false;
1321
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001322 // C++ [temp.arg.nontype]p1:
1323 //
1324 // A template-argument for a non-type, non-template
1325 // template-parameter shall be one of: [...]
1326 //
1327 // -- the address of an object or function with external
1328 // linkage, including function templates and function
1329 // template-ids but excluding non-static class members,
1330 // expressed as & id-expression where the & is optional if
1331 // the name refers to a function or array, or if the
1332 // corresponding template-parameter is a reference; or
1333 DeclRefExpr *DRE = 0;
1334
1335 // Ignore (and complain about) any excess parentheses.
1336 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1337 if (!Invalid) {
1338 Diag(Arg->getSourceRange().getBegin(),
1339 diag::err_template_arg_extra_parens)
1340 << Arg->getSourceRange();
1341 Invalid = true;
1342 }
1343
1344 Arg = Parens->getSubExpr();
1345 }
1346
1347 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1348 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1349 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1350 } else
1351 DRE = dyn_cast<DeclRefExpr>(Arg);
1352
1353 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1354 return Diag(Arg->getSourceRange().getBegin(),
1355 diag::err_template_arg_not_object_or_func_form)
1356 << Arg->getSourceRange();
1357
1358 // Cannot refer to non-static data members
1359 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1360 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1361 << Field << Arg->getSourceRange();
1362
1363 // Cannot refer to non-static member functions
1364 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1365 if (!Method->isStatic())
1366 return Diag(Arg->getSourceRange().getBegin(),
1367 diag::err_template_arg_method)
1368 << Method << Arg->getSourceRange();
1369
1370 // Functions must have external linkage.
1371 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1372 if (Func->getStorageClass() == FunctionDecl::Static) {
1373 Diag(Arg->getSourceRange().getBegin(),
1374 diag::err_template_arg_function_not_extern)
1375 << Func << Arg->getSourceRange();
1376 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1377 << true;
1378 return true;
1379 }
1380
1381 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001382 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001383 return Invalid;
1384 }
1385
1386 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1387 if (!Var->hasGlobalStorage()) {
1388 Diag(Arg->getSourceRange().getBegin(),
1389 diag::err_template_arg_object_not_extern)
1390 << Var << Arg->getSourceRange();
1391 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1392 << true;
1393 return true;
1394 }
1395
1396 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001397 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001398 return Invalid;
1399 }
1400
1401 // We found something else, but we don't know specifically what it is.
1402 Diag(Arg->getSourceRange().getBegin(),
1403 diag::err_template_arg_not_object_or_func)
1404 << Arg->getSourceRange();
1405 Diag(DRE->getDecl()->getLocation(),
1406 diag::note_template_arg_refers_here);
1407 return true;
1408}
1409
1410/// \brief Checks whether the given template argument is a pointer to
1411/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001412bool
1413Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001414 bool Invalid = false;
1415
1416 // See through any implicit casts we added to fix the type.
1417 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1418 Arg = Cast->getSubExpr();
1419
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001420 // C++0x allows nullptr, and there's no further checking to be done for that.
1421 if (Arg->getType()->isNullPtrType())
1422 return false;
1423
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001424 // C++ [temp.arg.nontype]p1:
1425 //
1426 // A template-argument for a non-type, non-template
1427 // template-parameter shall be one of: [...]
1428 //
1429 // -- a pointer to member expressed as described in 5.3.1.
1430 QualifiedDeclRefExpr *DRE = 0;
1431
1432 // Ignore (and complain about) any excess parentheses.
1433 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1434 if (!Invalid) {
1435 Diag(Arg->getSourceRange().getBegin(),
1436 diag::err_template_arg_extra_parens)
1437 << Arg->getSourceRange();
1438 Invalid = true;
1439 }
1440
1441 Arg = Parens->getSubExpr();
1442 }
1443
1444 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1445 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1446 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1447
1448 if (!DRE)
1449 return Diag(Arg->getSourceRange().getBegin(),
1450 diag::err_template_arg_not_pointer_to_member_form)
1451 << Arg->getSourceRange();
1452
1453 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1454 assert((isa<FieldDecl>(DRE->getDecl()) ||
1455 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1456 "Only non-static member pointers can make it here");
1457
1458 // Okay: this is the address of a non-static member, and therefore
1459 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001460 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001461 return Invalid;
1462 }
1463
1464 // We found something else, but we don't know specifically what it is.
1465 Diag(Arg->getSourceRange().getBegin(),
1466 diag::err_template_arg_not_pointer_to_member_form)
1467 << Arg->getSourceRange();
1468 Diag(DRE->getDecl()->getLocation(),
1469 diag::note_template_arg_refers_here);
1470 return true;
1471}
1472
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001473/// \brief Check a template argument against its corresponding
1474/// non-type template parameter.
1475///
Douglas Gregored3a3982009-03-03 04:44:36 +00001476/// This routine implements the semantics of C++ [temp.arg.nontype].
1477/// It returns true if an error occurred, and false otherwise. \p
1478/// InstantiatedParamType is the type of the non-type template
1479/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001480///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001481/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001482bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001483 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001484 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001485 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1486
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001487 // If either the parameter has a dependent type or the argument is
1488 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001489 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001490 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1491 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001492 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001493 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001494 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001495
1496 // C++ [temp.arg.nontype]p5:
1497 // The following conversions are performed on each expression used
1498 // as a non-type template-argument. If a non-type
1499 // template-argument cannot be converted to the type of the
1500 // corresponding template-parameter then the program is
1501 // ill-formed.
1502 //
1503 // -- for a non-type template-parameter of integral or
1504 // enumeration type, integral promotions (4.5) and integral
1505 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001506 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001507 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001508 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001509 // C++ [temp.arg.nontype]p1:
1510 // A template-argument for a non-type, non-template
1511 // template-parameter shall be one of:
1512 //
1513 // -- an integral constant-expression of integral or enumeration
1514 // type; or
1515 // -- the name of a non-type template-parameter; or
1516 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001517 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001518 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1519 Diag(Arg->getSourceRange().getBegin(),
1520 diag::err_template_arg_not_integral_or_enumeral)
1521 << ArgType << Arg->getSourceRange();
1522 Diag(Param->getLocation(), diag::note_template_param_here);
1523 return true;
1524 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001525 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001526 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1527 << ArgType << Arg->getSourceRange();
1528 return true;
1529 }
1530
1531 // FIXME: We need some way to more easily get the unqualified form
1532 // of the types without going all the way to the
1533 // canonical type.
1534 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1535 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1536 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1537 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1538
1539 // Try to convert the argument to the parameter's type.
1540 if (ParamType == ArgType) {
1541 // Okay: no conversion necessary
1542 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1543 !ParamType->isEnumeralType()) {
1544 // This is an integral promotion or conversion.
1545 ImpCastExprToType(Arg, ParamType);
1546 } else {
1547 // We can't perform this conversion.
1548 Diag(Arg->getSourceRange().getBegin(),
1549 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001550 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001551 Diag(Param->getLocation(), diag::note_template_param_here);
1552 return true;
1553 }
1554
Douglas Gregorafc86942009-03-14 00:20:21 +00001555 QualType IntegerType = Context.getCanonicalType(ParamType);
1556 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001557 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001558
1559 if (!Arg->isValueDependent()) {
1560 // Check that an unsigned parameter does not receive a negative
1561 // value.
1562 if (IntegerType->isUnsignedIntegerType()
1563 && (Value.isSigned() && Value.isNegative())) {
1564 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1565 << Value.toString(10) << Param->getType()
1566 << Arg->getSourceRange();
1567 Diag(Param->getLocation(), diag::note_template_param_here);
1568 return true;
1569 }
1570
1571 // Check that we don't overflow the template parameter type.
1572 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1573 if (Value.getActiveBits() > AllowedBits) {
1574 Diag(Arg->getSourceRange().getBegin(),
1575 diag::err_template_arg_too_large)
1576 << Value.toString(10) << Param->getType()
1577 << Arg->getSourceRange();
1578 Diag(Param->getLocation(), diag::note_template_param_here);
1579 return true;
1580 }
1581
1582 if (Value.getBitWidth() != AllowedBits)
1583 Value.extOrTrunc(AllowedBits);
1584 Value.setIsSigned(IntegerType->isSignedIntegerType());
1585 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001586
Douglas Gregor8f378a92009-06-11 18:10:32 +00001587 // Add the value of this argument to the list of converted
1588 // arguments. We use the bitwidth and signedness of the template
1589 // parameter.
1590 if (Arg->isValueDependent()) {
1591 // The argument is value-dependent. Create a new
1592 // TemplateArgument with the converted expression.
1593 Converted = TemplateArgument(Arg);
1594 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001595 }
1596
Douglas Gregor8f378a92009-06-11 18:10:32 +00001597 Converted = TemplateArgument(StartLoc, Value,
1598 ParamType->isEnumeralType() ? ParamType
1599 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001600 return false;
1601 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001602
Douglas Gregor3f411962009-02-11 01:18:59 +00001603 // Handle pointer-to-function, reference-to-function, and
1604 // pointer-to-member-function all in (roughly) the same way.
1605 if (// -- For a non-type template-parameter of type pointer to
1606 // function, only the function-to-pointer conversion (4.3) is
1607 // applied. If the template-argument represents a set of
1608 // overloaded functions (or a pointer to such), the matching
1609 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001610 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001611 (ParamType->isPointerType() &&
1612 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1613 // -- For a non-type template-parameter of type reference to
1614 // function, no conversions apply. If the template-argument
1615 // represents a set of overloaded functions, the matching
1616 // function is selected from the set (13.4).
1617 (ParamType->isReferenceType() &&
1618 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1619 // -- For a non-type template-parameter of type pointer to
1620 // member function, no conversions apply. If the
1621 // template-argument represents a set of overloaded member
1622 // functions, the matching member function is selected from
1623 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001624 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001625 (ParamType->isMemberPointerType() &&
1626 ParamType->getAsMemberPointerType()->getPointeeType()
1627 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001628 if (Context.hasSameUnqualifiedType(ArgType,
1629 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001630 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001631 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1632 ParamType->isMemberPointerType())) {
1633 ArgType = ParamType;
1634 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001635 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001636 ArgType = Context.getPointerType(ArgType);
1637 ImpCastExprToType(Arg, ArgType);
1638 } else if (FunctionDecl *Fn
1639 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001640 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1641 return true;
1642
Douglas Gregor2eedd992009-02-11 00:19:33 +00001643 FixOverloadedFunctionReference(Arg, Fn);
1644 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001645 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001646 ArgType = Context.getPointerType(Arg->getType());
1647 ImpCastExprToType(Arg, ArgType);
1648 }
1649 }
1650
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001651 if (!Context.hasSameUnqualifiedType(ArgType,
1652 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001653 // We can't perform this conversion.
1654 Diag(Arg->getSourceRange().getBegin(),
1655 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001656 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001657 Diag(Param->getLocation(), diag::note_template_param_here);
1658 return true;
1659 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001660
Douglas Gregorad964b32009-02-17 01:05:43 +00001661 if (ParamType->isMemberPointerType()) {
1662 NamedDecl *Member = 0;
1663 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1664 return true;
1665
Douglas Gregor8f378a92009-06-11 18:10:32 +00001666 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1667 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001668 return false;
1669 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001670
Douglas Gregorad964b32009-02-17 01:05:43 +00001671 NamedDecl *Entity = 0;
1672 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1673 return true;
1674
Douglas Gregor8f378a92009-06-11 18:10:32 +00001675 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1676 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001677 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001678 }
1679
Chris Lattner320dff22009-02-20 21:37:53 +00001680 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001681 // -- for a non-type template-parameter of type pointer to
1682 // object, qualification conversions (4.4) and the
1683 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001684 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001685 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001686 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001687
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001688 if (ArgType->isNullPtrType()) {
1689 ArgType = ParamType;
1690 ImpCastExprToType(Arg, ParamType);
1691 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001692 ArgType = Context.getArrayDecayedType(ArgType);
1693 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001694 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001695
Douglas Gregor3f411962009-02-11 01:18:59 +00001696 if (IsQualificationConversion(ArgType, ParamType)) {
1697 ArgType = ParamType;
1698 ImpCastExprToType(Arg, ParamType);
1699 }
1700
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001701 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001702 // We can't perform this conversion.
1703 Diag(Arg->getSourceRange().getBegin(),
1704 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001705 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001706 Diag(Param->getLocation(), diag::note_template_param_here);
1707 return true;
1708 }
1709
Douglas Gregorad964b32009-02-17 01:05:43 +00001710 NamedDecl *Entity = 0;
1711 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1712 return true;
1713
Douglas Gregor8f378a92009-06-11 18:10:32 +00001714 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1715 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001716 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001717 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001718
1719 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1720 // -- For a non-type template-parameter of type reference to
1721 // object, no conversions apply. The type referred to by the
1722 // reference may be more cv-qualified than the (otherwise
1723 // identical) type of the template-argument. The
1724 // template-parameter is bound directly to the
1725 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001726 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001727 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001728
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001729 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001730 Diag(Arg->getSourceRange().getBegin(),
1731 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001732 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001733 << Arg->getSourceRange();
1734 Diag(Param->getLocation(), diag::note_template_param_here);
1735 return true;
1736 }
1737
1738 unsigned ParamQuals
1739 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1740 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1741
1742 if ((ParamQuals | ArgQuals) != ParamQuals) {
1743 Diag(Arg->getSourceRange().getBegin(),
1744 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001745 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001746 << Arg->getSourceRange();
1747 Diag(Param->getLocation(), diag::note_template_param_here);
1748 return true;
1749 }
1750
Douglas Gregorad964b32009-02-17 01:05:43 +00001751 NamedDecl *Entity = 0;
1752 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1753 return true;
1754
Douglas Gregor8f378a92009-06-11 18:10:32 +00001755 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1756 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001757 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001758 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001759
1760 // -- For a non-type template-parameter of type pointer to data
1761 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001762 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001763 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1764
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001765 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001766 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001767 } else if (ArgType->isNullPtrType()) {
1768 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001769 } else if (IsQualificationConversion(ArgType, ParamType)) {
1770 ImpCastExprToType(Arg, ParamType);
1771 } else {
1772 // We can't perform this conversion.
1773 Diag(Arg->getSourceRange().getBegin(),
1774 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001775 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001776 Diag(Param->getLocation(), diag::note_template_param_here);
1777 return true;
1778 }
1779
Douglas Gregorad964b32009-02-17 01:05:43 +00001780 NamedDecl *Member = 0;
1781 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1782 return true;
1783
Douglas Gregor8f378a92009-06-11 18:10:32 +00001784 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1785 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001786 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001787}
1788
1789/// \brief Check a template argument against its corresponding
1790/// template template parameter.
1791///
1792/// This routine implements the semantics of C++ [temp.arg.template].
1793/// It returns true if an error occurred, and false otherwise.
1794bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1795 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001796 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1797 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1798
1799 // C++ [temp.arg.template]p1:
1800 // A template-argument for a template template-parameter shall be
1801 // the name of a class template, expressed as id-expression. Only
1802 // primary class templates are considered when matching the
1803 // template template argument with the corresponding parameter;
1804 // partial specializations are not considered even if their
1805 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001806 //
1807 // Note that we also allow template template parameters here, which
1808 // will happen when we are dealing with, e.g., class template
1809 // partial specializations.
1810 if (!isa<ClassTemplateDecl>(Template) &&
1811 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001812 assert(isa<FunctionTemplateDecl>(Template) &&
1813 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001814 Diag(Arg->getSourceRange().getBegin(),
1815 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001816 << Template;
1817 }
1818
1819 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1820 Param->getTemplateParameters(),
1821 true, true,
1822 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001823}
1824
Douglas Gregord406b032009-02-06 22:42:48 +00001825/// \brief Determine whether the given template parameter lists are
1826/// equivalent.
1827///
1828/// \param New The new template parameter list, typically written in the
1829/// source code as part of a new template declaration.
1830///
1831/// \param Old The old template parameter list, typically found via
1832/// name lookup of the template declared with this template parameter
1833/// list.
1834///
1835/// \param Complain If true, this routine will produce a diagnostic if
1836/// the template parameter lists are not equivalent.
1837///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001838/// \param IsTemplateTemplateParm If true, this routine is being
1839/// called to compare the template parameter lists of a template
1840/// template parameter.
1841///
1842/// \param TemplateArgLoc If this source location is valid, then we
1843/// are actually checking the template parameter list of a template
1844/// argument (New) against the template parameter list of its
1845/// corresponding template template parameter (Old). We produce
1846/// slightly different diagnostics in this scenario.
1847///
Douglas Gregord406b032009-02-06 22:42:48 +00001848/// \returns True if the template parameter lists are equal, false
1849/// otherwise.
1850bool
1851Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1852 TemplateParameterList *Old,
1853 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001854 bool IsTemplateTemplateParm,
1855 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001856 if (Old->size() != New->size()) {
1857 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001858 unsigned NextDiag = diag::err_template_param_list_different_arity;
1859 if (TemplateArgLoc.isValid()) {
1860 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1861 NextDiag = diag::note_template_param_list_different_arity;
1862 }
1863 Diag(New->getTemplateLoc(), NextDiag)
1864 << (New->size() > Old->size())
1865 << IsTemplateTemplateParm
1866 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001867 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1868 << IsTemplateTemplateParm
1869 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1870 }
1871
1872 return false;
1873 }
1874
1875 for (TemplateParameterList::iterator OldParm = Old->begin(),
1876 OldParmEnd = Old->end(), NewParm = New->begin();
1877 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1878 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001879 unsigned NextDiag = diag::err_template_param_different_kind;
1880 if (TemplateArgLoc.isValid()) {
1881 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1882 NextDiag = diag::note_template_param_different_kind;
1883 }
1884 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001885 << IsTemplateTemplateParm;
1886 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1887 << IsTemplateTemplateParm;
1888 return false;
1889 }
1890
1891 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1892 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001893 // know we're at the same index).
1894#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001895 // FIXME: Enable this code in debug mode *after* we properly go through
1896 // and "instantiate" the template parameter lists of template template
1897 // parameters. It's only after this instantiation that (1) any dependent
1898 // types within the template parameter list of the template template
1899 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001900 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001901 QualType OldParmType
1902 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1903 QualType NewParmType
1904 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1905 assert(Context.getCanonicalType(OldParmType) ==
1906 Context.getCanonicalType(NewParmType) &&
1907 "type parameter mismatch?");
1908#endif
1909 } else if (NonTypeTemplateParmDecl *OldNTTP
1910 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1911 // The types of non-type template parameters must agree.
1912 NonTypeTemplateParmDecl *NewNTTP
1913 = cast<NonTypeTemplateParmDecl>(*NewParm);
1914 if (Context.getCanonicalType(OldNTTP->getType()) !=
1915 Context.getCanonicalType(NewNTTP->getType())) {
1916 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001917 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1918 if (TemplateArgLoc.isValid()) {
1919 Diag(TemplateArgLoc,
1920 diag::err_template_arg_template_params_mismatch);
1921 NextDiag = diag::note_template_nontype_parm_different_type;
1922 }
1923 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001924 << NewNTTP->getType()
1925 << IsTemplateTemplateParm;
1926 Diag(OldNTTP->getLocation(),
1927 diag::note_template_nontype_parm_prev_declaration)
1928 << OldNTTP->getType();
1929 }
1930 return false;
1931 }
1932 } else {
1933 // The template parameter lists of template template
1934 // parameters must agree.
1935 // FIXME: Could we perform a faster "type" comparison here?
1936 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1937 "Only template template parameters handled here");
1938 TemplateTemplateParmDecl *OldTTP
1939 = cast<TemplateTemplateParmDecl>(*OldParm);
1940 TemplateTemplateParmDecl *NewTTP
1941 = cast<TemplateTemplateParmDecl>(*NewParm);
1942 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1943 OldTTP->getTemplateParameters(),
1944 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001945 /*IsTemplateTemplateParm=*/true,
1946 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001947 return false;
1948 }
1949 }
1950
1951 return true;
1952}
1953
1954/// \brief Check whether a template can be declared within this scope.
1955///
1956/// If the template declaration is valid in this scope, returns
1957/// false. Otherwise, issues a diagnostic and returns true.
1958bool
1959Sema::CheckTemplateDeclScope(Scope *S,
1960 MultiTemplateParamsArg &TemplateParameterLists) {
1961 assert(TemplateParameterLists.size() > 0 && "Not a template");
1962
1963 // Find the nearest enclosing declaration scope.
1964 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1965 (S->getFlags() & Scope::TemplateParamScope) != 0)
1966 S = S->getParent();
1967
1968 TemplateParameterList *TemplateParams =
1969 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1970 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1971 SourceRange TemplateRange
1972 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1973
1974 // C++ [temp]p2:
1975 // A template-declaration can appear only as a namespace scope or
1976 // class scope declaration.
1977 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1978 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1979 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1980 return Diag(TemplateLoc, diag::err_template_linkage)
1981 << TemplateRange;
1982
1983 Ctx = Ctx->getParent();
1984 }
1985
1986 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1987 return false;
1988
1989 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1990 << TemplateRange;
1991}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001992
Douglas Gregor90177912009-05-13 18:28:20 +00001993/// \brief Check whether a class template specialization or explicit
1994/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001995///
Douglas Gregor90177912009-05-13 18:28:20 +00001996/// This routine determines whether a class template specialization or
1997/// explicit instantiation can be declared in the current context
1998/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1999/// appropriate diagnostics if there was an error. It returns true if
2000// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002001bool
2002Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2003 ClassTemplateSpecializationDecl *PrevDecl,
2004 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002005 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002006 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002007 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002008 // C++ [temp.expl.spec]p2:
2009 // An explicit specialization shall be declared in the namespace
2010 // of which the template is a member, or, for member templates, in
2011 // the namespace of which the enclosing class or enclosing class
2012 // template is a member. An explicit specialization of a member
2013 // function, member class or static data member of a class
2014 // template shall be declared in the namespace of which the class
2015 // template is a member. Such a declaration may also be a
2016 // definition. If the declaration is not a definition, the
2017 // specialization may be defined later in the name- space in which
2018 // the explicit specialization was declared, or in a namespace
2019 // that encloses the one in which the explicit specialization was
2020 // declared.
2021 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002022 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002023 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002024 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002025 return true;
2026 }
2027
2028 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2029 DeclContext *TemplateContext
2030 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002031 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2032 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002033 // There is no prior declaration of this entity, so this
2034 // specialization must be in the same context as the template
2035 // itself.
2036 if (DC != TemplateContext) {
2037 if (isa<TranslationUnitDecl>(TemplateContext))
2038 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002039 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002040 << ClassTemplate << ScopeSpecifierRange;
2041 else if (isa<NamespaceDecl>(TemplateContext))
2042 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002043 << PartialSpecialization << ClassTemplate
2044 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002045
2046 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2047 }
2048
2049 return false;
2050 }
2051
2052 // We have a previous declaration of this entity. Make sure that
2053 // this redeclaration (or definition) occurs in an enclosing namespace.
2054 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002055 // FIXME: In C++98, we would like to turn these errors into warnings,
2056 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002057 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002058 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002059 if (isa<TranslationUnitDecl>(TemplateContext)) {
2060 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2061 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002062 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002063 else
2064 SuppressedDiag = true;
2065 } else if (isa<NamespaceDecl>(TemplateContext)) {
2066 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2067 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002068 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002069 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2070 else
2071 SuppressedDiag = true;
2072 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002073
Douglas Gregor90177912009-05-13 18:28:20 +00002074 if (!SuppressedDiag)
2075 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002076 }
2077
2078 return false;
2079}
2080
Douglas Gregor76e79952009-06-12 21:21:02 +00002081/// \brief Check the non-type template arguments of a class template
2082/// partial specialization according to C++ [temp.class.spec]p9.
2083///
Douglas Gregor42476442009-06-12 22:08:06 +00002084/// \param TemplateParams the template parameters of the primary class
2085/// template.
2086///
2087/// \param TemplateArg the template arguments of the class template
2088/// partial specialization.
2089///
2090/// \param MirrorsPrimaryTemplate will be set true if the class
2091/// template partial specialization arguments are identical to the
2092/// implicit template arguments of the primary template. This is not
2093/// necessarily an error (C++0x), and it is left to the caller to diagnose
2094/// this condition when it is an error.
2095///
Douglas Gregor76e79952009-06-12 21:21:02 +00002096/// \returns true if there was an error, false otherwise.
2097bool Sema::CheckClassTemplatePartialSpecializationArgs(
2098 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002099 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002100 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002101 // FIXME: the interface to this function will have to change to
2102 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002103 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002104
2105 const TemplateArgument *ArgList = TemplateArgs.getFlatArgumentList();
2106
Douglas Gregor76e79952009-06-12 21:21:02 +00002107 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002108 // Determine whether the template argument list of the partial
2109 // specialization is identical to the implicit argument list of
2110 // the primary template. The caller may need to diagnostic this as
2111 // an error per C++ [temp.class.spec]p9b3.
2112 if (MirrorsPrimaryTemplate) {
2113 if (TemplateTypeParmDecl *TTP
2114 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2115 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002116 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002117 MirrorsPrimaryTemplate = false;
2118 } else if (TemplateTemplateParmDecl *TTP
2119 = dyn_cast<TemplateTemplateParmDecl>(
2120 TemplateParams->getParam(I))) {
2121 // FIXME: We should settle on either Declaration storage or
2122 // Expression storage for template template parameters.
2123 TemplateTemplateParmDecl *ArgDecl
2124 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002125 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002126 if (!ArgDecl)
2127 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002128 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002129 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2130
2131 if (!ArgDecl ||
2132 ArgDecl->getIndex() != TTP->getIndex() ||
2133 ArgDecl->getDepth() != TTP->getDepth())
2134 MirrorsPrimaryTemplate = false;
2135 }
2136 }
2137
Douglas Gregor76e79952009-06-12 21:21:02 +00002138 NonTypeTemplateParmDecl *Param
2139 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002140 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002141 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002142 }
2143
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002144 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002145 if (!ArgExpr) {
2146 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002147 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002148 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002149
2150 // C++ [temp.class.spec]p8:
2151 // A non-type argument is non-specialized if it is the name of a
2152 // non-type parameter. All other non-type arguments are
2153 // specialized.
2154 //
2155 // Below, we check the two conditions that only apply to
2156 // specialized non-type arguments, so skip any non-specialized
2157 // arguments.
2158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002159 if (NonTypeTemplateParmDecl *NTTP
2160 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2161 if (MirrorsPrimaryTemplate &&
2162 (Param->getIndex() != NTTP->getIndex() ||
2163 Param->getDepth() != NTTP->getDepth()))
2164 MirrorsPrimaryTemplate = false;
2165
Douglas Gregor76e79952009-06-12 21:21:02 +00002166 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002167 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002168
2169 // C++ [temp.class.spec]p9:
2170 // Within the argument list of a class template partial
2171 // specialization, the following restrictions apply:
2172 // -- A partially specialized non-type argument expression
2173 // shall not involve a template parameter of the partial
2174 // specialization except when the argument expression is a
2175 // simple identifier.
2176 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2177 Diag(ArgExpr->getLocStart(),
2178 diag::err_dependent_non_type_arg_in_partial_spec)
2179 << ArgExpr->getSourceRange();
2180 return true;
2181 }
2182
2183 // -- The type of a template parameter corresponding to a
2184 // specialized non-type argument shall not be dependent on a
2185 // parameter of the specialization.
2186 if (Param->getType()->isDependentType()) {
2187 Diag(ArgExpr->getLocStart(),
2188 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2189 << Param->getType()
2190 << ArgExpr->getSourceRange();
2191 Diag(Param->getLocation(), diag::note_template_param_here);
2192 return true;
2193 }
Douglas Gregor42476442009-06-12 22:08:06 +00002194
2195 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002196 }
2197
2198 return false;
2199}
2200
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002201Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002202Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2203 SourceLocation KWLoc,
2204 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002205 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002206 SourceLocation TemplateNameLoc,
2207 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002208 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002209 SourceLocation *TemplateArgLocs,
2210 SourceLocation RAngleLoc,
2211 AttributeList *Attr,
2212 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002213 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002214 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002215 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002216 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002217
Douglas Gregor58944ac2009-05-31 09:31:02 +00002218 bool isPartialSpecialization = false;
2219
Douglas Gregor0d93f692009-02-25 22:02:03 +00002220 // Check the validity of the template headers that introduce this
2221 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002222 // FIXME: Once we have member templates, we'll need to check
2223 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2224 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002225 if (TemplateParameterLists.size() == 0)
2226 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002227 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002228 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002229 TemplateParameterList *TemplateParams
2230 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002231 if (TemplateParameterLists.size() > 1) {
2232 Diag(TemplateParams->getTemplateLoc(),
2233 diag::err_template_spec_extra_headers);
2234 return true;
2235 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002236
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002237 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002238 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002239
2240 // C++ [temp.class.spec]p10:
2241 // The template parameter list of a specialization shall not
2242 // contain default template argument values.
2243 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2244 Decl *Param = TemplateParams->getParam(I);
2245 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2246 if (TTP->hasDefaultArgument()) {
2247 Diag(TTP->getDefaultArgumentLoc(),
2248 diag::err_default_arg_in_partial_spec);
2249 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2250 }
2251 } else if (NonTypeTemplateParmDecl *NTTP
2252 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2253 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2254 Diag(NTTP->getDefaultArgumentLoc(),
2255 diag::err_default_arg_in_partial_spec)
2256 << DefArg->getSourceRange();
2257 NTTP->setDefaultArgument(0);
2258 DefArg->Destroy(Context);
2259 }
2260 } else {
2261 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2262 if (Expr *DefArg = TTP->getDefaultArgument()) {
2263 Diag(TTP->getDefaultArgumentLoc(),
2264 diag::err_default_arg_in_partial_spec)
2265 << DefArg->getSourceRange();
2266 TTP->setDefaultArgument(0);
2267 DefArg->Destroy(Context);
2268 }
2269 }
2270 }
2271 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002272 }
2273
Douglas Gregora08b6c72009-02-17 23:15:12 +00002274 // Check that the specialization uses the same tag kind as the
2275 // original template.
2276 TagDecl::TagKind Kind;
2277 switch (TagSpec) {
2278 default: assert(0 && "Unknown tag type!");
2279 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2280 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2281 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2282 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002283 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2284 Kind, KWLoc,
2285 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002286 Diag(KWLoc, diag::err_use_with_wrong_tag)
2287 << ClassTemplate
2288 << CodeModificationHint::CreateReplacement(KWLoc,
2289 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002290 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2291 diag::note_previous_use);
2292 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2293 }
2294
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002295 // Translate the parser's template argument list in our AST format.
2296 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2297 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2298
Douglas Gregora08b6c72009-02-17 23:15:12 +00002299 // Check that the template argument list is well-formed for this
2300 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002301 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002302 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002303 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002304 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002305 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002306
Anders Carlsson023cbac2009-06-15 17:56:45 +00002307 assert((ConvertedTemplateArgs.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002308 ClassTemplate->getTemplateParameters()->size()) &&
2309 "Converted template argument list is too short!");
2310
Douglas Gregor58944ac2009-05-31 09:31:02 +00002311 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002312 // corresponds to these arguments.
2313 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002314 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002315 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002316 if (CheckClassTemplatePartialSpecializationArgs(
2317 ClassTemplate->getTemplateParameters(),
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002318 ConvertedTemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002319 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002320 return true;
2321
Douglas Gregor42476442009-06-12 22:08:06 +00002322 if (MirrorsPrimaryTemplate) {
2323 // C++ [temp.class.spec]p9b3:
2324 //
2325 // -- The argument list of the specialization shall not be identical
2326 // to the implicit argument list of the primary template.
2327 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2328 << (TK == TK_Definition)
2329 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2330 RAngleLoc));
2331 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2332 ClassTemplate->getIdentifier(),
2333 TemplateNameLoc,
2334 Attr,
2335 move(TemplateParameterLists),
2336 AS_none);
2337 }
2338
Douglas Gregor58944ac2009-05-31 09:31:02 +00002339 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002340 ClassTemplatePartialSpecializationDecl::Profile(ID,
2341 ConvertedTemplateArgs.getFlatArgumentList(),
2342 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002343 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002344 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002345 ClassTemplateSpecializationDecl::Profile(ID,
2346 ConvertedTemplateArgs.getFlatArgumentList(),
2347 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002348 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002349 ClassTemplateSpecializationDecl *PrevDecl = 0;
2350
2351 if (isPartialSpecialization)
2352 PrevDecl
2353 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2354 InsertPos);
2355 else
2356 PrevDecl
2357 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002358
2359 ClassTemplateSpecializationDecl *Specialization = 0;
2360
Douglas Gregor0d93f692009-02-25 22:02:03 +00002361 // Check whether we can declare a class template specialization in
2362 // the current scope.
2363 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2364 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002365 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002366 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002367 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002368 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002369
Douglas Gregora08b6c72009-02-17 23:15:12 +00002370 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2371 // Since the only prior class template specialization with these
2372 // arguments was referenced but not declared, reuse that
2373 // declaration node as our own, updating its source location to
2374 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002375 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002376 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002377 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002378 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002379 // Create a new class template partial specialization declaration node.
2380 TemplateParameterList *TemplateParams
2381 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2382 ClassTemplatePartialSpecializationDecl *PrevPartial
2383 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2384 ClassTemplatePartialSpecializationDecl *Partial
2385 = ClassTemplatePartialSpecializationDecl::Create(Context,
2386 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002387 TemplateNameLoc,
2388 TemplateParams,
2389 ClassTemplate,
2390 ConvertedTemplateArgs,
2391 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002392
2393 if (PrevPartial) {
2394 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2395 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2396 } else {
2397 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2398 }
2399 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002400
2401 // Check that all of the template parameters of the class template
2402 // partial specialization are deducible from the template
2403 // arguments. If not, this class template partial specialization
2404 // will never be used.
2405 llvm::SmallVector<bool, 8> DeducibleParams;
2406 DeducibleParams.resize(TemplateParams->size());
2407 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2408 unsigned NumNonDeducible = 0;
2409 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2410 if (!DeducibleParams[I])
2411 ++NumNonDeducible;
2412
2413 if (NumNonDeducible) {
2414 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2415 << (NumNonDeducible > 1)
2416 << SourceRange(TemplateNameLoc, RAngleLoc);
2417 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2418 if (!DeducibleParams[I]) {
2419 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2420 if (Param->getDeclName())
2421 Diag(Param->getLocation(),
2422 diag::note_partial_spec_unused_parameter)
2423 << Param->getDeclName();
2424 else
2425 Diag(Param->getLocation(),
2426 diag::note_partial_spec_unused_parameter)
2427 << std::string("<anonymous>");
2428 }
2429 }
2430 }
2431
Douglas Gregora08b6c72009-02-17 23:15:12 +00002432 } else {
2433 // Create a new class template specialization declaration node for
2434 // this explicit specialization.
2435 Specialization
2436 = ClassTemplateSpecializationDecl::Create(Context,
2437 ClassTemplate->getDeclContext(),
2438 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002439 ClassTemplate,
2440 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002441 PrevDecl);
2442
2443 if (PrevDecl) {
2444 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2445 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2446 } else {
2447 ClassTemplate->getSpecializations().InsertNode(Specialization,
2448 InsertPos);
2449 }
2450 }
2451
2452 // Note that this is an explicit specialization.
2453 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2454
2455 // Check that this isn't a redefinition of this specialization.
2456 if (TK == TK_Definition) {
2457 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002458 // FIXME: Should also handle explicit specialization after implicit
2459 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002460 SourceRange Range(TemplateNameLoc, RAngleLoc);
2461 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002462 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002463 Diag(Def->getLocation(), diag::note_previous_definition);
2464 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002465 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002466 }
2467 }
2468
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002469 // Build the fully-sugared type for this class template
2470 // specialization as the user wrote in the specialization
2471 // itself. This means that we'll pretty-print the type retrieved
2472 // from the specialization's declaration the way that the user
2473 // actually wrote the specialization, rather than formatting the
2474 // name based on the "canonical" representation used to store the
2475 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002476 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002477 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002478 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002479 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002480 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002481 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002482 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002483
Douglas Gregor50113ca2009-02-25 22:18:32 +00002484 // C++ [temp.expl.spec]p9:
2485 // A template explicit specialization is in the scope of the
2486 // namespace in which the template was defined.
2487 //
2488 // We actually implement this paragraph where we set the semantic
2489 // context (in the creation of the ClassTemplateSpecializationDecl),
2490 // but we also maintain the lexical context where the actual
2491 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002492 Specialization->setLexicalDeclContext(CurContext);
2493
2494 // We may be starting the definition of this specialization.
2495 if (TK == TK_Definition)
2496 Specialization->startDefinition();
2497
2498 // Add the specialization into its lexical context, so that it can
2499 // be seen when iterating through the list of declarations in that
2500 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002501 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002502 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002503}
Douglas Gregord3022602009-03-27 23:10:48 +00002504
Douglas Gregor96b6df92009-05-14 00:28:11 +00002505// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002506Sema::DeclResult
2507Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2508 unsigned TagSpec,
2509 SourceLocation KWLoc,
2510 const CXXScopeSpec &SS,
2511 TemplateTy TemplateD,
2512 SourceLocation TemplateNameLoc,
2513 SourceLocation LAngleLoc,
2514 ASTTemplateArgsPtr TemplateArgsIn,
2515 SourceLocation *TemplateArgLocs,
2516 SourceLocation RAngleLoc,
2517 AttributeList *Attr) {
2518 // Find the class template we're specializing
2519 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2520 ClassTemplateDecl *ClassTemplate
2521 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2522
2523 // Check that the specialization uses the same tag kind as the
2524 // original template.
2525 TagDecl::TagKind Kind;
2526 switch (TagSpec) {
2527 default: assert(0 && "Unknown tag type!");
2528 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2529 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2530 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2531 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002532 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2533 Kind, KWLoc,
2534 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002535 Diag(KWLoc, diag::err_use_with_wrong_tag)
2536 << ClassTemplate
2537 << CodeModificationHint::CreateReplacement(KWLoc,
2538 ClassTemplate->getTemplatedDecl()->getKindName());
2539 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2540 diag::note_previous_use);
2541 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2542 }
2543
Douglas Gregor90177912009-05-13 18:28:20 +00002544 // C++0x [temp.explicit]p2:
2545 // [...] An explicit instantiation shall appear in an enclosing
2546 // namespace of its template. [...]
2547 //
2548 // This is C++ DR 275.
2549 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2550 TemplateNameLoc,
2551 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002552 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002553 /*ExplicitInstantiation=*/true))
2554 return true;
2555
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002556 // Translate the parser's template argument list in our AST format.
2557 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2558 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2559
2560 // Check that the template argument list is well-formed for this
2561 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002562 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002563 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002564 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002565 RAngleLoc, ConvertedTemplateArgs))
2566 return true;
2567
Anders Carlsson023cbac2009-06-15 17:56:45 +00002568 assert((ConvertedTemplateArgs.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002569 ClassTemplate->getTemplateParameters()->size()) &&
2570 "Converted template argument list is too short!");
2571
2572 // Find the class template specialization declaration that
2573 // corresponds to these arguments.
2574 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002575 ClassTemplateSpecializationDecl::Profile(ID,
2576 ConvertedTemplateArgs.getFlatArgumentList(),
2577 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002578 void *InsertPos = 0;
2579 ClassTemplateSpecializationDecl *PrevDecl
2580 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2581
2582 ClassTemplateSpecializationDecl *Specialization = 0;
2583
Douglas Gregor90177912009-05-13 18:28:20 +00002584 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002585 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002586 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002587 // This particular specialization has already been declared or
2588 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002589 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2590 << Context.getTypeDeclType(PrevDecl);
2591 Diag(PrevDecl->getLocation(),
2592 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002593 return DeclPtrTy::make(PrevDecl);
2594 }
2595
Douglas Gregor90177912009-05-13 18:28:20 +00002596 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002597 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002598 // For a given set of template parameters, if an explicit
2599 // instantiation of a template appears after a declaration of
2600 // an explicit specialization for that template, the explicit
2601 // instantiation has no effect.
2602 if (!getLangOptions().CPlusPlus0x) {
2603 Diag(TemplateNameLoc,
2604 diag::ext_explicit_instantiation_after_specialization)
2605 << Context.getTypeDeclType(PrevDecl);
2606 Diag(PrevDecl->getLocation(),
2607 diag::note_previous_template_specialization);
2608 }
2609
2610 // Create a new class template specialization declaration node
2611 // for this explicit specialization. This node is only used to
2612 // record the existence of this explicit instantiation for
2613 // accurate reproduction of the source code; we don't actually
2614 // use it for anything, since it is semantically irrelevant.
2615 Specialization
2616 = ClassTemplateSpecializationDecl::Create(Context,
2617 ClassTemplate->getDeclContext(),
2618 TemplateNameLoc,
2619 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002620 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002621 Specialization->setLexicalDeclContext(CurContext);
2622 CurContext->addDecl(Context, Specialization);
2623 return DeclPtrTy::make(Specialization);
2624 }
2625
2626 // If we have already (implicitly) instantiated this
2627 // specialization, there is less work to do.
2628 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2629 SpecializationRequiresInstantiation = false;
2630
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002631 // Since the only prior class template specialization with these
2632 // arguments was referenced but not declared, reuse that
2633 // declaration node as our own, updating its source location to
2634 // reflect our new declaration.
2635 Specialization = PrevDecl;
2636 Specialization->setLocation(TemplateNameLoc);
2637 PrevDecl = 0;
2638 } else {
2639 // Create a new class template specialization declaration node for
2640 // this explicit specialization.
2641 Specialization
2642 = ClassTemplateSpecializationDecl::Create(Context,
2643 ClassTemplate->getDeclContext(),
2644 TemplateNameLoc,
2645 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002646 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002647
2648 ClassTemplate->getSpecializations().InsertNode(Specialization,
2649 InsertPos);
2650 }
2651
2652 // Build the fully-sugared type for this explicit instantiation as
2653 // the user wrote in the explicit instantiation itself. This means
2654 // that we'll pretty-print the type retrieved from the
2655 // specialization's declaration the way that the user actually wrote
2656 // the explicit instantiation, rather than formatting the name based
2657 // on the "canonical" representation used to store the template
2658 // arguments in the specialization.
2659 QualType WrittenTy
2660 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002661 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002662 TemplateArgs.size(),
2663 Context.getTypeDeclType(Specialization));
2664 Specialization->setTypeAsWritten(WrittenTy);
2665 TemplateArgsIn.release();
2666
2667 // Add the explicit instantiation into its lexical context. However,
2668 // since explicit instantiations are never found by name lookup, we
2669 // just put it into the declaration context directly.
2670 Specialization->setLexicalDeclContext(CurContext);
2671 CurContext->addDecl(Context, Specialization);
2672
2673 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002674 // A definition of a class template or class member template
2675 // shall be in scope at the point of the explicit instantiation of
2676 // the class template or class member template.
2677 //
2678 // This check comes when we actually try to perform the
2679 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002680 if (SpecializationRequiresInstantiation)
2681 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002682 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002683 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002684
2685 return DeclPtrTy::make(Specialization);
2686}
2687
Douglas Gregor96b6df92009-05-14 00:28:11 +00002688// Explicit instantiation of a member class of a class template.
2689Sema::DeclResult
2690Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2691 unsigned TagSpec,
2692 SourceLocation KWLoc,
2693 const CXXScopeSpec &SS,
2694 IdentifierInfo *Name,
2695 SourceLocation NameLoc,
2696 AttributeList *Attr) {
2697
Douglas Gregor71f06032009-05-28 23:31:59 +00002698 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002699 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002700 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002701 if (!TagD)
2702 return true;
2703
2704 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2705 if (Tag->isEnum()) {
2706 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2707 << Context.getTypeDeclType(Tag);
2708 return true;
2709 }
2710
Douglas Gregord769bfa2009-05-27 17:30:49 +00002711 if (Tag->isInvalidDecl())
2712 return true;
2713
Douglas Gregor96b6df92009-05-14 00:28:11 +00002714 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2715 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2716 if (!Pattern) {
2717 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2718 << Context.getTypeDeclType(Record);
2719 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2720 return true;
2721 }
2722
2723 // C++0x [temp.explicit]p2:
2724 // [...] An explicit instantiation shall appear in an enclosing
2725 // namespace of its template. [...]
2726 //
2727 // This is C++ DR 275.
2728 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002729 // FIXME: In C++98, we would like to turn these errors into warnings,
2730 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002731 DeclContext *PatternContext
2732 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2733 if (!CurContext->Encloses(PatternContext)) {
2734 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2735 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2736 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2737 }
2738 }
2739
Douglas Gregor96b6df92009-05-14 00:28:11 +00002740 if (!Record->getDefinition(Context)) {
2741 // If the class has a definition, instantiate it (and all of its
2742 // members, recursively).
2743 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2744 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002745 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002746 /*ExplicitInstantiation=*/true))
2747 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002748 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002749 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002750 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002751
Mike Stumpe127ae32009-05-16 07:39:55 +00002752 // FIXME: We don't have any representation for explicit instantiations of
2753 // member classes. Such a representation is not needed for compilation, but it
2754 // should be available for clients that want to see all of the declarations in
2755 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002756 return TagD;
2757}
2758
Douglas Gregord3022602009-03-27 23:10:48 +00002759Sema::TypeResult
2760Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2761 const IdentifierInfo &II, SourceLocation IdLoc) {
2762 NestedNameSpecifier *NNS
2763 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2764 if (!NNS)
2765 return true;
2766
2767 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002768 if (T.isNull())
2769 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002770 return T.getAsOpaquePtr();
2771}
2772
Douglas Gregor77da5802009-04-01 00:28:59 +00002773Sema::TypeResult
2774Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2775 SourceLocation TemplateLoc, TypeTy *Ty) {
2776 QualType T = QualType::getFromOpaquePtr(Ty);
2777 NestedNameSpecifier *NNS
2778 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2779 const TemplateSpecializationType *TemplateId
2780 = T->getAsTemplateSpecializationType();
2781 assert(TemplateId && "Expected a template specialization type");
2782
2783 if (NNS->isDependent())
2784 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2785
2786 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2787}
2788
Douglas Gregord3022602009-03-27 23:10:48 +00002789/// \brief Build the type that describes a C++ typename specifier,
2790/// e.g., "typename T::type".
2791QualType
2792Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2793 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002794 CXXRecordDecl *CurrentInstantiation = 0;
2795 if (NNS->isDependent()) {
2796 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002797
Douglas Gregor3eb20702009-05-11 19:58:34 +00002798 // If the nested-name-specifier does not refer to the current
2799 // instantiation, then build a typename type.
2800 if (!CurrentInstantiation)
2801 return Context.getTypenameType(NNS, &II);
2802 }
Douglas Gregord3022602009-03-27 23:10:48 +00002803
Douglas Gregor3eb20702009-05-11 19:58:34 +00002804 DeclContext *Ctx = 0;
2805
2806 if (CurrentInstantiation)
2807 Ctx = CurrentInstantiation;
2808 else {
2809 CXXScopeSpec SS;
2810 SS.setScopeRep(NNS);
2811 SS.setRange(Range);
2812 if (RequireCompleteDeclContext(SS))
2813 return QualType();
2814
2815 Ctx = computeDeclContext(SS);
2816 }
Douglas Gregord3022602009-03-27 23:10:48 +00002817 assert(Ctx && "No declaration context?");
2818
2819 DeclarationName Name(&II);
2820 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2821 false);
2822 unsigned DiagID = 0;
2823 Decl *Referenced = 0;
2824 switch (Result.getKind()) {
2825 case LookupResult::NotFound:
2826 if (Ctx->isTranslationUnit())
2827 DiagID = diag::err_typename_nested_not_found_global;
2828 else
2829 DiagID = diag::err_typename_nested_not_found;
2830 break;
2831
2832 case LookupResult::Found:
2833 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2834 // We found a type. Build a QualifiedNameType, since the
2835 // typename-specifier was just sugar. FIXME: Tell
2836 // QualifiedNameType that it has a "typename" prefix.
2837 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2838 }
2839
2840 DiagID = diag::err_typename_nested_not_type;
2841 Referenced = Result.getAsDecl();
2842 break;
2843
2844 case LookupResult::FoundOverloaded:
2845 DiagID = diag::err_typename_nested_not_type;
2846 Referenced = *Result.begin();
2847 break;
2848
2849 case LookupResult::AmbiguousBaseSubobjectTypes:
2850 case LookupResult::AmbiguousBaseSubobjects:
2851 case LookupResult::AmbiguousReference:
2852 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2853 return QualType();
2854 }
2855
2856 // If we get here, it's because name lookup did not find a
2857 // type. Emit an appropriate diagnostic and return an error.
2858 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2859 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2860 else
2861 Diag(Range.getEnd(), DiagID) << Range << Name;
2862 if (Referenced)
2863 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2864 << Name;
2865 return QualType();
2866}