blob: 00d3e54565e266951c26bd919ccf8d2cce56702e [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregord406b032009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000166 Depth, Position, ParamName, Typename,
167 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000168 if (Invalid)
169 Param->setInvalidDecl();
170
171 if (ParamName) {
172 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000173 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000174 IdResolver.AddDecl(Param);
175 }
176
Chris Lattner5261d0c2009-03-28 19:18:32 +0000177 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000178}
179
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000183 SourceLocation EqualLoc,
184 SourceLocation DefaultLoc,
185 TypeTy *DefaultT) {
186 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000187 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000188 QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
Anders Carlssona2333782009-06-12 22:30:13 +0000190 // C++0x [temp.param]p9:
191 // A default template-argument may be specified for any kind of
192 // template-parameter that is not a template parameter pack.
193 if (Parm->isParameterPack()) {
194 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
195 Parm->setInvalidDecl();
196 return;
197 }
198
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000199 // C++ [temp.param]p14:
200 // A template-parameter shall not be used in its own default argument.
201 // FIXME: Implement this check! Needs a recursive walk over the types.
202
203 // Check the template argument itself.
204 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
205 Parm->setInvalidDecl();
206 return;
207 }
208
209 Parm->setDefaultArgument(Default, DefaultLoc, false);
210}
211
Douglas Gregored3a3982009-03-03 04:44:36 +0000212/// \brief Check that the type of a non-type template parameter is
213/// well-formed.
214///
215/// \returns the (possibly-promoted) parameter type if valid;
216/// otherwise, produces a diagnostic and returns a NULL type.
217QualType
218Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
219 // C++ [temp.param]p4:
220 //
221 // A non-type template-parameter shall have one of the following
222 // (optionally cv-qualified) types:
223 //
224 // -- integral or enumeration type,
225 if (T->isIntegralType() || T->isEnumeralType() ||
226 // -- pointer to object or pointer to function,
227 (T->isPointerType() &&
228 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
229 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
230 // -- reference to object or reference to function,
231 T->isReferenceType() ||
232 // -- pointer to member.
233 T->isMemberPointerType() ||
234 // If T is a dependent type, we can't do the check now, so we
235 // assume that it is well-formed.
236 T->isDependentType())
237 return T;
238 // C++ [temp.param]p8:
239 //
240 // A non-type template-parameter of type "array of T" or
241 // "function returning T" is adjusted to be of type "pointer to
242 // T" or "pointer to function returning T", respectively.
243 else if (T->isArrayType())
244 // FIXME: Keep the type prior to promotion?
245 return Context.getArrayDecayedType(T);
246 else if (T->isFunctionType())
247 // FIXME: Keep the type prior to promotion?
248 return Context.getPointerType(T);
249
250 Diag(Loc, diag::err_template_nontype_parm_bad_type)
251 << T;
252
253 return QualType();
254}
255
Douglas Gregordd861062008-12-05 18:15:24 +0000256/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
257/// template parameter (e.g., "int Size" in "template<int Size>
258/// class Array") has been parsed. S is the current scope and D is
259/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000260Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
261 unsigned Depth,
262 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000263 QualType T = GetTypeForDeclarator(D, S);
264
Douglas Gregor279272e2009-02-04 19:02:06 +0000265 assert(S->isTemplateParamScope() &&
266 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000267 bool Invalid = false;
268
269 IdentifierInfo *ParamName = D.getIdentifier();
270 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000271 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000272 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000273 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000275 }
276
Douglas Gregored3a3982009-03-03 04:44:36 +0000277 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000278 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000279 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000280 Invalid = true;
281 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000282
Douglas Gregordd861062008-12-05 18:15:24 +0000283 NonTypeTemplateParmDecl *Param
284 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000285 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000286 if (Invalid)
287 Param->setInvalidDecl();
288
289 if (D.getIdentifier()) {
290 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000291 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000292 IdResolver.AddDecl(Param);
293 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000294 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000295}
Douglas Gregor52473432008-12-24 02:52:09 +0000296
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000297/// \brief Adds a default argument to the given non-type template
298/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000299void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000300 SourceLocation EqualLoc,
301 ExprArg DefaultE) {
302 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000303 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000304 Expr *Default = static_cast<Expr *>(DefaultE.get());
305
306 // C++ [temp.param]p14:
307 // A template-parameter shall not be used in its own default argument.
308 // FIXME: Implement this check! Needs a recursive walk over the types.
309
310 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000311 TemplateArgument Converted;
312 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
313 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000314 TemplateParm->setInvalidDecl();
315 return;
316 }
317
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000318 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000319}
320
Douglas Gregor279272e2009-02-04 19:02:06 +0000321
322/// ActOnTemplateTemplateParameter - Called when a C++ template template
323/// parameter (e.g. T in template <template <typename> class T> class array)
324/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000325Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
326 SourceLocation TmpLoc,
327 TemplateParamsTy *Params,
328 IdentifierInfo *Name,
329 SourceLocation NameLoc,
330 unsigned Depth,
331 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000332{
333 assert(S->isTemplateParamScope() &&
334 "Template template parameter not in template parameter scope!");
335
336 // Construct the parameter object.
337 TemplateTemplateParmDecl *Param =
338 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
339 Position, Name,
340 (TemplateParameterList*)Params);
341
342 // Make sure the parameter is valid.
343 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
344 // do anything yet. However, if the template parameter list or (eventual)
345 // default value is ever invalidated, that will propagate here.
346 bool Invalid = false;
347 if (Invalid) {
348 Param->setInvalidDecl();
349 }
350
351 // If the tt-param has a name, then link the identifier into the scope
352 // and lookup mechanisms.
353 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000355 IdResolver.AddDecl(Param);
356 }
357
Chris Lattner5261d0c2009-03-28 19:18:32 +0000358 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000359}
360
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000361/// \brief Adds a default argument to the given template template
362/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000363void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000364 SourceLocation EqualLoc,
365 ExprArg DefaultE) {
366 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000367 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000368
369 // Since a template-template parameter's default argument is an
370 // id-expression, it must be a DeclRefExpr.
371 DeclRefExpr *Default
372 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
373
374 // C++ [temp.param]p14:
375 // A template-parameter shall not be used in its own default argument.
376 // FIXME: Implement this check! Needs a recursive walk over the types.
377
378 // Check the well-formedness of the template argument.
379 if (!isa<TemplateDecl>(Default->getDecl())) {
380 Diag(Default->getSourceRange().getBegin(),
381 diag::err_template_arg_must_be_template)
382 << Default->getSourceRange();
383 TemplateParm->setInvalidDecl();
384 return;
385 }
386 if (CheckTemplateArgument(TemplateParm, Default)) {
387 TemplateParm->setInvalidDecl();
388 return;
389 }
390
391 DefaultE.release();
392 TemplateParm->setDefaultArgument(Default);
393}
394
Douglas Gregor52473432008-12-24 02:52:09 +0000395/// ActOnTemplateParameterList - Builds a TemplateParameterList that
396/// contains the template parameters in Params/NumParams.
397Sema::TemplateParamsTy *
398Sema::ActOnTemplateParameterList(unsigned Depth,
399 SourceLocation ExportLoc,
400 SourceLocation TemplateLoc,
401 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000402 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000403 SourceLocation RAngleLoc) {
404 if (ExportLoc.isValid())
405 Diag(ExportLoc, diag::note_template_export_unsupported);
406
Douglas Gregord406b032009-02-06 22:42:48 +0000407 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
408 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000409}
Douglas Gregor279272e2009-02-04 19:02:06 +0000410
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000412Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
413 SourceLocation KWLoc, const CXXScopeSpec &SS,
414 IdentifierInfo *Name, SourceLocation NameLoc,
415 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000416 MultiTemplateParamsArg TemplateParameterLists,
417 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000418 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
419 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000420 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000421
422 // Check that we can declare a template here.
423 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000425
426 TagDecl::TagKind Kind;
427 switch (TagSpec) {
428 default: assert(0 && "Unknown tag type!");
429 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
430 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
431 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
432 }
433
434 // There is no such thing as an unnamed class template.
435 if (!Name) {
436 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000437 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000438 }
439
440 // Find any previous declaration with this name.
441 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
442 true);
443 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
444 NamedDecl *PrevDecl = 0;
445 if (Previous.begin() != Previous.end())
446 PrevDecl = *Previous.begin();
447
448 DeclContext *SemanticContext = CurContext;
449 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000450 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000451
Mike Stumpe127ae32009-05-16 07:39:55 +0000452 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000453 }
454
455 // FIXME: member templates!
456 TemplateParameterList *TemplateParams
457 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
458
459 // If there is a previous declaration with the same name, check
460 // whether this is a valid redeclaration.
461 ClassTemplateDecl *PrevClassTemplate
462 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
463 if (PrevClassTemplate) {
464 // Ensure that the template parameter lists are compatible.
465 if (!TemplateParameterListsAreEqual(TemplateParams,
466 PrevClassTemplate->getTemplateParameters(),
467 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000468 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000469
470 // C++ [temp.class]p4:
471 // In a redeclaration, partial specialization, explicit
472 // specialization or explicit instantiation of a class template,
473 // the class-key shall agree in kind with the original class
474 // template declaration (7.1.5.3).
475 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000476 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000477 Diag(KWLoc, diag::err_use_with_wrong_tag)
478 << Name
479 << CodeModificationHint::CreateReplacement(KWLoc,
480 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000481 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000482 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000483 }
484
Douglas Gregord406b032009-02-06 22:42:48 +0000485 // Check for redefinition of this class template.
486 if (TK == TK_Definition) {
487 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
488 Diag(NameLoc, diag::err_redefinition) << Name;
489 Diag(Def->getLocation(), diag::note_previous_definition);
490 // FIXME: Would it make sense to try to "forget" the previous
491 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000492 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000493 }
494 }
495 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
496 // Maybe we will complain about the shadowed template parameter.
497 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
498 // Just pretend that we didn't see the previous declaration.
499 PrevDecl = 0;
500 } else if (PrevDecl) {
501 // C++ [temp]p5:
502 // A class template shall not have the same name as any other
503 // template, class, function, object, enumeration, enumerator,
504 // namespace, or type in the same scope (3.3), except as specified
505 // in (14.5.4).
506 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
507 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000508 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000509 }
510
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000511 // Check the template parameter list of this declaration, possibly
512 // merging in the template parameter list from the previous class
513 // template declaration.
514 if (CheckTemplateParameterList(TemplateParams,
515 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
516 Invalid = true;
517
Douglas Gregor9054f982009-05-10 22:57:19 +0000518 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000519 // declaration!
520
Douglas Gregor55216ac2009-03-26 00:10:35 +0000521 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000522 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
523 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000524 PrevClassTemplate->getTemplatedDecl() : 0,
525 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000526
527 ClassTemplateDecl *NewTemplate
528 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
529 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000530 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000531 NewClass->setDescribedClassTemplate(NewTemplate);
532
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000533 // Build the type for the class template declaration now.
534 QualType T =
535 Context.getTypeDeclType(NewClass,
536 PrevClassTemplate?
537 PrevClassTemplate->getTemplatedDecl() : 0);
538 assert(T->isDependentType() && "Class template type is not dependent?");
539 (void)T;
540
Anders Carlsson4ca43492009-03-26 01:24:28 +0000541 // Set the access specifier.
542 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
543
Douglas Gregord406b032009-02-06 22:42:48 +0000544 // Set the lexical context of these templates
545 NewClass->setLexicalDeclContext(CurContext);
546 NewTemplate->setLexicalDeclContext(CurContext);
547
548 if (TK == TK_Definition)
549 NewClass->startDefinition();
550
551 if (Attr)
552 ProcessDeclAttributeList(NewClass, Attr);
553
554 PushOnScopeChains(NewTemplate, S);
555
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000556 if (Invalid) {
557 NewTemplate->setInvalidDecl();
558 NewClass->setInvalidDecl();
559 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000560 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000561}
562
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000563/// \brief Checks the validity of a template parameter list, possibly
564/// considering the template parameter list from a previous
565/// declaration.
566///
567/// If an "old" template parameter list is provided, it must be
568/// equivalent (per TemplateParameterListsAreEqual) to the "new"
569/// template parameter list.
570///
571/// \param NewParams Template parameter list for a new template
572/// declaration. This template parameter list will be updated with any
573/// default arguments that are carried through from the previous
574/// template parameter list.
575///
576/// \param OldParams If provided, template parameter list from a
577/// previous declaration of the same template. Default template
578/// arguments will be merged from the old template parameter list to
579/// the new template parameter list.
580///
581/// \returns true if an error occurred, false otherwise.
582bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
583 TemplateParameterList *OldParams) {
584 bool Invalid = false;
585
586 // C++ [temp.param]p10:
587 // The set of default template-arguments available for use with a
588 // template declaration or definition is obtained by merging the
589 // default arguments from the definition (if in scope) and all
590 // declarations in scope in the same way default function
591 // arguments are (8.3.6).
592 bool SawDefaultArgument = false;
593 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000594
Mike Stumpe0b7e032009-02-11 23:03:27 +0000595 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000596 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000597 if (OldParams)
598 OldParam = OldParams->begin();
599
600 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
601 NewParamEnd = NewParams->end();
602 NewParam != NewParamEnd; ++NewParam) {
603 // Variables used to diagnose redundant default arguments
604 bool RedundantDefaultArg = false;
605 SourceLocation OldDefaultLoc;
606 SourceLocation NewDefaultLoc;
607
608 // Variables used to diagnose missing default arguments
609 bool MissingDefaultArg = false;
610
611 // Merge default arguments for template type parameters.
612 if (TemplateTypeParmDecl *NewTypeParm
613 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
614 TemplateTypeParmDecl *OldTypeParm
615 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
616
617 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
618 NewTypeParm->hasDefaultArgument()) {
619 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
620 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
621 SawDefaultArgument = true;
622 RedundantDefaultArg = true;
623 PreviousDefaultArgLoc = NewDefaultLoc;
624 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
625 // Merge the default argument from the old declaration to the
626 // new declaration.
627 SawDefaultArgument = true;
628 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
629 OldTypeParm->getDefaultArgumentLoc(),
630 true);
631 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
632 } else if (NewTypeParm->hasDefaultArgument()) {
633 SawDefaultArgument = true;
634 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
635 } else if (SawDefaultArgument)
636 MissingDefaultArg = true;
637 }
638 // Merge default arguments for non-type template parameters
639 else if (NonTypeTemplateParmDecl *NewNonTypeParm
640 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
641 NonTypeTemplateParmDecl *OldNonTypeParm
642 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
643 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
644 NewNonTypeParm->hasDefaultArgument()) {
645 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
646 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
647 SawDefaultArgument = true;
648 RedundantDefaultArg = true;
649 PreviousDefaultArgLoc = NewDefaultLoc;
650 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
651 // Merge the default argument from the old declaration to the
652 // new declaration.
653 SawDefaultArgument = true;
654 // FIXME: We need to create a new kind of "default argument"
655 // expression that points to a previous template template
656 // parameter.
657 NewNonTypeParm->setDefaultArgument(
658 OldNonTypeParm->getDefaultArgument());
659 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
660 } else if (NewNonTypeParm->hasDefaultArgument()) {
661 SawDefaultArgument = true;
662 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
663 } else if (SawDefaultArgument)
664 MissingDefaultArg = true;
665 }
666 // Merge default arguments for template template parameters
667 else {
668 TemplateTemplateParmDecl *NewTemplateParm
669 = cast<TemplateTemplateParmDecl>(*NewParam);
670 TemplateTemplateParmDecl *OldTemplateParm
671 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
672 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
673 NewTemplateParm->hasDefaultArgument()) {
674 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
675 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
676 SawDefaultArgument = true;
677 RedundantDefaultArg = true;
678 PreviousDefaultArgLoc = NewDefaultLoc;
679 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
680 // Merge the default argument from the old declaration to the
681 // new declaration.
682 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000683 // FIXME: We need to create a new kind of "default argument" expression
684 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000685 NewTemplateParm->setDefaultArgument(
686 OldTemplateParm->getDefaultArgument());
687 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
688 } else if (NewTemplateParm->hasDefaultArgument()) {
689 SawDefaultArgument = true;
690 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
691 } else if (SawDefaultArgument)
692 MissingDefaultArg = true;
693 }
694
695 if (RedundantDefaultArg) {
696 // C++ [temp.param]p12:
697 // A template-parameter shall not be given default arguments
698 // by two different declarations in the same scope.
699 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
700 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
701 Invalid = true;
702 } else if (MissingDefaultArg) {
703 // C++ [temp.param]p11:
704 // If a template-parameter has a default template-argument,
705 // all subsequent template-parameters shall have a default
706 // template-argument supplied.
707 Diag((*NewParam)->getLocation(),
708 diag::err_template_param_default_arg_missing);
709 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
710 Invalid = true;
711 }
712
713 // If we have an old template parameter list that we're merging
714 // in, move on to the next parameter.
715 if (OldParams)
716 ++OldParam;
717 }
718
719 return Invalid;
720}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000721
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000722/// \brief Translates template arguments as provided by the parser
723/// into template arguments used by semantic analysis.
724static void
725translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
726 SourceLocation *TemplateArgLocs,
727 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
728 TemplateArgs.reserve(TemplateArgsIn.size());
729
730 void **Args = TemplateArgsIn.getArgs();
731 bool *ArgIsType = TemplateArgsIn.getArgIsType();
732 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
733 TemplateArgs.push_back(
734 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
735 QualType::getFromOpaquePtr(Args[Arg]))
736 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
737 }
738}
739
Douglas Gregoraabb8502009-03-31 00:43:58 +0000740/// \brief Build a canonical version of a template argument list.
741///
742/// This function builds a canonical version of the given template
743/// argument list, where each of the template arguments has been
744/// converted into its canonical form. This routine is typically used
745/// to canonicalize a template argument list when the template name
746/// itself is dependent. When the template name refers to an actual
747/// template declaration, Sema::CheckTemplateArgumentList should be
748/// used to check and canonicalize the template arguments.
749///
750/// \param TemplateArgs The incoming template arguments.
751///
752/// \param NumTemplateArgs The number of template arguments in \p
753/// TemplateArgs.
754///
755/// \param Canonical A vector to be filled with the canonical versions
756/// of the template arguments.
757///
758/// \param Context The ASTContext in which the template arguments live.
759static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
760 unsigned NumTemplateArgs,
761 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
762 ASTContext &Context) {
763 Canonical.reserve(NumTemplateArgs);
764 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
765 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000766 case TemplateArgument::Null:
767 assert(false && "Should never see a NULL template argument here");
768 break;
769
Douglas Gregoraabb8502009-03-31 00:43:58 +0000770 case TemplateArgument::Expression:
771 // FIXME: Build canonical expression (!)
772 Canonical.push_back(TemplateArgs[Idx]);
773 break;
774
775 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000776 Canonical.push_back(
777 TemplateArgument(SourceLocation(),
778 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000779 break;
780
781 case TemplateArgument::Integral:
782 Canonical.push_back(TemplateArgument(SourceLocation(),
783 *TemplateArgs[Idx].getAsIntegral(),
784 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000785 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000786
787 case TemplateArgument::Type: {
788 QualType CanonType
789 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
790 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000791 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000792 }
793 }
794 }
795}
796
Douglas Gregordd13e842009-03-30 22:58:21 +0000797QualType Sema::CheckTemplateIdType(TemplateName Name,
798 SourceLocation TemplateLoc,
799 SourceLocation LAngleLoc,
800 const TemplateArgument *TemplateArgs,
801 unsigned NumTemplateArgs,
802 SourceLocation RAngleLoc) {
803 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000804 if (!Template) {
805 // The template name does not resolve to a template, so we just
806 // build a dependent template-id type.
807
808 // Canonicalize the template arguments to build the canonical
809 // template-id type.
810 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
811 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
812 CanonicalTemplateArgs, Context);
813
Douglas Gregor905406b2009-05-07 06:49:52 +0000814 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000815 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000816 = Context.getTemplateSpecializationType(CanonName,
817 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000818 CanonicalTemplateArgs.size());
819
820 // Build the dependent template-id type.
821 return Context.getTemplateSpecializationType(Name, TemplateArgs,
822 NumTemplateArgs, CanonType);
823 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000824
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000825 // Check that the template argument list is well-formed for this
826 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000827 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000828 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000829 TemplateArgs, NumTemplateArgs, RAngleLoc,
830 ConvertedTemplateArgs))
831 return QualType();
832
833 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000834 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000835 "Converted template argument list is too short!");
836
837 QualType CanonType;
838
Douglas Gregordd13e842009-03-30 22:58:21 +0000839 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000840 TemplateArgs,
841 NumTemplateArgs)) {
842 // This class template specialization is a dependent
843 // type. Therefore, its canonical type is another class template
844 // specialization type that contains all of the converted
845 // arguments in canonical form. This ensures that, e.g., A<T> and
846 // A<T, T> have identical types when A is declared as:
847 //
848 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000849 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
850 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000851 ConvertedTemplateArgs.getFlatArgumentList(),
852 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000853 } else if (ClassTemplateDecl *ClassTemplate
854 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000855 // Find the class template specialization declaration that
856 // corresponds to these arguments.
857 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000858 ClassTemplateSpecializationDecl::Profile(ID,
859 ConvertedTemplateArgs.getFlatArgumentList(),
860 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000861 void *InsertPos = 0;
862 ClassTemplateSpecializationDecl *Decl
863 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
864 if (!Decl) {
865 // This is the first time we have referenced this class template
866 // specialization. Create the canonical declaration and add it to
867 // the set of specializations.
868 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000869 ClassTemplate->getDeclContext(),
870 TemplateLoc,
871 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000872 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000873 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
874 Decl->setLexicalDeclContext(CurContext);
875 }
876
877 CanonType = Context.getTypeDeclType(Decl);
878 }
879
880 // Build the fully-sugared type for this class template
881 // specialization, which refers back to the class template
882 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000883 return Context.getTemplateSpecializationType(Name, TemplateArgs,
884 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000885}
886
Douglas Gregora08b6c72009-02-17 23:15:12 +0000887Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000888Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
889 SourceLocation LAngleLoc,
890 ASTTemplateArgsPtr TemplateArgsIn,
891 SourceLocation *TemplateArgLocs,
892 SourceLocation RAngleLoc) {
893 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000894
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000895 // Translate the parser's template argument list in our AST format.
896 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
897 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000898
Douglas Gregordd13e842009-03-30 22:58:21 +0000899 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000900 TemplateArgs.data(),
901 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000902 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000903 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000904
905 if (Result.isNull())
906 return true;
907
Douglas Gregor6f37b582009-02-09 19:34:22 +0000908 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000909}
910
Douglas Gregoraabb8502009-03-31 00:43:58 +0000911/// \brief Form a dependent template name.
912///
913/// This action forms a dependent template name given the template
914/// name and its (presumably dependent) scope specifier. For
915/// example, given "MetaFun::template apply", the scope specifier \p
916/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
917/// of the "template" keyword, and "apply" is the \p Name.
918Sema::TemplateTy
919Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
920 const IdentifierInfo &Name,
921 SourceLocation NameLoc,
922 const CXXScopeSpec &SS) {
923 if (!SS.isSet() || SS.isInvalid())
924 return TemplateTy();
925
926 NestedNameSpecifier *Qualifier
927 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
928
929 // FIXME: member of the current instantiation
930
931 if (!Qualifier->isDependent()) {
932 // C++0x [temp.names]p5:
933 // If a name prefixed by the keyword template is not the name of
934 // a template, the program is ill-formed. [Note: the keyword
935 // template may not be applied to non-template members of class
936 // templates. -end note ] [ Note: as is the case with the
937 // typename prefix, the template prefix is allowed in cases
938 // where it is not strictly necessary; i.e., when the
939 // nested-name-specifier or the expression on the left of the ->
940 // or . is not dependent on a template-parameter, or the use
941 // does not appear in the scope of a template. -end note]
942 //
943 // Note: C++03 was more strict here, because it banned the use of
944 // the "template" keyword prior to a template-name that was not a
945 // dependent name. C++ DR468 relaxed this requirement (the
946 // "template" keyword is now permitted). We follow the C++0x
947 // rules, even in C++03 mode, retroactively applying the DR.
948 TemplateTy Template;
949 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
950 if (TNK == TNK_Non_template) {
951 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
952 << &Name;
953 return TemplateTy();
954 }
955
956 return Template;
957 }
958
959 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
960}
961
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000962/// \brief Check that the given template argument list is well-formed
963/// for specializing the given template.
964bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
965 SourceLocation TemplateLoc,
966 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000967 const TemplateArgument *TemplateArgs,
968 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000969 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +0000970 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000971 TemplateParameterList *Params = Template->getTemplateParameters();
972 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000973 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000974 bool Invalid = false;
975
976 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000977 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000978 // FIXME: point at either the first arg beyond what we can handle,
979 // or the '>', depending on whether we have too many or too few
980 // arguments.
981 SourceRange Range;
982 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000983 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000984 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
985 << (NumArgs > NumParams)
986 << (isa<ClassTemplateDecl>(Template)? 0 :
987 isa<FunctionTemplateDecl>(Template)? 1 :
988 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
989 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000990 Diag(Template->getLocation(), diag::note_template_decl_here)
991 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000992 Invalid = true;
993 }
994
995 // C++ [temp.arg]p1:
996 // [...] The type and form of each template-argument specified in
997 // a template-id shall match the type and form specified for the
998 // corresponding parameter declared by the template in its
999 // template-parameter-list.
1000 unsigned ArgIdx = 0;
1001 for (TemplateParameterList::iterator Param = Params->begin(),
1002 ParamEnd = Params->end();
1003 Param != ParamEnd; ++Param, ++ArgIdx) {
1004 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001005 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001006 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001007 // Retrieve the default template argument from the template
1008 // parameter.
1009 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1010 if (!TTP->hasDefaultArgument())
1011 break;
1012
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001013 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001014
1015 // If the argument type is dependent, instantiate it now based
1016 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001017 if (ArgType->isDependentType()) {
1018 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001019 Template, Converted.getFlatArgumentList(),
1020 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001021 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001022
Anders Carlsson0233eb62009-06-05 04:47:51 +00001023 TemplateArgumentList TemplateArgs(Context, Converted,
1024 /*CopyArgs=*/false,
1025 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001026 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001027 TTP->getDefaultArgumentLoc(),
1028 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001029 }
Douglas Gregor74296542009-02-27 19:31:52 +00001030
1031 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001032 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001033
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001034 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001035 } else if (NonTypeTemplateParmDecl *NTTP
1036 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1037 if (!NTTP->hasDefaultArgument())
1038 break;
1039
Anders Carlsson0297caf2009-06-11 16:06:49 +00001040 InstantiatingTemplate Inst(*this, TemplateLoc,
1041 Template, Converted.getFlatArgumentList(),
1042 Converted.flatSize(),
1043 SourceRange(TemplateLoc, RAngleLoc));
1044
1045 TemplateArgumentList TemplateArgs(Context, Converted,
1046 /*CopyArgs=*/false,
1047 /*FlattenArgs=*/false);
1048
1049 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1050 TemplateArgs);
1051 if (E.isInvalid())
1052 return true;
1053
1054 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001055 } else {
1056 TemplateTemplateParmDecl *TempParm
1057 = cast<TemplateTemplateParmDecl>(*Param);
1058
1059 if (!TempParm->hasDefaultArgument())
1060 break;
1061
Douglas Gregored3a3982009-03-03 04:44:36 +00001062 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001063 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001064 }
1065 } else {
1066 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001067 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001068 }
1069
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001070
1071 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1072 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001073 if (Arg.getKind() == TemplateArgument::Type) {
1074 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001075 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001076
1077 // Add the converted template type argument.
1078 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001079 TemplateArgument(Arg.getLocation(),
1080 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001081 continue;
1082 }
1083
1084 // C++ [temp.arg.type]p1:
1085 // A template-argument for a template-parameter which is a
1086 // type shall be a type-id.
1087
1088 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001089 // is not a type.
1090 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001091 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001092 Invalid = true;
1093 } else if (NonTypeTemplateParmDecl *NTTP
1094 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1095 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001096
1097 // Instantiate the type of the non-type template parameter with
1098 // the template arguments we've seen thus far.
1099 QualType NTTPType = NTTP->getType();
1100 if (NTTPType->isDependentType()) {
1101 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001102 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001103 Template, Converted.getFlatArgumentList(),
1104 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001105 SourceRange(TemplateLoc, RAngleLoc));
1106
Anders Carlsson0233eb62009-06-05 04:47:51 +00001107 TemplateArgumentList TemplateArgs(Context, Converted,
1108 /*CopyArgs=*/false,
1109 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001110 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001111 NTTP->getLocation(),
1112 NTTP->getDeclName());
1113 // If that worked, check the non-type template parameter type
1114 // for validity.
1115 if (!NTTPType.isNull())
1116 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1117 NTTP->getLocation());
1118
1119 if (NTTPType.isNull()) {
1120 Invalid = true;
1121 break;
1122 }
1123 }
1124
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001125 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001126 case TemplateArgument::Null:
1127 assert(false && "Should never see a NULL template argument here");
1128 break;
1129
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001130 case TemplateArgument::Expression: {
1131 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001132 TemplateArgument Result;
1133 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001134 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001135 else
1136 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001137 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001138 }
1139
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001140 case TemplateArgument::Declaration:
1141 case TemplateArgument::Integral:
1142 // We've already checked this template argument, so just copy
1143 // it to the list of converted arguments.
1144 Converted.push_back(Arg);
1145 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001146
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001147 case TemplateArgument::Type:
1148 // We have a non-type template parameter but the template
1149 // argument is a type.
1150
1151 // C++ [temp.arg]p2:
1152 // In a template-argument, an ambiguity between a type-id and
1153 // an expression is resolved to a type-id, regardless of the
1154 // form of the corresponding template-parameter.
1155 //
1156 // We warn specifically about this case, since it can be rather
1157 // confusing for users.
1158 if (Arg.getAsType()->isFunctionType())
1159 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1160 << Arg.getAsType();
1161 else
1162 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1163 Diag((*Param)->getLocation(), diag::note_template_param_here);
1164 Invalid = true;
1165 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001166 } else {
1167 // Check template template parameters.
1168 TemplateTemplateParmDecl *TempParm
1169 = cast<TemplateTemplateParmDecl>(*Param);
1170
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001171 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001172 case TemplateArgument::Null:
1173 assert(false && "Should never see a NULL template argument here");
1174 break;
1175
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001176 case TemplateArgument::Expression: {
1177 Expr *ArgExpr = Arg.getAsExpr();
1178 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1179 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1180 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1181 Invalid = true;
1182
1183 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001184 Decl *D
1185 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1186 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001187 continue;
1188 }
1189 }
1190 // fall through
1191
1192 case TemplateArgument::Type: {
1193 // We have a template template parameter but the template
1194 // argument does not refer to a template.
1195 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1196 Invalid = true;
1197 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001198 }
1199
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001200 case TemplateArgument::Declaration:
1201 // We've already checked this template argument, so just copy
1202 // it to the list of converted arguments.
1203 Converted.push_back(Arg);
1204 break;
1205
1206 case TemplateArgument::Integral:
1207 assert(false && "Integral argument with template template parameter");
1208 break;
1209 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001210 }
1211 }
1212
1213 return Invalid;
1214}
1215
1216/// \brief Check a template argument against its corresponding
1217/// template type parameter.
1218///
1219/// This routine implements the semantics of C++ [temp.arg.type]. It
1220/// returns true if an error occurred, and false otherwise.
1221bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1222 QualType Arg, SourceLocation ArgLoc) {
1223 // C++ [temp.arg.type]p2:
1224 // A local type, a type with no linkage, an unnamed type or a type
1225 // compounded from any of these types shall not be used as a
1226 // template-argument for a template type-parameter.
1227 //
1228 // FIXME: Perform the recursive and no-linkage type checks.
1229 const TagType *Tag = 0;
1230 if (const EnumType *EnumT = Arg->getAsEnumType())
1231 Tag = EnumT;
1232 else if (const RecordType *RecordT = Arg->getAsRecordType())
1233 Tag = RecordT;
1234 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1235 return Diag(ArgLoc, diag::err_template_arg_local_type)
1236 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001237 else if (Tag && !Tag->getDecl()->getDeclName() &&
1238 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001239 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1240 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1241 return true;
1242 }
1243
1244 return false;
1245}
1246
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001247/// \brief Checks whether the given template argument is the address
1248/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001249bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1250 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001251 bool Invalid = false;
1252
1253 // See through any implicit casts we added to fix the type.
1254 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1255 Arg = Cast->getSubExpr();
1256
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001257 // C++0x allows nullptr, and there's no further checking to be done for that.
1258 if (Arg->getType()->isNullPtrType())
1259 return false;
1260
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001261 // C++ [temp.arg.nontype]p1:
1262 //
1263 // A template-argument for a non-type, non-template
1264 // template-parameter shall be one of: [...]
1265 //
1266 // -- the address of an object or function with external
1267 // linkage, including function templates and function
1268 // template-ids but excluding non-static class members,
1269 // expressed as & id-expression where the & is optional if
1270 // the name refers to a function or array, or if the
1271 // corresponding template-parameter is a reference; or
1272 DeclRefExpr *DRE = 0;
1273
1274 // Ignore (and complain about) any excess parentheses.
1275 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1276 if (!Invalid) {
1277 Diag(Arg->getSourceRange().getBegin(),
1278 diag::err_template_arg_extra_parens)
1279 << Arg->getSourceRange();
1280 Invalid = true;
1281 }
1282
1283 Arg = Parens->getSubExpr();
1284 }
1285
1286 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1287 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1288 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1289 } else
1290 DRE = dyn_cast<DeclRefExpr>(Arg);
1291
1292 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1293 return Diag(Arg->getSourceRange().getBegin(),
1294 diag::err_template_arg_not_object_or_func_form)
1295 << Arg->getSourceRange();
1296
1297 // Cannot refer to non-static data members
1298 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1299 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1300 << Field << Arg->getSourceRange();
1301
1302 // Cannot refer to non-static member functions
1303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1304 if (!Method->isStatic())
1305 return Diag(Arg->getSourceRange().getBegin(),
1306 diag::err_template_arg_method)
1307 << Method << Arg->getSourceRange();
1308
1309 // Functions must have external linkage.
1310 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1311 if (Func->getStorageClass() == FunctionDecl::Static) {
1312 Diag(Arg->getSourceRange().getBegin(),
1313 diag::err_template_arg_function_not_extern)
1314 << Func << Arg->getSourceRange();
1315 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1316 << true;
1317 return true;
1318 }
1319
1320 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001321 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001322 return Invalid;
1323 }
1324
1325 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1326 if (!Var->hasGlobalStorage()) {
1327 Diag(Arg->getSourceRange().getBegin(),
1328 diag::err_template_arg_object_not_extern)
1329 << Var << Arg->getSourceRange();
1330 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1331 << true;
1332 return true;
1333 }
1334
1335 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001336 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001337 return Invalid;
1338 }
1339
1340 // We found something else, but we don't know specifically what it is.
1341 Diag(Arg->getSourceRange().getBegin(),
1342 diag::err_template_arg_not_object_or_func)
1343 << Arg->getSourceRange();
1344 Diag(DRE->getDecl()->getLocation(),
1345 diag::note_template_arg_refers_here);
1346 return true;
1347}
1348
1349/// \brief Checks whether the given template argument is a pointer to
1350/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001351bool
1352Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001353 bool Invalid = false;
1354
1355 // See through any implicit casts we added to fix the type.
1356 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1357 Arg = Cast->getSubExpr();
1358
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001359 // C++0x allows nullptr, and there's no further checking to be done for that.
1360 if (Arg->getType()->isNullPtrType())
1361 return false;
1362
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001363 // C++ [temp.arg.nontype]p1:
1364 //
1365 // A template-argument for a non-type, non-template
1366 // template-parameter shall be one of: [...]
1367 //
1368 // -- a pointer to member expressed as described in 5.3.1.
1369 QualifiedDeclRefExpr *DRE = 0;
1370
1371 // Ignore (and complain about) any excess parentheses.
1372 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1373 if (!Invalid) {
1374 Diag(Arg->getSourceRange().getBegin(),
1375 diag::err_template_arg_extra_parens)
1376 << Arg->getSourceRange();
1377 Invalid = true;
1378 }
1379
1380 Arg = Parens->getSubExpr();
1381 }
1382
1383 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1384 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1385 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1386
1387 if (!DRE)
1388 return Diag(Arg->getSourceRange().getBegin(),
1389 diag::err_template_arg_not_pointer_to_member_form)
1390 << Arg->getSourceRange();
1391
1392 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1393 assert((isa<FieldDecl>(DRE->getDecl()) ||
1394 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1395 "Only non-static member pointers can make it here");
1396
1397 // Okay: this is the address of a non-static member, and therefore
1398 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001399 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001400 return Invalid;
1401 }
1402
1403 // We found something else, but we don't know specifically what it is.
1404 Diag(Arg->getSourceRange().getBegin(),
1405 diag::err_template_arg_not_pointer_to_member_form)
1406 << Arg->getSourceRange();
1407 Diag(DRE->getDecl()->getLocation(),
1408 diag::note_template_arg_refers_here);
1409 return true;
1410}
1411
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001412/// \brief Check a template argument against its corresponding
1413/// non-type template parameter.
1414///
Douglas Gregored3a3982009-03-03 04:44:36 +00001415/// This routine implements the semantics of C++ [temp.arg.nontype].
1416/// It returns true if an error occurred, and false otherwise. \p
1417/// InstantiatedParamType is the type of the non-type template
1418/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001419///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001420/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001421bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001422 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001423 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001424 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1425
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001426 // If either the parameter has a dependent type or the argument is
1427 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001428 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001429 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1430 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001431 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001432 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001433 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001434
1435 // C++ [temp.arg.nontype]p5:
1436 // The following conversions are performed on each expression used
1437 // as a non-type template-argument. If a non-type
1438 // template-argument cannot be converted to the type of the
1439 // corresponding template-parameter then the program is
1440 // ill-formed.
1441 //
1442 // -- for a non-type template-parameter of integral or
1443 // enumeration type, integral promotions (4.5) and integral
1444 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001445 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001446 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001447 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001448 // C++ [temp.arg.nontype]p1:
1449 // A template-argument for a non-type, non-template
1450 // template-parameter shall be one of:
1451 //
1452 // -- an integral constant-expression of integral or enumeration
1453 // type; or
1454 // -- the name of a non-type template-parameter; or
1455 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001456 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001457 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1458 Diag(Arg->getSourceRange().getBegin(),
1459 diag::err_template_arg_not_integral_or_enumeral)
1460 << ArgType << Arg->getSourceRange();
1461 Diag(Param->getLocation(), diag::note_template_param_here);
1462 return true;
1463 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001464 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001465 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1466 << ArgType << Arg->getSourceRange();
1467 return true;
1468 }
1469
1470 // FIXME: We need some way to more easily get the unqualified form
1471 // of the types without going all the way to the
1472 // canonical type.
1473 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1474 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1475 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1476 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1477
1478 // Try to convert the argument to the parameter's type.
1479 if (ParamType == ArgType) {
1480 // Okay: no conversion necessary
1481 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1482 !ParamType->isEnumeralType()) {
1483 // This is an integral promotion or conversion.
1484 ImpCastExprToType(Arg, ParamType);
1485 } else {
1486 // We can't perform this conversion.
1487 Diag(Arg->getSourceRange().getBegin(),
1488 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001489 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001490 Diag(Param->getLocation(), diag::note_template_param_here);
1491 return true;
1492 }
1493
Douglas Gregorafc86942009-03-14 00:20:21 +00001494 QualType IntegerType = Context.getCanonicalType(ParamType);
1495 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001496 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001497
1498 if (!Arg->isValueDependent()) {
1499 // Check that an unsigned parameter does not receive a negative
1500 // value.
1501 if (IntegerType->isUnsignedIntegerType()
1502 && (Value.isSigned() && Value.isNegative())) {
1503 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1504 << Value.toString(10) << Param->getType()
1505 << Arg->getSourceRange();
1506 Diag(Param->getLocation(), diag::note_template_param_here);
1507 return true;
1508 }
1509
1510 // Check that we don't overflow the template parameter type.
1511 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1512 if (Value.getActiveBits() > AllowedBits) {
1513 Diag(Arg->getSourceRange().getBegin(),
1514 diag::err_template_arg_too_large)
1515 << Value.toString(10) << Param->getType()
1516 << Arg->getSourceRange();
1517 Diag(Param->getLocation(), diag::note_template_param_here);
1518 return true;
1519 }
1520
1521 if (Value.getBitWidth() != AllowedBits)
1522 Value.extOrTrunc(AllowedBits);
1523 Value.setIsSigned(IntegerType->isSignedIntegerType());
1524 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001525
Douglas Gregor8f378a92009-06-11 18:10:32 +00001526 // Add the value of this argument to the list of converted
1527 // arguments. We use the bitwidth and signedness of the template
1528 // parameter.
1529 if (Arg->isValueDependent()) {
1530 // The argument is value-dependent. Create a new
1531 // TemplateArgument with the converted expression.
1532 Converted = TemplateArgument(Arg);
1533 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001534 }
1535
Douglas Gregor8f378a92009-06-11 18:10:32 +00001536 Converted = TemplateArgument(StartLoc, Value,
1537 ParamType->isEnumeralType() ? ParamType
1538 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001539 return false;
1540 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001541
Douglas Gregor3f411962009-02-11 01:18:59 +00001542 // Handle pointer-to-function, reference-to-function, and
1543 // pointer-to-member-function all in (roughly) the same way.
1544 if (// -- For a non-type template-parameter of type pointer to
1545 // function, only the function-to-pointer conversion (4.3) is
1546 // applied. If the template-argument represents a set of
1547 // overloaded functions (or a pointer to such), the matching
1548 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001549 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001550 (ParamType->isPointerType() &&
1551 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1552 // -- For a non-type template-parameter of type reference to
1553 // function, no conversions apply. If the template-argument
1554 // represents a set of overloaded functions, the matching
1555 // function is selected from the set (13.4).
1556 (ParamType->isReferenceType() &&
1557 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1558 // -- For a non-type template-parameter of type pointer to
1559 // member function, no conversions apply. If the
1560 // template-argument represents a set of overloaded member
1561 // functions, the matching member function is selected from
1562 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001563 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001564 (ParamType->isMemberPointerType() &&
1565 ParamType->getAsMemberPointerType()->getPointeeType()
1566 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001567 if (Context.hasSameUnqualifiedType(ArgType,
1568 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001569 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001570 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1571 ParamType->isMemberPointerType())) {
1572 ArgType = ParamType;
1573 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001574 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001575 ArgType = Context.getPointerType(ArgType);
1576 ImpCastExprToType(Arg, ArgType);
1577 } else if (FunctionDecl *Fn
1578 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001579 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1580 return true;
1581
Douglas Gregor2eedd992009-02-11 00:19:33 +00001582 FixOverloadedFunctionReference(Arg, Fn);
1583 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001584 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001585 ArgType = Context.getPointerType(Arg->getType());
1586 ImpCastExprToType(Arg, ArgType);
1587 }
1588 }
1589
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001590 if (!Context.hasSameUnqualifiedType(ArgType,
1591 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001592 // We can't perform this conversion.
1593 Diag(Arg->getSourceRange().getBegin(),
1594 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001595 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001596 Diag(Param->getLocation(), diag::note_template_param_here);
1597 return true;
1598 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001599
Douglas Gregorad964b32009-02-17 01:05:43 +00001600 if (ParamType->isMemberPointerType()) {
1601 NamedDecl *Member = 0;
1602 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1603 return true;
1604
Douglas Gregor8f378a92009-06-11 18:10:32 +00001605 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1606 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001607 return false;
1608 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001609
Douglas Gregorad964b32009-02-17 01:05:43 +00001610 NamedDecl *Entity = 0;
1611 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1612 return true;
1613
Douglas Gregor8f378a92009-06-11 18:10:32 +00001614 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1615 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001616 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001617 }
1618
Chris Lattner320dff22009-02-20 21:37:53 +00001619 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001620 // -- for a non-type template-parameter of type pointer to
1621 // object, qualification conversions (4.4) and the
1622 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001623 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001624 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001625 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001626
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001627 if (ArgType->isNullPtrType()) {
1628 ArgType = ParamType;
1629 ImpCastExprToType(Arg, ParamType);
1630 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001631 ArgType = Context.getArrayDecayedType(ArgType);
1632 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001633 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001634
Douglas Gregor3f411962009-02-11 01:18:59 +00001635 if (IsQualificationConversion(ArgType, ParamType)) {
1636 ArgType = ParamType;
1637 ImpCastExprToType(Arg, ParamType);
1638 }
1639
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001640 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001641 // We can't perform this conversion.
1642 Diag(Arg->getSourceRange().getBegin(),
1643 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001644 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001645 Diag(Param->getLocation(), diag::note_template_param_here);
1646 return true;
1647 }
1648
Douglas Gregorad964b32009-02-17 01:05:43 +00001649 NamedDecl *Entity = 0;
1650 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1651 return true;
1652
Douglas Gregor8f378a92009-06-11 18:10:32 +00001653 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1654 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001655 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001656 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001657
1658 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1659 // -- For a non-type template-parameter of type reference to
1660 // object, no conversions apply. The type referred to by the
1661 // reference may be more cv-qualified than the (otherwise
1662 // identical) type of the template-argument. The
1663 // template-parameter is bound directly to the
1664 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001665 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001666 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001667
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001668 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001669 Diag(Arg->getSourceRange().getBegin(),
1670 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001671 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001672 << Arg->getSourceRange();
1673 Diag(Param->getLocation(), diag::note_template_param_here);
1674 return true;
1675 }
1676
1677 unsigned ParamQuals
1678 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1679 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1680
1681 if ((ParamQuals | ArgQuals) != ParamQuals) {
1682 Diag(Arg->getSourceRange().getBegin(),
1683 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001684 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001685 << Arg->getSourceRange();
1686 Diag(Param->getLocation(), diag::note_template_param_here);
1687 return true;
1688 }
1689
Douglas Gregorad964b32009-02-17 01:05:43 +00001690 NamedDecl *Entity = 0;
1691 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1692 return true;
1693
Douglas Gregor8f378a92009-06-11 18:10:32 +00001694 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1695 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001696 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001697 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001698
1699 // -- For a non-type template-parameter of type pointer to data
1700 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001701 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001702 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1703
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001704 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001705 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001706 } else if (ArgType->isNullPtrType()) {
1707 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001708 } else if (IsQualificationConversion(ArgType, ParamType)) {
1709 ImpCastExprToType(Arg, ParamType);
1710 } else {
1711 // We can't perform this conversion.
1712 Diag(Arg->getSourceRange().getBegin(),
1713 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001714 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001715 Diag(Param->getLocation(), diag::note_template_param_here);
1716 return true;
1717 }
1718
Douglas Gregorad964b32009-02-17 01:05:43 +00001719 NamedDecl *Member = 0;
1720 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1721 return true;
1722
Douglas Gregor8f378a92009-06-11 18:10:32 +00001723 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1724 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001725 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001726}
1727
1728/// \brief Check a template argument against its corresponding
1729/// template template parameter.
1730///
1731/// This routine implements the semantics of C++ [temp.arg.template].
1732/// It returns true if an error occurred, and false otherwise.
1733bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1734 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001735 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1736 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1737
1738 // C++ [temp.arg.template]p1:
1739 // A template-argument for a template template-parameter shall be
1740 // the name of a class template, expressed as id-expression. Only
1741 // primary class templates are considered when matching the
1742 // template template argument with the corresponding parameter;
1743 // partial specializations are not considered even if their
1744 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001745 //
1746 // Note that we also allow template template parameters here, which
1747 // will happen when we are dealing with, e.g., class template
1748 // partial specializations.
1749 if (!isa<ClassTemplateDecl>(Template) &&
1750 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001751 assert(isa<FunctionTemplateDecl>(Template) &&
1752 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001753 Diag(Arg->getSourceRange().getBegin(),
1754 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001755 << Template;
1756 }
1757
1758 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1759 Param->getTemplateParameters(),
1760 true, true,
1761 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001762}
1763
Douglas Gregord406b032009-02-06 22:42:48 +00001764/// \brief Determine whether the given template parameter lists are
1765/// equivalent.
1766///
1767/// \param New The new template parameter list, typically written in the
1768/// source code as part of a new template declaration.
1769///
1770/// \param Old The old template parameter list, typically found via
1771/// name lookup of the template declared with this template parameter
1772/// list.
1773///
1774/// \param Complain If true, this routine will produce a diagnostic if
1775/// the template parameter lists are not equivalent.
1776///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001777/// \param IsTemplateTemplateParm If true, this routine is being
1778/// called to compare the template parameter lists of a template
1779/// template parameter.
1780///
1781/// \param TemplateArgLoc If this source location is valid, then we
1782/// are actually checking the template parameter list of a template
1783/// argument (New) against the template parameter list of its
1784/// corresponding template template parameter (Old). We produce
1785/// slightly different diagnostics in this scenario.
1786///
Douglas Gregord406b032009-02-06 22:42:48 +00001787/// \returns True if the template parameter lists are equal, false
1788/// otherwise.
1789bool
1790Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1791 TemplateParameterList *Old,
1792 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001793 bool IsTemplateTemplateParm,
1794 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001795 if (Old->size() != New->size()) {
1796 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001797 unsigned NextDiag = diag::err_template_param_list_different_arity;
1798 if (TemplateArgLoc.isValid()) {
1799 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1800 NextDiag = diag::note_template_param_list_different_arity;
1801 }
1802 Diag(New->getTemplateLoc(), NextDiag)
1803 << (New->size() > Old->size())
1804 << IsTemplateTemplateParm
1805 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001806 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1807 << IsTemplateTemplateParm
1808 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1809 }
1810
1811 return false;
1812 }
1813
1814 for (TemplateParameterList::iterator OldParm = Old->begin(),
1815 OldParmEnd = Old->end(), NewParm = New->begin();
1816 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1817 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001818 unsigned NextDiag = diag::err_template_param_different_kind;
1819 if (TemplateArgLoc.isValid()) {
1820 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1821 NextDiag = diag::note_template_param_different_kind;
1822 }
1823 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001824 << IsTemplateTemplateParm;
1825 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1826 << IsTemplateTemplateParm;
1827 return false;
1828 }
1829
1830 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1831 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001832 // know we're at the same index).
1833#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001834 // FIXME: Enable this code in debug mode *after* we properly go through
1835 // and "instantiate" the template parameter lists of template template
1836 // parameters. It's only after this instantiation that (1) any dependent
1837 // types within the template parameter list of the template template
1838 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001839 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001840 QualType OldParmType
1841 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1842 QualType NewParmType
1843 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1844 assert(Context.getCanonicalType(OldParmType) ==
1845 Context.getCanonicalType(NewParmType) &&
1846 "type parameter mismatch?");
1847#endif
1848 } else if (NonTypeTemplateParmDecl *OldNTTP
1849 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1850 // The types of non-type template parameters must agree.
1851 NonTypeTemplateParmDecl *NewNTTP
1852 = cast<NonTypeTemplateParmDecl>(*NewParm);
1853 if (Context.getCanonicalType(OldNTTP->getType()) !=
1854 Context.getCanonicalType(NewNTTP->getType())) {
1855 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001856 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1857 if (TemplateArgLoc.isValid()) {
1858 Diag(TemplateArgLoc,
1859 diag::err_template_arg_template_params_mismatch);
1860 NextDiag = diag::note_template_nontype_parm_different_type;
1861 }
1862 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001863 << NewNTTP->getType()
1864 << IsTemplateTemplateParm;
1865 Diag(OldNTTP->getLocation(),
1866 diag::note_template_nontype_parm_prev_declaration)
1867 << OldNTTP->getType();
1868 }
1869 return false;
1870 }
1871 } else {
1872 // The template parameter lists of template template
1873 // parameters must agree.
1874 // FIXME: Could we perform a faster "type" comparison here?
1875 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1876 "Only template template parameters handled here");
1877 TemplateTemplateParmDecl *OldTTP
1878 = cast<TemplateTemplateParmDecl>(*OldParm);
1879 TemplateTemplateParmDecl *NewTTP
1880 = cast<TemplateTemplateParmDecl>(*NewParm);
1881 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1882 OldTTP->getTemplateParameters(),
1883 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001884 /*IsTemplateTemplateParm=*/true,
1885 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001886 return false;
1887 }
1888 }
1889
1890 return true;
1891}
1892
1893/// \brief Check whether a template can be declared within this scope.
1894///
1895/// If the template declaration is valid in this scope, returns
1896/// false. Otherwise, issues a diagnostic and returns true.
1897bool
1898Sema::CheckTemplateDeclScope(Scope *S,
1899 MultiTemplateParamsArg &TemplateParameterLists) {
1900 assert(TemplateParameterLists.size() > 0 && "Not a template");
1901
1902 // Find the nearest enclosing declaration scope.
1903 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1904 (S->getFlags() & Scope::TemplateParamScope) != 0)
1905 S = S->getParent();
1906
1907 TemplateParameterList *TemplateParams =
1908 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1909 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1910 SourceRange TemplateRange
1911 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1912
1913 // C++ [temp]p2:
1914 // A template-declaration can appear only as a namespace scope or
1915 // class scope declaration.
1916 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1917 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1918 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1919 return Diag(TemplateLoc, diag::err_template_linkage)
1920 << TemplateRange;
1921
1922 Ctx = Ctx->getParent();
1923 }
1924
1925 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1926 return false;
1927
1928 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1929 << TemplateRange;
1930}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001931
Douglas Gregor90177912009-05-13 18:28:20 +00001932/// \brief Check whether a class template specialization or explicit
1933/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001934///
Douglas Gregor90177912009-05-13 18:28:20 +00001935/// This routine determines whether a class template specialization or
1936/// explicit instantiation can be declared in the current context
1937/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1938/// appropriate diagnostics if there was an error. It returns true if
1939// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001940bool
1941Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1942 ClassTemplateSpecializationDecl *PrevDecl,
1943 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001944 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001945 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001946 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001947 // C++ [temp.expl.spec]p2:
1948 // An explicit specialization shall be declared in the namespace
1949 // of which the template is a member, or, for member templates, in
1950 // the namespace of which the enclosing class or enclosing class
1951 // template is a member. An explicit specialization of a member
1952 // function, member class or static data member of a class
1953 // template shall be declared in the namespace of which the class
1954 // template is a member. Such a declaration may also be a
1955 // definition. If the declaration is not a definition, the
1956 // specialization may be defined later in the name- space in which
1957 // the explicit specialization was declared, or in a namespace
1958 // that encloses the one in which the explicit specialization was
1959 // declared.
1960 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00001961 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001962 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001963 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001964 return true;
1965 }
1966
1967 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1968 DeclContext *TemplateContext
1969 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001970 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1971 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001972 // There is no prior declaration of this entity, so this
1973 // specialization must be in the same context as the template
1974 // itself.
1975 if (DC != TemplateContext) {
1976 if (isa<TranslationUnitDecl>(TemplateContext))
1977 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001978 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00001979 << ClassTemplate << ScopeSpecifierRange;
1980 else if (isa<NamespaceDecl>(TemplateContext))
1981 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001982 << PartialSpecialization << ClassTemplate
1983 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001984
1985 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1986 }
1987
1988 return false;
1989 }
1990
1991 // We have a previous declaration of this entity. Make sure that
1992 // this redeclaration (or definition) occurs in an enclosing namespace.
1993 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001994 // FIXME: In C++98, we would like to turn these errors into warnings,
1995 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00001996 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00001997 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00001998 if (isa<TranslationUnitDecl>(TemplateContext)) {
1999 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2000 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002001 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002002 else
2003 SuppressedDiag = true;
2004 } else if (isa<NamespaceDecl>(TemplateContext)) {
2005 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2006 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002007 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002008 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2009 else
2010 SuppressedDiag = true;
2011 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002012
Douglas Gregor90177912009-05-13 18:28:20 +00002013 if (!SuppressedDiag)
2014 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002015 }
2016
2017 return false;
2018}
2019
Douglas Gregor76e79952009-06-12 21:21:02 +00002020/// \brief Check the non-type template arguments of a class template
2021/// partial specialization according to C++ [temp.class.spec]p9.
2022///
Douglas Gregor42476442009-06-12 22:08:06 +00002023/// \param TemplateParams the template parameters of the primary class
2024/// template.
2025///
2026/// \param TemplateArg the template arguments of the class template
2027/// partial specialization.
2028///
2029/// \param MirrorsPrimaryTemplate will be set true if the class
2030/// template partial specialization arguments are identical to the
2031/// implicit template arguments of the primary template. This is not
2032/// necessarily an error (C++0x), and it is left to the caller to diagnose
2033/// this condition when it is an error.
2034///
Douglas Gregor76e79952009-06-12 21:21:02 +00002035/// \returns true if there was an error, false otherwise.
2036bool Sema::CheckClassTemplatePartialSpecializationArgs(
2037 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002038 const TemplateArgument *TemplateArgs,
2039 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002040 // FIXME: the interface to this function will have to change to
2041 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002042 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002043 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002044 // Determine whether the template argument list of the partial
2045 // specialization is identical to the implicit argument list of
2046 // the primary template. The caller may need to diagnostic this as
2047 // an error per C++ [temp.class.spec]p9b3.
2048 if (MirrorsPrimaryTemplate) {
2049 if (TemplateTypeParmDecl *TTP
2050 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2051 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2052 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2053 MirrorsPrimaryTemplate = false;
2054 } else if (TemplateTemplateParmDecl *TTP
2055 = dyn_cast<TemplateTemplateParmDecl>(
2056 TemplateParams->getParam(I))) {
2057 // FIXME: We should settle on either Declaration storage or
2058 // Expression storage for template template parameters.
2059 TemplateTemplateParmDecl *ArgDecl
2060 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2061 TemplateArgs[I].getAsDecl());
2062 if (!ArgDecl)
2063 if (DeclRefExpr *DRE
2064 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2065 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2066
2067 if (!ArgDecl ||
2068 ArgDecl->getIndex() != TTP->getIndex() ||
2069 ArgDecl->getDepth() != TTP->getDepth())
2070 MirrorsPrimaryTemplate = false;
2071 }
2072 }
2073
Douglas Gregor76e79952009-06-12 21:21:02 +00002074 NonTypeTemplateParmDecl *Param
2075 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002076 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002077 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002078 }
2079
Douglas Gregor76e79952009-06-12 21:21:02 +00002080 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002081 if (!ArgExpr) {
2082 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002083 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002084 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002085
2086 // C++ [temp.class.spec]p8:
2087 // A non-type argument is non-specialized if it is the name of a
2088 // non-type parameter. All other non-type arguments are
2089 // specialized.
2090 //
2091 // Below, we check the two conditions that only apply to
2092 // specialized non-type arguments, so skip any non-specialized
2093 // arguments.
2094 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002095 if (NonTypeTemplateParmDecl *NTTP
2096 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2097 if (MirrorsPrimaryTemplate &&
2098 (Param->getIndex() != NTTP->getIndex() ||
2099 Param->getDepth() != NTTP->getDepth()))
2100 MirrorsPrimaryTemplate = false;
2101
Douglas Gregor76e79952009-06-12 21:21:02 +00002102 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002103 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002104
2105 // C++ [temp.class.spec]p9:
2106 // Within the argument list of a class template partial
2107 // specialization, the following restrictions apply:
2108 // -- A partially specialized non-type argument expression
2109 // shall not involve a template parameter of the partial
2110 // specialization except when the argument expression is a
2111 // simple identifier.
2112 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2113 Diag(ArgExpr->getLocStart(),
2114 diag::err_dependent_non_type_arg_in_partial_spec)
2115 << ArgExpr->getSourceRange();
2116 return true;
2117 }
2118
2119 // -- The type of a template parameter corresponding to a
2120 // specialized non-type argument shall not be dependent on a
2121 // parameter of the specialization.
2122 if (Param->getType()->isDependentType()) {
2123 Diag(ArgExpr->getLocStart(),
2124 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2125 << Param->getType()
2126 << ArgExpr->getSourceRange();
2127 Diag(Param->getLocation(), diag::note_template_param_here);
2128 return true;
2129 }
Douglas Gregor42476442009-06-12 22:08:06 +00002130
2131 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002132 }
2133
2134 return false;
2135}
2136
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002137Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002138Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2139 SourceLocation KWLoc,
2140 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002141 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002142 SourceLocation TemplateNameLoc,
2143 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002144 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002145 SourceLocation *TemplateArgLocs,
2146 SourceLocation RAngleLoc,
2147 AttributeList *Attr,
2148 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002149 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002150 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002151 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002152 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002153
Douglas Gregor58944ac2009-05-31 09:31:02 +00002154 bool isPartialSpecialization = false;
2155
Douglas Gregor0d93f692009-02-25 22:02:03 +00002156 // Check the validity of the template headers that introduce this
2157 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002158 // FIXME: Once we have member templates, we'll need to check
2159 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2160 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002161 if (TemplateParameterLists.size() == 0)
2162 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002163 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002164 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002165 TemplateParameterList *TemplateParams
2166 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002167 if (TemplateParameterLists.size() > 1) {
2168 Diag(TemplateParams->getTemplateLoc(),
2169 diag::err_template_spec_extra_headers);
2170 return true;
2171 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002172
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002173 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002174 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002175
2176 // C++ [temp.class.spec]p10:
2177 // The template parameter list of a specialization shall not
2178 // contain default template argument values.
2179 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2180 Decl *Param = TemplateParams->getParam(I);
2181 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2182 if (TTP->hasDefaultArgument()) {
2183 Diag(TTP->getDefaultArgumentLoc(),
2184 diag::err_default_arg_in_partial_spec);
2185 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2186 }
2187 } else if (NonTypeTemplateParmDecl *NTTP
2188 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2189 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2190 Diag(NTTP->getDefaultArgumentLoc(),
2191 diag::err_default_arg_in_partial_spec)
2192 << DefArg->getSourceRange();
2193 NTTP->setDefaultArgument(0);
2194 DefArg->Destroy(Context);
2195 }
2196 } else {
2197 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2198 if (Expr *DefArg = TTP->getDefaultArgument()) {
2199 Diag(TTP->getDefaultArgumentLoc(),
2200 diag::err_default_arg_in_partial_spec)
2201 << DefArg->getSourceRange();
2202 TTP->setDefaultArgument(0);
2203 DefArg->Destroy(Context);
2204 }
2205 }
2206 }
2207 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002208 }
2209
Douglas Gregora08b6c72009-02-17 23:15:12 +00002210 // Check that the specialization uses the same tag kind as the
2211 // original template.
2212 TagDecl::TagKind Kind;
2213 switch (TagSpec) {
2214 default: assert(0 && "Unknown tag type!");
2215 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2216 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2217 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2218 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002219 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2220 Kind, KWLoc,
2221 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002222 Diag(KWLoc, diag::err_use_with_wrong_tag)
2223 << ClassTemplate
2224 << CodeModificationHint::CreateReplacement(KWLoc,
2225 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002226 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2227 diag::note_previous_use);
2228 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2229 }
2230
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002231 // Translate the parser's template argument list in our AST format.
2232 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2233 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2234
Douglas Gregora08b6c72009-02-17 23:15:12 +00002235 // Check that the template argument list is well-formed for this
2236 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002237 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002238 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002239 &TemplateArgs[0], TemplateArgs.size(),
2240 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002241 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002242
2243 assert((ConvertedTemplateArgs.size() ==
2244 ClassTemplate->getTemplateParameters()->size()) &&
2245 "Converted template argument list is too short!");
2246
Douglas Gregor58944ac2009-05-31 09:31:02 +00002247 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002248 // corresponds to these arguments.
2249 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002250 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002251 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002252 if (CheckClassTemplatePartialSpecializationArgs(
2253 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002254 ConvertedTemplateArgs.getFlatArgumentList(),
2255 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002256 return true;
2257
Douglas Gregor42476442009-06-12 22:08:06 +00002258 if (MirrorsPrimaryTemplate) {
2259 // C++ [temp.class.spec]p9b3:
2260 //
2261 // -- The argument list of the specialization shall not be identical
2262 // to the implicit argument list of the primary template.
2263 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2264 << (TK == TK_Definition)
2265 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2266 RAngleLoc));
2267 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2268 ClassTemplate->getIdentifier(),
2269 TemplateNameLoc,
2270 Attr,
2271 move(TemplateParameterLists),
2272 AS_none);
2273 }
2274
Douglas Gregor58944ac2009-05-31 09:31:02 +00002275 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002276 ClassTemplatePartialSpecializationDecl::Profile(ID,
2277 ConvertedTemplateArgs.getFlatArgumentList(),
2278 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002279 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002280 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002281 ClassTemplateSpecializationDecl::Profile(ID,
2282 ConvertedTemplateArgs.getFlatArgumentList(),
2283 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002284 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002285 ClassTemplateSpecializationDecl *PrevDecl = 0;
2286
2287 if (isPartialSpecialization)
2288 PrevDecl
2289 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2290 InsertPos);
2291 else
2292 PrevDecl
2293 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002294
2295 ClassTemplateSpecializationDecl *Specialization = 0;
2296
Douglas Gregor0d93f692009-02-25 22:02:03 +00002297 // Check whether we can declare a class template specialization in
2298 // the current scope.
2299 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2300 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002301 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002302 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002303 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002304 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002305
Douglas Gregora08b6c72009-02-17 23:15:12 +00002306 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2307 // Since the only prior class template specialization with these
2308 // arguments was referenced but not declared, reuse that
2309 // declaration node as our own, updating its source location to
2310 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002311 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002312 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002313 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002314 } else if (isPartialSpecialization) {
2315 // FIXME: extra checking for partial specializations
2316
2317 // Create a new class template partial specialization declaration node.
2318 TemplateParameterList *TemplateParams
2319 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2320 ClassTemplatePartialSpecializationDecl *PrevPartial
2321 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2322 ClassTemplatePartialSpecializationDecl *Partial
2323 = ClassTemplatePartialSpecializationDecl::Create(Context,
2324 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002325 TemplateNameLoc,
2326 TemplateParams,
2327 ClassTemplate,
2328 ConvertedTemplateArgs,
2329 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002330
2331 if (PrevPartial) {
2332 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2333 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2334 } else {
2335 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2336 }
2337 Specialization = Partial;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002338 } else {
2339 // Create a new class template specialization declaration node for
2340 // this explicit specialization.
2341 Specialization
2342 = ClassTemplateSpecializationDecl::Create(Context,
2343 ClassTemplate->getDeclContext(),
2344 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002345 ClassTemplate,
2346 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002347 PrevDecl);
2348
2349 if (PrevDecl) {
2350 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2351 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2352 } else {
2353 ClassTemplate->getSpecializations().InsertNode(Specialization,
2354 InsertPos);
2355 }
2356 }
2357
2358 // Note that this is an explicit specialization.
2359 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2360
2361 // Check that this isn't a redefinition of this specialization.
2362 if (TK == TK_Definition) {
2363 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002364 // FIXME: Should also handle explicit specialization after implicit
2365 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002366 SourceRange Range(TemplateNameLoc, RAngleLoc);
2367 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002368 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002369 Diag(Def->getLocation(), diag::note_previous_definition);
2370 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002371 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002372 }
2373 }
2374
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002375 // Build the fully-sugared type for this class template
2376 // specialization as the user wrote in the specialization
2377 // itself. This means that we'll pretty-print the type retrieved
2378 // from the specialization's declaration the way that the user
2379 // actually wrote the specialization, rather than formatting the
2380 // name based on the "canonical" representation used to store the
2381 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002382 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002383 = Context.getTemplateSpecializationType(Name,
2384 &TemplateArgs[0],
2385 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002386 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002387 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002388 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002389
Douglas Gregor50113ca2009-02-25 22:18:32 +00002390 // C++ [temp.expl.spec]p9:
2391 // A template explicit specialization is in the scope of the
2392 // namespace in which the template was defined.
2393 //
2394 // We actually implement this paragraph where we set the semantic
2395 // context (in the creation of the ClassTemplateSpecializationDecl),
2396 // but we also maintain the lexical context where the actual
2397 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002398 Specialization->setLexicalDeclContext(CurContext);
2399
2400 // We may be starting the definition of this specialization.
2401 if (TK == TK_Definition)
2402 Specialization->startDefinition();
2403
2404 // Add the specialization into its lexical context, so that it can
2405 // be seen when iterating through the list of declarations in that
2406 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002407 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002408 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002409}
Douglas Gregord3022602009-03-27 23:10:48 +00002410
Douglas Gregor96b6df92009-05-14 00:28:11 +00002411// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002412Sema::DeclResult
2413Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2414 unsigned TagSpec,
2415 SourceLocation KWLoc,
2416 const CXXScopeSpec &SS,
2417 TemplateTy TemplateD,
2418 SourceLocation TemplateNameLoc,
2419 SourceLocation LAngleLoc,
2420 ASTTemplateArgsPtr TemplateArgsIn,
2421 SourceLocation *TemplateArgLocs,
2422 SourceLocation RAngleLoc,
2423 AttributeList *Attr) {
2424 // Find the class template we're specializing
2425 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2426 ClassTemplateDecl *ClassTemplate
2427 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2428
2429 // Check that the specialization uses the same tag kind as the
2430 // original template.
2431 TagDecl::TagKind Kind;
2432 switch (TagSpec) {
2433 default: assert(0 && "Unknown tag type!");
2434 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2435 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2436 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2437 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002438 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2439 Kind, KWLoc,
2440 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002441 Diag(KWLoc, diag::err_use_with_wrong_tag)
2442 << ClassTemplate
2443 << CodeModificationHint::CreateReplacement(KWLoc,
2444 ClassTemplate->getTemplatedDecl()->getKindName());
2445 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2446 diag::note_previous_use);
2447 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2448 }
2449
Douglas Gregor90177912009-05-13 18:28:20 +00002450 // C++0x [temp.explicit]p2:
2451 // [...] An explicit instantiation shall appear in an enclosing
2452 // namespace of its template. [...]
2453 //
2454 // This is C++ DR 275.
2455 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2456 TemplateNameLoc,
2457 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002458 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002459 /*ExplicitInstantiation=*/true))
2460 return true;
2461
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002462 // Translate the parser's template argument list in our AST format.
2463 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2464 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2465
2466 // Check that the template argument list is well-formed for this
2467 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002468 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002469 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002470 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002471 RAngleLoc, ConvertedTemplateArgs))
2472 return true;
2473
2474 assert((ConvertedTemplateArgs.size() ==
2475 ClassTemplate->getTemplateParameters()->size()) &&
2476 "Converted template argument list is too short!");
2477
2478 // Find the class template specialization declaration that
2479 // corresponds to these arguments.
2480 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002481 ClassTemplateSpecializationDecl::Profile(ID,
2482 ConvertedTemplateArgs.getFlatArgumentList(),
2483 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002484 void *InsertPos = 0;
2485 ClassTemplateSpecializationDecl *PrevDecl
2486 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2487
2488 ClassTemplateSpecializationDecl *Specialization = 0;
2489
Douglas Gregor90177912009-05-13 18:28:20 +00002490 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002491 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002492 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002493 // This particular specialization has already been declared or
2494 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002495 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2496 << Context.getTypeDeclType(PrevDecl);
2497 Diag(PrevDecl->getLocation(),
2498 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002499 return DeclPtrTy::make(PrevDecl);
2500 }
2501
Douglas Gregor90177912009-05-13 18:28:20 +00002502 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002503 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002504 // For a given set of template parameters, if an explicit
2505 // instantiation of a template appears after a declaration of
2506 // an explicit specialization for that template, the explicit
2507 // instantiation has no effect.
2508 if (!getLangOptions().CPlusPlus0x) {
2509 Diag(TemplateNameLoc,
2510 diag::ext_explicit_instantiation_after_specialization)
2511 << Context.getTypeDeclType(PrevDecl);
2512 Diag(PrevDecl->getLocation(),
2513 diag::note_previous_template_specialization);
2514 }
2515
2516 // Create a new class template specialization declaration node
2517 // for this explicit specialization. This node is only used to
2518 // record the existence of this explicit instantiation for
2519 // accurate reproduction of the source code; we don't actually
2520 // use it for anything, since it is semantically irrelevant.
2521 Specialization
2522 = ClassTemplateSpecializationDecl::Create(Context,
2523 ClassTemplate->getDeclContext(),
2524 TemplateNameLoc,
2525 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002526 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002527 Specialization->setLexicalDeclContext(CurContext);
2528 CurContext->addDecl(Context, Specialization);
2529 return DeclPtrTy::make(Specialization);
2530 }
2531
2532 // If we have already (implicitly) instantiated this
2533 // specialization, there is less work to do.
2534 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2535 SpecializationRequiresInstantiation = false;
2536
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002537 // Since the only prior class template specialization with these
2538 // arguments was referenced but not declared, reuse that
2539 // declaration node as our own, updating its source location to
2540 // reflect our new declaration.
2541 Specialization = PrevDecl;
2542 Specialization->setLocation(TemplateNameLoc);
2543 PrevDecl = 0;
2544 } else {
2545 // Create a new class template specialization declaration node for
2546 // this explicit specialization.
2547 Specialization
2548 = ClassTemplateSpecializationDecl::Create(Context,
2549 ClassTemplate->getDeclContext(),
2550 TemplateNameLoc,
2551 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002552 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002553
2554 ClassTemplate->getSpecializations().InsertNode(Specialization,
2555 InsertPos);
2556 }
2557
2558 // Build the fully-sugared type for this explicit instantiation as
2559 // the user wrote in the explicit instantiation itself. This means
2560 // that we'll pretty-print the type retrieved from the
2561 // specialization's declaration the way that the user actually wrote
2562 // the explicit instantiation, rather than formatting the name based
2563 // on the "canonical" representation used to store the template
2564 // arguments in the specialization.
2565 QualType WrittenTy
2566 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002567 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002568 TemplateArgs.size(),
2569 Context.getTypeDeclType(Specialization));
2570 Specialization->setTypeAsWritten(WrittenTy);
2571 TemplateArgsIn.release();
2572
2573 // Add the explicit instantiation into its lexical context. However,
2574 // since explicit instantiations are never found by name lookup, we
2575 // just put it into the declaration context directly.
2576 Specialization->setLexicalDeclContext(CurContext);
2577 CurContext->addDecl(Context, Specialization);
2578
2579 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002580 // A definition of a class template or class member template
2581 // shall be in scope at the point of the explicit instantiation of
2582 // the class template or class member template.
2583 //
2584 // This check comes when we actually try to perform the
2585 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002586 if (SpecializationRequiresInstantiation)
2587 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002588 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002589 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002590
2591 return DeclPtrTy::make(Specialization);
2592}
2593
Douglas Gregor96b6df92009-05-14 00:28:11 +00002594// Explicit instantiation of a member class of a class template.
2595Sema::DeclResult
2596Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2597 unsigned TagSpec,
2598 SourceLocation KWLoc,
2599 const CXXScopeSpec &SS,
2600 IdentifierInfo *Name,
2601 SourceLocation NameLoc,
2602 AttributeList *Attr) {
2603
Douglas Gregor71f06032009-05-28 23:31:59 +00002604 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002605 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002606 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002607 if (!TagD)
2608 return true;
2609
2610 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2611 if (Tag->isEnum()) {
2612 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2613 << Context.getTypeDeclType(Tag);
2614 return true;
2615 }
2616
Douglas Gregord769bfa2009-05-27 17:30:49 +00002617 if (Tag->isInvalidDecl())
2618 return true;
2619
Douglas Gregor96b6df92009-05-14 00:28:11 +00002620 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2621 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2622 if (!Pattern) {
2623 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2624 << Context.getTypeDeclType(Record);
2625 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2626 return true;
2627 }
2628
2629 // C++0x [temp.explicit]p2:
2630 // [...] An explicit instantiation shall appear in an enclosing
2631 // namespace of its template. [...]
2632 //
2633 // This is C++ DR 275.
2634 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002635 // FIXME: In C++98, we would like to turn these errors into warnings,
2636 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002637 DeclContext *PatternContext
2638 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2639 if (!CurContext->Encloses(PatternContext)) {
2640 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2641 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2642 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2643 }
2644 }
2645
Douglas Gregor96b6df92009-05-14 00:28:11 +00002646 if (!Record->getDefinition(Context)) {
2647 // If the class has a definition, instantiate it (and all of its
2648 // members, recursively).
2649 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2650 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002651 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002652 /*ExplicitInstantiation=*/true))
2653 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002654 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002655 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002656 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002657
Mike Stumpe127ae32009-05-16 07:39:55 +00002658 // FIXME: We don't have any representation for explicit instantiations of
2659 // member classes. Such a representation is not needed for compilation, but it
2660 // should be available for clients that want to see all of the declarations in
2661 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002662 return TagD;
2663}
2664
Douglas Gregord3022602009-03-27 23:10:48 +00002665Sema::TypeResult
2666Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2667 const IdentifierInfo &II, SourceLocation IdLoc) {
2668 NestedNameSpecifier *NNS
2669 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2670 if (!NNS)
2671 return true;
2672
2673 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002674 if (T.isNull())
2675 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002676 return T.getAsOpaquePtr();
2677}
2678
Douglas Gregor77da5802009-04-01 00:28:59 +00002679Sema::TypeResult
2680Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2681 SourceLocation TemplateLoc, TypeTy *Ty) {
2682 QualType T = QualType::getFromOpaquePtr(Ty);
2683 NestedNameSpecifier *NNS
2684 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2685 const TemplateSpecializationType *TemplateId
2686 = T->getAsTemplateSpecializationType();
2687 assert(TemplateId && "Expected a template specialization type");
2688
2689 if (NNS->isDependent())
2690 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2691
2692 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2693}
2694
Douglas Gregord3022602009-03-27 23:10:48 +00002695/// \brief Build the type that describes a C++ typename specifier,
2696/// e.g., "typename T::type".
2697QualType
2698Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2699 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002700 CXXRecordDecl *CurrentInstantiation = 0;
2701 if (NNS->isDependent()) {
2702 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002703
Douglas Gregor3eb20702009-05-11 19:58:34 +00002704 // If the nested-name-specifier does not refer to the current
2705 // instantiation, then build a typename type.
2706 if (!CurrentInstantiation)
2707 return Context.getTypenameType(NNS, &II);
2708 }
Douglas Gregord3022602009-03-27 23:10:48 +00002709
Douglas Gregor3eb20702009-05-11 19:58:34 +00002710 DeclContext *Ctx = 0;
2711
2712 if (CurrentInstantiation)
2713 Ctx = CurrentInstantiation;
2714 else {
2715 CXXScopeSpec SS;
2716 SS.setScopeRep(NNS);
2717 SS.setRange(Range);
2718 if (RequireCompleteDeclContext(SS))
2719 return QualType();
2720
2721 Ctx = computeDeclContext(SS);
2722 }
Douglas Gregord3022602009-03-27 23:10:48 +00002723 assert(Ctx && "No declaration context?");
2724
2725 DeclarationName Name(&II);
2726 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2727 false);
2728 unsigned DiagID = 0;
2729 Decl *Referenced = 0;
2730 switch (Result.getKind()) {
2731 case LookupResult::NotFound:
2732 if (Ctx->isTranslationUnit())
2733 DiagID = diag::err_typename_nested_not_found_global;
2734 else
2735 DiagID = diag::err_typename_nested_not_found;
2736 break;
2737
2738 case LookupResult::Found:
2739 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2740 // We found a type. Build a QualifiedNameType, since the
2741 // typename-specifier was just sugar. FIXME: Tell
2742 // QualifiedNameType that it has a "typename" prefix.
2743 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2744 }
2745
2746 DiagID = diag::err_typename_nested_not_type;
2747 Referenced = Result.getAsDecl();
2748 break;
2749
2750 case LookupResult::FoundOverloaded:
2751 DiagID = diag::err_typename_nested_not_type;
2752 Referenced = *Result.begin();
2753 break;
2754
2755 case LookupResult::AmbiguousBaseSubobjectTypes:
2756 case LookupResult::AmbiguousBaseSubobjects:
2757 case LookupResult::AmbiguousReference:
2758 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2759 return QualType();
2760 }
2761
2762 // If we get here, it's because name lookup did not find a
2763 // type. Emit an appropriate diagnostic and return an error.
2764 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2765 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2766 else
2767 Diag(Range.getEnd(), DiagID) << Range << Name;
2768 if (Referenced)
2769 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2770 << Name;
2771 return QualType();
2772}