blob: 8058ad2d63fc68a0bd97ebbe40c4cb44f0d810c8 [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
190 // C++ [temp.param]p14:
191 // A template-parameter shall not be used in its own default argument.
192 // FIXME: Implement this check! Needs a recursive walk over the types.
193
194 // Check the template argument itself.
195 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
196 Parm->setInvalidDecl();
197 return;
198 }
199
200 Parm->setDefaultArgument(Default, DefaultLoc, false);
201}
202
Douglas Gregored3a3982009-03-03 04:44:36 +0000203/// \brief Check that the type of a non-type template parameter is
204/// well-formed.
205///
206/// \returns the (possibly-promoted) parameter type if valid;
207/// otherwise, produces a diagnostic and returns a NULL type.
208QualType
209Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
210 // C++ [temp.param]p4:
211 //
212 // A non-type template-parameter shall have one of the following
213 // (optionally cv-qualified) types:
214 //
215 // -- integral or enumeration type,
216 if (T->isIntegralType() || T->isEnumeralType() ||
217 // -- pointer to object or pointer to function,
218 (T->isPointerType() &&
219 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
220 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
221 // -- reference to object or reference to function,
222 T->isReferenceType() ||
223 // -- pointer to member.
224 T->isMemberPointerType() ||
225 // If T is a dependent type, we can't do the check now, so we
226 // assume that it is well-formed.
227 T->isDependentType())
228 return T;
229 // C++ [temp.param]p8:
230 //
231 // A non-type template-parameter of type "array of T" or
232 // "function returning T" is adjusted to be of type "pointer to
233 // T" or "pointer to function returning T", respectively.
234 else if (T->isArrayType())
235 // FIXME: Keep the type prior to promotion?
236 return Context.getArrayDecayedType(T);
237 else if (T->isFunctionType())
238 // FIXME: Keep the type prior to promotion?
239 return Context.getPointerType(T);
240
241 Diag(Loc, diag::err_template_nontype_parm_bad_type)
242 << T;
243
244 return QualType();
245}
246
Douglas Gregordd861062008-12-05 18:15:24 +0000247/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
248/// template parameter (e.g., "int Size" in "template<int Size>
249/// class Array") has been parsed. S is the current scope and D is
250/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000251Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
252 unsigned Depth,
253 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000254 QualType T = GetTypeForDeclarator(D, S);
255
Douglas Gregor279272e2009-02-04 19:02:06 +0000256 assert(S->isTemplateParamScope() &&
257 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000258 bool Invalid = false;
259
260 IdentifierInfo *ParamName = D.getIdentifier();
261 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000262 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000263 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000264 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000265 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000266 }
267
Douglas Gregored3a3982009-03-03 04:44:36 +0000268 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000269 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000270 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000271 Invalid = true;
272 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000273
Douglas Gregordd861062008-12-05 18:15:24 +0000274 NonTypeTemplateParmDecl *Param
275 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000276 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000277 if (Invalid)
278 Param->setInvalidDecl();
279
280 if (D.getIdentifier()) {
281 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000282 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000283 IdResolver.AddDecl(Param);
284 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000285 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000286}
Douglas Gregor52473432008-12-24 02:52:09 +0000287
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000288/// \brief Adds a default argument to the given non-type template
289/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000290void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000291 SourceLocation EqualLoc,
292 ExprArg DefaultE) {
293 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000294 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000295 Expr *Default = static_cast<Expr *>(DefaultE.get());
296
297 // C++ [temp.param]p14:
298 // A template-parameter shall not be used in its own default argument.
299 // FIXME: Implement this check! Needs a recursive walk over the types.
300
301 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000302 TemplateArgument Converted;
303 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
304 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000305 TemplateParm->setInvalidDecl();
306 return;
307 }
308
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000309 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000310}
311
Douglas Gregor279272e2009-02-04 19:02:06 +0000312
313/// ActOnTemplateTemplateParameter - Called when a C++ template template
314/// parameter (e.g. T in template <template <typename> class T> class array)
315/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000316Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
317 SourceLocation TmpLoc,
318 TemplateParamsTy *Params,
319 IdentifierInfo *Name,
320 SourceLocation NameLoc,
321 unsigned Depth,
322 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000323{
324 assert(S->isTemplateParamScope() &&
325 "Template template parameter not in template parameter scope!");
326
327 // Construct the parameter object.
328 TemplateTemplateParmDecl *Param =
329 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
330 Position, Name,
331 (TemplateParameterList*)Params);
332
333 // Make sure the parameter is valid.
334 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
335 // do anything yet. However, if the template parameter list or (eventual)
336 // default value is ever invalidated, that will propagate here.
337 bool Invalid = false;
338 if (Invalid) {
339 Param->setInvalidDecl();
340 }
341
342 // If the tt-param has a name, then link the identifier into the scope
343 // and lookup mechanisms.
344 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000345 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000346 IdResolver.AddDecl(Param);
347 }
348
Chris Lattner5261d0c2009-03-28 19:18:32 +0000349 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000350}
351
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000352/// \brief Adds a default argument to the given template template
353/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000355 SourceLocation EqualLoc,
356 ExprArg DefaultE) {
357 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000358 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000359
360 // Since a template-template parameter's default argument is an
361 // id-expression, it must be a DeclRefExpr.
362 DeclRefExpr *Default
363 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
364
365 // C++ [temp.param]p14:
366 // A template-parameter shall not be used in its own default argument.
367 // FIXME: Implement this check! Needs a recursive walk over the types.
368
369 // Check the well-formedness of the template argument.
370 if (!isa<TemplateDecl>(Default->getDecl())) {
371 Diag(Default->getSourceRange().getBegin(),
372 diag::err_template_arg_must_be_template)
373 << Default->getSourceRange();
374 TemplateParm->setInvalidDecl();
375 return;
376 }
377 if (CheckTemplateArgument(TemplateParm, Default)) {
378 TemplateParm->setInvalidDecl();
379 return;
380 }
381
382 DefaultE.release();
383 TemplateParm->setDefaultArgument(Default);
384}
385
Douglas Gregor52473432008-12-24 02:52:09 +0000386/// ActOnTemplateParameterList - Builds a TemplateParameterList that
387/// contains the template parameters in Params/NumParams.
388Sema::TemplateParamsTy *
389Sema::ActOnTemplateParameterList(unsigned Depth,
390 SourceLocation ExportLoc,
391 SourceLocation TemplateLoc,
392 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000393 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000394 SourceLocation RAngleLoc) {
395 if (ExportLoc.isValid())
396 Diag(ExportLoc, diag::note_template_export_unsupported);
397
Douglas Gregord406b032009-02-06 22:42:48 +0000398 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
399 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000400}
Douglas Gregor279272e2009-02-04 19:02:06 +0000401
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000402Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000403Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
404 SourceLocation KWLoc, const CXXScopeSpec &SS,
405 IdentifierInfo *Name, SourceLocation NameLoc,
406 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000407 MultiTemplateParamsArg TemplateParameterLists,
408 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000409 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
410 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000411 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000412
413 // Check that we can declare a template here.
414 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000415 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000416
417 TagDecl::TagKind Kind;
418 switch (TagSpec) {
419 default: assert(0 && "Unknown tag type!");
420 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
421 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
422 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
423 }
424
425 // There is no such thing as an unnamed class template.
426 if (!Name) {
427 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000428 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000429 }
430
431 // Find any previous declaration with this name.
432 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
433 true);
434 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
435 NamedDecl *PrevDecl = 0;
436 if (Previous.begin() != Previous.end())
437 PrevDecl = *Previous.begin();
438
439 DeclContext *SemanticContext = CurContext;
440 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000441 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000442
Mike Stumpe127ae32009-05-16 07:39:55 +0000443 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000444 }
445
446 // FIXME: member templates!
447 TemplateParameterList *TemplateParams
448 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
449
450 // If there is a previous declaration with the same name, check
451 // whether this is a valid redeclaration.
452 ClassTemplateDecl *PrevClassTemplate
453 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
454 if (PrevClassTemplate) {
455 // Ensure that the template parameter lists are compatible.
456 if (!TemplateParameterListsAreEqual(TemplateParams,
457 PrevClassTemplate->getTemplateParameters(),
458 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000459 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000460
461 // C++ [temp.class]p4:
462 // In a redeclaration, partial specialization, explicit
463 // specialization or explicit instantiation of a class template,
464 // the class-key shall agree in kind with the original class
465 // template declaration (7.1.5.3).
466 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000467 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000468 Diag(KWLoc, diag::err_use_with_wrong_tag)
469 << Name
470 << CodeModificationHint::CreateReplacement(KWLoc,
471 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000472 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000473 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000474 }
475
Douglas Gregord406b032009-02-06 22:42:48 +0000476 // Check for redefinition of this class template.
477 if (TK == TK_Definition) {
478 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
479 Diag(NameLoc, diag::err_redefinition) << Name;
480 Diag(Def->getLocation(), diag::note_previous_definition);
481 // FIXME: Would it make sense to try to "forget" the previous
482 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000483 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000484 }
485 }
486 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
487 // Maybe we will complain about the shadowed template parameter.
488 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
489 // Just pretend that we didn't see the previous declaration.
490 PrevDecl = 0;
491 } else if (PrevDecl) {
492 // C++ [temp]p5:
493 // A class template shall not have the same name as any other
494 // template, class, function, object, enumeration, enumerator,
495 // namespace, or type in the same scope (3.3), except as specified
496 // in (14.5.4).
497 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
498 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000499 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000500 }
501
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000502 // Check the template parameter list of this declaration, possibly
503 // merging in the template parameter list from the previous class
504 // template declaration.
505 if (CheckTemplateParameterList(TemplateParams,
506 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
507 Invalid = true;
508
Douglas Gregor9054f982009-05-10 22:57:19 +0000509 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000510 // declaration!
511
Douglas Gregor55216ac2009-03-26 00:10:35 +0000512 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000513 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
514 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000515 PrevClassTemplate->getTemplatedDecl() : 0,
516 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000517
518 ClassTemplateDecl *NewTemplate
519 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
520 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000521 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000522 NewClass->setDescribedClassTemplate(NewTemplate);
523
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000524 // Build the type for the class template declaration now.
525 QualType T =
526 Context.getTypeDeclType(NewClass,
527 PrevClassTemplate?
528 PrevClassTemplate->getTemplatedDecl() : 0);
529 assert(T->isDependentType() && "Class template type is not dependent?");
530 (void)T;
531
Anders Carlsson4ca43492009-03-26 01:24:28 +0000532 // Set the access specifier.
533 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
534
Douglas Gregord406b032009-02-06 22:42:48 +0000535 // Set the lexical context of these templates
536 NewClass->setLexicalDeclContext(CurContext);
537 NewTemplate->setLexicalDeclContext(CurContext);
538
539 if (TK == TK_Definition)
540 NewClass->startDefinition();
541
542 if (Attr)
543 ProcessDeclAttributeList(NewClass, Attr);
544
545 PushOnScopeChains(NewTemplate, S);
546
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000547 if (Invalid) {
548 NewTemplate->setInvalidDecl();
549 NewClass->setInvalidDecl();
550 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000551 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000552}
553
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000554/// \brief Checks the validity of a template parameter list, possibly
555/// considering the template parameter list from a previous
556/// declaration.
557///
558/// If an "old" template parameter list is provided, it must be
559/// equivalent (per TemplateParameterListsAreEqual) to the "new"
560/// template parameter list.
561///
562/// \param NewParams Template parameter list for a new template
563/// declaration. This template parameter list will be updated with any
564/// default arguments that are carried through from the previous
565/// template parameter list.
566///
567/// \param OldParams If provided, template parameter list from a
568/// previous declaration of the same template. Default template
569/// arguments will be merged from the old template parameter list to
570/// the new template parameter list.
571///
572/// \returns true if an error occurred, false otherwise.
573bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
574 TemplateParameterList *OldParams) {
575 bool Invalid = false;
576
577 // C++ [temp.param]p10:
578 // The set of default template-arguments available for use with a
579 // template declaration or definition is obtained by merging the
580 // default arguments from the definition (if in scope) and all
581 // declarations in scope in the same way default function
582 // arguments are (8.3.6).
583 bool SawDefaultArgument = false;
584 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000585
Mike Stumpe0b7e032009-02-11 23:03:27 +0000586 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000587 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000588 if (OldParams)
589 OldParam = OldParams->begin();
590
591 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
592 NewParamEnd = NewParams->end();
593 NewParam != NewParamEnd; ++NewParam) {
594 // Variables used to diagnose redundant default arguments
595 bool RedundantDefaultArg = false;
596 SourceLocation OldDefaultLoc;
597 SourceLocation NewDefaultLoc;
598
599 // Variables used to diagnose missing default arguments
600 bool MissingDefaultArg = false;
601
602 // Merge default arguments for template type parameters.
603 if (TemplateTypeParmDecl *NewTypeParm
604 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
605 TemplateTypeParmDecl *OldTypeParm
606 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
607
608 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
609 NewTypeParm->hasDefaultArgument()) {
610 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
611 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
612 SawDefaultArgument = true;
613 RedundantDefaultArg = true;
614 PreviousDefaultArgLoc = NewDefaultLoc;
615 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
616 // Merge the default argument from the old declaration to the
617 // new declaration.
618 SawDefaultArgument = true;
619 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
620 OldTypeParm->getDefaultArgumentLoc(),
621 true);
622 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
623 } else if (NewTypeParm->hasDefaultArgument()) {
624 SawDefaultArgument = true;
625 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
626 } else if (SawDefaultArgument)
627 MissingDefaultArg = true;
628 }
629 // Merge default arguments for non-type template parameters
630 else if (NonTypeTemplateParmDecl *NewNonTypeParm
631 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
632 NonTypeTemplateParmDecl *OldNonTypeParm
633 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
634 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
635 NewNonTypeParm->hasDefaultArgument()) {
636 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
637 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
638 SawDefaultArgument = true;
639 RedundantDefaultArg = true;
640 PreviousDefaultArgLoc = NewDefaultLoc;
641 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
642 // Merge the default argument from the old declaration to the
643 // new declaration.
644 SawDefaultArgument = true;
645 // FIXME: We need to create a new kind of "default argument"
646 // expression that points to a previous template template
647 // parameter.
648 NewNonTypeParm->setDefaultArgument(
649 OldNonTypeParm->getDefaultArgument());
650 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
651 } else if (NewNonTypeParm->hasDefaultArgument()) {
652 SawDefaultArgument = true;
653 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
654 } else if (SawDefaultArgument)
655 MissingDefaultArg = true;
656 }
657 // Merge default arguments for template template parameters
658 else {
659 TemplateTemplateParmDecl *NewTemplateParm
660 = cast<TemplateTemplateParmDecl>(*NewParam);
661 TemplateTemplateParmDecl *OldTemplateParm
662 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
663 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
664 NewTemplateParm->hasDefaultArgument()) {
665 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
666 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
667 SawDefaultArgument = true;
668 RedundantDefaultArg = true;
669 PreviousDefaultArgLoc = NewDefaultLoc;
670 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
671 // Merge the default argument from the old declaration to the
672 // new declaration.
673 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000674 // FIXME: We need to create a new kind of "default argument" expression
675 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000676 NewTemplateParm->setDefaultArgument(
677 OldTemplateParm->getDefaultArgument());
678 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
679 } else if (NewTemplateParm->hasDefaultArgument()) {
680 SawDefaultArgument = true;
681 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
682 } else if (SawDefaultArgument)
683 MissingDefaultArg = true;
684 }
685
686 if (RedundantDefaultArg) {
687 // C++ [temp.param]p12:
688 // A template-parameter shall not be given default arguments
689 // by two different declarations in the same scope.
690 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
691 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
692 Invalid = true;
693 } else if (MissingDefaultArg) {
694 // C++ [temp.param]p11:
695 // If a template-parameter has a default template-argument,
696 // all subsequent template-parameters shall have a default
697 // template-argument supplied.
698 Diag((*NewParam)->getLocation(),
699 diag::err_template_param_default_arg_missing);
700 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
701 Invalid = true;
702 }
703
704 // If we have an old template parameter list that we're merging
705 // in, move on to the next parameter.
706 if (OldParams)
707 ++OldParam;
708 }
709
710 return Invalid;
711}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000712
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000713/// \brief Translates template arguments as provided by the parser
714/// into template arguments used by semantic analysis.
715static void
716translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
717 SourceLocation *TemplateArgLocs,
718 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
719 TemplateArgs.reserve(TemplateArgsIn.size());
720
721 void **Args = TemplateArgsIn.getArgs();
722 bool *ArgIsType = TemplateArgsIn.getArgIsType();
723 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
724 TemplateArgs.push_back(
725 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
726 QualType::getFromOpaquePtr(Args[Arg]))
727 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
728 }
729}
730
Douglas Gregoraabb8502009-03-31 00:43:58 +0000731/// \brief Build a canonical version of a template argument list.
732///
733/// This function builds a canonical version of the given template
734/// argument list, where each of the template arguments has been
735/// converted into its canonical form. This routine is typically used
736/// to canonicalize a template argument list when the template name
737/// itself is dependent. When the template name refers to an actual
738/// template declaration, Sema::CheckTemplateArgumentList should be
739/// used to check and canonicalize the template arguments.
740///
741/// \param TemplateArgs The incoming template arguments.
742///
743/// \param NumTemplateArgs The number of template arguments in \p
744/// TemplateArgs.
745///
746/// \param Canonical A vector to be filled with the canonical versions
747/// of the template arguments.
748///
749/// \param Context The ASTContext in which the template arguments live.
750static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
751 unsigned NumTemplateArgs,
752 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
753 ASTContext &Context) {
754 Canonical.reserve(NumTemplateArgs);
755 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
756 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000757 case TemplateArgument::Null:
758 assert(false && "Should never see a NULL template argument here");
759 break;
760
Douglas Gregoraabb8502009-03-31 00:43:58 +0000761 case TemplateArgument::Expression:
762 // FIXME: Build canonical expression (!)
763 Canonical.push_back(TemplateArgs[Idx]);
764 break;
765
766 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000767 Canonical.push_back(
768 TemplateArgument(SourceLocation(),
769 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000770 break;
771
772 case TemplateArgument::Integral:
773 Canonical.push_back(TemplateArgument(SourceLocation(),
774 *TemplateArgs[Idx].getAsIntegral(),
775 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000776 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000777
778 case TemplateArgument::Type: {
779 QualType CanonType
780 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
781 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000782 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000783 }
784 }
785 }
786}
787
Douglas Gregordd13e842009-03-30 22:58:21 +0000788QualType Sema::CheckTemplateIdType(TemplateName Name,
789 SourceLocation TemplateLoc,
790 SourceLocation LAngleLoc,
791 const TemplateArgument *TemplateArgs,
792 unsigned NumTemplateArgs,
793 SourceLocation RAngleLoc) {
794 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000795 if (!Template) {
796 // The template name does not resolve to a template, so we just
797 // build a dependent template-id type.
798
799 // Canonicalize the template arguments to build the canonical
800 // template-id type.
801 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
802 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
803 CanonicalTemplateArgs, Context);
804
Douglas Gregor905406b2009-05-07 06:49:52 +0000805 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000806 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000807 = Context.getTemplateSpecializationType(CanonName,
808 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000809 CanonicalTemplateArgs.size());
810
811 // Build the dependent template-id type.
812 return Context.getTemplateSpecializationType(Name, TemplateArgs,
813 NumTemplateArgs, CanonType);
814 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000815
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000816 // Check that the template argument list is well-formed for this
817 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000818 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000819 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000820 TemplateArgs, NumTemplateArgs, RAngleLoc,
821 ConvertedTemplateArgs))
822 return QualType();
823
824 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000825 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000826 "Converted template argument list is too short!");
827
828 QualType CanonType;
829
Douglas Gregordd13e842009-03-30 22:58:21 +0000830 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000831 TemplateArgs,
832 NumTemplateArgs)) {
833 // This class template specialization is a dependent
834 // type. Therefore, its canonical type is another class template
835 // specialization type that contains all of the converted
836 // arguments in canonical form. This ensures that, e.g., A<T> and
837 // A<T, T> have identical types when A is declared as:
838 //
839 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000840 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
841 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000842 ConvertedTemplateArgs.getFlatArgumentList(),
843 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000844 } else if (ClassTemplateDecl *ClassTemplate
845 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000846 // Find the class template specialization declaration that
847 // corresponds to these arguments.
848 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000849 ClassTemplateSpecializationDecl::Profile(ID,
850 ConvertedTemplateArgs.getFlatArgumentList(),
851 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000852 void *InsertPos = 0;
853 ClassTemplateSpecializationDecl *Decl
854 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
855 if (!Decl) {
856 // This is the first time we have referenced this class template
857 // specialization. Create the canonical declaration and add it to
858 // the set of specializations.
859 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000860 ClassTemplate->getDeclContext(),
861 TemplateLoc,
862 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000863 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000864 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
865 Decl->setLexicalDeclContext(CurContext);
866 }
867
868 CanonType = Context.getTypeDeclType(Decl);
869 }
870
871 // Build the fully-sugared type for this class template
872 // specialization, which refers back to the class template
873 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000874 return Context.getTemplateSpecializationType(Name, TemplateArgs,
875 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000876}
877
Douglas Gregora08b6c72009-02-17 23:15:12 +0000878Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000879Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
880 SourceLocation LAngleLoc,
881 ASTTemplateArgsPtr TemplateArgsIn,
882 SourceLocation *TemplateArgLocs,
883 SourceLocation RAngleLoc) {
884 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000885
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000886 // Translate the parser's template argument list in our AST format.
887 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
888 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000889
Douglas Gregordd13e842009-03-30 22:58:21 +0000890 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000891 TemplateArgs.data(),
892 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000893 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000894 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000895
896 if (Result.isNull())
897 return true;
898
Douglas Gregor6f37b582009-02-09 19:34:22 +0000899 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000900}
901
Douglas Gregoraabb8502009-03-31 00:43:58 +0000902/// \brief Form a dependent template name.
903///
904/// This action forms a dependent template name given the template
905/// name and its (presumably dependent) scope specifier. For
906/// example, given "MetaFun::template apply", the scope specifier \p
907/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
908/// of the "template" keyword, and "apply" is the \p Name.
909Sema::TemplateTy
910Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
911 const IdentifierInfo &Name,
912 SourceLocation NameLoc,
913 const CXXScopeSpec &SS) {
914 if (!SS.isSet() || SS.isInvalid())
915 return TemplateTy();
916
917 NestedNameSpecifier *Qualifier
918 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
919
920 // FIXME: member of the current instantiation
921
922 if (!Qualifier->isDependent()) {
923 // C++0x [temp.names]p5:
924 // If a name prefixed by the keyword template is not the name of
925 // a template, the program is ill-formed. [Note: the keyword
926 // template may not be applied to non-template members of class
927 // templates. -end note ] [ Note: as is the case with the
928 // typename prefix, the template prefix is allowed in cases
929 // where it is not strictly necessary; i.e., when the
930 // nested-name-specifier or the expression on the left of the ->
931 // or . is not dependent on a template-parameter, or the use
932 // does not appear in the scope of a template. -end note]
933 //
934 // Note: C++03 was more strict here, because it banned the use of
935 // the "template" keyword prior to a template-name that was not a
936 // dependent name. C++ DR468 relaxed this requirement (the
937 // "template" keyword is now permitted). We follow the C++0x
938 // rules, even in C++03 mode, retroactively applying the DR.
939 TemplateTy Template;
940 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
941 if (TNK == TNK_Non_template) {
942 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
943 << &Name;
944 return TemplateTy();
945 }
946
947 return Template;
948 }
949
950 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
951}
952
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000953/// \brief Check that the given template argument list is well-formed
954/// for specializing the given template.
955bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
956 SourceLocation TemplateLoc,
957 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000958 const TemplateArgument *TemplateArgs,
959 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000960 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +0000961 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000962 TemplateParameterList *Params = Template->getTemplateParameters();
963 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000964 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000965 bool Invalid = false;
966
967 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000968 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000969 // FIXME: point at either the first arg beyond what we can handle,
970 // or the '>', depending on whether we have too many or too few
971 // arguments.
972 SourceRange Range;
973 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000974 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000975 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
976 << (NumArgs > NumParams)
977 << (isa<ClassTemplateDecl>(Template)? 0 :
978 isa<FunctionTemplateDecl>(Template)? 1 :
979 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
980 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000981 Diag(Template->getLocation(), diag::note_template_decl_here)
982 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000983 Invalid = true;
984 }
985
986 // C++ [temp.arg]p1:
987 // [...] The type and form of each template-argument specified in
988 // a template-id shall match the type and form specified for the
989 // corresponding parameter declared by the template in its
990 // template-parameter-list.
991 unsigned ArgIdx = 0;
992 for (TemplateParameterList::iterator Param = Params->begin(),
993 ParamEnd = Params->end();
994 Param != ParamEnd; ++Param, ++ArgIdx) {
995 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000996 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000997 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000998 // Retrieve the default template argument from the template
999 // parameter.
1000 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1001 if (!TTP->hasDefaultArgument())
1002 break;
1003
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001004 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001005
1006 // If the argument type is dependent, instantiate it now based
1007 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001008 if (ArgType->isDependentType()) {
1009 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001010 Template, Converted.getFlatArgumentList(),
1011 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001012 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001013
Anders Carlsson0233eb62009-06-05 04:47:51 +00001014 TemplateArgumentList TemplateArgs(Context, Converted,
1015 /*CopyArgs=*/false,
1016 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001017 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001018 TTP->getDefaultArgumentLoc(),
1019 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001020 }
Douglas Gregor74296542009-02-27 19:31:52 +00001021
1022 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001023 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001024
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001025 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001026 } else if (NonTypeTemplateParmDecl *NTTP
1027 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1028 if (!NTTP->hasDefaultArgument())
1029 break;
1030
Anders Carlsson0297caf2009-06-11 16:06:49 +00001031 InstantiatingTemplate Inst(*this, TemplateLoc,
1032 Template, Converted.getFlatArgumentList(),
1033 Converted.flatSize(),
1034 SourceRange(TemplateLoc, RAngleLoc));
1035
1036 TemplateArgumentList TemplateArgs(Context, Converted,
1037 /*CopyArgs=*/false,
1038 /*FlattenArgs=*/false);
1039
1040 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1041 TemplateArgs);
1042 if (E.isInvalid())
1043 return true;
1044
1045 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001046 } else {
1047 TemplateTemplateParmDecl *TempParm
1048 = cast<TemplateTemplateParmDecl>(*Param);
1049
1050 if (!TempParm->hasDefaultArgument())
1051 break;
1052
Douglas Gregored3a3982009-03-03 04:44:36 +00001053 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001054 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001055 }
1056 } else {
1057 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001058 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001059 }
1060
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001061
1062 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1063 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001064 if (Arg.getKind() == TemplateArgument::Type) {
1065 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001066 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001067
1068 // Add the converted template type argument.
1069 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001070 TemplateArgument(Arg.getLocation(),
1071 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001072 continue;
1073 }
1074
1075 // C++ [temp.arg.type]p1:
1076 // A template-argument for a template-parameter which is a
1077 // type shall be a type-id.
1078
1079 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001080 // is not a type.
1081 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001082 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001083 Invalid = true;
1084 } else if (NonTypeTemplateParmDecl *NTTP
1085 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1086 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001087
1088 // Instantiate the type of the non-type template parameter with
1089 // the template arguments we've seen thus far.
1090 QualType NTTPType = NTTP->getType();
1091 if (NTTPType->isDependentType()) {
1092 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001093 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001094 Template, Converted.getFlatArgumentList(),
1095 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001096 SourceRange(TemplateLoc, RAngleLoc));
1097
Anders Carlsson0233eb62009-06-05 04:47:51 +00001098 TemplateArgumentList TemplateArgs(Context, Converted,
1099 /*CopyArgs=*/false,
1100 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001101 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001102 NTTP->getLocation(),
1103 NTTP->getDeclName());
1104 // If that worked, check the non-type template parameter type
1105 // for validity.
1106 if (!NTTPType.isNull())
1107 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1108 NTTP->getLocation());
1109
1110 if (NTTPType.isNull()) {
1111 Invalid = true;
1112 break;
1113 }
1114 }
1115
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001116 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001117 case TemplateArgument::Null:
1118 assert(false && "Should never see a NULL template argument here");
1119 break;
1120
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001121 case TemplateArgument::Expression: {
1122 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001123 TemplateArgument Result;
1124 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001125 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001126 else
1127 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001128 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001129 }
1130
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001131 case TemplateArgument::Declaration:
1132 case TemplateArgument::Integral:
1133 // We've already checked this template argument, so just copy
1134 // it to the list of converted arguments.
1135 Converted.push_back(Arg);
1136 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001137
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001138 case TemplateArgument::Type:
1139 // We have a non-type template parameter but the template
1140 // argument is a type.
1141
1142 // C++ [temp.arg]p2:
1143 // In a template-argument, an ambiguity between a type-id and
1144 // an expression is resolved to a type-id, regardless of the
1145 // form of the corresponding template-parameter.
1146 //
1147 // We warn specifically about this case, since it can be rather
1148 // confusing for users.
1149 if (Arg.getAsType()->isFunctionType())
1150 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1151 << Arg.getAsType();
1152 else
1153 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1154 Diag((*Param)->getLocation(), diag::note_template_param_here);
1155 Invalid = true;
1156 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001157 } else {
1158 // Check template template parameters.
1159 TemplateTemplateParmDecl *TempParm
1160 = cast<TemplateTemplateParmDecl>(*Param);
1161
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001162 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001163 case TemplateArgument::Null:
1164 assert(false && "Should never see a NULL template argument here");
1165 break;
1166
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001167 case TemplateArgument::Expression: {
1168 Expr *ArgExpr = Arg.getAsExpr();
1169 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1170 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1171 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1172 Invalid = true;
1173
1174 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001175 Decl *D
1176 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1177 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001178 continue;
1179 }
1180 }
1181 // fall through
1182
1183 case TemplateArgument::Type: {
1184 // We have a template template parameter but the template
1185 // argument does not refer to a template.
1186 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1187 Invalid = true;
1188 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001189 }
1190
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001191 case TemplateArgument::Declaration:
1192 // We've already checked this template argument, so just copy
1193 // it to the list of converted arguments.
1194 Converted.push_back(Arg);
1195 break;
1196
1197 case TemplateArgument::Integral:
1198 assert(false && "Integral argument with template template parameter");
1199 break;
1200 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001201 }
1202 }
1203
1204 return Invalid;
1205}
1206
1207/// \brief Check a template argument against its corresponding
1208/// template type parameter.
1209///
1210/// This routine implements the semantics of C++ [temp.arg.type]. It
1211/// returns true if an error occurred, and false otherwise.
1212bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1213 QualType Arg, SourceLocation ArgLoc) {
1214 // C++ [temp.arg.type]p2:
1215 // A local type, a type with no linkage, an unnamed type or a type
1216 // compounded from any of these types shall not be used as a
1217 // template-argument for a template type-parameter.
1218 //
1219 // FIXME: Perform the recursive and no-linkage type checks.
1220 const TagType *Tag = 0;
1221 if (const EnumType *EnumT = Arg->getAsEnumType())
1222 Tag = EnumT;
1223 else if (const RecordType *RecordT = Arg->getAsRecordType())
1224 Tag = RecordT;
1225 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1226 return Diag(ArgLoc, diag::err_template_arg_local_type)
1227 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001228 else if (Tag && !Tag->getDecl()->getDeclName() &&
1229 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001230 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1231 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001238/// \brief Checks whether the given template argument is the address
1239/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001240bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1241 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001242 bool Invalid = false;
1243
1244 // See through any implicit casts we added to fix the type.
1245 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1246 Arg = Cast->getSubExpr();
1247
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001248 // C++0x allows nullptr, and there's no further checking to be done for that.
1249 if (Arg->getType()->isNullPtrType())
1250 return false;
1251
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001252 // C++ [temp.arg.nontype]p1:
1253 //
1254 // A template-argument for a non-type, non-template
1255 // template-parameter shall be one of: [...]
1256 //
1257 // -- the address of an object or function with external
1258 // linkage, including function templates and function
1259 // template-ids but excluding non-static class members,
1260 // expressed as & id-expression where the & is optional if
1261 // the name refers to a function or array, or if the
1262 // corresponding template-parameter is a reference; or
1263 DeclRefExpr *DRE = 0;
1264
1265 // Ignore (and complain about) any excess parentheses.
1266 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1267 if (!Invalid) {
1268 Diag(Arg->getSourceRange().getBegin(),
1269 diag::err_template_arg_extra_parens)
1270 << Arg->getSourceRange();
1271 Invalid = true;
1272 }
1273
1274 Arg = Parens->getSubExpr();
1275 }
1276
1277 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1278 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1279 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1280 } else
1281 DRE = dyn_cast<DeclRefExpr>(Arg);
1282
1283 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1284 return Diag(Arg->getSourceRange().getBegin(),
1285 diag::err_template_arg_not_object_or_func_form)
1286 << Arg->getSourceRange();
1287
1288 // Cannot refer to non-static data members
1289 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1290 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1291 << Field << Arg->getSourceRange();
1292
1293 // Cannot refer to non-static member functions
1294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1295 if (!Method->isStatic())
1296 return Diag(Arg->getSourceRange().getBegin(),
1297 diag::err_template_arg_method)
1298 << Method << Arg->getSourceRange();
1299
1300 // Functions must have external linkage.
1301 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1302 if (Func->getStorageClass() == FunctionDecl::Static) {
1303 Diag(Arg->getSourceRange().getBegin(),
1304 diag::err_template_arg_function_not_extern)
1305 << Func << Arg->getSourceRange();
1306 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1307 << true;
1308 return true;
1309 }
1310
1311 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001312 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001313 return Invalid;
1314 }
1315
1316 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1317 if (!Var->hasGlobalStorage()) {
1318 Diag(Arg->getSourceRange().getBegin(),
1319 diag::err_template_arg_object_not_extern)
1320 << Var << Arg->getSourceRange();
1321 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1322 << true;
1323 return true;
1324 }
1325
1326 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001327 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001328 return Invalid;
1329 }
1330
1331 // We found something else, but we don't know specifically what it is.
1332 Diag(Arg->getSourceRange().getBegin(),
1333 diag::err_template_arg_not_object_or_func)
1334 << Arg->getSourceRange();
1335 Diag(DRE->getDecl()->getLocation(),
1336 diag::note_template_arg_refers_here);
1337 return true;
1338}
1339
1340/// \brief Checks whether the given template argument is a pointer to
1341/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001342bool
1343Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001344 bool Invalid = false;
1345
1346 // See through any implicit casts we added to fix the type.
1347 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1348 Arg = Cast->getSubExpr();
1349
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001350 // C++0x allows nullptr, and there's no further checking to be done for that.
1351 if (Arg->getType()->isNullPtrType())
1352 return false;
1353
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001354 // C++ [temp.arg.nontype]p1:
1355 //
1356 // A template-argument for a non-type, non-template
1357 // template-parameter shall be one of: [...]
1358 //
1359 // -- a pointer to member expressed as described in 5.3.1.
1360 QualifiedDeclRefExpr *DRE = 0;
1361
1362 // Ignore (and complain about) any excess parentheses.
1363 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1364 if (!Invalid) {
1365 Diag(Arg->getSourceRange().getBegin(),
1366 diag::err_template_arg_extra_parens)
1367 << Arg->getSourceRange();
1368 Invalid = true;
1369 }
1370
1371 Arg = Parens->getSubExpr();
1372 }
1373
1374 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1375 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1376 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1377
1378 if (!DRE)
1379 return Diag(Arg->getSourceRange().getBegin(),
1380 diag::err_template_arg_not_pointer_to_member_form)
1381 << Arg->getSourceRange();
1382
1383 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1384 assert((isa<FieldDecl>(DRE->getDecl()) ||
1385 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1386 "Only non-static member pointers can make it here");
1387
1388 // Okay: this is the address of a non-static member, and therefore
1389 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001390 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001391 return Invalid;
1392 }
1393
1394 // We found something else, but we don't know specifically what it is.
1395 Diag(Arg->getSourceRange().getBegin(),
1396 diag::err_template_arg_not_pointer_to_member_form)
1397 << Arg->getSourceRange();
1398 Diag(DRE->getDecl()->getLocation(),
1399 diag::note_template_arg_refers_here);
1400 return true;
1401}
1402
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001403/// \brief Check a template argument against its corresponding
1404/// non-type template parameter.
1405///
Douglas Gregored3a3982009-03-03 04:44:36 +00001406/// This routine implements the semantics of C++ [temp.arg.nontype].
1407/// It returns true if an error occurred, and false otherwise. \p
1408/// InstantiatedParamType is the type of the non-type template
1409/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001410///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001411/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001412bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001413 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001414 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001415 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1416
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001417 // If either the parameter has a dependent type or the argument is
1418 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001419 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001420 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1421 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001422 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001423 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001424 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001425
1426 // C++ [temp.arg.nontype]p5:
1427 // The following conversions are performed on each expression used
1428 // as a non-type template-argument. If a non-type
1429 // template-argument cannot be converted to the type of the
1430 // corresponding template-parameter then the program is
1431 // ill-formed.
1432 //
1433 // -- for a non-type template-parameter of integral or
1434 // enumeration type, integral promotions (4.5) and integral
1435 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001436 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001437 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001438 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001439 // C++ [temp.arg.nontype]p1:
1440 // A template-argument for a non-type, non-template
1441 // template-parameter shall be one of:
1442 //
1443 // -- an integral constant-expression of integral or enumeration
1444 // type; or
1445 // -- the name of a non-type template-parameter; or
1446 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001447 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001448 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1449 Diag(Arg->getSourceRange().getBegin(),
1450 diag::err_template_arg_not_integral_or_enumeral)
1451 << ArgType << Arg->getSourceRange();
1452 Diag(Param->getLocation(), diag::note_template_param_here);
1453 return true;
1454 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001455 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001456 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1457 << ArgType << Arg->getSourceRange();
1458 return true;
1459 }
1460
1461 // FIXME: We need some way to more easily get the unqualified form
1462 // of the types without going all the way to the
1463 // canonical type.
1464 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1465 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1466 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1467 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1468
1469 // Try to convert the argument to the parameter's type.
1470 if (ParamType == ArgType) {
1471 // Okay: no conversion necessary
1472 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1473 !ParamType->isEnumeralType()) {
1474 // This is an integral promotion or conversion.
1475 ImpCastExprToType(Arg, ParamType);
1476 } else {
1477 // We can't perform this conversion.
1478 Diag(Arg->getSourceRange().getBegin(),
1479 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001480 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001481 Diag(Param->getLocation(), diag::note_template_param_here);
1482 return true;
1483 }
1484
Douglas Gregorafc86942009-03-14 00:20:21 +00001485 QualType IntegerType = Context.getCanonicalType(ParamType);
1486 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001487 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001488
1489 if (!Arg->isValueDependent()) {
1490 // Check that an unsigned parameter does not receive a negative
1491 // value.
1492 if (IntegerType->isUnsignedIntegerType()
1493 && (Value.isSigned() && Value.isNegative())) {
1494 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1495 << Value.toString(10) << Param->getType()
1496 << Arg->getSourceRange();
1497 Diag(Param->getLocation(), diag::note_template_param_here);
1498 return true;
1499 }
1500
1501 // Check that we don't overflow the template parameter type.
1502 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1503 if (Value.getActiveBits() > AllowedBits) {
1504 Diag(Arg->getSourceRange().getBegin(),
1505 diag::err_template_arg_too_large)
1506 << Value.toString(10) << Param->getType()
1507 << Arg->getSourceRange();
1508 Diag(Param->getLocation(), diag::note_template_param_here);
1509 return true;
1510 }
1511
1512 if (Value.getBitWidth() != AllowedBits)
1513 Value.extOrTrunc(AllowedBits);
1514 Value.setIsSigned(IntegerType->isSignedIntegerType());
1515 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001516
Douglas Gregor8f378a92009-06-11 18:10:32 +00001517 // Add the value of this argument to the list of converted
1518 // arguments. We use the bitwidth and signedness of the template
1519 // parameter.
1520 if (Arg->isValueDependent()) {
1521 // The argument is value-dependent. Create a new
1522 // TemplateArgument with the converted expression.
1523 Converted = TemplateArgument(Arg);
1524 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001525 }
1526
Douglas Gregor8f378a92009-06-11 18:10:32 +00001527 Converted = TemplateArgument(StartLoc, Value,
1528 ParamType->isEnumeralType() ? ParamType
1529 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001530 return false;
1531 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001532
Douglas Gregor3f411962009-02-11 01:18:59 +00001533 // Handle pointer-to-function, reference-to-function, and
1534 // pointer-to-member-function all in (roughly) the same way.
1535 if (// -- For a non-type template-parameter of type pointer to
1536 // function, only the function-to-pointer conversion (4.3) is
1537 // applied. If the template-argument represents a set of
1538 // overloaded functions (or a pointer to such), the matching
1539 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001540 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001541 (ParamType->isPointerType() &&
1542 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1543 // -- For a non-type template-parameter of type reference to
1544 // function, no conversions apply. If the template-argument
1545 // represents a set of overloaded functions, the matching
1546 // function is selected from the set (13.4).
1547 (ParamType->isReferenceType() &&
1548 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1549 // -- For a non-type template-parameter of type pointer to
1550 // member function, no conversions apply. If the
1551 // template-argument represents a set of overloaded member
1552 // functions, the matching member function is selected from
1553 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001554 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001555 (ParamType->isMemberPointerType() &&
1556 ParamType->getAsMemberPointerType()->getPointeeType()
1557 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001558 if (Context.hasSameUnqualifiedType(ArgType,
1559 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001560 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001561 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1562 ParamType->isMemberPointerType())) {
1563 ArgType = ParamType;
1564 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001565 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001566 ArgType = Context.getPointerType(ArgType);
1567 ImpCastExprToType(Arg, ArgType);
1568 } else if (FunctionDecl *Fn
1569 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001570 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1571 return true;
1572
Douglas Gregor2eedd992009-02-11 00:19:33 +00001573 FixOverloadedFunctionReference(Arg, Fn);
1574 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001575 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001576 ArgType = Context.getPointerType(Arg->getType());
1577 ImpCastExprToType(Arg, ArgType);
1578 }
1579 }
1580
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001581 if (!Context.hasSameUnqualifiedType(ArgType,
1582 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001583 // We can't perform this conversion.
1584 Diag(Arg->getSourceRange().getBegin(),
1585 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001586 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001587 Diag(Param->getLocation(), diag::note_template_param_here);
1588 return true;
1589 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001590
Douglas Gregorad964b32009-02-17 01:05:43 +00001591 if (ParamType->isMemberPointerType()) {
1592 NamedDecl *Member = 0;
1593 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1594 return true;
1595
Douglas Gregor8f378a92009-06-11 18:10:32 +00001596 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1597 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001598 return false;
1599 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001600
Douglas Gregorad964b32009-02-17 01:05:43 +00001601 NamedDecl *Entity = 0;
1602 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1603 return true;
1604
Douglas Gregor8f378a92009-06-11 18:10:32 +00001605 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1606 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001607 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001608 }
1609
Chris Lattner320dff22009-02-20 21:37:53 +00001610 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001611 // -- for a non-type template-parameter of type pointer to
1612 // object, qualification conversions (4.4) and the
1613 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001614 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001615 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001616 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001617
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001618 if (ArgType->isNullPtrType()) {
1619 ArgType = ParamType;
1620 ImpCastExprToType(Arg, ParamType);
1621 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001622 ArgType = Context.getArrayDecayedType(ArgType);
1623 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001624 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001625
Douglas Gregor3f411962009-02-11 01:18:59 +00001626 if (IsQualificationConversion(ArgType, ParamType)) {
1627 ArgType = ParamType;
1628 ImpCastExprToType(Arg, ParamType);
1629 }
1630
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001631 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001632 // We can't perform this conversion.
1633 Diag(Arg->getSourceRange().getBegin(),
1634 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001635 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001636 Diag(Param->getLocation(), diag::note_template_param_here);
1637 return true;
1638 }
1639
Douglas Gregorad964b32009-02-17 01:05:43 +00001640 NamedDecl *Entity = 0;
1641 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1642 return true;
1643
Douglas Gregor8f378a92009-06-11 18:10:32 +00001644 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1645 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001646 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001647 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001648
1649 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1650 // -- For a non-type template-parameter of type reference to
1651 // object, no conversions apply. The type referred to by the
1652 // reference may be more cv-qualified than the (otherwise
1653 // identical) type of the template-argument. The
1654 // template-parameter is bound directly to the
1655 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001656 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001657 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001658
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001659 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001660 Diag(Arg->getSourceRange().getBegin(),
1661 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001662 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001663 << Arg->getSourceRange();
1664 Diag(Param->getLocation(), diag::note_template_param_here);
1665 return true;
1666 }
1667
1668 unsigned ParamQuals
1669 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1670 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1671
1672 if ((ParamQuals | ArgQuals) != ParamQuals) {
1673 Diag(Arg->getSourceRange().getBegin(),
1674 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001675 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001676 << Arg->getSourceRange();
1677 Diag(Param->getLocation(), diag::note_template_param_here);
1678 return true;
1679 }
1680
Douglas Gregorad964b32009-02-17 01:05:43 +00001681 NamedDecl *Entity = 0;
1682 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1683 return true;
1684
Douglas Gregor8f378a92009-06-11 18:10:32 +00001685 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1686 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001687 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001688 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001689
1690 // -- For a non-type template-parameter of type pointer to data
1691 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001692 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001693 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1694
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001695 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001696 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001697 } else if (ArgType->isNullPtrType()) {
1698 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001699 } else if (IsQualificationConversion(ArgType, ParamType)) {
1700 ImpCastExprToType(Arg, ParamType);
1701 } else {
1702 // We can't perform this conversion.
1703 Diag(Arg->getSourceRange().getBegin(),
1704 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001705 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001706 Diag(Param->getLocation(), diag::note_template_param_here);
1707 return true;
1708 }
1709
Douglas Gregorad964b32009-02-17 01:05:43 +00001710 NamedDecl *Member = 0;
1711 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1712 return true;
1713
Douglas Gregor8f378a92009-06-11 18:10:32 +00001714 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1715 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001716 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001717}
1718
1719/// \brief Check a template argument against its corresponding
1720/// template template parameter.
1721///
1722/// This routine implements the semantics of C++ [temp.arg.template].
1723/// It returns true if an error occurred, and false otherwise.
1724bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1725 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001726 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1727 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1728
1729 // C++ [temp.arg.template]p1:
1730 // A template-argument for a template template-parameter shall be
1731 // the name of a class template, expressed as id-expression. Only
1732 // primary class templates are considered when matching the
1733 // template template argument with the corresponding parameter;
1734 // partial specializations are not considered even if their
1735 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001736 //
1737 // Note that we also allow template template parameters here, which
1738 // will happen when we are dealing with, e.g., class template
1739 // partial specializations.
1740 if (!isa<ClassTemplateDecl>(Template) &&
1741 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001742 assert(isa<FunctionTemplateDecl>(Template) &&
1743 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001744 Diag(Arg->getSourceRange().getBegin(),
1745 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001746 << Template;
1747 }
1748
1749 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1750 Param->getTemplateParameters(),
1751 true, true,
1752 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001753}
1754
Douglas Gregord406b032009-02-06 22:42:48 +00001755/// \brief Determine whether the given template parameter lists are
1756/// equivalent.
1757///
1758/// \param New The new template parameter list, typically written in the
1759/// source code as part of a new template declaration.
1760///
1761/// \param Old The old template parameter list, typically found via
1762/// name lookup of the template declared with this template parameter
1763/// list.
1764///
1765/// \param Complain If true, this routine will produce a diagnostic if
1766/// the template parameter lists are not equivalent.
1767///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001768/// \param IsTemplateTemplateParm If true, this routine is being
1769/// called to compare the template parameter lists of a template
1770/// template parameter.
1771///
1772/// \param TemplateArgLoc If this source location is valid, then we
1773/// are actually checking the template parameter list of a template
1774/// argument (New) against the template parameter list of its
1775/// corresponding template template parameter (Old). We produce
1776/// slightly different diagnostics in this scenario.
1777///
Douglas Gregord406b032009-02-06 22:42:48 +00001778/// \returns True if the template parameter lists are equal, false
1779/// otherwise.
1780bool
1781Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1782 TemplateParameterList *Old,
1783 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001784 bool IsTemplateTemplateParm,
1785 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001786 if (Old->size() != New->size()) {
1787 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001788 unsigned NextDiag = diag::err_template_param_list_different_arity;
1789 if (TemplateArgLoc.isValid()) {
1790 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1791 NextDiag = diag::note_template_param_list_different_arity;
1792 }
1793 Diag(New->getTemplateLoc(), NextDiag)
1794 << (New->size() > Old->size())
1795 << IsTemplateTemplateParm
1796 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001797 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1798 << IsTemplateTemplateParm
1799 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1800 }
1801
1802 return false;
1803 }
1804
1805 for (TemplateParameterList::iterator OldParm = Old->begin(),
1806 OldParmEnd = Old->end(), NewParm = New->begin();
1807 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1808 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001809 unsigned NextDiag = diag::err_template_param_different_kind;
1810 if (TemplateArgLoc.isValid()) {
1811 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1812 NextDiag = diag::note_template_param_different_kind;
1813 }
1814 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001815 << IsTemplateTemplateParm;
1816 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1817 << IsTemplateTemplateParm;
1818 return false;
1819 }
1820
1821 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1822 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001823 // know we're at the same index).
1824#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001825 // FIXME: Enable this code in debug mode *after* we properly go through
1826 // and "instantiate" the template parameter lists of template template
1827 // parameters. It's only after this instantiation that (1) any dependent
1828 // types within the template parameter list of the template template
1829 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001830 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001831 QualType OldParmType
1832 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1833 QualType NewParmType
1834 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1835 assert(Context.getCanonicalType(OldParmType) ==
1836 Context.getCanonicalType(NewParmType) &&
1837 "type parameter mismatch?");
1838#endif
1839 } else if (NonTypeTemplateParmDecl *OldNTTP
1840 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1841 // The types of non-type template parameters must agree.
1842 NonTypeTemplateParmDecl *NewNTTP
1843 = cast<NonTypeTemplateParmDecl>(*NewParm);
1844 if (Context.getCanonicalType(OldNTTP->getType()) !=
1845 Context.getCanonicalType(NewNTTP->getType())) {
1846 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001847 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1848 if (TemplateArgLoc.isValid()) {
1849 Diag(TemplateArgLoc,
1850 diag::err_template_arg_template_params_mismatch);
1851 NextDiag = diag::note_template_nontype_parm_different_type;
1852 }
1853 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001854 << NewNTTP->getType()
1855 << IsTemplateTemplateParm;
1856 Diag(OldNTTP->getLocation(),
1857 diag::note_template_nontype_parm_prev_declaration)
1858 << OldNTTP->getType();
1859 }
1860 return false;
1861 }
1862 } else {
1863 // The template parameter lists of template template
1864 // parameters must agree.
1865 // FIXME: Could we perform a faster "type" comparison here?
1866 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1867 "Only template template parameters handled here");
1868 TemplateTemplateParmDecl *OldTTP
1869 = cast<TemplateTemplateParmDecl>(*OldParm);
1870 TemplateTemplateParmDecl *NewTTP
1871 = cast<TemplateTemplateParmDecl>(*NewParm);
1872 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1873 OldTTP->getTemplateParameters(),
1874 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001875 /*IsTemplateTemplateParm=*/true,
1876 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001877 return false;
1878 }
1879 }
1880
1881 return true;
1882}
1883
1884/// \brief Check whether a template can be declared within this scope.
1885///
1886/// If the template declaration is valid in this scope, returns
1887/// false. Otherwise, issues a diagnostic and returns true.
1888bool
1889Sema::CheckTemplateDeclScope(Scope *S,
1890 MultiTemplateParamsArg &TemplateParameterLists) {
1891 assert(TemplateParameterLists.size() > 0 && "Not a template");
1892
1893 // Find the nearest enclosing declaration scope.
1894 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1895 (S->getFlags() & Scope::TemplateParamScope) != 0)
1896 S = S->getParent();
1897
1898 TemplateParameterList *TemplateParams =
1899 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1900 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1901 SourceRange TemplateRange
1902 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1903
1904 // C++ [temp]p2:
1905 // A template-declaration can appear only as a namespace scope or
1906 // class scope declaration.
1907 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1908 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1909 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1910 return Diag(TemplateLoc, diag::err_template_linkage)
1911 << TemplateRange;
1912
1913 Ctx = Ctx->getParent();
1914 }
1915
1916 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1917 return false;
1918
1919 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1920 << TemplateRange;
1921}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001922
Douglas Gregor90177912009-05-13 18:28:20 +00001923/// \brief Check whether a class template specialization or explicit
1924/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001925///
Douglas Gregor90177912009-05-13 18:28:20 +00001926/// This routine determines whether a class template specialization or
1927/// explicit instantiation can be declared in the current context
1928/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1929/// appropriate diagnostics if there was an error. It returns true if
1930// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001931bool
1932Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1933 ClassTemplateSpecializationDecl *PrevDecl,
1934 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001935 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001936 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001937 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001938 // C++ [temp.expl.spec]p2:
1939 // An explicit specialization shall be declared in the namespace
1940 // of which the template is a member, or, for member templates, in
1941 // the namespace of which the enclosing class or enclosing class
1942 // template is a member. An explicit specialization of a member
1943 // function, member class or static data member of a class
1944 // template shall be declared in the namespace of which the class
1945 // template is a member. Such a declaration may also be a
1946 // definition. If the declaration is not a definition, the
1947 // specialization may be defined later in the name- space in which
1948 // the explicit specialization was declared, or in a namespace
1949 // that encloses the one in which the explicit specialization was
1950 // declared.
1951 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00001952 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001953 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001954 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001955 return true;
1956 }
1957
1958 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1959 DeclContext *TemplateContext
1960 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001961 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1962 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001963 // There is no prior declaration of this entity, so this
1964 // specialization must be in the same context as the template
1965 // itself.
1966 if (DC != TemplateContext) {
1967 if (isa<TranslationUnitDecl>(TemplateContext))
1968 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001969 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00001970 << ClassTemplate << ScopeSpecifierRange;
1971 else if (isa<NamespaceDecl>(TemplateContext))
1972 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001973 << PartialSpecialization << ClassTemplate
1974 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001975
1976 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1977 }
1978
1979 return false;
1980 }
1981
1982 // We have a previous declaration of this entity. Make sure that
1983 // this redeclaration (or definition) occurs in an enclosing namespace.
1984 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001985 // FIXME: In C++98, we would like to turn these errors into warnings,
1986 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00001987 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00001988 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00001989 if (isa<TranslationUnitDecl>(TemplateContext)) {
1990 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1991 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001992 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00001993 else
1994 SuppressedDiag = true;
1995 } else if (isa<NamespaceDecl>(TemplateContext)) {
1996 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1997 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001998 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00001999 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2000 else
2001 SuppressedDiag = true;
2002 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002003
Douglas Gregor90177912009-05-13 18:28:20 +00002004 if (!SuppressedDiag)
2005 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002006 }
2007
2008 return false;
2009}
2010
Douglas Gregor76e79952009-06-12 21:21:02 +00002011/// \brief Check the non-type template arguments of a class template
2012/// partial specialization according to C++ [temp.class.spec]p9.
2013///
Douglas Gregor42476442009-06-12 22:08:06 +00002014/// \param TemplateParams the template parameters of the primary class
2015/// template.
2016///
2017/// \param TemplateArg the template arguments of the class template
2018/// partial specialization.
2019///
2020/// \param MirrorsPrimaryTemplate will be set true if the class
2021/// template partial specialization arguments are identical to the
2022/// implicit template arguments of the primary template. This is not
2023/// necessarily an error (C++0x), and it is left to the caller to diagnose
2024/// this condition when it is an error.
2025///
Douglas Gregor76e79952009-06-12 21:21:02 +00002026/// \returns true if there was an error, false otherwise.
2027bool Sema::CheckClassTemplatePartialSpecializationArgs(
2028 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002029 const TemplateArgument *TemplateArgs,
2030 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002031 // FIXME: the interface to this function will have to change to
2032 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002033 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002034 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002035 // Determine whether the template argument list of the partial
2036 // specialization is identical to the implicit argument list of
2037 // the primary template. The caller may need to diagnostic this as
2038 // an error per C++ [temp.class.spec]p9b3.
2039 if (MirrorsPrimaryTemplate) {
2040 if (TemplateTypeParmDecl *TTP
2041 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2042 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2043 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2044 MirrorsPrimaryTemplate = false;
2045 } else if (TemplateTemplateParmDecl *TTP
2046 = dyn_cast<TemplateTemplateParmDecl>(
2047 TemplateParams->getParam(I))) {
2048 // FIXME: We should settle on either Declaration storage or
2049 // Expression storage for template template parameters.
2050 TemplateTemplateParmDecl *ArgDecl
2051 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2052 TemplateArgs[I].getAsDecl());
2053 if (!ArgDecl)
2054 if (DeclRefExpr *DRE
2055 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2056 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2057
2058 if (!ArgDecl ||
2059 ArgDecl->getIndex() != TTP->getIndex() ||
2060 ArgDecl->getDepth() != TTP->getDepth())
2061 MirrorsPrimaryTemplate = false;
2062 }
2063 }
2064
Douglas Gregor76e79952009-06-12 21:21:02 +00002065 NonTypeTemplateParmDecl *Param
2066 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002067 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002068 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002069 }
2070
Douglas Gregor76e79952009-06-12 21:21:02 +00002071 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002072 if (!ArgExpr) {
2073 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002074 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002075 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002076
2077 // C++ [temp.class.spec]p8:
2078 // A non-type argument is non-specialized if it is the name of a
2079 // non-type parameter. All other non-type arguments are
2080 // specialized.
2081 //
2082 // Below, we check the two conditions that only apply to
2083 // specialized non-type arguments, so skip any non-specialized
2084 // arguments.
2085 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002086 if (NonTypeTemplateParmDecl *NTTP
2087 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2088 if (MirrorsPrimaryTemplate &&
2089 (Param->getIndex() != NTTP->getIndex() ||
2090 Param->getDepth() != NTTP->getDepth()))
2091 MirrorsPrimaryTemplate = false;
2092
Douglas Gregor76e79952009-06-12 21:21:02 +00002093 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002094 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002095
2096 // C++ [temp.class.spec]p9:
2097 // Within the argument list of a class template partial
2098 // specialization, the following restrictions apply:
2099 // -- A partially specialized non-type argument expression
2100 // shall not involve a template parameter of the partial
2101 // specialization except when the argument expression is a
2102 // simple identifier.
2103 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2104 Diag(ArgExpr->getLocStart(),
2105 diag::err_dependent_non_type_arg_in_partial_spec)
2106 << ArgExpr->getSourceRange();
2107 return true;
2108 }
2109
2110 // -- The type of a template parameter corresponding to a
2111 // specialized non-type argument shall not be dependent on a
2112 // parameter of the specialization.
2113 if (Param->getType()->isDependentType()) {
2114 Diag(ArgExpr->getLocStart(),
2115 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2116 << Param->getType()
2117 << ArgExpr->getSourceRange();
2118 Diag(Param->getLocation(), diag::note_template_param_here);
2119 return true;
2120 }
Douglas Gregor42476442009-06-12 22:08:06 +00002121
2122 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002123 }
2124
2125 return false;
2126}
2127
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002128Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002129Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2130 SourceLocation KWLoc,
2131 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002132 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002133 SourceLocation TemplateNameLoc,
2134 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002135 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002136 SourceLocation *TemplateArgLocs,
2137 SourceLocation RAngleLoc,
2138 AttributeList *Attr,
2139 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002140 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002141 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002142 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002143 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002144
Douglas Gregor58944ac2009-05-31 09:31:02 +00002145 bool isPartialSpecialization = false;
2146
Douglas Gregor0d93f692009-02-25 22:02:03 +00002147 // Check the validity of the template headers that introduce this
2148 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002149 // FIXME: Once we have member templates, we'll need to check
2150 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2151 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002152 if (TemplateParameterLists.size() == 0)
2153 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002154 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002155 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002156 TemplateParameterList *TemplateParams
2157 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002158 if (TemplateParameterLists.size() > 1) {
2159 Diag(TemplateParams->getTemplateLoc(),
2160 diag::err_template_spec_extra_headers);
2161 return true;
2162 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002163
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002164 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002165 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002166
2167 // C++ [temp.class.spec]p10:
2168 // The template parameter list of a specialization shall not
2169 // contain default template argument values.
2170 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2171 Decl *Param = TemplateParams->getParam(I);
2172 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2173 if (TTP->hasDefaultArgument()) {
2174 Diag(TTP->getDefaultArgumentLoc(),
2175 diag::err_default_arg_in_partial_spec);
2176 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2177 }
2178 } else if (NonTypeTemplateParmDecl *NTTP
2179 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2180 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2181 Diag(NTTP->getDefaultArgumentLoc(),
2182 diag::err_default_arg_in_partial_spec)
2183 << DefArg->getSourceRange();
2184 NTTP->setDefaultArgument(0);
2185 DefArg->Destroy(Context);
2186 }
2187 } else {
2188 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2189 if (Expr *DefArg = TTP->getDefaultArgument()) {
2190 Diag(TTP->getDefaultArgumentLoc(),
2191 diag::err_default_arg_in_partial_spec)
2192 << DefArg->getSourceRange();
2193 TTP->setDefaultArgument(0);
2194 DefArg->Destroy(Context);
2195 }
2196 }
2197 }
2198 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002199 }
2200
Douglas Gregora08b6c72009-02-17 23:15:12 +00002201 // Check that the specialization uses the same tag kind as the
2202 // original template.
2203 TagDecl::TagKind Kind;
2204 switch (TagSpec) {
2205 default: assert(0 && "Unknown tag type!");
2206 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2207 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2208 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2209 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002210 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2211 Kind, KWLoc,
2212 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002213 Diag(KWLoc, diag::err_use_with_wrong_tag)
2214 << ClassTemplate
2215 << CodeModificationHint::CreateReplacement(KWLoc,
2216 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002217 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2218 diag::note_previous_use);
2219 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2220 }
2221
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002222 // Translate the parser's template argument list in our AST format.
2223 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2224 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2225
Douglas Gregora08b6c72009-02-17 23:15:12 +00002226 // Check that the template argument list is well-formed for this
2227 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002228 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002229 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002230 &TemplateArgs[0], TemplateArgs.size(),
2231 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002232 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002233
2234 assert((ConvertedTemplateArgs.size() ==
2235 ClassTemplate->getTemplateParameters()->size()) &&
2236 "Converted template argument list is too short!");
2237
Douglas Gregor58944ac2009-05-31 09:31:02 +00002238 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002239 // corresponds to these arguments.
2240 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002241 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002242 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002243 if (CheckClassTemplatePartialSpecializationArgs(
2244 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002245 ConvertedTemplateArgs.getFlatArgumentList(),
2246 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002247 return true;
2248
Douglas Gregor42476442009-06-12 22:08:06 +00002249 if (MirrorsPrimaryTemplate) {
2250 // C++ [temp.class.spec]p9b3:
2251 //
2252 // -- The argument list of the specialization shall not be identical
2253 // to the implicit argument list of the primary template.
2254 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2255 << (TK == TK_Definition)
2256 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2257 RAngleLoc));
2258 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2259 ClassTemplate->getIdentifier(),
2260 TemplateNameLoc,
2261 Attr,
2262 move(TemplateParameterLists),
2263 AS_none);
2264 }
2265
Douglas Gregor58944ac2009-05-31 09:31:02 +00002266 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002267 ClassTemplatePartialSpecializationDecl::Profile(ID,
2268 ConvertedTemplateArgs.getFlatArgumentList(),
2269 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002270 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002271 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002272 ClassTemplateSpecializationDecl::Profile(ID,
2273 ConvertedTemplateArgs.getFlatArgumentList(),
2274 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002275 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002276 ClassTemplateSpecializationDecl *PrevDecl = 0;
2277
2278 if (isPartialSpecialization)
2279 PrevDecl
2280 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2281 InsertPos);
2282 else
2283 PrevDecl
2284 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002285
2286 ClassTemplateSpecializationDecl *Specialization = 0;
2287
Douglas Gregor0d93f692009-02-25 22:02:03 +00002288 // Check whether we can declare a class template specialization in
2289 // the current scope.
2290 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2291 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002292 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002293 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002294 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002295 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002296
Douglas Gregora08b6c72009-02-17 23:15:12 +00002297 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2298 // Since the only prior class template specialization with these
2299 // arguments was referenced but not declared, reuse that
2300 // declaration node as our own, updating its source location to
2301 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002302 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002303 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002304 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002305 } else if (isPartialSpecialization) {
2306 // FIXME: extra checking for partial specializations
2307
2308 // Create a new class template partial specialization declaration node.
2309 TemplateParameterList *TemplateParams
2310 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2311 ClassTemplatePartialSpecializationDecl *PrevPartial
2312 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2313 ClassTemplatePartialSpecializationDecl *Partial
2314 = ClassTemplatePartialSpecializationDecl::Create(Context,
2315 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002316 TemplateNameLoc,
2317 TemplateParams,
2318 ClassTemplate,
2319 ConvertedTemplateArgs,
2320 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002321
2322 if (PrevPartial) {
2323 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2324 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2325 } else {
2326 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2327 }
2328 Specialization = Partial;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002329 } else {
2330 // Create a new class template specialization declaration node for
2331 // this explicit specialization.
2332 Specialization
2333 = ClassTemplateSpecializationDecl::Create(Context,
2334 ClassTemplate->getDeclContext(),
2335 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002336 ClassTemplate,
2337 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002338 PrevDecl);
2339
2340 if (PrevDecl) {
2341 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2342 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2343 } else {
2344 ClassTemplate->getSpecializations().InsertNode(Specialization,
2345 InsertPos);
2346 }
2347 }
2348
2349 // Note that this is an explicit specialization.
2350 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2351
2352 // Check that this isn't a redefinition of this specialization.
2353 if (TK == TK_Definition) {
2354 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002355 // FIXME: Should also handle explicit specialization after implicit
2356 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002357 SourceRange Range(TemplateNameLoc, RAngleLoc);
2358 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002359 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002360 Diag(Def->getLocation(), diag::note_previous_definition);
2361 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002362 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002363 }
2364 }
2365
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002366 // Build the fully-sugared type for this class template
2367 // specialization as the user wrote in the specialization
2368 // itself. This means that we'll pretty-print the type retrieved
2369 // from the specialization's declaration the way that the user
2370 // actually wrote the specialization, rather than formatting the
2371 // name based on the "canonical" representation used to store the
2372 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002373 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002374 = Context.getTemplateSpecializationType(Name,
2375 &TemplateArgs[0],
2376 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002377 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002378 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002379 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002380
Douglas Gregor50113ca2009-02-25 22:18:32 +00002381 // C++ [temp.expl.spec]p9:
2382 // A template explicit specialization is in the scope of the
2383 // namespace in which the template was defined.
2384 //
2385 // We actually implement this paragraph where we set the semantic
2386 // context (in the creation of the ClassTemplateSpecializationDecl),
2387 // but we also maintain the lexical context where the actual
2388 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002389 Specialization->setLexicalDeclContext(CurContext);
2390
2391 // We may be starting the definition of this specialization.
2392 if (TK == TK_Definition)
2393 Specialization->startDefinition();
2394
2395 // Add the specialization into its lexical context, so that it can
2396 // be seen when iterating through the list of declarations in that
2397 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002398 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002399 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002400}
Douglas Gregord3022602009-03-27 23:10:48 +00002401
Douglas Gregor96b6df92009-05-14 00:28:11 +00002402// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002403Sema::DeclResult
2404Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2405 unsigned TagSpec,
2406 SourceLocation KWLoc,
2407 const CXXScopeSpec &SS,
2408 TemplateTy TemplateD,
2409 SourceLocation TemplateNameLoc,
2410 SourceLocation LAngleLoc,
2411 ASTTemplateArgsPtr TemplateArgsIn,
2412 SourceLocation *TemplateArgLocs,
2413 SourceLocation RAngleLoc,
2414 AttributeList *Attr) {
2415 // Find the class template we're specializing
2416 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2417 ClassTemplateDecl *ClassTemplate
2418 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2419
2420 // Check that the specialization uses the same tag kind as the
2421 // original template.
2422 TagDecl::TagKind Kind;
2423 switch (TagSpec) {
2424 default: assert(0 && "Unknown tag type!");
2425 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2426 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2427 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2428 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002429 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2430 Kind, KWLoc,
2431 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002432 Diag(KWLoc, diag::err_use_with_wrong_tag)
2433 << ClassTemplate
2434 << CodeModificationHint::CreateReplacement(KWLoc,
2435 ClassTemplate->getTemplatedDecl()->getKindName());
2436 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2437 diag::note_previous_use);
2438 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2439 }
2440
Douglas Gregor90177912009-05-13 18:28:20 +00002441 // C++0x [temp.explicit]p2:
2442 // [...] An explicit instantiation shall appear in an enclosing
2443 // namespace of its template. [...]
2444 //
2445 // This is C++ DR 275.
2446 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2447 TemplateNameLoc,
2448 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002449 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002450 /*ExplicitInstantiation=*/true))
2451 return true;
2452
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002453 // Translate the parser's template argument list in our AST format.
2454 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2455 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2456
2457 // Check that the template argument list is well-formed for this
2458 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002459 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002460 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002461 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002462 RAngleLoc, ConvertedTemplateArgs))
2463 return true;
2464
2465 assert((ConvertedTemplateArgs.size() ==
2466 ClassTemplate->getTemplateParameters()->size()) &&
2467 "Converted template argument list is too short!");
2468
2469 // Find the class template specialization declaration that
2470 // corresponds to these arguments.
2471 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002472 ClassTemplateSpecializationDecl::Profile(ID,
2473 ConvertedTemplateArgs.getFlatArgumentList(),
2474 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002475 void *InsertPos = 0;
2476 ClassTemplateSpecializationDecl *PrevDecl
2477 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2478
2479 ClassTemplateSpecializationDecl *Specialization = 0;
2480
Douglas Gregor90177912009-05-13 18:28:20 +00002481 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002482 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002483 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002484 // This particular specialization has already been declared or
2485 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002486 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2487 << Context.getTypeDeclType(PrevDecl);
2488 Diag(PrevDecl->getLocation(),
2489 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002490 return DeclPtrTy::make(PrevDecl);
2491 }
2492
Douglas Gregor90177912009-05-13 18:28:20 +00002493 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002494 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002495 // For a given set of template parameters, if an explicit
2496 // instantiation of a template appears after a declaration of
2497 // an explicit specialization for that template, the explicit
2498 // instantiation has no effect.
2499 if (!getLangOptions().CPlusPlus0x) {
2500 Diag(TemplateNameLoc,
2501 diag::ext_explicit_instantiation_after_specialization)
2502 << Context.getTypeDeclType(PrevDecl);
2503 Diag(PrevDecl->getLocation(),
2504 diag::note_previous_template_specialization);
2505 }
2506
2507 // Create a new class template specialization declaration node
2508 // for this explicit specialization. This node is only used to
2509 // record the existence of this explicit instantiation for
2510 // accurate reproduction of the source code; we don't actually
2511 // use it for anything, since it is semantically irrelevant.
2512 Specialization
2513 = ClassTemplateSpecializationDecl::Create(Context,
2514 ClassTemplate->getDeclContext(),
2515 TemplateNameLoc,
2516 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002517 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002518 Specialization->setLexicalDeclContext(CurContext);
2519 CurContext->addDecl(Context, Specialization);
2520 return DeclPtrTy::make(Specialization);
2521 }
2522
2523 // If we have already (implicitly) instantiated this
2524 // specialization, there is less work to do.
2525 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2526 SpecializationRequiresInstantiation = false;
2527
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002528 // Since the only prior class template specialization with these
2529 // arguments was referenced but not declared, reuse that
2530 // declaration node as our own, updating its source location to
2531 // reflect our new declaration.
2532 Specialization = PrevDecl;
2533 Specialization->setLocation(TemplateNameLoc);
2534 PrevDecl = 0;
2535 } else {
2536 // Create a new class template specialization declaration node for
2537 // this explicit specialization.
2538 Specialization
2539 = ClassTemplateSpecializationDecl::Create(Context,
2540 ClassTemplate->getDeclContext(),
2541 TemplateNameLoc,
2542 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002543 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002544
2545 ClassTemplate->getSpecializations().InsertNode(Specialization,
2546 InsertPos);
2547 }
2548
2549 // Build the fully-sugared type for this explicit instantiation as
2550 // the user wrote in the explicit instantiation itself. This means
2551 // that we'll pretty-print the type retrieved from the
2552 // specialization's declaration the way that the user actually wrote
2553 // the explicit instantiation, rather than formatting the name based
2554 // on the "canonical" representation used to store the template
2555 // arguments in the specialization.
2556 QualType WrittenTy
2557 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002558 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002559 TemplateArgs.size(),
2560 Context.getTypeDeclType(Specialization));
2561 Specialization->setTypeAsWritten(WrittenTy);
2562 TemplateArgsIn.release();
2563
2564 // Add the explicit instantiation into its lexical context. However,
2565 // since explicit instantiations are never found by name lookup, we
2566 // just put it into the declaration context directly.
2567 Specialization->setLexicalDeclContext(CurContext);
2568 CurContext->addDecl(Context, Specialization);
2569
2570 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002571 // A definition of a class template or class member template
2572 // shall be in scope at the point of the explicit instantiation of
2573 // the class template or class member template.
2574 //
2575 // This check comes when we actually try to perform the
2576 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002577 if (SpecializationRequiresInstantiation)
2578 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002579 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002580 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002581
2582 return DeclPtrTy::make(Specialization);
2583}
2584
Douglas Gregor96b6df92009-05-14 00:28:11 +00002585// Explicit instantiation of a member class of a class template.
2586Sema::DeclResult
2587Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2588 unsigned TagSpec,
2589 SourceLocation KWLoc,
2590 const CXXScopeSpec &SS,
2591 IdentifierInfo *Name,
2592 SourceLocation NameLoc,
2593 AttributeList *Attr) {
2594
Douglas Gregor71f06032009-05-28 23:31:59 +00002595 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002596 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002597 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002598 if (!TagD)
2599 return true;
2600
2601 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2602 if (Tag->isEnum()) {
2603 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2604 << Context.getTypeDeclType(Tag);
2605 return true;
2606 }
2607
Douglas Gregord769bfa2009-05-27 17:30:49 +00002608 if (Tag->isInvalidDecl())
2609 return true;
2610
Douglas Gregor96b6df92009-05-14 00:28:11 +00002611 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2612 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2613 if (!Pattern) {
2614 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2615 << Context.getTypeDeclType(Record);
2616 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2617 return true;
2618 }
2619
2620 // C++0x [temp.explicit]p2:
2621 // [...] An explicit instantiation shall appear in an enclosing
2622 // namespace of its template. [...]
2623 //
2624 // This is C++ DR 275.
2625 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002626 // FIXME: In C++98, we would like to turn these errors into warnings,
2627 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002628 DeclContext *PatternContext
2629 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2630 if (!CurContext->Encloses(PatternContext)) {
2631 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2632 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2633 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2634 }
2635 }
2636
Douglas Gregor96b6df92009-05-14 00:28:11 +00002637 if (!Record->getDefinition(Context)) {
2638 // If the class has a definition, instantiate it (and all of its
2639 // members, recursively).
2640 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2641 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002642 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002643 /*ExplicitInstantiation=*/true))
2644 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002645 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002646 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002647 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002648
Mike Stumpe127ae32009-05-16 07:39:55 +00002649 // FIXME: We don't have any representation for explicit instantiations of
2650 // member classes. Such a representation is not needed for compilation, but it
2651 // should be available for clients that want to see all of the declarations in
2652 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002653 return TagD;
2654}
2655
Douglas Gregord3022602009-03-27 23:10:48 +00002656Sema::TypeResult
2657Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2658 const IdentifierInfo &II, SourceLocation IdLoc) {
2659 NestedNameSpecifier *NNS
2660 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2661 if (!NNS)
2662 return true;
2663
2664 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002665 if (T.isNull())
2666 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002667 return T.getAsOpaquePtr();
2668}
2669
Douglas Gregor77da5802009-04-01 00:28:59 +00002670Sema::TypeResult
2671Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2672 SourceLocation TemplateLoc, TypeTy *Ty) {
2673 QualType T = QualType::getFromOpaquePtr(Ty);
2674 NestedNameSpecifier *NNS
2675 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2676 const TemplateSpecializationType *TemplateId
2677 = T->getAsTemplateSpecializationType();
2678 assert(TemplateId && "Expected a template specialization type");
2679
2680 if (NNS->isDependent())
2681 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2682
2683 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2684}
2685
Douglas Gregord3022602009-03-27 23:10:48 +00002686/// \brief Build the type that describes a C++ typename specifier,
2687/// e.g., "typename T::type".
2688QualType
2689Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2690 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002691 CXXRecordDecl *CurrentInstantiation = 0;
2692 if (NNS->isDependent()) {
2693 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002694
Douglas Gregor3eb20702009-05-11 19:58:34 +00002695 // If the nested-name-specifier does not refer to the current
2696 // instantiation, then build a typename type.
2697 if (!CurrentInstantiation)
2698 return Context.getTypenameType(NNS, &II);
2699 }
Douglas Gregord3022602009-03-27 23:10:48 +00002700
Douglas Gregor3eb20702009-05-11 19:58:34 +00002701 DeclContext *Ctx = 0;
2702
2703 if (CurrentInstantiation)
2704 Ctx = CurrentInstantiation;
2705 else {
2706 CXXScopeSpec SS;
2707 SS.setScopeRep(NNS);
2708 SS.setRange(Range);
2709 if (RequireCompleteDeclContext(SS))
2710 return QualType();
2711
2712 Ctx = computeDeclContext(SS);
2713 }
Douglas Gregord3022602009-03-27 23:10:48 +00002714 assert(Ctx && "No declaration context?");
2715
2716 DeclarationName Name(&II);
2717 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2718 false);
2719 unsigned DiagID = 0;
2720 Decl *Referenced = 0;
2721 switch (Result.getKind()) {
2722 case LookupResult::NotFound:
2723 if (Ctx->isTranslationUnit())
2724 DiagID = diag::err_typename_nested_not_found_global;
2725 else
2726 DiagID = diag::err_typename_nested_not_found;
2727 break;
2728
2729 case LookupResult::Found:
2730 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2731 // We found a type. Build a QualifiedNameType, since the
2732 // typename-specifier was just sugar. FIXME: Tell
2733 // QualifiedNameType that it has a "typename" prefix.
2734 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2735 }
2736
2737 DiagID = diag::err_typename_nested_not_type;
2738 Referenced = Result.getAsDecl();
2739 break;
2740
2741 case LookupResult::FoundOverloaded:
2742 DiagID = diag::err_typename_nested_not_type;
2743 Referenced = *Result.begin();
2744 break;
2745
2746 case LookupResult::AmbiguousBaseSubobjectTypes:
2747 case LookupResult::AmbiguousBaseSubobjects:
2748 case LookupResult::AmbiguousReference:
2749 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2750 return QualType();
2751 }
2752
2753 // If we get here, it's because name lookup did not find a
2754 // type. Emit an appropriate diagnostic and return an error.
2755 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2756 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2757 else
2758 Diag(Range.getEnd(), DiagID) << Range << Name;
2759 if (Referenced)
2760 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2761 << Name;
2762 return QualType();
2763}