blob: ec2907f65a76e66ba7c5e30c5fc66c5a072229d3 [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,
Douglas Gregor279272e2009-02-04 19:02:06 +0000166 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000167 if (Invalid)
168 Param->setInvalidDecl();
169
170 if (ParamName) {
171 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000172 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000173 IdResolver.AddDecl(Param);
174 }
175
Chris Lattner5261d0c2009-03-28 19:18:32 +0000176 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000177}
178
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000179/// ActOnTypeParameterDefault - Adds a default argument (the type
180/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000181void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000182 SourceLocation EqualLoc,
183 SourceLocation DefaultLoc,
184 TypeTy *DefaultT) {
185 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000186 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000187 QualType Default = QualType::getFromOpaquePtr(DefaultT);
188
189 // C++ [temp.param]p14:
190 // A template-parameter shall not be used in its own default argument.
191 // FIXME: Implement this check! Needs a recursive walk over the types.
192
193 // Check the template argument itself.
194 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
195 Parm->setInvalidDecl();
196 return;
197 }
198
199 Parm->setDefaultArgument(Default, DefaultLoc, false);
200}
201
Douglas Gregored3a3982009-03-03 04:44:36 +0000202/// \brief Check that the type of a non-type template parameter is
203/// well-formed.
204///
205/// \returns the (possibly-promoted) parameter type if valid;
206/// otherwise, produces a diagnostic and returns a NULL type.
207QualType
208Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
209 // C++ [temp.param]p4:
210 //
211 // A non-type template-parameter shall have one of the following
212 // (optionally cv-qualified) types:
213 //
214 // -- integral or enumeration type,
215 if (T->isIntegralType() || T->isEnumeralType() ||
216 // -- pointer to object or pointer to function,
217 (T->isPointerType() &&
218 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
219 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
220 // -- reference to object or reference to function,
221 T->isReferenceType() ||
222 // -- pointer to member.
223 T->isMemberPointerType() ||
224 // If T is a dependent type, we can't do the check now, so we
225 // assume that it is well-formed.
226 T->isDependentType())
227 return T;
228 // C++ [temp.param]p8:
229 //
230 // A non-type template-parameter of type "array of T" or
231 // "function returning T" is adjusted to be of type "pointer to
232 // T" or "pointer to function returning T", respectively.
233 else if (T->isArrayType())
234 // FIXME: Keep the type prior to promotion?
235 return Context.getArrayDecayedType(T);
236 else if (T->isFunctionType())
237 // FIXME: Keep the type prior to promotion?
238 return Context.getPointerType(T);
239
240 Diag(Loc, diag::err_template_nontype_parm_bad_type)
241 << T;
242
243 return QualType();
244}
245
Douglas Gregordd861062008-12-05 18:15:24 +0000246/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
247/// template parameter (e.g., "int Size" in "template<int Size>
248/// class Array") has been parsed. S is the current scope and D is
249/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000250Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
251 unsigned Depth,
252 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000253 QualType T = GetTypeForDeclarator(D, S);
254
Douglas Gregor279272e2009-02-04 19:02:06 +0000255 assert(S->isTemplateParamScope() &&
256 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000257 bool Invalid = false;
258
259 IdentifierInfo *ParamName = D.getIdentifier();
260 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000261 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000262 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000263 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000264 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000265 }
266
Douglas Gregored3a3982009-03-03 04:44:36 +0000267 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000268 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000269 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000270 Invalid = true;
271 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000272
Douglas Gregordd861062008-12-05 18:15:24 +0000273 NonTypeTemplateParmDecl *Param
274 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000275 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000276 if (Invalid)
277 Param->setInvalidDecl();
278
279 if (D.getIdentifier()) {
280 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000281 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000282 IdResolver.AddDecl(Param);
283 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000284 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000285}
Douglas Gregor52473432008-12-24 02:52:09 +0000286
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000287/// \brief Adds a default argument to the given non-type template
288/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000289void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000290 SourceLocation EqualLoc,
291 ExprArg DefaultE) {
292 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000293 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000294 Expr *Default = static_cast<Expr *>(DefaultE.get());
295
296 // C++ [temp.param]p14:
297 // A template-parameter shall not be used in its own default argument.
298 // FIXME: Implement this check! Needs a recursive walk over the types.
299
300 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000301 TemplateArgument Converted;
302 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
303 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000304 TemplateParm->setInvalidDecl();
305 return;
306 }
307
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000308 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000309}
310
Douglas Gregor279272e2009-02-04 19:02:06 +0000311
312/// ActOnTemplateTemplateParameter - Called when a C++ template template
313/// parameter (e.g. T in template <template <typename> class T> class array)
314/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000315Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
316 SourceLocation TmpLoc,
317 TemplateParamsTy *Params,
318 IdentifierInfo *Name,
319 SourceLocation NameLoc,
320 unsigned Depth,
321 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000322{
323 assert(S->isTemplateParamScope() &&
324 "Template template parameter not in template parameter scope!");
325
326 // Construct the parameter object.
327 TemplateTemplateParmDecl *Param =
328 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
329 Position, Name,
330 (TemplateParameterList*)Params);
331
332 // Make sure the parameter is valid.
333 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
334 // do anything yet. However, if the template parameter list or (eventual)
335 // default value is ever invalidated, that will propagate here.
336 bool Invalid = false;
337 if (Invalid) {
338 Param->setInvalidDecl();
339 }
340
341 // If the tt-param has a name, then link the identifier into the scope
342 // and lookup mechanisms.
343 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000344 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000345 IdResolver.AddDecl(Param);
346 }
347
Chris Lattner5261d0c2009-03-28 19:18:32 +0000348 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000349}
350
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000351/// \brief Adds a default argument to the given template template
352/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000353void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000354 SourceLocation EqualLoc,
355 ExprArg DefaultE) {
356 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000357 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000358
359 // Since a template-template parameter's default argument is an
360 // id-expression, it must be a DeclRefExpr.
361 DeclRefExpr *Default
362 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
363
364 // C++ [temp.param]p14:
365 // A template-parameter shall not be used in its own default argument.
366 // FIXME: Implement this check! Needs a recursive walk over the types.
367
368 // Check the well-formedness of the template argument.
369 if (!isa<TemplateDecl>(Default->getDecl())) {
370 Diag(Default->getSourceRange().getBegin(),
371 diag::err_template_arg_must_be_template)
372 << Default->getSourceRange();
373 TemplateParm->setInvalidDecl();
374 return;
375 }
376 if (CheckTemplateArgument(TemplateParm, Default)) {
377 TemplateParm->setInvalidDecl();
378 return;
379 }
380
381 DefaultE.release();
382 TemplateParm->setDefaultArgument(Default);
383}
384
Douglas Gregor52473432008-12-24 02:52:09 +0000385/// ActOnTemplateParameterList - Builds a TemplateParameterList that
386/// contains the template parameters in Params/NumParams.
387Sema::TemplateParamsTy *
388Sema::ActOnTemplateParameterList(unsigned Depth,
389 SourceLocation ExportLoc,
390 SourceLocation TemplateLoc,
391 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000392 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000393 SourceLocation RAngleLoc) {
394 if (ExportLoc.isValid())
395 Diag(ExportLoc, diag::note_template_export_unsupported);
396
Douglas Gregord406b032009-02-06 22:42:48 +0000397 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
398 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000399}
Douglas Gregor279272e2009-02-04 19:02:06 +0000400
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000401Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000402Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
403 SourceLocation KWLoc, const CXXScopeSpec &SS,
404 IdentifierInfo *Name, SourceLocation NameLoc,
405 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000406 MultiTemplateParamsArg TemplateParameterLists,
407 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000408 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
409 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000410 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000411
412 // Check that we can declare a template here.
413 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000414 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000415
416 TagDecl::TagKind Kind;
417 switch (TagSpec) {
418 default: assert(0 && "Unknown tag type!");
419 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
420 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
421 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
422 }
423
424 // There is no such thing as an unnamed class template.
425 if (!Name) {
426 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000427 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000428 }
429
430 // Find any previous declaration with this name.
431 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
432 true);
433 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
434 NamedDecl *PrevDecl = 0;
435 if (Previous.begin() != Previous.end())
436 PrevDecl = *Previous.begin();
437
438 DeclContext *SemanticContext = CurContext;
439 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000440 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000441
Mike Stumpe127ae32009-05-16 07:39:55 +0000442 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000443 }
444
445 // FIXME: member templates!
446 TemplateParameterList *TemplateParams
447 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
448
449 // If there is a previous declaration with the same name, check
450 // whether this is a valid redeclaration.
451 ClassTemplateDecl *PrevClassTemplate
452 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
453 if (PrevClassTemplate) {
454 // Ensure that the template parameter lists are compatible.
455 if (!TemplateParameterListsAreEqual(TemplateParams,
456 PrevClassTemplate->getTemplateParameters(),
457 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000458 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000459
460 // C++ [temp.class]p4:
461 // In a redeclaration, partial specialization, explicit
462 // specialization or explicit instantiation of a class template,
463 // the class-key shall agree in kind with the original class
464 // template declaration (7.1.5.3).
465 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000466 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000467 Diag(KWLoc, diag::err_use_with_wrong_tag)
468 << Name
469 << CodeModificationHint::CreateReplacement(KWLoc,
470 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000471 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000472 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000473 }
474
Douglas Gregord406b032009-02-06 22:42:48 +0000475 // Check for redefinition of this class template.
476 if (TK == TK_Definition) {
477 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
478 Diag(NameLoc, diag::err_redefinition) << Name;
479 Diag(Def->getLocation(), diag::note_previous_definition);
480 // FIXME: Would it make sense to try to "forget" the previous
481 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000482 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000483 }
484 }
485 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
486 // Maybe we will complain about the shadowed template parameter.
487 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
488 // Just pretend that we didn't see the previous declaration.
489 PrevDecl = 0;
490 } else if (PrevDecl) {
491 // C++ [temp]p5:
492 // A class template shall not have the same name as any other
493 // template, class, function, object, enumeration, enumerator,
494 // namespace, or type in the same scope (3.3), except as specified
495 // in (14.5.4).
496 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
497 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000498 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000499 }
500
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000501 // Check the template parameter list of this declaration, possibly
502 // merging in the template parameter list from the previous class
503 // template declaration.
504 if (CheckTemplateParameterList(TemplateParams,
505 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
506 Invalid = true;
507
Douglas Gregor9054f982009-05-10 22:57:19 +0000508 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000509 // declaration!
510
Douglas Gregor55216ac2009-03-26 00:10:35 +0000511 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000512 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
513 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000514 PrevClassTemplate->getTemplatedDecl() : 0,
515 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000516
517 ClassTemplateDecl *NewTemplate
518 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
519 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000520 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000521 NewClass->setDescribedClassTemplate(NewTemplate);
522
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000523 // Build the type for the class template declaration now.
524 QualType T =
525 Context.getTypeDeclType(NewClass,
526 PrevClassTemplate?
527 PrevClassTemplate->getTemplatedDecl() : 0);
528 assert(T->isDependentType() && "Class template type is not dependent?");
529 (void)T;
530
Anders Carlsson4ca43492009-03-26 01:24:28 +0000531 // Set the access specifier.
532 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
533
Douglas Gregord406b032009-02-06 22:42:48 +0000534 // Set the lexical context of these templates
535 NewClass->setLexicalDeclContext(CurContext);
536 NewTemplate->setLexicalDeclContext(CurContext);
537
538 if (TK == TK_Definition)
539 NewClass->startDefinition();
540
541 if (Attr)
542 ProcessDeclAttributeList(NewClass, Attr);
543
544 PushOnScopeChains(NewTemplate, S);
545
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000546 if (Invalid) {
547 NewTemplate->setInvalidDecl();
548 NewClass->setInvalidDecl();
549 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000550 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000551}
552
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000553/// \brief Checks the validity of a template parameter list, possibly
554/// considering the template parameter list from a previous
555/// declaration.
556///
557/// If an "old" template parameter list is provided, it must be
558/// equivalent (per TemplateParameterListsAreEqual) to the "new"
559/// template parameter list.
560///
561/// \param NewParams Template parameter list for a new template
562/// declaration. This template parameter list will be updated with any
563/// default arguments that are carried through from the previous
564/// template parameter list.
565///
566/// \param OldParams If provided, template parameter list from a
567/// previous declaration of the same template. Default template
568/// arguments will be merged from the old template parameter list to
569/// the new template parameter list.
570///
571/// \returns true if an error occurred, false otherwise.
572bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
573 TemplateParameterList *OldParams) {
574 bool Invalid = false;
575
576 // C++ [temp.param]p10:
577 // The set of default template-arguments available for use with a
578 // template declaration or definition is obtained by merging the
579 // default arguments from the definition (if in scope) and all
580 // declarations in scope in the same way default function
581 // arguments are (8.3.6).
582 bool SawDefaultArgument = false;
583 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000584
Mike Stumpe0b7e032009-02-11 23:03:27 +0000585 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000586 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000587 if (OldParams)
588 OldParam = OldParams->begin();
589
590 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
591 NewParamEnd = NewParams->end();
592 NewParam != NewParamEnd; ++NewParam) {
593 // Variables used to diagnose redundant default arguments
594 bool RedundantDefaultArg = false;
595 SourceLocation OldDefaultLoc;
596 SourceLocation NewDefaultLoc;
597
598 // Variables used to diagnose missing default arguments
599 bool MissingDefaultArg = false;
600
601 // Merge default arguments for template type parameters.
602 if (TemplateTypeParmDecl *NewTypeParm
603 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
604 TemplateTypeParmDecl *OldTypeParm
605 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
606
607 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
608 NewTypeParm->hasDefaultArgument()) {
609 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
610 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
611 SawDefaultArgument = true;
612 RedundantDefaultArg = true;
613 PreviousDefaultArgLoc = NewDefaultLoc;
614 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
615 // Merge the default argument from the old declaration to the
616 // new declaration.
617 SawDefaultArgument = true;
618 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
619 OldTypeParm->getDefaultArgumentLoc(),
620 true);
621 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
622 } else if (NewTypeParm->hasDefaultArgument()) {
623 SawDefaultArgument = true;
624 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
625 } else if (SawDefaultArgument)
626 MissingDefaultArg = true;
627 }
628 // Merge default arguments for non-type template parameters
629 else if (NonTypeTemplateParmDecl *NewNonTypeParm
630 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
631 NonTypeTemplateParmDecl *OldNonTypeParm
632 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
633 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
634 NewNonTypeParm->hasDefaultArgument()) {
635 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
636 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
637 SawDefaultArgument = true;
638 RedundantDefaultArg = true;
639 PreviousDefaultArgLoc = NewDefaultLoc;
640 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
641 // Merge the default argument from the old declaration to the
642 // new declaration.
643 SawDefaultArgument = true;
644 // FIXME: We need to create a new kind of "default argument"
645 // expression that points to a previous template template
646 // parameter.
647 NewNonTypeParm->setDefaultArgument(
648 OldNonTypeParm->getDefaultArgument());
649 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
650 } else if (NewNonTypeParm->hasDefaultArgument()) {
651 SawDefaultArgument = true;
652 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
653 } else if (SawDefaultArgument)
654 MissingDefaultArg = true;
655 }
656 // Merge default arguments for template template parameters
657 else {
658 TemplateTemplateParmDecl *NewTemplateParm
659 = cast<TemplateTemplateParmDecl>(*NewParam);
660 TemplateTemplateParmDecl *OldTemplateParm
661 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
662 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
663 NewTemplateParm->hasDefaultArgument()) {
664 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
665 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
666 SawDefaultArgument = true;
667 RedundantDefaultArg = true;
668 PreviousDefaultArgLoc = NewDefaultLoc;
669 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
670 // Merge the default argument from the old declaration to the
671 // new declaration.
672 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000673 // FIXME: We need to create a new kind of "default argument" expression
674 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000675 NewTemplateParm->setDefaultArgument(
676 OldTemplateParm->getDefaultArgument());
677 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
678 } else if (NewTemplateParm->hasDefaultArgument()) {
679 SawDefaultArgument = true;
680 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
681 } else if (SawDefaultArgument)
682 MissingDefaultArg = true;
683 }
684
685 if (RedundantDefaultArg) {
686 // C++ [temp.param]p12:
687 // A template-parameter shall not be given default arguments
688 // by two different declarations in the same scope.
689 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
690 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
691 Invalid = true;
692 } else if (MissingDefaultArg) {
693 // C++ [temp.param]p11:
694 // If a template-parameter has a default template-argument,
695 // all subsequent template-parameters shall have a default
696 // template-argument supplied.
697 Diag((*NewParam)->getLocation(),
698 diag::err_template_param_default_arg_missing);
699 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
700 Invalid = true;
701 }
702
703 // If we have an old template parameter list that we're merging
704 // in, move on to the next parameter.
705 if (OldParams)
706 ++OldParam;
707 }
708
709 return Invalid;
710}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000711
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000712/// \brief Translates template arguments as provided by the parser
713/// into template arguments used by semantic analysis.
714static void
715translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
716 SourceLocation *TemplateArgLocs,
717 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
718 TemplateArgs.reserve(TemplateArgsIn.size());
719
720 void **Args = TemplateArgsIn.getArgs();
721 bool *ArgIsType = TemplateArgsIn.getArgIsType();
722 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
723 TemplateArgs.push_back(
724 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
725 QualType::getFromOpaquePtr(Args[Arg]))
726 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
727 }
728}
729
Douglas Gregoraabb8502009-03-31 00:43:58 +0000730/// \brief Build a canonical version of a template argument list.
731///
732/// This function builds a canonical version of the given template
733/// argument list, where each of the template arguments has been
734/// converted into its canonical form. This routine is typically used
735/// to canonicalize a template argument list when the template name
736/// itself is dependent. When the template name refers to an actual
737/// template declaration, Sema::CheckTemplateArgumentList should be
738/// used to check and canonicalize the template arguments.
739///
740/// \param TemplateArgs The incoming template arguments.
741///
742/// \param NumTemplateArgs The number of template arguments in \p
743/// TemplateArgs.
744///
745/// \param Canonical A vector to be filled with the canonical versions
746/// of the template arguments.
747///
748/// \param Context The ASTContext in which the template arguments live.
749static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
750 unsigned NumTemplateArgs,
751 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
752 ASTContext &Context) {
753 Canonical.reserve(NumTemplateArgs);
754 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
755 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000756 case TemplateArgument::Null:
757 assert(false && "Should never see a NULL template argument here");
758 break;
759
Douglas Gregoraabb8502009-03-31 00:43:58 +0000760 case TemplateArgument::Expression:
761 // FIXME: Build canonical expression (!)
762 Canonical.push_back(TemplateArgs[Idx]);
763 break;
764
765 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000766 Canonical.push_back(
767 TemplateArgument(SourceLocation(),
768 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000769 break;
770
771 case TemplateArgument::Integral:
772 Canonical.push_back(TemplateArgument(SourceLocation(),
773 *TemplateArgs[Idx].getAsIntegral(),
774 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000775 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000776
777 case TemplateArgument::Type: {
778 QualType CanonType
779 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
780 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000781 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000782 }
783 }
784 }
785}
786
Douglas Gregordd13e842009-03-30 22:58:21 +0000787QualType Sema::CheckTemplateIdType(TemplateName Name,
788 SourceLocation TemplateLoc,
789 SourceLocation LAngleLoc,
790 const TemplateArgument *TemplateArgs,
791 unsigned NumTemplateArgs,
792 SourceLocation RAngleLoc) {
793 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000794 if (!Template) {
795 // The template name does not resolve to a template, so we just
796 // build a dependent template-id type.
797
798 // Canonicalize the template arguments to build the canonical
799 // template-id type.
800 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
801 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
802 CanonicalTemplateArgs, Context);
803
Douglas Gregor905406b2009-05-07 06:49:52 +0000804 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000805 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000806 = Context.getTemplateSpecializationType(CanonName,
807 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000808 CanonicalTemplateArgs.size());
809
810 // Build the dependent template-id type.
811 return Context.getTemplateSpecializationType(Name, TemplateArgs,
812 NumTemplateArgs, CanonType);
813 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000814
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000815 // Check that the template argument list is well-formed for this
816 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000817 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000818 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000819 TemplateArgs, NumTemplateArgs, RAngleLoc,
820 ConvertedTemplateArgs))
821 return QualType();
822
823 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000824 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000825 "Converted template argument list is too short!");
826
827 QualType CanonType;
828
Douglas Gregordd13e842009-03-30 22:58:21 +0000829 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000830 TemplateArgs,
831 NumTemplateArgs)) {
832 // This class template specialization is a dependent
833 // type. Therefore, its canonical type is another class template
834 // specialization type that contains all of the converted
835 // arguments in canonical form. This ensures that, e.g., A<T> and
836 // A<T, T> have identical types when A is declared as:
837 //
838 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000839 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
840 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000841 ConvertedTemplateArgs.getFlatArgumentList(),
842 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000843 } else if (ClassTemplateDecl *ClassTemplate
844 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000845 // Find the class template specialization declaration that
846 // corresponds to these arguments.
847 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000848 ClassTemplateSpecializationDecl::Profile(ID,
849 ConvertedTemplateArgs.getFlatArgumentList(),
850 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000851 void *InsertPos = 0;
852 ClassTemplateSpecializationDecl *Decl
853 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
854 if (!Decl) {
855 // This is the first time we have referenced this class template
856 // specialization. Create the canonical declaration and add it to
857 // the set of specializations.
858 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000859 ClassTemplate->getDeclContext(),
860 TemplateLoc,
861 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000862 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000863 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
864 Decl->setLexicalDeclContext(CurContext);
865 }
866
867 CanonType = Context.getTypeDeclType(Decl);
868 }
869
870 // Build the fully-sugared type for this class template
871 // specialization, which refers back to the class template
872 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000873 return Context.getTemplateSpecializationType(Name, TemplateArgs,
874 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000875}
876
Douglas Gregora08b6c72009-02-17 23:15:12 +0000877Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000878Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
879 SourceLocation LAngleLoc,
880 ASTTemplateArgsPtr TemplateArgsIn,
881 SourceLocation *TemplateArgLocs,
882 SourceLocation RAngleLoc) {
883 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000884
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000885 // Translate the parser's template argument list in our AST format.
886 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
887 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000888
Douglas Gregordd13e842009-03-30 22:58:21 +0000889 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000890 TemplateArgs.data(),
891 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000892 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000893 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000894
895 if (Result.isNull())
896 return true;
897
Douglas Gregor6f37b582009-02-09 19:34:22 +0000898 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000899}
900
Douglas Gregoraabb8502009-03-31 00:43:58 +0000901/// \brief Form a dependent template name.
902///
903/// This action forms a dependent template name given the template
904/// name and its (presumably dependent) scope specifier. For
905/// example, given "MetaFun::template apply", the scope specifier \p
906/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
907/// of the "template" keyword, and "apply" is the \p Name.
908Sema::TemplateTy
909Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
910 const IdentifierInfo &Name,
911 SourceLocation NameLoc,
912 const CXXScopeSpec &SS) {
913 if (!SS.isSet() || SS.isInvalid())
914 return TemplateTy();
915
916 NestedNameSpecifier *Qualifier
917 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
918
919 // FIXME: member of the current instantiation
920
921 if (!Qualifier->isDependent()) {
922 // C++0x [temp.names]p5:
923 // If a name prefixed by the keyword template is not the name of
924 // a template, the program is ill-formed. [Note: the keyword
925 // template may not be applied to non-template members of class
926 // templates. -end note ] [ Note: as is the case with the
927 // typename prefix, the template prefix is allowed in cases
928 // where it is not strictly necessary; i.e., when the
929 // nested-name-specifier or the expression on the left of the ->
930 // or . is not dependent on a template-parameter, or the use
931 // does not appear in the scope of a template. -end note]
932 //
933 // Note: C++03 was more strict here, because it banned the use of
934 // the "template" keyword prior to a template-name that was not a
935 // dependent name. C++ DR468 relaxed this requirement (the
936 // "template" keyword is now permitted). We follow the C++0x
937 // rules, even in C++03 mode, retroactively applying the DR.
938 TemplateTy Template;
939 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
940 if (TNK == TNK_Non_template) {
941 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
942 << &Name;
943 return TemplateTy();
944 }
945
946 return Template;
947 }
948
949 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
950}
951
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000952/// \brief Check that the given template argument list is well-formed
953/// for specializing the given template.
954bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
955 SourceLocation TemplateLoc,
956 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000957 const TemplateArgument *TemplateArgs,
958 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000959 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +0000960 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000961 TemplateParameterList *Params = Template->getTemplateParameters();
962 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000963 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000964 bool Invalid = false;
965
966 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000967 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000968 // FIXME: point at either the first arg beyond what we can handle,
969 // or the '>', depending on whether we have too many or too few
970 // arguments.
971 SourceRange Range;
972 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000973 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000974 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
975 << (NumArgs > NumParams)
976 << (isa<ClassTemplateDecl>(Template)? 0 :
977 isa<FunctionTemplateDecl>(Template)? 1 :
978 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
979 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000980 Diag(Template->getLocation(), diag::note_template_decl_here)
981 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000982 Invalid = true;
983 }
984
985 // C++ [temp.arg]p1:
986 // [...] The type and form of each template-argument specified in
987 // a template-id shall match the type and form specified for the
988 // corresponding parameter declared by the template in its
989 // template-parameter-list.
990 unsigned ArgIdx = 0;
991 for (TemplateParameterList::iterator Param = Params->begin(),
992 ParamEnd = Params->end();
993 Param != ParamEnd; ++Param, ++ArgIdx) {
994 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000995 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000996 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000997 // Retrieve the default template argument from the template
998 // parameter.
999 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1000 if (!TTP->hasDefaultArgument())
1001 break;
1002
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001003 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001004
1005 // If the argument type is dependent, instantiate it now based
1006 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001007 if (ArgType->isDependentType()) {
1008 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001009 Template, Converted.getFlatArgumentList(),
1010 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001011 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001012
Anders Carlsson0233eb62009-06-05 04:47:51 +00001013 TemplateArgumentList TemplateArgs(Context, Converted,
1014 /*CopyArgs=*/false,
1015 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001016 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001017 TTP->getDefaultArgumentLoc(),
1018 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001019 }
Douglas Gregor74296542009-02-27 19:31:52 +00001020
1021 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001022 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001023
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001024 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001025 } else if (NonTypeTemplateParmDecl *NTTP
1026 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1027 if (!NTTP->hasDefaultArgument())
1028 break;
1029
Anders Carlsson0297caf2009-06-11 16:06:49 +00001030 InstantiatingTemplate Inst(*this, TemplateLoc,
1031 Template, Converted.getFlatArgumentList(),
1032 Converted.flatSize(),
1033 SourceRange(TemplateLoc, RAngleLoc));
1034
1035 TemplateArgumentList TemplateArgs(Context, Converted,
1036 /*CopyArgs=*/false,
1037 /*FlattenArgs=*/false);
1038
1039 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1040 TemplateArgs);
1041 if (E.isInvalid())
1042 return true;
1043
1044 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001045 } else {
1046 TemplateTemplateParmDecl *TempParm
1047 = cast<TemplateTemplateParmDecl>(*Param);
1048
1049 if (!TempParm->hasDefaultArgument())
1050 break;
1051
Douglas Gregored3a3982009-03-03 04:44:36 +00001052 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001053 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001054 }
1055 } else {
1056 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001057 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001058 }
1059
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001060
1061 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1062 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001063 if (Arg.getKind() == TemplateArgument::Type) {
1064 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001065 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001066
1067 // Add the converted template type argument.
1068 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001069 TemplateArgument(Arg.getLocation(),
1070 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001071 continue;
1072 }
1073
1074 // C++ [temp.arg.type]p1:
1075 // A template-argument for a template-parameter which is a
1076 // type shall be a type-id.
1077
1078 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001079 // is not a type.
1080 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001081 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001082 Invalid = true;
1083 } else if (NonTypeTemplateParmDecl *NTTP
1084 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1085 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001086
1087 // Instantiate the type of the non-type template parameter with
1088 // the template arguments we've seen thus far.
1089 QualType NTTPType = NTTP->getType();
1090 if (NTTPType->isDependentType()) {
1091 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001092 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001093 Template, Converted.getFlatArgumentList(),
1094 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001095 SourceRange(TemplateLoc, RAngleLoc));
1096
Anders Carlsson0233eb62009-06-05 04:47:51 +00001097 TemplateArgumentList TemplateArgs(Context, Converted,
1098 /*CopyArgs=*/false,
1099 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001100 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001101 NTTP->getLocation(),
1102 NTTP->getDeclName());
1103 // If that worked, check the non-type template parameter type
1104 // for validity.
1105 if (!NTTPType.isNull())
1106 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1107 NTTP->getLocation());
1108
1109 if (NTTPType.isNull()) {
1110 Invalid = true;
1111 break;
1112 }
1113 }
1114
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001115 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001116 case TemplateArgument::Null:
1117 assert(false && "Should never see a NULL template argument here");
1118 break;
1119
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001120 case TemplateArgument::Expression: {
1121 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001122 TemplateArgument Result;
1123 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001124 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001125 else
1126 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001127 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001128 }
1129
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001130 case TemplateArgument::Declaration:
1131 case TemplateArgument::Integral:
1132 // We've already checked this template argument, so just copy
1133 // it to the list of converted arguments.
1134 Converted.push_back(Arg);
1135 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001136
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001137 case TemplateArgument::Type:
1138 // We have a non-type template parameter but the template
1139 // argument is a type.
1140
1141 // C++ [temp.arg]p2:
1142 // In a template-argument, an ambiguity between a type-id and
1143 // an expression is resolved to a type-id, regardless of the
1144 // form of the corresponding template-parameter.
1145 //
1146 // We warn specifically about this case, since it can be rather
1147 // confusing for users.
1148 if (Arg.getAsType()->isFunctionType())
1149 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1150 << Arg.getAsType();
1151 else
1152 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1153 Diag((*Param)->getLocation(), diag::note_template_param_here);
1154 Invalid = true;
1155 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001156 } else {
1157 // Check template template parameters.
1158 TemplateTemplateParmDecl *TempParm
1159 = cast<TemplateTemplateParmDecl>(*Param);
1160
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001161 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001162 case TemplateArgument::Null:
1163 assert(false && "Should never see a NULL template argument here");
1164 break;
1165
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001166 case TemplateArgument::Expression: {
1167 Expr *ArgExpr = Arg.getAsExpr();
1168 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1169 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1170 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1171 Invalid = true;
1172
1173 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001174 Decl *D
1175 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1176 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001177 continue;
1178 }
1179 }
1180 // fall through
1181
1182 case TemplateArgument::Type: {
1183 // We have a template template parameter but the template
1184 // argument does not refer to a template.
1185 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1186 Invalid = true;
1187 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001188 }
1189
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001190 case TemplateArgument::Declaration:
1191 // We've already checked this template argument, so just copy
1192 // it to the list of converted arguments.
1193 Converted.push_back(Arg);
1194 break;
1195
1196 case TemplateArgument::Integral:
1197 assert(false && "Integral argument with template template parameter");
1198 break;
1199 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001200 }
1201 }
1202
1203 return Invalid;
1204}
1205
1206/// \brief Check a template argument against its corresponding
1207/// template type parameter.
1208///
1209/// This routine implements the semantics of C++ [temp.arg.type]. It
1210/// returns true if an error occurred, and false otherwise.
1211bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1212 QualType Arg, SourceLocation ArgLoc) {
1213 // C++ [temp.arg.type]p2:
1214 // A local type, a type with no linkage, an unnamed type or a type
1215 // compounded from any of these types shall not be used as a
1216 // template-argument for a template type-parameter.
1217 //
1218 // FIXME: Perform the recursive and no-linkage type checks.
1219 const TagType *Tag = 0;
1220 if (const EnumType *EnumT = Arg->getAsEnumType())
1221 Tag = EnumT;
1222 else if (const RecordType *RecordT = Arg->getAsRecordType())
1223 Tag = RecordT;
1224 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1225 return Diag(ArgLoc, diag::err_template_arg_local_type)
1226 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001227 else if (Tag && !Tag->getDecl()->getDeclName() &&
1228 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001229 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1230 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1231 return true;
1232 }
1233
1234 return false;
1235}
1236
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001237/// \brief Checks whether the given template argument is the address
1238/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001239bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1240 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001241 bool Invalid = false;
1242
1243 // See through any implicit casts we added to fix the type.
1244 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1245 Arg = Cast->getSubExpr();
1246
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001247 // C++0x allows nullptr, and there's no further checking to be done for that.
1248 if (Arg->getType()->isNullPtrType())
1249 return false;
1250
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001251 // C++ [temp.arg.nontype]p1:
1252 //
1253 // A template-argument for a non-type, non-template
1254 // template-parameter shall be one of: [...]
1255 //
1256 // -- the address of an object or function with external
1257 // linkage, including function templates and function
1258 // template-ids but excluding non-static class members,
1259 // expressed as & id-expression where the & is optional if
1260 // the name refers to a function or array, or if the
1261 // corresponding template-parameter is a reference; or
1262 DeclRefExpr *DRE = 0;
1263
1264 // Ignore (and complain about) any excess parentheses.
1265 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1266 if (!Invalid) {
1267 Diag(Arg->getSourceRange().getBegin(),
1268 diag::err_template_arg_extra_parens)
1269 << Arg->getSourceRange();
1270 Invalid = true;
1271 }
1272
1273 Arg = Parens->getSubExpr();
1274 }
1275
1276 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1277 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1278 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1279 } else
1280 DRE = dyn_cast<DeclRefExpr>(Arg);
1281
1282 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1283 return Diag(Arg->getSourceRange().getBegin(),
1284 diag::err_template_arg_not_object_or_func_form)
1285 << Arg->getSourceRange();
1286
1287 // Cannot refer to non-static data members
1288 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1289 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1290 << Field << Arg->getSourceRange();
1291
1292 // Cannot refer to non-static member functions
1293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1294 if (!Method->isStatic())
1295 return Diag(Arg->getSourceRange().getBegin(),
1296 diag::err_template_arg_method)
1297 << Method << Arg->getSourceRange();
1298
1299 // Functions must have external linkage.
1300 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1301 if (Func->getStorageClass() == FunctionDecl::Static) {
1302 Diag(Arg->getSourceRange().getBegin(),
1303 diag::err_template_arg_function_not_extern)
1304 << Func << Arg->getSourceRange();
1305 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1306 << true;
1307 return true;
1308 }
1309
1310 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001311 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001312 return Invalid;
1313 }
1314
1315 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1316 if (!Var->hasGlobalStorage()) {
1317 Diag(Arg->getSourceRange().getBegin(),
1318 diag::err_template_arg_object_not_extern)
1319 << Var << Arg->getSourceRange();
1320 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1321 << true;
1322 return true;
1323 }
1324
1325 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001326 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001327 return Invalid;
1328 }
1329
1330 // We found something else, but we don't know specifically what it is.
1331 Diag(Arg->getSourceRange().getBegin(),
1332 diag::err_template_arg_not_object_or_func)
1333 << Arg->getSourceRange();
1334 Diag(DRE->getDecl()->getLocation(),
1335 diag::note_template_arg_refers_here);
1336 return true;
1337}
1338
1339/// \brief Checks whether the given template argument is a pointer to
1340/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001341bool
1342Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001343 bool Invalid = false;
1344
1345 // See through any implicit casts we added to fix the type.
1346 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1347 Arg = Cast->getSubExpr();
1348
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001349 // C++0x allows nullptr, and there's no further checking to be done for that.
1350 if (Arg->getType()->isNullPtrType())
1351 return false;
1352
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001353 // C++ [temp.arg.nontype]p1:
1354 //
1355 // A template-argument for a non-type, non-template
1356 // template-parameter shall be one of: [...]
1357 //
1358 // -- a pointer to member expressed as described in 5.3.1.
1359 QualifiedDeclRefExpr *DRE = 0;
1360
1361 // Ignore (and complain about) any excess parentheses.
1362 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1363 if (!Invalid) {
1364 Diag(Arg->getSourceRange().getBegin(),
1365 diag::err_template_arg_extra_parens)
1366 << Arg->getSourceRange();
1367 Invalid = true;
1368 }
1369
1370 Arg = Parens->getSubExpr();
1371 }
1372
1373 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1374 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1375 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1376
1377 if (!DRE)
1378 return Diag(Arg->getSourceRange().getBegin(),
1379 diag::err_template_arg_not_pointer_to_member_form)
1380 << Arg->getSourceRange();
1381
1382 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1383 assert((isa<FieldDecl>(DRE->getDecl()) ||
1384 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1385 "Only non-static member pointers can make it here");
1386
1387 // Okay: this is the address of a non-static member, and therefore
1388 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001389 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001390 return Invalid;
1391 }
1392
1393 // We found something else, but we don't know specifically what it is.
1394 Diag(Arg->getSourceRange().getBegin(),
1395 diag::err_template_arg_not_pointer_to_member_form)
1396 << Arg->getSourceRange();
1397 Diag(DRE->getDecl()->getLocation(),
1398 diag::note_template_arg_refers_here);
1399 return true;
1400}
1401
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001402/// \brief Check a template argument against its corresponding
1403/// non-type template parameter.
1404///
Douglas Gregored3a3982009-03-03 04:44:36 +00001405/// This routine implements the semantics of C++ [temp.arg.nontype].
1406/// It returns true if an error occurred, and false otherwise. \p
1407/// InstantiatedParamType is the type of the non-type template
1408/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001409///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001410/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001411bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001412 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001413 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001414 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1415
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001416 // If either the parameter has a dependent type or the argument is
1417 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001418 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001419 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1420 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001421 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001422 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001423 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001424
1425 // C++ [temp.arg.nontype]p5:
1426 // The following conversions are performed on each expression used
1427 // as a non-type template-argument. If a non-type
1428 // template-argument cannot be converted to the type of the
1429 // corresponding template-parameter then the program is
1430 // ill-formed.
1431 //
1432 // -- for a non-type template-parameter of integral or
1433 // enumeration type, integral promotions (4.5) and integral
1434 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001435 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001436 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001437 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001438 // C++ [temp.arg.nontype]p1:
1439 // A template-argument for a non-type, non-template
1440 // template-parameter shall be one of:
1441 //
1442 // -- an integral constant-expression of integral or enumeration
1443 // type; or
1444 // -- the name of a non-type template-parameter; or
1445 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001446 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001447 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1448 Diag(Arg->getSourceRange().getBegin(),
1449 diag::err_template_arg_not_integral_or_enumeral)
1450 << ArgType << Arg->getSourceRange();
1451 Diag(Param->getLocation(), diag::note_template_param_here);
1452 return true;
1453 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001454 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001455 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1456 << ArgType << Arg->getSourceRange();
1457 return true;
1458 }
1459
1460 // FIXME: We need some way to more easily get the unqualified form
1461 // of the types without going all the way to the
1462 // canonical type.
1463 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1464 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1465 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1466 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1467
1468 // Try to convert the argument to the parameter's type.
1469 if (ParamType == ArgType) {
1470 // Okay: no conversion necessary
1471 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1472 !ParamType->isEnumeralType()) {
1473 // This is an integral promotion or conversion.
1474 ImpCastExprToType(Arg, ParamType);
1475 } else {
1476 // We can't perform this conversion.
1477 Diag(Arg->getSourceRange().getBegin(),
1478 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001479 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001480 Diag(Param->getLocation(), diag::note_template_param_here);
1481 return true;
1482 }
1483
Douglas Gregorafc86942009-03-14 00:20:21 +00001484 QualType IntegerType = Context.getCanonicalType(ParamType);
1485 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001486 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001487
1488 if (!Arg->isValueDependent()) {
1489 // Check that an unsigned parameter does not receive a negative
1490 // value.
1491 if (IntegerType->isUnsignedIntegerType()
1492 && (Value.isSigned() && Value.isNegative())) {
1493 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1494 << Value.toString(10) << Param->getType()
1495 << Arg->getSourceRange();
1496 Diag(Param->getLocation(), diag::note_template_param_here);
1497 return true;
1498 }
1499
1500 // Check that we don't overflow the template parameter type.
1501 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1502 if (Value.getActiveBits() > AllowedBits) {
1503 Diag(Arg->getSourceRange().getBegin(),
1504 diag::err_template_arg_too_large)
1505 << Value.toString(10) << Param->getType()
1506 << Arg->getSourceRange();
1507 Diag(Param->getLocation(), diag::note_template_param_here);
1508 return true;
1509 }
1510
1511 if (Value.getBitWidth() != AllowedBits)
1512 Value.extOrTrunc(AllowedBits);
1513 Value.setIsSigned(IntegerType->isSignedIntegerType());
1514 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001515
Douglas Gregor8f378a92009-06-11 18:10:32 +00001516 // Add the value of this argument to the list of converted
1517 // arguments. We use the bitwidth and signedness of the template
1518 // parameter.
1519 if (Arg->isValueDependent()) {
1520 // The argument is value-dependent. Create a new
1521 // TemplateArgument with the converted expression.
1522 Converted = TemplateArgument(Arg);
1523 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001524 }
1525
Douglas Gregor8f378a92009-06-11 18:10:32 +00001526 Converted = TemplateArgument(StartLoc, Value,
1527 ParamType->isEnumeralType() ? ParamType
1528 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001529 return false;
1530 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001531
Douglas Gregor3f411962009-02-11 01:18:59 +00001532 // Handle pointer-to-function, reference-to-function, and
1533 // pointer-to-member-function all in (roughly) the same way.
1534 if (// -- For a non-type template-parameter of type pointer to
1535 // function, only the function-to-pointer conversion (4.3) is
1536 // applied. If the template-argument represents a set of
1537 // overloaded functions (or a pointer to such), the matching
1538 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001539 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001540 (ParamType->isPointerType() &&
1541 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1542 // -- For a non-type template-parameter of type reference to
1543 // function, no conversions apply. If the template-argument
1544 // represents a set of overloaded functions, the matching
1545 // function is selected from the set (13.4).
1546 (ParamType->isReferenceType() &&
1547 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1548 // -- For a non-type template-parameter of type pointer to
1549 // member function, no conversions apply. If the
1550 // template-argument represents a set of overloaded member
1551 // functions, the matching member function is selected from
1552 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001553 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001554 (ParamType->isMemberPointerType() &&
1555 ParamType->getAsMemberPointerType()->getPointeeType()
1556 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001557 if (Context.hasSameUnqualifiedType(ArgType,
1558 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001559 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001560 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1561 ParamType->isMemberPointerType())) {
1562 ArgType = ParamType;
1563 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001564 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001565 ArgType = Context.getPointerType(ArgType);
1566 ImpCastExprToType(Arg, ArgType);
1567 } else if (FunctionDecl *Fn
1568 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001569 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1570 return true;
1571
Douglas Gregor2eedd992009-02-11 00:19:33 +00001572 FixOverloadedFunctionReference(Arg, Fn);
1573 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001574 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001575 ArgType = Context.getPointerType(Arg->getType());
1576 ImpCastExprToType(Arg, ArgType);
1577 }
1578 }
1579
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001580 if (!Context.hasSameUnqualifiedType(ArgType,
1581 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001582 // We can't perform this conversion.
1583 Diag(Arg->getSourceRange().getBegin(),
1584 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001585 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001586 Diag(Param->getLocation(), diag::note_template_param_here);
1587 return true;
1588 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001589
Douglas Gregorad964b32009-02-17 01:05:43 +00001590 if (ParamType->isMemberPointerType()) {
1591 NamedDecl *Member = 0;
1592 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1593 return true;
1594
Douglas Gregor8f378a92009-06-11 18:10:32 +00001595 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1596 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001597 return false;
1598 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001599
Douglas Gregorad964b32009-02-17 01:05:43 +00001600 NamedDecl *Entity = 0;
1601 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1602 return true;
1603
Douglas Gregor8f378a92009-06-11 18:10:32 +00001604 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1605 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001606 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001607 }
1608
Chris Lattner320dff22009-02-20 21:37:53 +00001609 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001610 // -- for a non-type template-parameter of type pointer to
1611 // object, qualification conversions (4.4) and the
1612 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001613 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001614 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001615 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001616
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001617 if (ArgType->isNullPtrType()) {
1618 ArgType = ParamType;
1619 ImpCastExprToType(Arg, ParamType);
1620 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001621 ArgType = Context.getArrayDecayedType(ArgType);
1622 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001623 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001624
Douglas Gregor3f411962009-02-11 01:18:59 +00001625 if (IsQualificationConversion(ArgType, ParamType)) {
1626 ArgType = ParamType;
1627 ImpCastExprToType(Arg, ParamType);
1628 }
1629
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001630 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001631 // We can't perform this conversion.
1632 Diag(Arg->getSourceRange().getBegin(),
1633 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001634 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001635 Diag(Param->getLocation(), diag::note_template_param_here);
1636 return true;
1637 }
1638
Douglas Gregorad964b32009-02-17 01:05:43 +00001639 NamedDecl *Entity = 0;
1640 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1641 return true;
1642
Douglas Gregor8f378a92009-06-11 18:10:32 +00001643 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1644 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001645 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001646 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001647
1648 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1649 // -- For a non-type template-parameter of type reference to
1650 // object, no conversions apply. The type referred to by the
1651 // reference may be more cv-qualified than the (otherwise
1652 // identical) type of the template-argument. The
1653 // template-parameter is bound directly to the
1654 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001655 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001656 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001657
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001658 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001659 Diag(Arg->getSourceRange().getBegin(),
1660 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001661 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001662 << Arg->getSourceRange();
1663 Diag(Param->getLocation(), diag::note_template_param_here);
1664 return true;
1665 }
1666
1667 unsigned ParamQuals
1668 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1669 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1670
1671 if ((ParamQuals | ArgQuals) != ParamQuals) {
1672 Diag(Arg->getSourceRange().getBegin(),
1673 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001674 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001675 << Arg->getSourceRange();
1676 Diag(Param->getLocation(), diag::note_template_param_here);
1677 return true;
1678 }
1679
Douglas Gregorad964b32009-02-17 01:05:43 +00001680 NamedDecl *Entity = 0;
1681 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1682 return true;
1683
Douglas Gregor8f378a92009-06-11 18:10:32 +00001684 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1685 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001686 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001687 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001688
1689 // -- For a non-type template-parameter of type pointer to data
1690 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001691 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001692 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1693
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001694 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001695 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001696 } else if (ArgType->isNullPtrType()) {
1697 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001698 } else if (IsQualificationConversion(ArgType, ParamType)) {
1699 ImpCastExprToType(Arg, ParamType);
1700 } else {
1701 // We can't perform this conversion.
1702 Diag(Arg->getSourceRange().getBegin(),
1703 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001704 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001705 Diag(Param->getLocation(), diag::note_template_param_here);
1706 return true;
1707 }
1708
Douglas Gregorad964b32009-02-17 01:05:43 +00001709 NamedDecl *Member = 0;
1710 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1711 return true;
1712
Douglas Gregor8f378a92009-06-11 18:10:32 +00001713 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1714 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001715 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001716}
1717
1718/// \brief Check a template argument against its corresponding
1719/// template template parameter.
1720///
1721/// This routine implements the semantics of C++ [temp.arg.template].
1722/// It returns true if an error occurred, and false otherwise.
1723bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1724 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001725 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1726 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1727
1728 // C++ [temp.arg.template]p1:
1729 // A template-argument for a template template-parameter shall be
1730 // the name of a class template, expressed as id-expression. Only
1731 // primary class templates are considered when matching the
1732 // template template argument with the corresponding parameter;
1733 // partial specializations are not considered even if their
1734 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001735 //
1736 // Note that we also allow template template parameters here, which
1737 // will happen when we are dealing with, e.g., class template
1738 // partial specializations.
1739 if (!isa<ClassTemplateDecl>(Template) &&
1740 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001741 assert(isa<FunctionTemplateDecl>(Template) &&
1742 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001743 Diag(Arg->getSourceRange().getBegin(),
1744 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001745 << Template;
1746 }
1747
1748 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1749 Param->getTemplateParameters(),
1750 true, true,
1751 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001752}
1753
Douglas Gregord406b032009-02-06 22:42:48 +00001754/// \brief Determine whether the given template parameter lists are
1755/// equivalent.
1756///
1757/// \param New The new template parameter list, typically written in the
1758/// source code as part of a new template declaration.
1759///
1760/// \param Old The old template parameter list, typically found via
1761/// name lookup of the template declared with this template parameter
1762/// list.
1763///
1764/// \param Complain If true, this routine will produce a diagnostic if
1765/// the template parameter lists are not equivalent.
1766///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001767/// \param IsTemplateTemplateParm If true, this routine is being
1768/// called to compare the template parameter lists of a template
1769/// template parameter.
1770///
1771/// \param TemplateArgLoc If this source location is valid, then we
1772/// are actually checking the template parameter list of a template
1773/// argument (New) against the template parameter list of its
1774/// corresponding template template parameter (Old). We produce
1775/// slightly different diagnostics in this scenario.
1776///
Douglas Gregord406b032009-02-06 22:42:48 +00001777/// \returns True if the template parameter lists are equal, false
1778/// otherwise.
1779bool
1780Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1781 TemplateParameterList *Old,
1782 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001783 bool IsTemplateTemplateParm,
1784 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001785 if (Old->size() != New->size()) {
1786 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001787 unsigned NextDiag = diag::err_template_param_list_different_arity;
1788 if (TemplateArgLoc.isValid()) {
1789 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1790 NextDiag = diag::note_template_param_list_different_arity;
1791 }
1792 Diag(New->getTemplateLoc(), NextDiag)
1793 << (New->size() > Old->size())
1794 << IsTemplateTemplateParm
1795 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001796 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1797 << IsTemplateTemplateParm
1798 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1799 }
1800
1801 return false;
1802 }
1803
1804 for (TemplateParameterList::iterator OldParm = Old->begin(),
1805 OldParmEnd = Old->end(), NewParm = New->begin();
1806 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1807 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001808 unsigned NextDiag = diag::err_template_param_different_kind;
1809 if (TemplateArgLoc.isValid()) {
1810 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1811 NextDiag = diag::note_template_param_different_kind;
1812 }
1813 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001814 << IsTemplateTemplateParm;
1815 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1816 << IsTemplateTemplateParm;
1817 return false;
1818 }
1819
1820 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1821 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001822 // know we're at the same index).
1823#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001824 // FIXME: Enable this code in debug mode *after* we properly go through
1825 // and "instantiate" the template parameter lists of template template
1826 // parameters. It's only after this instantiation that (1) any dependent
1827 // types within the template parameter list of the template template
1828 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001829 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001830 QualType OldParmType
1831 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1832 QualType NewParmType
1833 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1834 assert(Context.getCanonicalType(OldParmType) ==
1835 Context.getCanonicalType(NewParmType) &&
1836 "type parameter mismatch?");
1837#endif
1838 } else if (NonTypeTemplateParmDecl *OldNTTP
1839 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1840 // The types of non-type template parameters must agree.
1841 NonTypeTemplateParmDecl *NewNTTP
1842 = cast<NonTypeTemplateParmDecl>(*NewParm);
1843 if (Context.getCanonicalType(OldNTTP->getType()) !=
1844 Context.getCanonicalType(NewNTTP->getType())) {
1845 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001846 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1847 if (TemplateArgLoc.isValid()) {
1848 Diag(TemplateArgLoc,
1849 diag::err_template_arg_template_params_mismatch);
1850 NextDiag = diag::note_template_nontype_parm_different_type;
1851 }
1852 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001853 << NewNTTP->getType()
1854 << IsTemplateTemplateParm;
1855 Diag(OldNTTP->getLocation(),
1856 diag::note_template_nontype_parm_prev_declaration)
1857 << OldNTTP->getType();
1858 }
1859 return false;
1860 }
1861 } else {
1862 // The template parameter lists of template template
1863 // parameters must agree.
1864 // FIXME: Could we perform a faster "type" comparison here?
1865 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1866 "Only template template parameters handled here");
1867 TemplateTemplateParmDecl *OldTTP
1868 = cast<TemplateTemplateParmDecl>(*OldParm);
1869 TemplateTemplateParmDecl *NewTTP
1870 = cast<TemplateTemplateParmDecl>(*NewParm);
1871 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1872 OldTTP->getTemplateParameters(),
1873 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001874 /*IsTemplateTemplateParm=*/true,
1875 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001876 return false;
1877 }
1878 }
1879
1880 return true;
1881}
1882
1883/// \brief Check whether a template can be declared within this scope.
1884///
1885/// If the template declaration is valid in this scope, returns
1886/// false. Otherwise, issues a diagnostic and returns true.
1887bool
1888Sema::CheckTemplateDeclScope(Scope *S,
1889 MultiTemplateParamsArg &TemplateParameterLists) {
1890 assert(TemplateParameterLists.size() > 0 && "Not a template");
1891
1892 // Find the nearest enclosing declaration scope.
1893 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1894 (S->getFlags() & Scope::TemplateParamScope) != 0)
1895 S = S->getParent();
1896
1897 TemplateParameterList *TemplateParams =
1898 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1899 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1900 SourceRange TemplateRange
1901 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1902
1903 // C++ [temp]p2:
1904 // A template-declaration can appear only as a namespace scope or
1905 // class scope declaration.
1906 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1907 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1908 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1909 return Diag(TemplateLoc, diag::err_template_linkage)
1910 << TemplateRange;
1911
1912 Ctx = Ctx->getParent();
1913 }
1914
1915 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1916 return false;
1917
1918 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1919 << TemplateRange;
1920}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001921
Douglas Gregor90177912009-05-13 18:28:20 +00001922/// \brief Check whether a class template specialization or explicit
1923/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001924///
Douglas Gregor90177912009-05-13 18:28:20 +00001925/// This routine determines whether a class template specialization or
1926/// explicit instantiation can be declared in the current context
1927/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1928/// appropriate diagnostics if there was an error. It returns true if
1929// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001930bool
1931Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1932 ClassTemplateSpecializationDecl *PrevDecl,
1933 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001934 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001935 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001936 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001937 // C++ [temp.expl.spec]p2:
1938 // An explicit specialization shall be declared in the namespace
1939 // of which the template is a member, or, for member templates, in
1940 // the namespace of which the enclosing class or enclosing class
1941 // template is a member. An explicit specialization of a member
1942 // function, member class or static data member of a class
1943 // template shall be declared in the namespace of which the class
1944 // template is a member. Such a declaration may also be a
1945 // definition. If the declaration is not a definition, the
1946 // specialization may be defined later in the name- space in which
1947 // the explicit specialization was declared, or in a namespace
1948 // that encloses the one in which the explicit specialization was
1949 // declared.
1950 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00001951 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001952 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001953 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001954 return true;
1955 }
1956
1957 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1958 DeclContext *TemplateContext
1959 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001960 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1961 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001962 // There is no prior declaration of this entity, so this
1963 // specialization must be in the same context as the template
1964 // itself.
1965 if (DC != TemplateContext) {
1966 if (isa<TranslationUnitDecl>(TemplateContext))
1967 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001968 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00001969 << ClassTemplate << ScopeSpecifierRange;
1970 else if (isa<NamespaceDecl>(TemplateContext))
1971 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001972 << PartialSpecialization << ClassTemplate
1973 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001974
1975 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1976 }
1977
1978 return false;
1979 }
1980
1981 // We have a previous declaration of this entity. Make sure that
1982 // this redeclaration (or definition) occurs in an enclosing namespace.
1983 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001984 // FIXME: In C++98, we would like to turn these errors into warnings,
1985 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00001986 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00001987 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00001988 if (isa<TranslationUnitDecl>(TemplateContext)) {
1989 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1990 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001991 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00001992 else
1993 SuppressedDiag = true;
1994 } else if (isa<NamespaceDecl>(TemplateContext)) {
1995 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1996 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001997 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00001998 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
1999 else
2000 SuppressedDiag = true;
2001 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002002
Douglas Gregor90177912009-05-13 18:28:20 +00002003 if (!SuppressedDiag)
2004 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002005 }
2006
2007 return false;
2008}
2009
Douglas Gregor76e79952009-06-12 21:21:02 +00002010/// \brief Check the non-type template arguments of a class template
2011/// partial specialization according to C++ [temp.class.spec]p9.
2012///
Douglas Gregor42476442009-06-12 22:08:06 +00002013/// \param TemplateParams the template parameters of the primary class
2014/// template.
2015///
2016/// \param TemplateArg the template arguments of the class template
2017/// partial specialization.
2018///
2019/// \param MirrorsPrimaryTemplate will be set true if the class
2020/// template partial specialization arguments are identical to the
2021/// implicit template arguments of the primary template. This is not
2022/// necessarily an error (C++0x), and it is left to the caller to diagnose
2023/// this condition when it is an error.
2024///
Douglas Gregor76e79952009-06-12 21:21:02 +00002025/// \returns true if there was an error, false otherwise.
2026bool Sema::CheckClassTemplatePartialSpecializationArgs(
2027 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002028 const TemplateArgument *TemplateArgs,
2029 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002030 // FIXME: the interface to this function will have to change to
2031 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002032 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002033 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002034 // Determine whether the template argument list of the partial
2035 // specialization is identical to the implicit argument list of
2036 // the primary template. The caller may need to diagnostic this as
2037 // an error per C++ [temp.class.spec]p9b3.
2038 if (MirrorsPrimaryTemplate) {
2039 if (TemplateTypeParmDecl *TTP
2040 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2041 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2042 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2043 MirrorsPrimaryTemplate = false;
2044 } else if (TemplateTemplateParmDecl *TTP
2045 = dyn_cast<TemplateTemplateParmDecl>(
2046 TemplateParams->getParam(I))) {
2047 // FIXME: We should settle on either Declaration storage or
2048 // Expression storage for template template parameters.
2049 TemplateTemplateParmDecl *ArgDecl
2050 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2051 TemplateArgs[I].getAsDecl());
2052 if (!ArgDecl)
2053 if (DeclRefExpr *DRE
2054 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2055 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2056
2057 if (!ArgDecl ||
2058 ArgDecl->getIndex() != TTP->getIndex() ||
2059 ArgDecl->getDepth() != TTP->getDepth())
2060 MirrorsPrimaryTemplate = false;
2061 }
2062 }
2063
Douglas Gregor76e79952009-06-12 21:21:02 +00002064 NonTypeTemplateParmDecl *Param
2065 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002066 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002067 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002068 }
2069
Douglas Gregor76e79952009-06-12 21:21:02 +00002070 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002071 if (!ArgExpr) {
2072 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002073 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002074 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002075
2076 // C++ [temp.class.spec]p8:
2077 // A non-type argument is non-specialized if it is the name of a
2078 // non-type parameter. All other non-type arguments are
2079 // specialized.
2080 //
2081 // Below, we check the two conditions that only apply to
2082 // specialized non-type arguments, so skip any non-specialized
2083 // arguments.
2084 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002085 if (NonTypeTemplateParmDecl *NTTP
2086 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2087 if (MirrorsPrimaryTemplate &&
2088 (Param->getIndex() != NTTP->getIndex() ||
2089 Param->getDepth() != NTTP->getDepth()))
2090 MirrorsPrimaryTemplate = false;
2091
Douglas Gregor76e79952009-06-12 21:21:02 +00002092 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002093 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002094
2095 // C++ [temp.class.spec]p9:
2096 // Within the argument list of a class template partial
2097 // specialization, the following restrictions apply:
2098 // -- A partially specialized non-type argument expression
2099 // shall not involve a template parameter of the partial
2100 // specialization except when the argument expression is a
2101 // simple identifier.
2102 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2103 Diag(ArgExpr->getLocStart(),
2104 diag::err_dependent_non_type_arg_in_partial_spec)
2105 << ArgExpr->getSourceRange();
2106 return true;
2107 }
2108
2109 // -- The type of a template parameter corresponding to a
2110 // specialized non-type argument shall not be dependent on a
2111 // parameter of the specialization.
2112 if (Param->getType()->isDependentType()) {
2113 Diag(ArgExpr->getLocStart(),
2114 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2115 << Param->getType()
2116 << ArgExpr->getSourceRange();
2117 Diag(Param->getLocation(), diag::note_template_param_here);
2118 return true;
2119 }
Douglas Gregor42476442009-06-12 22:08:06 +00002120
2121 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002122 }
2123
2124 return false;
2125}
2126
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002127Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002128Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2129 SourceLocation KWLoc,
2130 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002131 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002132 SourceLocation TemplateNameLoc,
2133 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002134 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002135 SourceLocation *TemplateArgLocs,
2136 SourceLocation RAngleLoc,
2137 AttributeList *Attr,
2138 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002139 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002140 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002141 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002142 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002143
Douglas Gregor58944ac2009-05-31 09:31:02 +00002144 bool isPartialSpecialization = false;
2145
Douglas Gregor0d93f692009-02-25 22:02:03 +00002146 // Check the validity of the template headers that introduce this
2147 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002148 // FIXME: Once we have member templates, we'll need to check
2149 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2150 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002151 if (TemplateParameterLists.size() == 0)
2152 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002153 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002154 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002155 TemplateParameterList *TemplateParams
2156 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002157 if (TemplateParameterLists.size() > 1) {
2158 Diag(TemplateParams->getTemplateLoc(),
2159 diag::err_template_spec_extra_headers);
2160 return true;
2161 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002162
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002163 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002164 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002165
2166 // C++ [temp.class.spec]p10:
2167 // The template parameter list of a specialization shall not
2168 // contain default template argument values.
2169 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2170 Decl *Param = TemplateParams->getParam(I);
2171 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2172 if (TTP->hasDefaultArgument()) {
2173 Diag(TTP->getDefaultArgumentLoc(),
2174 diag::err_default_arg_in_partial_spec);
2175 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2176 }
2177 } else if (NonTypeTemplateParmDecl *NTTP
2178 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2179 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2180 Diag(NTTP->getDefaultArgumentLoc(),
2181 diag::err_default_arg_in_partial_spec)
2182 << DefArg->getSourceRange();
2183 NTTP->setDefaultArgument(0);
2184 DefArg->Destroy(Context);
2185 }
2186 } else {
2187 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2188 if (Expr *DefArg = TTP->getDefaultArgument()) {
2189 Diag(TTP->getDefaultArgumentLoc(),
2190 diag::err_default_arg_in_partial_spec)
2191 << DefArg->getSourceRange();
2192 TTP->setDefaultArgument(0);
2193 DefArg->Destroy(Context);
2194 }
2195 }
2196 }
2197 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002198 }
2199
Douglas Gregora08b6c72009-02-17 23:15:12 +00002200 // Check that the specialization uses the same tag kind as the
2201 // original template.
2202 TagDecl::TagKind Kind;
2203 switch (TagSpec) {
2204 default: assert(0 && "Unknown tag type!");
2205 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2206 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2207 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2208 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002209 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2210 Kind, KWLoc,
2211 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002212 Diag(KWLoc, diag::err_use_with_wrong_tag)
2213 << ClassTemplate
2214 << CodeModificationHint::CreateReplacement(KWLoc,
2215 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002216 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2217 diag::note_previous_use);
2218 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2219 }
2220
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002221 // Translate the parser's template argument list in our AST format.
2222 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2223 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2224
Douglas Gregora08b6c72009-02-17 23:15:12 +00002225 // Check that the template argument list is well-formed for this
2226 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002227 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002228 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002229 &TemplateArgs[0], TemplateArgs.size(),
2230 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002231 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002232
2233 assert((ConvertedTemplateArgs.size() ==
2234 ClassTemplate->getTemplateParameters()->size()) &&
2235 "Converted template argument list is too short!");
2236
Douglas Gregor58944ac2009-05-31 09:31:02 +00002237 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002238 // corresponds to these arguments.
2239 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002240 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002241 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002242 if (CheckClassTemplatePartialSpecializationArgs(
2243 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002244 ConvertedTemplateArgs.getFlatArgumentList(),
2245 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002246 return true;
2247
Douglas Gregor42476442009-06-12 22:08:06 +00002248 if (MirrorsPrimaryTemplate) {
2249 // C++ [temp.class.spec]p9b3:
2250 //
2251 // -- The argument list of the specialization shall not be identical
2252 // to the implicit argument list of the primary template.
2253 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2254 << (TK == TK_Definition)
2255 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2256 RAngleLoc));
2257 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2258 ClassTemplate->getIdentifier(),
2259 TemplateNameLoc,
2260 Attr,
2261 move(TemplateParameterLists),
2262 AS_none);
2263 }
2264
Douglas Gregor58944ac2009-05-31 09:31:02 +00002265 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002266 ClassTemplatePartialSpecializationDecl::Profile(ID,
2267 ConvertedTemplateArgs.getFlatArgumentList(),
2268 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002269 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002270 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002271 ClassTemplateSpecializationDecl::Profile(ID,
2272 ConvertedTemplateArgs.getFlatArgumentList(),
2273 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002274 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002275 ClassTemplateSpecializationDecl *PrevDecl = 0;
2276
2277 if (isPartialSpecialization)
2278 PrevDecl
2279 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2280 InsertPos);
2281 else
2282 PrevDecl
2283 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002284
2285 ClassTemplateSpecializationDecl *Specialization = 0;
2286
Douglas Gregor0d93f692009-02-25 22:02:03 +00002287 // Check whether we can declare a class template specialization in
2288 // the current scope.
2289 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2290 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002291 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002292 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002293 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002294 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002295
Douglas Gregora08b6c72009-02-17 23:15:12 +00002296 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2297 // Since the only prior class template specialization with these
2298 // arguments was referenced but not declared, reuse that
2299 // declaration node as our own, updating its source location to
2300 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002301 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002302 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002303 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002304 } else if (isPartialSpecialization) {
2305 // FIXME: extra checking for partial specializations
2306
2307 // Create a new class template partial specialization declaration node.
2308 TemplateParameterList *TemplateParams
2309 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2310 ClassTemplatePartialSpecializationDecl *PrevPartial
2311 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2312 ClassTemplatePartialSpecializationDecl *Partial
2313 = ClassTemplatePartialSpecializationDecl::Create(Context,
2314 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002315 TemplateNameLoc,
2316 TemplateParams,
2317 ClassTemplate,
2318 ConvertedTemplateArgs,
2319 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002320
2321 if (PrevPartial) {
2322 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2323 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2324 } else {
2325 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2326 }
2327 Specialization = Partial;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002328 } else {
2329 // Create a new class template specialization declaration node for
2330 // this explicit specialization.
2331 Specialization
2332 = ClassTemplateSpecializationDecl::Create(Context,
2333 ClassTemplate->getDeclContext(),
2334 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002335 ClassTemplate,
2336 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002337 PrevDecl);
2338
2339 if (PrevDecl) {
2340 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2341 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2342 } else {
2343 ClassTemplate->getSpecializations().InsertNode(Specialization,
2344 InsertPos);
2345 }
2346 }
2347
2348 // Note that this is an explicit specialization.
2349 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2350
2351 // Check that this isn't a redefinition of this specialization.
2352 if (TK == TK_Definition) {
2353 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002354 // FIXME: Should also handle explicit specialization after implicit
2355 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002356 SourceRange Range(TemplateNameLoc, RAngleLoc);
2357 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002358 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002359 Diag(Def->getLocation(), diag::note_previous_definition);
2360 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002361 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002362 }
2363 }
2364
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002365 // Build the fully-sugared type for this class template
2366 // specialization as the user wrote in the specialization
2367 // itself. This means that we'll pretty-print the type retrieved
2368 // from the specialization's declaration the way that the user
2369 // actually wrote the specialization, rather than formatting the
2370 // name based on the "canonical" representation used to store the
2371 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002372 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002373 = Context.getTemplateSpecializationType(Name,
2374 &TemplateArgs[0],
2375 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002376 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002377 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002378 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002379
Douglas Gregor50113ca2009-02-25 22:18:32 +00002380 // C++ [temp.expl.spec]p9:
2381 // A template explicit specialization is in the scope of the
2382 // namespace in which the template was defined.
2383 //
2384 // We actually implement this paragraph where we set the semantic
2385 // context (in the creation of the ClassTemplateSpecializationDecl),
2386 // but we also maintain the lexical context where the actual
2387 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002388 Specialization->setLexicalDeclContext(CurContext);
2389
2390 // We may be starting the definition of this specialization.
2391 if (TK == TK_Definition)
2392 Specialization->startDefinition();
2393
2394 // Add the specialization into its lexical context, so that it can
2395 // be seen when iterating through the list of declarations in that
2396 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002397 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002398 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002399}
Douglas Gregord3022602009-03-27 23:10:48 +00002400
Douglas Gregor96b6df92009-05-14 00:28:11 +00002401// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002402Sema::DeclResult
2403Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2404 unsigned TagSpec,
2405 SourceLocation KWLoc,
2406 const CXXScopeSpec &SS,
2407 TemplateTy TemplateD,
2408 SourceLocation TemplateNameLoc,
2409 SourceLocation LAngleLoc,
2410 ASTTemplateArgsPtr TemplateArgsIn,
2411 SourceLocation *TemplateArgLocs,
2412 SourceLocation RAngleLoc,
2413 AttributeList *Attr) {
2414 // Find the class template we're specializing
2415 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2416 ClassTemplateDecl *ClassTemplate
2417 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2418
2419 // Check that the specialization uses the same tag kind as the
2420 // original template.
2421 TagDecl::TagKind Kind;
2422 switch (TagSpec) {
2423 default: assert(0 && "Unknown tag type!");
2424 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2425 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2426 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2427 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002428 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2429 Kind, KWLoc,
2430 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002431 Diag(KWLoc, diag::err_use_with_wrong_tag)
2432 << ClassTemplate
2433 << CodeModificationHint::CreateReplacement(KWLoc,
2434 ClassTemplate->getTemplatedDecl()->getKindName());
2435 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2436 diag::note_previous_use);
2437 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2438 }
2439
Douglas Gregor90177912009-05-13 18:28:20 +00002440 // C++0x [temp.explicit]p2:
2441 // [...] An explicit instantiation shall appear in an enclosing
2442 // namespace of its template. [...]
2443 //
2444 // This is C++ DR 275.
2445 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2446 TemplateNameLoc,
2447 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002448 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002449 /*ExplicitInstantiation=*/true))
2450 return true;
2451
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002452 // Translate the parser's template argument list in our AST format.
2453 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2454 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2455
2456 // Check that the template argument list is well-formed for this
2457 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002458 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002459 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002460 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002461 RAngleLoc, ConvertedTemplateArgs))
2462 return true;
2463
2464 assert((ConvertedTemplateArgs.size() ==
2465 ClassTemplate->getTemplateParameters()->size()) &&
2466 "Converted template argument list is too short!");
2467
2468 // Find the class template specialization declaration that
2469 // corresponds to these arguments.
2470 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002471 ClassTemplateSpecializationDecl::Profile(ID,
2472 ConvertedTemplateArgs.getFlatArgumentList(),
2473 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002474 void *InsertPos = 0;
2475 ClassTemplateSpecializationDecl *PrevDecl
2476 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2477
2478 ClassTemplateSpecializationDecl *Specialization = 0;
2479
Douglas Gregor90177912009-05-13 18:28:20 +00002480 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002481 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002482 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002483 // This particular specialization has already been declared or
2484 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002485 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2486 << Context.getTypeDeclType(PrevDecl);
2487 Diag(PrevDecl->getLocation(),
2488 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002489 return DeclPtrTy::make(PrevDecl);
2490 }
2491
Douglas Gregor90177912009-05-13 18:28:20 +00002492 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002493 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002494 // For a given set of template parameters, if an explicit
2495 // instantiation of a template appears after a declaration of
2496 // an explicit specialization for that template, the explicit
2497 // instantiation has no effect.
2498 if (!getLangOptions().CPlusPlus0x) {
2499 Diag(TemplateNameLoc,
2500 diag::ext_explicit_instantiation_after_specialization)
2501 << Context.getTypeDeclType(PrevDecl);
2502 Diag(PrevDecl->getLocation(),
2503 diag::note_previous_template_specialization);
2504 }
2505
2506 // Create a new class template specialization declaration node
2507 // for this explicit specialization. This node is only used to
2508 // record the existence of this explicit instantiation for
2509 // accurate reproduction of the source code; we don't actually
2510 // use it for anything, since it is semantically irrelevant.
2511 Specialization
2512 = ClassTemplateSpecializationDecl::Create(Context,
2513 ClassTemplate->getDeclContext(),
2514 TemplateNameLoc,
2515 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002516 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002517 Specialization->setLexicalDeclContext(CurContext);
2518 CurContext->addDecl(Context, Specialization);
2519 return DeclPtrTy::make(Specialization);
2520 }
2521
2522 // If we have already (implicitly) instantiated this
2523 // specialization, there is less work to do.
2524 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2525 SpecializationRequiresInstantiation = false;
2526
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002527 // Since the only prior class template specialization with these
2528 // arguments was referenced but not declared, reuse that
2529 // declaration node as our own, updating its source location to
2530 // reflect our new declaration.
2531 Specialization = PrevDecl;
2532 Specialization->setLocation(TemplateNameLoc);
2533 PrevDecl = 0;
2534 } else {
2535 // Create a new class template specialization declaration node for
2536 // this explicit specialization.
2537 Specialization
2538 = ClassTemplateSpecializationDecl::Create(Context,
2539 ClassTemplate->getDeclContext(),
2540 TemplateNameLoc,
2541 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002542 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002543
2544 ClassTemplate->getSpecializations().InsertNode(Specialization,
2545 InsertPos);
2546 }
2547
2548 // Build the fully-sugared type for this explicit instantiation as
2549 // the user wrote in the explicit instantiation itself. This means
2550 // that we'll pretty-print the type retrieved from the
2551 // specialization's declaration the way that the user actually wrote
2552 // the explicit instantiation, rather than formatting the name based
2553 // on the "canonical" representation used to store the template
2554 // arguments in the specialization.
2555 QualType WrittenTy
2556 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002557 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002558 TemplateArgs.size(),
2559 Context.getTypeDeclType(Specialization));
2560 Specialization->setTypeAsWritten(WrittenTy);
2561 TemplateArgsIn.release();
2562
2563 // Add the explicit instantiation into its lexical context. However,
2564 // since explicit instantiations are never found by name lookup, we
2565 // just put it into the declaration context directly.
2566 Specialization->setLexicalDeclContext(CurContext);
2567 CurContext->addDecl(Context, Specialization);
2568
2569 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002570 // A definition of a class template or class member template
2571 // shall be in scope at the point of the explicit instantiation of
2572 // the class template or class member template.
2573 //
2574 // This check comes when we actually try to perform the
2575 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002576 if (SpecializationRequiresInstantiation)
2577 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002578 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002579 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002580
2581 return DeclPtrTy::make(Specialization);
2582}
2583
Douglas Gregor96b6df92009-05-14 00:28:11 +00002584// Explicit instantiation of a member class of a class template.
2585Sema::DeclResult
2586Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2587 unsigned TagSpec,
2588 SourceLocation KWLoc,
2589 const CXXScopeSpec &SS,
2590 IdentifierInfo *Name,
2591 SourceLocation NameLoc,
2592 AttributeList *Attr) {
2593
Douglas Gregor71f06032009-05-28 23:31:59 +00002594 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002595 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002596 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002597 if (!TagD)
2598 return true;
2599
2600 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2601 if (Tag->isEnum()) {
2602 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2603 << Context.getTypeDeclType(Tag);
2604 return true;
2605 }
2606
Douglas Gregord769bfa2009-05-27 17:30:49 +00002607 if (Tag->isInvalidDecl())
2608 return true;
2609
Douglas Gregor96b6df92009-05-14 00:28:11 +00002610 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2611 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2612 if (!Pattern) {
2613 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2614 << Context.getTypeDeclType(Record);
2615 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2616 return true;
2617 }
2618
2619 // C++0x [temp.explicit]p2:
2620 // [...] An explicit instantiation shall appear in an enclosing
2621 // namespace of its template. [...]
2622 //
2623 // This is C++ DR 275.
2624 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002625 // FIXME: In C++98, we would like to turn these errors into warnings,
2626 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002627 DeclContext *PatternContext
2628 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2629 if (!CurContext->Encloses(PatternContext)) {
2630 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2631 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2632 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2633 }
2634 }
2635
Douglas Gregor96b6df92009-05-14 00:28:11 +00002636 if (!Record->getDefinition(Context)) {
2637 // If the class has a definition, instantiate it (and all of its
2638 // members, recursively).
2639 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2640 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002641 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002642 /*ExplicitInstantiation=*/true))
2643 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002644 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002645 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002646 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002647
Mike Stumpe127ae32009-05-16 07:39:55 +00002648 // FIXME: We don't have any representation for explicit instantiations of
2649 // member classes. Such a representation is not needed for compilation, but it
2650 // should be available for clients that want to see all of the declarations in
2651 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002652 return TagD;
2653}
2654
Douglas Gregord3022602009-03-27 23:10:48 +00002655Sema::TypeResult
2656Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2657 const IdentifierInfo &II, SourceLocation IdLoc) {
2658 NestedNameSpecifier *NNS
2659 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2660 if (!NNS)
2661 return true;
2662
2663 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002664 if (T.isNull())
2665 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002666 return T.getAsOpaquePtr();
2667}
2668
Douglas Gregor77da5802009-04-01 00:28:59 +00002669Sema::TypeResult
2670Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2671 SourceLocation TemplateLoc, TypeTy *Ty) {
2672 QualType T = QualType::getFromOpaquePtr(Ty);
2673 NestedNameSpecifier *NNS
2674 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2675 const TemplateSpecializationType *TemplateId
2676 = T->getAsTemplateSpecializationType();
2677 assert(TemplateId && "Expected a template specialization type");
2678
2679 if (NNS->isDependent())
2680 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2681
2682 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2683}
2684
Douglas Gregord3022602009-03-27 23:10:48 +00002685/// \brief Build the type that describes a C++ typename specifier,
2686/// e.g., "typename T::type".
2687QualType
2688Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2689 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002690 CXXRecordDecl *CurrentInstantiation = 0;
2691 if (NNS->isDependent()) {
2692 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002693
Douglas Gregor3eb20702009-05-11 19:58:34 +00002694 // If the nested-name-specifier does not refer to the current
2695 // instantiation, then build a typename type.
2696 if (!CurrentInstantiation)
2697 return Context.getTypenameType(NNS, &II);
2698 }
Douglas Gregord3022602009-03-27 23:10:48 +00002699
Douglas Gregor3eb20702009-05-11 19:58:34 +00002700 DeclContext *Ctx = 0;
2701
2702 if (CurrentInstantiation)
2703 Ctx = CurrentInstantiation;
2704 else {
2705 CXXScopeSpec SS;
2706 SS.setScopeRep(NNS);
2707 SS.setRange(Range);
2708 if (RequireCompleteDeclContext(SS))
2709 return QualType();
2710
2711 Ctx = computeDeclContext(SS);
2712 }
Douglas Gregord3022602009-03-27 23:10:48 +00002713 assert(Ctx && "No declaration context?");
2714
2715 DeclarationName Name(&II);
2716 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2717 false);
2718 unsigned DiagID = 0;
2719 Decl *Referenced = 0;
2720 switch (Result.getKind()) {
2721 case LookupResult::NotFound:
2722 if (Ctx->isTranslationUnit())
2723 DiagID = diag::err_typename_nested_not_found_global;
2724 else
2725 DiagID = diag::err_typename_nested_not_found;
2726 break;
2727
2728 case LookupResult::Found:
2729 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2730 // We found a type. Build a QualifiedNameType, since the
2731 // typename-specifier was just sugar. FIXME: Tell
2732 // QualifiedNameType that it has a "typename" prefix.
2733 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2734 }
2735
2736 DiagID = diag::err_typename_nested_not_type;
2737 Referenced = Result.getAsDecl();
2738 break;
2739
2740 case LookupResult::FoundOverloaded:
2741 DiagID = diag::err_typename_nested_not_type;
2742 Referenced = *Result.begin();
2743 break;
2744
2745 case LookupResult::AmbiguousBaseSubobjectTypes:
2746 case LookupResult::AmbiguousBaseSubobjects:
2747 case LookupResult::AmbiguousReference:
2748 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2749 return QualType();
2750 }
2751
2752 // If we get here, it's because name lookup did not find a
2753 // type. Emit an appropriate diagnostic and return an error.
2754 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2755 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2756 else
2757 Diag(Range.getEnd(), DiagID) << Range << Name;
2758 if (Referenced)
2759 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2760 << Name;
2761 return QualType();
2762}