blob: 981b8508c565e0274cd57bfbdb139f02c3e8cbee [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()) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor9614dad2009-06-24 00:23:40 +000070 // FIXME: What follows is a slightly less gross hack than what used to
71 // follow.
Douglas Gregor2fa10442008-12-18 19:37:40 +000072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor9614dad2009-06-24 00:23:40 +000073 if (FD->getDescribedFunctionTemplate()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000074 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000075 return TNK_Function_template;
76 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000077 } else if (OverloadedFunctionDecl *Ovl
78 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
79 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
80 FEnd = Ovl->function_end();
81 F != FEnd; ++F) {
Douglas Gregorb60eb752009-06-25 22:08:12 +000082 if (isa<FunctionTemplateDecl>(*F)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000083 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000084 return TNK_Function_template;
85 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000086 }
87 }
Douglas Gregordd13e842009-03-30 22:58:21 +000088
89 if (TNK != TNK_Non_template) {
90 if (SS && SS->isSet() && !SS->isInvalid()) {
91 NestedNameSpecifier *Qualifier
92 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
93 TemplateResult
94 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
95 false,
96 Template));
97 } else
98 TemplateResult = TemplateTy::make(TemplateName(Template));
99 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000100 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000101 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000102}
103
Douglas Gregordd861062008-12-05 18:15:24 +0000104/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
105/// that the template parameter 'PrevDecl' is being shadowed by a new
106/// declaration at location Loc. Returns true to indicate that this is
107/// an error, and false otherwise.
108bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000109 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000110
111 // Microsoft Visual C++ permits template parameters to be shadowed.
112 if (getLangOptions().Microsoft)
113 return false;
114
115 // C++ [temp.local]p4:
116 // A template-parameter shall not be redeclared within its
117 // scope (including nested scopes).
118 Diag(Loc, diag::err_template_param_shadow)
119 << cast<NamedDecl>(PrevDecl)->getDeclName();
120 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
121 return true;
122}
123
Douglas Gregored3a3982009-03-03 04:44:36 +0000124/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000125/// the parameter D to reference the templated declaration and return a pointer
126/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000127TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
128 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
129 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000130 return Temp;
131 }
132 return 0;
133}
134
Douglas Gregordd861062008-12-05 18:15:24 +0000135/// ActOnTypeParameter - Called when a C++ template type parameter
136/// (e.g., "typename T") has been parsed. Typename specifies whether
137/// the keyword "typename" was used to declare the type parameter
138/// (otherwise, "class" was used), and KeyLoc is the location of the
139/// "class" or "typename" keyword. ParamName is the name of the
140/// parameter (NULL indicates an unnamed template parameter) and
141/// ParamName is the location of the parameter name (if any).
142/// If the type parameter has a default argument, it will be added
143/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000144Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
145 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000146 SourceLocation KeyLoc,
147 IdentifierInfo *ParamName,
148 SourceLocation ParamNameLoc,
149 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000150 assert(S->isTemplateParamScope() &&
151 "Template type parameter not in template parameter scope!");
152 bool Invalid = false;
153
154 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000155 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000156 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000157 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
158 PrevDecl);
159 }
160
Douglas Gregord406b032009-02-06 22:42:48 +0000161 SourceLocation Loc = ParamNameLoc;
162 if (!ParamName)
163 Loc = KeyLoc;
164
Douglas Gregordd861062008-12-05 18:15:24 +0000165 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000166 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000167 Depth, Position, ParamName, Typename,
168 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000169 if (Invalid)
170 Param->setInvalidDecl();
171
172 if (ParamName) {
173 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000174 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000175 IdResolver.AddDecl(Param);
176 }
177
Chris Lattner5261d0c2009-03-28 19:18:32 +0000178 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000179}
180
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000181/// ActOnTypeParameterDefault - Adds a default argument (the type
182/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000183void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000184 SourceLocation EqualLoc,
185 SourceLocation DefaultLoc,
186 TypeTy *DefaultT) {
187 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000188 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000189 QualType Default = QualType::getFromOpaquePtr(DefaultT);
190
Anders Carlssona2333782009-06-12 22:30:13 +0000191 // C++0x [temp.param]p9:
192 // A default template-argument may be specified for any kind of
193 // template-parameter that is not a template parameter pack.
194 if (Parm->isParameterPack()) {
195 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000196 return;
197 }
198
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000199 // C++ [temp.param]p14:
200 // A template-parameter shall not be used in its own default argument.
201 // FIXME: Implement this check! Needs a recursive walk over the types.
202
203 // Check the template argument itself.
204 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
205 Parm->setInvalidDecl();
206 return;
207 }
208
209 Parm->setDefaultArgument(Default, DefaultLoc, false);
210}
211
Douglas Gregored3a3982009-03-03 04:44:36 +0000212/// \brief Check that the type of a non-type template parameter is
213/// well-formed.
214///
215/// \returns the (possibly-promoted) parameter type if valid;
216/// otherwise, produces a diagnostic and returns a NULL type.
217QualType
218Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
219 // C++ [temp.param]p4:
220 //
221 // A non-type template-parameter shall have one of the following
222 // (optionally cv-qualified) types:
223 //
224 // -- integral or enumeration type,
225 if (T->isIntegralType() || T->isEnumeralType() ||
226 // -- pointer to object or pointer to function,
227 (T->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000228 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
229 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregored3a3982009-03-03 04:44:36 +0000230 // -- reference to object or reference to function,
231 T->isReferenceType() ||
232 // -- pointer to member.
233 T->isMemberPointerType() ||
234 // If T is a dependent type, we can't do the check now, so we
235 // assume that it is well-formed.
236 T->isDependentType())
237 return T;
238 // C++ [temp.param]p8:
239 //
240 // A non-type template-parameter of type "array of T" or
241 // "function returning T" is adjusted to be of type "pointer to
242 // T" or "pointer to function returning T", respectively.
243 else if (T->isArrayType())
244 // FIXME: Keep the type prior to promotion?
245 return Context.getArrayDecayedType(T);
246 else if (T->isFunctionType())
247 // FIXME: Keep the type prior to promotion?
248 return Context.getPointerType(T);
249
250 Diag(Loc, diag::err_template_nontype_parm_bad_type)
251 << T;
252
253 return QualType();
254}
255
Douglas Gregordd861062008-12-05 18:15:24 +0000256/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
257/// template parameter (e.g., "int Size" in "template<int Size>
258/// class Array") has been parsed. S is the current scope and D is
259/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000260Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
261 unsigned Depth,
262 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000263 QualType T = GetTypeForDeclarator(D, S);
264
Douglas Gregor279272e2009-02-04 19:02:06 +0000265 assert(S->isTemplateParamScope() &&
266 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000267 bool Invalid = false;
268
269 IdentifierInfo *ParamName = D.getIdentifier();
270 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000271 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000272 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000273 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000274 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000275 }
276
Douglas Gregored3a3982009-03-03 04:44:36 +0000277 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000278 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000279 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000280 Invalid = true;
281 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000282
Douglas Gregordd861062008-12-05 18:15:24 +0000283 NonTypeTemplateParmDecl *Param
284 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000285 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000286 if (Invalid)
287 Param->setInvalidDecl();
288
289 if (D.getIdentifier()) {
290 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000291 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000292 IdResolver.AddDecl(Param);
293 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000294 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000295}
Douglas Gregor52473432008-12-24 02:52:09 +0000296
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000297/// \brief Adds a default argument to the given non-type template
298/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000299void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000300 SourceLocation EqualLoc,
301 ExprArg DefaultE) {
302 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000303 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000304 Expr *Default = static_cast<Expr *>(DefaultE.get());
305
306 // C++ [temp.param]p14:
307 // A template-parameter shall not be used in its own default argument.
308 // FIXME: Implement this check! Needs a recursive walk over the types.
309
310 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000311 TemplateArgument Converted;
312 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
313 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000314 TemplateParm->setInvalidDecl();
315 return;
316 }
317
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000318 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000319}
320
Douglas Gregor279272e2009-02-04 19:02:06 +0000321
322/// ActOnTemplateTemplateParameter - Called when a C++ template template
323/// parameter (e.g. T in template <template <typename> class T> class array)
324/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000325Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
326 SourceLocation TmpLoc,
327 TemplateParamsTy *Params,
328 IdentifierInfo *Name,
329 SourceLocation NameLoc,
330 unsigned Depth,
331 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000332{
333 assert(S->isTemplateParamScope() &&
334 "Template template parameter not in template parameter scope!");
335
336 // Construct the parameter object.
337 TemplateTemplateParmDecl *Param =
338 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
339 Position, Name,
340 (TemplateParameterList*)Params);
341
342 // Make sure the parameter is valid.
343 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
344 // do anything yet. However, if the template parameter list or (eventual)
345 // default value is ever invalidated, that will propagate here.
346 bool Invalid = false;
347 if (Invalid) {
348 Param->setInvalidDecl();
349 }
350
351 // If the tt-param has a name, then link the identifier into the scope
352 // and lookup mechanisms.
353 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000355 IdResolver.AddDecl(Param);
356 }
357
Chris Lattner5261d0c2009-03-28 19:18:32 +0000358 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000359}
360
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000361/// \brief Adds a default argument to the given template template
362/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000363void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000364 SourceLocation EqualLoc,
365 ExprArg DefaultE) {
366 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000367 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000368
369 // Since a template-template parameter's default argument is an
370 // id-expression, it must be a DeclRefExpr.
371 DeclRefExpr *Default
372 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
373
374 // C++ [temp.param]p14:
375 // A template-parameter shall not be used in its own default argument.
376 // FIXME: Implement this check! Needs a recursive walk over the types.
377
378 // Check the well-formedness of the template argument.
379 if (!isa<TemplateDecl>(Default->getDecl())) {
380 Diag(Default->getSourceRange().getBegin(),
381 diag::err_template_arg_must_be_template)
382 << Default->getSourceRange();
383 TemplateParm->setInvalidDecl();
384 return;
385 }
386 if (CheckTemplateArgument(TemplateParm, Default)) {
387 TemplateParm->setInvalidDecl();
388 return;
389 }
390
391 DefaultE.release();
392 TemplateParm->setDefaultArgument(Default);
393}
394
Douglas Gregor52473432008-12-24 02:52:09 +0000395/// ActOnTemplateParameterList - Builds a TemplateParameterList that
396/// contains the template parameters in Params/NumParams.
397Sema::TemplateParamsTy *
398Sema::ActOnTemplateParameterList(unsigned Depth,
399 SourceLocation ExportLoc,
400 SourceLocation TemplateLoc,
401 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000402 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000403 SourceLocation RAngleLoc) {
404 if (ExportLoc.isValid())
405 Diag(ExportLoc, diag::note_template_export_unsupported);
406
Douglas Gregord406b032009-02-06 22:42:48 +0000407 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
408 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000409}
Douglas Gregor279272e2009-02-04 19:02:06 +0000410
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000412Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
413 SourceLocation KWLoc, const CXXScopeSpec &SS,
414 IdentifierInfo *Name, SourceLocation NameLoc,
415 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000416 MultiTemplateParamsArg TemplateParameterLists,
417 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000418 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
419 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000420 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000421
422 // Check that we can declare a template here.
423 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000424 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000425
426 TagDecl::TagKind Kind;
427 switch (TagSpec) {
428 default: assert(0 && "Unknown tag type!");
429 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
430 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
431 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
432 }
433
434 // There is no such thing as an unnamed class template.
435 if (!Name) {
436 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000437 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000438 }
439
440 // Find any previous declaration with this name.
441 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
442 true);
443 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
444 NamedDecl *PrevDecl = 0;
445 if (Previous.begin() != Previous.end())
446 PrevDecl = *Previous.begin();
447
Douglas Gregor23521802009-06-17 23:37:01 +0000448 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
449 PrevDecl = 0;
450
Douglas Gregord406b032009-02-06 22:42:48 +0000451 DeclContext *SemanticContext = CurContext;
452 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000453 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000454
Mike Stumpe127ae32009-05-16 07:39:55 +0000455 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000456 }
457
458 // FIXME: member templates!
459 TemplateParameterList *TemplateParams
460 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
461
462 // If there is a previous declaration with the same name, check
463 // whether this is a valid redeclaration.
464 ClassTemplateDecl *PrevClassTemplate
465 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
466 if (PrevClassTemplate) {
467 // Ensure that the template parameter lists are compatible.
468 if (!TemplateParameterListsAreEqual(TemplateParams,
469 PrevClassTemplate->getTemplateParameters(),
470 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000471 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000472
473 // C++ [temp.class]p4:
474 // In a redeclaration, partial specialization, explicit
475 // specialization or explicit instantiation of a class template,
476 // the class-key shall agree in kind with the original class
477 // template declaration (7.1.5.3).
478 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000479 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000480 Diag(KWLoc, diag::err_use_with_wrong_tag)
481 << Name
482 << CodeModificationHint::CreateReplacement(KWLoc,
483 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000484 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000485 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000486 }
487
Douglas Gregord406b032009-02-06 22:42:48 +0000488 // Check for redefinition of this class template.
489 if (TK == TK_Definition) {
490 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
491 Diag(NameLoc, diag::err_redefinition) << Name;
492 Diag(Def->getLocation(), diag::note_previous_definition);
493 // FIXME: Would it make sense to try to "forget" the previous
494 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000495 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000496 }
497 }
498 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
499 // Maybe we will complain about the shadowed template parameter.
500 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
501 // Just pretend that we didn't see the previous declaration.
502 PrevDecl = 0;
503 } else if (PrevDecl) {
504 // C++ [temp]p5:
505 // A class template shall not have the same name as any other
506 // template, class, function, object, enumeration, enumerator,
507 // namespace, or type in the same scope (3.3), except as specified
508 // in (14.5.4).
509 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
510 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000511 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000512 }
513
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000514 // Check the template parameter list of this declaration, possibly
515 // merging in the template parameter list from the previous class
516 // template declaration.
517 if (CheckTemplateParameterList(TemplateParams,
518 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
519 Invalid = true;
520
Douglas Gregor9054f982009-05-10 22:57:19 +0000521 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000522 // declaration!
523
Douglas Gregor55216ac2009-03-26 00:10:35 +0000524 CXXRecordDecl *NewClass =
Douglas Gregor9060d0e2009-07-21 14:46:17 +0000525 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregord406b032009-02-06 22:42:48 +0000526 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000527 PrevClassTemplate->getTemplatedDecl() : 0,
528 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000529
530 ClassTemplateDecl *NewTemplate
531 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
532 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000533 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000534 NewClass->setDescribedClassTemplate(NewTemplate);
535
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000536 // Build the type for the class template declaration now.
537 QualType T =
538 Context.getTypeDeclType(NewClass,
539 PrevClassTemplate?
540 PrevClassTemplate->getTemplatedDecl() : 0);
541 assert(T->isDependentType() && "Class template type is not dependent?");
542 (void)T;
543
Anders Carlsson4ca43492009-03-26 01:24:28 +0000544 // Set the access specifier.
545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
546
Douglas Gregord406b032009-02-06 22:42:48 +0000547 // Set the lexical context of these templates
548 NewClass->setLexicalDeclContext(CurContext);
549 NewTemplate->setLexicalDeclContext(CurContext);
550
551 if (TK == TK_Definition)
552 NewClass->startDefinition();
553
554 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000555 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000556
557 PushOnScopeChains(NewTemplate, S);
558
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000559 if (Invalid) {
560 NewTemplate->setInvalidDecl();
561 NewClass->setInvalidDecl();
562 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000563 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000564}
565
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000566/// \brief Checks the validity of a template parameter list, possibly
567/// considering the template parameter list from a previous
568/// declaration.
569///
570/// If an "old" template parameter list is provided, it must be
571/// equivalent (per TemplateParameterListsAreEqual) to the "new"
572/// template parameter list.
573///
574/// \param NewParams Template parameter list for a new template
575/// declaration. This template parameter list will be updated with any
576/// default arguments that are carried through from the previous
577/// template parameter list.
578///
579/// \param OldParams If provided, template parameter list from a
580/// previous declaration of the same template. Default template
581/// arguments will be merged from the old template parameter list to
582/// the new template parameter list.
583///
584/// \returns true if an error occurred, false otherwise.
585bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
586 TemplateParameterList *OldParams) {
587 bool Invalid = false;
588
589 // C++ [temp.param]p10:
590 // The set of default template-arguments available for use with a
591 // template declaration or definition is obtained by merging the
592 // default arguments from the definition (if in scope) and all
593 // declarations in scope in the same way default function
594 // arguments are (8.3.6).
595 bool SawDefaultArgument = false;
596 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000597
Anders Carlssonb1929502009-06-12 23:20:15 +0000598 bool SawParameterPack = false;
599 SourceLocation ParameterPackLoc;
600
Mike Stumpe0b7e032009-02-11 23:03:27 +0000601 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000602 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000603 if (OldParams)
604 OldParam = OldParams->begin();
605
606 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
607 NewParamEnd = NewParams->end();
608 NewParam != NewParamEnd; ++NewParam) {
609 // Variables used to diagnose redundant default arguments
610 bool RedundantDefaultArg = false;
611 SourceLocation OldDefaultLoc;
612 SourceLocation NewDefaultLoc;
613
614 // Variables used to diagnose missing default arguments
615 bool MissingDefaultArg = false;
616
Anders Carlssonb1929502009-06-12 23:20:15 +0000617 // C++0x [temp.param]p11:
618 // If a template parameter of a class template is a template parameter pack,
619 // it must be the last template parameter.
620 if (SawParameterPack) {
621 Diag(ParameterPackLoc,
622 diag::err_template_param_pack_must_be_last_template_parameter);
623 Invalid = true;
624 }
625
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000626 // Merge default arguments for template type parameters.
627 if (TemplateTypeParmDecl *NewTypeParm
628 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
629 TemplateTypeParmDecl *OldTypeParm
630 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
631
Anders Carlssonb1929502009-06-12 23:20:15 +0000632 if (NewTypeParm->isParameterPack()) {
633 assert(!NewTypeParm->hasDefaultArgument() &&
634 "Parameter packs can't have a default argument!");
635 SawParameterPack = true;
636 ParameterPackLoc = NewTypeParm->getLocation();
637 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000638 NewTypeParm->hasDefaultArgument()) {
639 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
640 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
641 SawDefaultArgument = true;
642 RedundantDefaultArg = true;
643 PreviousDefaultArgLoc = NewDefaultLoc;
644 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
645 // Merge the default argument from the old declaration to the
646 // new declaration.
647 SawDefaultArgument = true;
648 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
649 OldTypeParm->getDefaultArgumentLoc(),
650 true);
651 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
652 } else if (NewTypeParm->hasDefaultArgument()) {
653 SawDefaultArgument = true;
654 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
655 } else if (SawDefaultArgument)
656 MissingDefaultArg = true;
657 }
658 // Merge default arguments for non-type template parameters
659 else if (NonTypeTemplateParmDecl *NewNonTypeParm
660 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
661 NonTypeTemplateParmDecl *OldNonTypeParm
662 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
663 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
664 NewNonTypeParm->hasDefaultArgument()) {
665 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
666 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
667 SawDefaultArgument = true;
668 RedundantDefaultArg = true;
669 PreviousDefaultArgLoc = NewDefaultLoc;
670 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
671 // Merge the default argument from the old declaration to the
672 // new declaration.
673 SawDefaultArgument = true;
674 // FIXME: We need to create a new kind of "default argument"
675 // expression that points to a previous template template
676 // parameter.
677 NewNonTypeParm->setDefaultArgument(
678 OldNonTypeParm->getDefaultArgument());
679 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
680 } else if (NewNonTypeParm->hasDefaultArgument()) {
681 SawDefaultArgument = true;
682 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
683 } else if (SawDefaultArgument)
684 MissingDefaultArg = true;
685 }
686 // Merge default arguments for template template parameters
687 else {
688 TemplateTemplateParmDecl *NewTemplateParm
689 = cast<TemplateTemplateParmDecl>(*NewParam);
690 TemplateTemplateParmDecl *OldTemplateParm
691 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
692 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
693 NewTemplateParm->hasDefaultArgument()) {
694 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
695 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
696 SawDefaultArgument = true;
697 RedundantDefaultArg = true;
698 PreviousDefaultArgLoc = NewDefaultLoc;
699 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
700 // Merge the default argument from the old declaration to the
701 // new declaration.
702 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000703 // FIXME: We need to create a new kind of "default argument" expression
704 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000705 NewTemplateParm->setDefaultArgument(
706 OldTemplateParm->getDefaultArgument());
707 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
708 } else if (NewTemplateParm->hasDefaultArgument()) {
709 SawDefaultArgument = true;
710 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
711 } else if (SawDefaultArgument)
712 MissingDefaultArg = true;
713 }
714
715 if (RedundantDefaultArg) {
716 // C++ [temp.param]p12:
717 // A template-parameter shall not be given default arguments
718 // by two different declarations in the same scope.
719 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
720 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
721 Invalid = true;
722 } else if (MissingDefaultArg) {
723 // C++ [temp.param]p11:
724 // If a template-parameter has a default template-argument,
725 // all subsequent template-parameters shall have a default
726 // template-argument supplied.
727 Diag((*NewParam)->getLocation(),
728 diag::err_template_param_default_arg_missing);
729 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
730 Invalid = true;
731 }
732
733 // If we have an old template parameter list that we're merging
734 // in, move on to the next parameter.
735 if (OldParams)
736 ++OldParam;
737 }
738
739 return Invalid;
740}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000741
Douglas Gregorb462c322009-07-21 23:53:31 +0000742/// \brief Match the given template parameter lists to the given scope
743/// specifier, returning the template parameter list that applies to the
744/// name.
745///
746/// \param DeclStartLoc the start of the declaration that has a scope
747/// specifier or a template parameter list.
748///
749/// \param SS the scope specifier that will be matched to the given template
750/// parameter lists. This scope specifier precedes a qualified name that is
751/// being declared.
752///
753/// \param ParamLists the template parameter lists, from the outermost to the
754/// innermost template parameter lists.
755///
756/// \param NumParamLists the number of template parameter lists in ParamLists.
757///
758/// \returns the template parameter list, if any, that corresponds to the
759/// name that is preceded by the scope specifier @p SS. This template
760/// parameter list may be have template parameters (if we're declaring a
761/// template) or may have no template parameters (if we're declaring a
762/// template specialization), or may be NULL (if we were's declaring isn't
763/// itself a template).
764TemplateParameterList *
765Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
766 const CXXScopeSpec &SS,
767 TemplateParameterList **ParamLists,
768 unsigned NumParamLists) {
769 // FIXME: This routine will need a lot more testing once we have support for
770 // member templates.
771
772 // Find the template-ids that occur within the nested-name-specifier. These
773 // template-ids will match up with the template parameter lists.
774 llvm::SmallVector<const TemplateSpecializationType *, 4>
775 TemplateIdsInSpecifier;
776 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
777 NNS; NNS = NNS->getPrefix()) {
778 if (const TemplateSpecializationType *SpecType
779 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
780 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
781 if (!Template)
782 continue; // FIXME: should this be an error? probably...
783
784 if (const RecordType *Record = SpecType->getAsRecordType()) {
785 ClassTemplateSpecializationDecl *SpecDecl
786 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
787 // If the nested name specifier refers to an explicit specialization,
788 // we don't need a template<> header.
789 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
790 continue;
791 }
792
793 TemplateIdsInSpecifier.push_back(SpecType);
794 }
795 }
796
797 // Reverse the list of template-ids in the scope specifier, so that we can
798 // more easily match up the template-ids and the template parameter lists.
799 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
800
801 SourceLocation FirstTemplateLoc = DeclStartLoc;
802 if (NumParamLists)
803 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
804
805 // Match the template-ids found in the specifier to the template parameter
806 // lists.
807 unsigned Idx = 0;
808 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
809 Idx != NumTemplateIds; ++Idx) {
810 bool DependentTemplateId = TemplateIdsInSpecifier[Idx]->isDependentType();
811 if (Idx >= NumParamLists) {
812 // We have a template-id without a corresponding template parameter
813 // list.
814 if (DependentTemplateId) {
815 // FIXME: the location information here isn't great.
816 Diag(SS.getRange().getBegin(),
817 diag::err_template_spec_needs_template_parameters)
818 << QualType(TemplateIdsInSpecifier[Idx], 0)
819 << SS.getRange();
820 } else {
821 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
822 << SS.getRange()
823 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
824 "template<> ");
825 }
826 return 0;
827 }
828
829 // Check the template parameter list against its corresponding template-id.
830 TemplateDecl *Template
831 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
832 TemplateParameterListsAreEqual(ParamLists[Idx],
833 Template->getTemplateParameters(),
834 true);
835 }
836
837 // If there were at least as many template-ids as there were template
838 // parameter lists, then there are no template parameter lists remaining for
839 // the declaration itself.
840 if (Idx >= NumParamLists)
841 return 0;
842
843 // If there were too many template parameter lists, complain about that now.
844 if (Idx != NumParamLists - 1) {
845 while (Idx < NumParamLists - 1) {
846 Diag(ParamLists[Idx]->getTemplateLoc(),
847 diag::err_template_spec_extra_headers)
848 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
849 ParamLists[Idx]->getRAngleLoc());
850 ++Idx;
851 }
852 }
853
854 // Return the last template parameter list, which corresponds to the
855 // entity being declared.
856 return ParamLists[NumParamLists - 1];
857}
858
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000859/// \brief Translates template arguments as provided by the parser
860/// into template arguments used by semantic analysis.
861static void
862translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
863 SourceLocation *TemplateArgLocs,
864 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
865 TemplateArgs.reserve(TemplateArgsIn.size());
866
867 void **Args = TemplateArgsIn.getArgs();
868 bool *ArgIsType = TemplateArgsIn.getArgIsType();
869 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
870 TemplateArgs.push_back(
871 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
872 QualType::getFromOpaquePtr(Args[Arg]))
873 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
874 }
875}
876
Douglas Gregoraabb8502009-03-31 00:43:58 +0000877/// \brief Build a canonical version of a template argument list.
878///
879/// This function builds a canonical version of the given template
880/// argument list, where each of the template arguments has been
881/// converted into its canonical form. This routine is typically used
882/// to canonicalize a template argument list when the template name
883/// itself is dependent. When the template name refers to an actual
884/// template declaration, Sema::CheckTemplateArgumentList should be
885/// used to check and canonicalize the template arguments.
886///
887/// \param TemplateArgs The incoming template arguments.
888///
889/// \param NumTemplateArgs The number of template arguments in \p
890/// TemplateArgs.
891///
892/// \param Canonical A vector to be filled with the canonical versions
893/// of the template arguments.
894///
895/// \param Context The ASTContext in which the template arguments live.
896static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
897 unsigned NumTemplateArgs,
898 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
899 ASTContext &Context) {
900 Canonical.reserve(NumTemplateArgs);
901 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
902 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000903 case TemplateArgument::Null:
904 assert(false && "Should never see a NULL template argument here");
905 break;
906
Douglas Gregoraabb8502009-03-31 00:43:58 +0000907 case TemplateArgument::Expression:
908 // FIXME: Build canonical expression (!)
909 Canonical.push_back(TemplateArgs[Idx]);
910 break;
911
912 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000913 Canonical.push_back(
914 TemplateArgument(SourceLocation(),
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +0000915 TemplateArgs[Idx].getAsDecl()->getCanonicalDecl()));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000916 break;
917
918 case TemplateArgument::Integral:
919 Canonical.push_back(TemplateArgument(SourceLocation(),
920 *TemplateArgs[Idx].getAsIntegral(),
921 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000922 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000923
924 case TemplateArgument::Type: {
925 QualType CanonType
926 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
927 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000928 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000929 }
Anders Carlsson584b5062009-06-15 17:04:53 +0000930
931 case TemplateArgument::Pack:
932 assert(0 && "FIXME: Implement!");
933 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000934 }
935 }
936}
937
Douglas Gregordd13e842009-03-30 22:58:21 +0000938QualType Sema::CheckTemplateIdType(TemplateName Name,
939 SourceLocation TemplateLoc,
940 SourceLocation LAngleLoc,
941 const TemplateArgument *TemplateArgs,
942 unsigned NumTemplateArgs,
943 SourceLocation RAngleLoc) {
944 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000945 if (!Template) {
946 // The template name does not resolve to a template, so we just
947 // build a dependent template-id type.
948
949 // Canonicalize the template arguments to build the canonical
950 // template-id type.
951 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
952 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
953 CanonicalTemplateArgs, Context);
954
Douglas Gregor905406b2009-05-07 06:49:52 +0000955 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000956 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000957 = Context.getTemplateSpecializationType(CanonName,
958 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000959 CanonicalTemplateArgs.size());
960
961 // Build the dependent template-id type.
962 return Context.getTemplateSpecializationType(Name, TemplateArgs,
963 NumTemplateArgs, CanonType);
964 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000965
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000966 // Check that the template argument list is well-formed for this
967 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000968 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
969 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +0000970 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000971 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +0000972 false, Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000973 return QualType();
974
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000975 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000976 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000977 "Converted template argument list is too short!");
978
979 QualType CanonType;
980
Douglas Gregordd13e842009-03-30 22:58:21 +0000981 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000982 TemplateArgs,
983 NumTemplateArgs)) {
984 // This class template specialization is a dependent
985 // type. Therefore, its canonical type is another class template
986 // specialization type that contains all of the converted
987 // arguments in canonical form. This ensures that, e.g., A<T> and
988 // A<T, T> have identical types when A is declared as:
989 //
990 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000991 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
992 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000993 Converted.getFlatArguments(),
994 Converted.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000995 } else if (ClassTemplateDecl *ClassTemplate
996 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000997 // Find the class template specialization declaration that
998 // corresponds to these arguments.
999 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00001000 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001001 Converted.getFlatArguments(),
1002 Converted.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001003 void *InsertPos = 0;
1004 ClassTemplateSpecializationDecl *Decl
1005 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1006 if (!Decl) {
1007 // This is the first time we have referenced this class template
1008 // specialization. Create the canonical declaration and add it to
1009 // the set of specializations.
1010 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +00001011 ClassTemplate->getDeclContext(),
1012 TemplateLoc,
1013 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001014 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001015 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1016 Decl->setLexicalDeclContext(CurContext);
1017 }
1018
1019 CanonType = Context.getTypeDeclType(Decl);
1020 }
1021
1022 // Build the fully-sugared type for this class template
1023 // specialization, which refers back to the class template
1024 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +00001025 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1026 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001027}
1028
Douglas Gregora08b6c72009-02-17 23:15:12 +00001029Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +00001030Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1031 SourceLocation LAngleLoc,
1032 ASTTemplateArgsPtr TemplateArgsIn,
1033 SourceLocation *TemplateArgLocs,
1034 SourceLocation RAngleLoc) {
1035 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001036
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001037 // Translate the parser's template argument list in our AST format.
1038 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1039 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001040
Douglas Gregordd13e842009-03-30 22:58:21 +00001041 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +00001042 TemplateArgs.data(),
1043 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +00001044 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001045 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +00001046
1047 if (Result.isNull())
1048 return true;
1049
Douglas Gregor6f37b582009-02-09 19:34:22 +00001050 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001051}
1052
Douglas Gregor28857752009-06-30 22:34:41 +00001053Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1054 SourceLocation TemplateNameLoc,
1055 SourceLocation LAngleLoc,
1056 const TemplateArgument *TemplateArgs,
1057 unsigned NumTemplateArgs,
1058 SourceLocation RAngleLoc) {
1059 // FIXME: Can we do any checking at this point? I guess we could check the
1060 // template arguments that we have against the template name, if the template
1061 // name refers to a single template. That's not a terribly common case,
1062 // though.
1063 return Owned(TemplateIdRefExpr::Create(Context,
1064 /*FIXME: New type?*/Context.OverloadTy,
1065 /*FIXME: Necessary?*/0,
1066 /*FIXME: Necessary?*/SourceRange(),
1067 Template, TemplateNameLoc, LAngleLoc,
1068 TemplateArgs,
1069 NumTemplateArgs, RAngleLoc));
1070}
1071
1072Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1073 SourceLocation TemplateNameLoc,
1074 SourceLocation LAngleLoc,
1075 ASTTemplateArgsPtr TemplateArgsIn,
1076 SourceLocation *TemplateArgLocs,
1077 SourceLocation RAngleLoc) {
1078 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1079
1080 // Translate the parser's template argument list in our AST format.
1081 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1082 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorf2fedc62009-07-22 20:55:49 +00001083 TemplateArgsIn.release();
Douglas Gregor28857752009-06-30 22:34:41 +00001084
1085 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1086 TemplateArgs.data(), TemplateArgs.size(),
1087 RAngleLoc);
1088}
1089
Douglas Gregoraabb8502009-03-31 00:43:58 +00001090/// \brief Form a dependent template name.
1091///
1092/// This action forms a dependent template name given the template
1093/// name and its (presumably dependent) scope specifier. For
1094/// example, given "MetaFun::template apply", the scope specifier \p
1095/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1096/// of the "template" keyword, and "apply" is the \p Name.
1097Sema::TemplateTy
1098Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1099 const IdentifierInfo &Name,
1100 SourceLocation NameLoc,
1101 const CXXScopeSpec &SS) {
1102 if (!SS.isSet() || SS.isInvalid())
1103 return TemplateTy();
1104
1105 NestedNameSpecifier *Qualifier
1106 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1107
1108 // FIXME: member of the current instantiation
1109
1110 if (!Qualifier->isDependent()) {
1111 // C++0x [temp.names]p5:
1112 // If a name prefixed by the keyword template is not the name of
1113 // a template, the program is ill-formed. [Note: the keyword
1114 // template may not be applied to non-template members of class
1115 // templates. -end note ] [ Note: as is the case with the
1116 // typename prefix, the template prefix is allowed in cases
1117 // where it is not strictly necessary; i.e., when the
1118 // nested-name-specifier or the expression on the left of the ->
1119 // or . is not dependent on a template-parameter, or the use
1120 // does not appear in the scope of a template. -end note]
1121 //
1122 // Note: C++03 was more strict here, because it banned the use of
1123 // the "template" keyword prior to a template-name that was not a
1124 // dependent name. C++ DR468 relaxed this requirement (the
1125 // "template" keyword is now permitted). We follow the C++0x
1126 // rules, even in C++03 mode, retroactively applying the DR.
1127 TemplateTy Template;
1128 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1129 if (TNK == TNK_Non_template) {
1130 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1131 << &Name;
1132 return TemplateTy();
1133 }
1134
1135 return Template;
1136 }
1137
1138 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1139}
1140
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001141bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1142 const TemplateArgument &Arg,
1143 TemplateArgumentListBuilder &Converted) {
1144 // Check template type parameter.
1145 if (Arg.getKind() != TemplateArgument::Type) {
1146 // C++ [temp.arg.type]p1:
1147 // A template-argument for a template-parameter which is a
1148 // type shall be a type-id.
1149
1150 // We have a template type parameter but the template argument
1151 // is not a type.
1152 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1153 Diag(Param->getLocation(), diag::note_template_param_here);
1154
1155 return true;
1156 }
1157
1158 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1159 return true;
1160
1161 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001162 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001163 TemplateArgument(Arg.getLocation(),
1164 Context.getCanonicalType(Arg.getAsType())));
1165 return false;
1166}
1167
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001168/// \brief Check that the given template argument list is well-formed
1169/// for specializing the given template.
1170bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1171 SourceLocation TemplateLoc,
1172 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001173 const TemplateArgument *TemplateArgs,
1174 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001175 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001176 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001177 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001178 TemplateParameterList *Params = Template->getTemplateParameters();
1179 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001180 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001181 bool Invalid = false;
1182
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001183 bool HasParameterPack =
1184 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1185
1186 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001187 (NumArgs < Params->getMinRequiredArguments() &&
1188 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001189 // FIXME: point at either the first arg beyond what we can handle,
1190 // or the '>', depending on whether we have too many or too few
1191 // arguments.
1192 SourceRange Range;
1193 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001194 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001195 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1196 << (NumArgs > NumParams)
1197 << (isa<ClassTemplateDecl>(Template)? 0 :
1198 isa<FunctionTemplateDecl>(Template)? 1 :
1199 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1200 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001201 Diag(Template->getLocation(), diag::note_template_decl_here)
1202 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001203 Invalid = true;
1204 }
1205
1206 // C++ [temp.arg]p1:
1207 // [...] The type and form of each template-argument specified in
1208 // a template-id shall match the type and form specified for the
1209 // corresponding parameter declared by the template in its
1210 // template-parameter-list.
1211 unsigned ArgIdx = 0;
1212 for (TemplateParameterList::iterator Param = Params->begin(),
1213 ParamEnd = Params->end();
1214 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001215 if (ArgIdx > NumArgs && PartialTemplateArgs)
1216 break;
1217
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001218 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001219 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001220 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001221 // Retrieve the default template argument from the template
1222 // parameter.
1223 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001224 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001225 // We have an empty argument pack.
1226 Converted.BeginPack();
1227 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001228 break;
1229 }
1230
Douglas Gregorad964b32009-02-17 01:05:43 +00001231 if (!TTP->hasDefaultArgument())
1232 break;
1233
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001234 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001235
1236 // If the argument type is dependent, instantiate it now based
1237 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001238 if (ArgType->isDependentType()) {
1239 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001240 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001241 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001242 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001243
Anders Carlsson0233eb62009-06-05 04:47:51 +00001244 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001245 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001246 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001247 TTP->getDefaultArgumentLoc(),
1248 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001249 }
Douglas Gregor74296542009-02-27 19:31:52 +00001250
1251 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001252 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001253
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001254 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001255 } else if (NonTypeTemplateParmDecl *NTTP
1256 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1257 if (!NTTP->hasDefaultArgument())
1258 break;
1259
Anders Carlsson0297caf2009-06-11 16:06:49 +00001260 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001261 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001262 Converted.flatSize(),
1263 SourceRange(TemplateLoc, RAngleLoc));
1264
1265 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001266 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001267
1268 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1269 TemplateArgs);
1270 if (E.isInvalid())
1271 return true;
1272
1273 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001274 } else {
1275 TemplateTemplateParmDecl *TempParm
1276 = cast<TemplateTemplateParmDecl>(*Param);
1277
1278 if (!TempParm->hasDefaultArgument())
1279 break;
1280
Douglas Gregored3a3982009-03-03 04:44:36 +00001281 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001282 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001283 }
1284 } else {
1285 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001286 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001287 }
1288
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001289
1290 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001291 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001292 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001293 // Check all the remaining arguments (if any).
1294 for (; ArgIdx < NumArgs; ++ArgIdx) {
1295 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1296 Invalid = true;
1297 }
1298
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001299 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001300 } else {
1301 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1302 Invalid = true;
1303 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001304 } else if (NonTypeTemplateParmDecl *NTTP
1305 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1306 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001307
1308 // Instantiate the type of the non-type template parameter with
1309 // the template arguments we've seen thus far.
1310 QualType NTTPType = NTTP->getType();
1311 if (NTTPType->isDependentType()) {
1312 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001313 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001314 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001315 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001316 SourceRange(TemplateLoc, RAngleLoc));
1317
Anders Carlsson0233eb62009-06-05 04:47:51 +00001318 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001319 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001320 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001321 NTTP->getLocation(),
1322 NTTP->getDeclName());
1323 // If that worked, check the non-type template parameter type
1324 // for validity.
1325 if (!NTTPType.isNull())
1326 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1327 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001328 if (NTTPType.isNull()) {
1329 Invalid = true;
1330 break;
1331 }
1332 }
1333
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001334 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001335 case TemplateArgument::Null:
1336 assert(false && "Should never see a NULL template argument here");
1337 break;
1338
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001339 case TemplateArgument::Expression: {
1340 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001341 TemplateArgument Result;
1342 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001343 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001344 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001345 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001346 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001347 }
1348
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001349 case TemplateArgument::Declaration:
1350 case TemplateArgument::Integral:
1351 // We've already checked this template argument, so just copy
1352 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001353 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001354 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001355
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001356 case TemplateArgument::Type:
1357 // We have a non-type template parameter but the template
1358 // argument is a type.
1359
1360 // C++ [temp.arg]p2:
1361 // In a template-argument, an ambiguity between a type-id and
1362 // an expression is resolved to a type-id, regardless of the
1363 // form of the corresponding template-parameter.
1364 //
1365 // We warn specifically about this case, since it can be rather
1366 // confusing for users.
1367 if (Arg.getAsType()->isFunctionType())
1368 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1369 << Arg.getAsType();
1370 else
1371 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1372 Diag((*Param)->getLocation(), diag::note_template_param_here);
1373 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001374 break;
1375
1376 case TemplateArgument::Pack:
1377 assert(0 && "FIXME: Implement!");
1378 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001379 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001380 } else {
1381 // Check template template parameters.
1382 TemplateTemplateParmDecl *TempParm
1383 = cast<TemplateTemplateParmDecl>(*Param);
1384
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001385 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001386 case TemplateArgument::Null:
1387 assert(false && "Should never see a NULL template argument here");
1388 break;
1389
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001390 case TemplateArgument::Expression: {
1391 Expr *ArgExpr = Arg.getAsExpr();
1392 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1393 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1394 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1395 Invalid = true;
1396
1397 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001398 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001399 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001400 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001401 continue;
1402 }
1403 }
1404 // fall through
1405
1406 case TemplateArgument::Type: {
1407 // We have a template template parameter but the template
1408 // argument does not refer to a template.
1409 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1410 Invalid = true;
1411 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001412 }
1413
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001414 case TemplateArgument::Declaration:
1415 // We've already checked this template argument, so just copy
1416 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001417 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001418 break;
1419
1420 case TemplateArgument::Integral:
1421 assert(false && "Integral argument with template template parameter");
1422 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001423
1424 case TemplateArgument::Pack:
1425 assert(0 && "FIXME: Implement!");
1426 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001427 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001428 }
1429 }
1430
1431 return Invalid;
1432}
1433
1434/// \brief Check a template argument against its corresponding
1435/// template type parameter.
1436///
1437/// This routine implements the semantics of C++ [temp.arg.type]. It
1438/// returns true if an error occurred, and false otherwise.
1439bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1440 QualType Arg, SourceLocation ArgLoc) {
1441 // C++ [temp.arg.type]p2:
1442 // A local type, a type with no linkage, an unnamed type or a type
1443 // compounded from any of these types shall not be used as a
1444 // template-argument for a template type-parameter.
1445 //
1446 // FIXME: Perform the recursive and no-linkage type checks.
1447 const TagType *Tag = 0;
1448 if (const EnumType *EnumT = Arg->getAsEnumType())
1449 Tag = EnumT;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001450 else if (const RecordType *RecordT = Arg->getAsRecordType())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001451 Tag = RecordT;
1452 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1453 return Diag(ArgLoc, diag::err_template_arg_local_type)
1454 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001455 else if (Tag && !Tag->getDecl()->getDeclName() &&
1456 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001457 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1458 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1459 return true;
1460 }
1461
1462 return false;
1463}
1464
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001465/// \brief Checks whether the given template argument is the address
1466/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001467bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1468 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001469 bool Invalid = false;
1470
1471 // See through any implicit casts we added to fix the type.
1472 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1473 Arg = Cast->getSubExpr();
1474
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001475 // C++0x allows nullptr, and there's no further checking to be done for that.
1476 if (Arg->getType()->isNullPtrType())
1477 return false;
1478
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001479 // C++ [temp.arg.nontype]p1:
1480 //
1481 // A template-argument for a non-type, non-template
1482 // template-parameter shall be one of: [...]
1483 //
1484 // -- the address of an object or function with external
1485 // linkage, including function templates and function
1486 // template-ids but excluding non-static class members,
1487 // expressed as & id-expression where the & is optional if
1488 // the name refers to a function or array, or if the
1489 // corresponding template-parameter is a reference; or
1490 DeclRefExpr *DRE = 0;
1491
1492 // Ignore (and complain about) any excess parentheses.
1493 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1494 if (!Invalid) {
1495 Diag(Arg->getSourceRange().getBegin(),
1496 diag::err_template_arg_extra_parens)
1497 << Arg->getSourceRange();
1498 Invalid = true;
1499 }
1500
1501 Arg = Parens->getSubExpr();
1502 }
1503
1504 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1505 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1506 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1507 } else
1508 DRE = dyn_cast<DeclRefExpr>(Arg);
1509
1510 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1511 return Diag(Arg->getSourceRange().getBegin(),
1512 diag::err_template_arg_not_object_or_func_form)
1513 << Arg->getSourceRange();
1514
1515 // Cannot refer to non-static data members
1516 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1517 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1518 << Field << Arg->getSourceRange();
1519
1520 // Cannot refer to non-static member functions
1521 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1522 if (!Method->isStatic())
1523 return Diag(Arg->getSourceRange().getBegin(),
1524 diag::err_template_arg_method)
1525 << Method << Arg->getSourceRange();
1526
1527 // Functions must have external linkage.
1528 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1529 if (Func->getStorageClass() == FunctionDecl::Static) {
1530 Diag(Arg->getSourceRange().getBegin(),
1531 diag::err_template_arg_function_not_extern)
1532 << Func << Arg->getSourceRange();
1533 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1534 << true;
1535 return true;
1536 }
1537
1538 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001539 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001540 return Invalid;
1541 }
1542
1543 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1544 if (!Var->hasGlobalStorage()) {
1545 Diag(Arg->getSourceRange().getBegin(),
1546 diag::err_template_arg_object_not_extern)
1547 << Var << Arg->getSourceRange();
1548 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1549 << true;
1550 return true;
1551 }
1552
1553 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001554 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001555 return Invalid;
1556 }
1557
1558 // We found something else, but we don't know specifically what it is.
1559 Diag(Arg->getSourceRange().getBegin(),
1560 diag::err_template_arg_not_object_or_func)
1561 << Arg->getSourceRange();
1562 Diag(DRE->getDecl()->getLocation(),
1563 diag::note_template_arg_refers_here);
1564 return true;
1565}
1566
1567/// \brief Checks whether the given template argument is a pointer to
1568/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001569bool
1570Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001571 bool Invalid = false;
1572
1573 // See through any implicit casts we added to fix the type.
1574 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1575 Arg = Cast->getSubExpr();
1576
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001577 // C++0x allows nullptr, and there's no further checking to be done for that.
1578 if (Arg->getType()->isNullPtrType())
1579 return false;
1580
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001581 // C++ [temp.arg.nontype]p1:
1582 //
1583 // A template-argument for a non-type, non-template
1584 // template-parameter shall be one of: [...]
1585 //
1586 // -- a pointer to member expressed as described in 5.3.1.
1587 QualifiedDeclRefExpr *DRE = 0;
1588
1589 // Ignore (and complain about) any excess parentheses.
1590 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1591 if (!Invalid) {
1592 Diag(Arg->getSourceRange().getBegin(),
1593 diag::err_template_arg_extra_parens)
1594 << Arg->getSourceRange();
1595 Invalid = true;
1596 }
1597
1598 Arg = Parens->getSubExpr();
1599 }
1600
1601 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1602 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1603 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1604
1605 if (!DRE)
1606 return Diag(Arg->getSourceRange().getBegin(),
1607 diag::err_template_arg_not_pointer_to_member_form)
1608 << Arg->getSourceRange();
1609
1610 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1611 assert((isa<FieldDecl>(DRE->getDecl()) ||
1612 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1613 "Only non-static member pointers can make it here");
1614
1615 // Okay: this is the address of a non-static member, and therefore
1616 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001617 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001618 return Invalid;
1619 }
1620
1621 // We found something else, but we don't know specifically what it is.
1622 Diag(Arg->getSourceRange().getBegin(),
1623 diag::err_template_arg_not_pointer_to_member_form)
1624 << Arg->getSourceRange();
1625 Diag(DRE->getDecl()->getLocation(),
1626 diag::note_template_arg_refers_here);
1627 return true;
1628}
1629
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001630/// \brief Check a template argument against its corresponding
1631/// non-type template parameter.
1632///
Douglas Gregored3a3982009-03-03 04:44:36 +00001633/// This routine implements the semantics of C++ [temp.arg.nontype].
1634/// It returns true if an error occurred, and false otherwise. \p
1635/// InstantiatedParamType is the type of the non-type template
1636/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001637///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001638/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001639bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001640 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001641 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001642 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1643
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001644 // If either the parameter has a dependent type or the argument is
1645 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001646 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001647 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1648 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001649 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001650 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001651 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001652
1653 // C++ [temp.arg.nontype]p5:
1654 // The following conversions are performed on each expression used
1655 // as a non-type template-argument. If a non-type
1656 // template-argument cannot be converted to the type of the
1657 // corresponding template-parameter then the program is
1658 // ill-formed.
1659 //
1660 // -- for a non-type template-parameter of integral or
1661 // enumeration type, integral promotions (4.5) and integral
1662 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001663 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001664 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001665 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001666 // C++ [temp.arg.nontype]p1:
1667 // A template-argument for a non-type, non-template
1668 // template-parameter shall be one of:
1669 //
1670 // -- an integral constant-expression of integral or enumeration
1671 // type; or
1672 // -- the name of a non-type template-parameter; or
1673 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001674 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001675 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1676 Diag(Arg->getSourceRange().getBegin(),
1677 diag::err_template_arg_not_integral_or_enumeral)
1678 << ArgType << Arg->getSourceRange();
1679 Diag(Param->getLocation(), diag::note_template_param_here);
1680 return true;
1681 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001682 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001683 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1684 << ArgType << Arg->getSourceRange();
1685 return true;
1686 }
1687
1688 // FIXME: We need some way to more easily get the unqualified form
1689 // of the types without going all the way to the
1690 // canonical type.
1691 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1692 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1693 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1694 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1695
1696 // Try to convert the argument to the parameter's type.
1697 if (ParamType == ArgType) {
1698 // Okay: no conversion necessary
1699 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1700 !ParamType->isEnumeralType()) {
1701 // This is an integral promotion or conversion.
1702 ImpCastExprToType(Arg, ParamType);
1703 } else {
1704 // We can't perform this conversion.
1705 Diag(Arg->getSourceRange().getBegin(),
1706 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001707 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001708 Diag(Param->getLocation(), diag::note_template_param_here);
1709 return true;
1710 }
1711
Douglas Gregorafc86942009-03-14 00:20:21 +00001712 QualType IntegerType = Context.getCanonicalType(ParamType);
1713 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001714 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001715
1716 if (!Arg->isValueDependent()) {
1717 // Check that an unsigned parameter does not receive a negative
1718 // value.
1719 if (IntegerType->isUnsignedIntegerType()
1720 && (Value.isSigned() && Value.isNegative())) {
1721 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1722 << Value.toString(10) << Param->getType()
1723 << Arg->getSourceRange();
1724 Diag(Param->getLocation(), diag::note_template_param_here);
1725 return true;
1726 }
1727
1728 // Check that we don't overflow the template parameter type.
1729 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1730 if (Value.getActiveBits() > AllowedBits) {
1731 Diag(Arg->getSourceRange().getBegin(),
1732 diag::err_template_arg_too_large)
1733 << Value.toString(10) << Param->getType()
1734 << Arg->getSourceRange();
1735 Diag(Param->getLocation(), diag::note_template_param_here);
1736 return true;
1737 }
1738
1739 if (Value.getBitWidth() != AllowedBits)
1740 Value.extOrTrunc(AllowedBits);
1741 Value.setIsSigned(IntegerType->isSignedIntegerType());
1742 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001743
Douglas Gregor8f378a92009-06-11 18:10:32 +00001744 // Add the value of this argument to the list of converted
1745 // arguments. We use the bitwidth and signedness of the template
1746 // parameter.
1747 if (Arg->isValueDependent()) {
1748 // The argument is value-dependent. Create a new
1749 // TemplateArgument with the converted expression.
1750 Converted = TemplateArgument(Arg);
1751 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001752 }
1753
Douglas Gregor8f378a92009-06-11 18:10:32 +00001754 Converted = TemplateArgument(StartLoc, Value,
1755 ParamType->isEnumeralType() ? ParamType
1756 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001757 return false;
1758 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001759
Douglas Gregor3f411962009-02-11 01:18:59 +00001760 // Handle pointer-to-function, reference-to-function, and
1761 // pointer-to-member-function all in (roughly) the same way.
1762 if (// -- For a non-type template-parameter of type pointer to
1763 // function, only the function-to-pointer conversion (4.3) is
1764 // applied. If the template-argument represents a set of
1765 // overloaded functions (or a pointer to such), the matching
1766 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001767 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001768 (ParamType->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001769 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001770 // -- For a non-type template-parameter of type reference to
1771 // function, no conversions apply. If the template-argument
1772 // represents a set of overloaded functions, the matching
1773 // function is selected from the set (13.4).
1774 (ParamType->isReferenceType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001775 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001776 // -- For a non-type template-parameter of type pointer to
1777 // member function, no conversions apply. If the
1778 // template-argument represents a set of overloaded member
1779 // functions, the matching member function is selected from
1780 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001781 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001782 (ParamType->isMemberPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001783 ParamType->getAsMemberPointerType()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001784 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001785 if (Context.hasSameUnqualifiedType(ArgType,
1786 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001787 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001788 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1789 ParamType->isMemberPointerType())) {
1790 ArgType = ParamType;
1791 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001792 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001793 ArgType = Context.getPointerType(ArgType);
1794 ImpCastExprToType(Arg, ArgType);
1795 } else if (FunctionDecl *Fn
1796 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001797 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1798 return true;
1799
Douglas Gregor2eedd992009-02-11 00:19:33 +00001800 FixOverloadedFunctionReference(Arg, Fn);
1801 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001802 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001803 ArgType = Context.getPointerType(Arg->getType());
1804 ImpCastExprToType(Arg, ArgType);
1805 }
1806 }
1807
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001808 if (!Context.hasSameUnqualifiedType(ArgType,
1809 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001810 // We can't perform this conversion.
1811 Diag(Arg->getSourceRange().getBegin(),
1812 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001813 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001814 Diag(Param->getLocation(), diag::note_template_param_here);
1815 return true;
1816 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001817
Douglas Gregorad964b32009-02-17 01:05:43 +00001818 if (ParamType->isMemberPointerType()) {
1819 NamedDecl *Member = 0;
1820 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1821 return true;
1822
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001823 if (Member)
1824 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001825 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001826 return false;
1827 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001828
Douglas Gregorad964b32009-02-17 01:05:43 +00001829 NamedDecl *Entity = 0;
1830 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1831 return true;
1832
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001833 if (Entity)
1834 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001835 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001836 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001837 }
1838
Chris Lattner320dff22009-02-20 21:37:53 +00001839 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001840 // -- for a non-type template-parameter of type pointer to
1841 // object, qualification conversions (4.4) and the
1842 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001843 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001844 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001845 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001846
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001847 if (ArgType->isNullPtrType()) {
1848 ArgType = ParamType;
1849 ImpCastExprToType(Arg, ParamType);
1850 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001851 ArgType = Context.getArrayDecayedType(ArgType);
1852 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001853 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001854
Douglas Gregor3f411962009-02-11 01:18:59 +00001855 if (IsQualificationConversion(ArgType, ParamType)) {
1856 ArgType = ParamType;
1857 ImpCastExprToType(Arg, ParamType);
1858 }
1859
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001860 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001861 // We can't perform this conversion.
1862 Diag(Arg->getSourceRange().getBegin(),
1863 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001864 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001865 Diag(Param->getLocation(), diag::note_template_param_here);
1866 return true;
1867 }
1868
Douglas Gregorad964b32009-02-17 01:05:43 +00001869 NamedDecl *Entity = 0;
1870 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1871 return true;
1872
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001873 if (Entity)
1874 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001875 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001876 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001877 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001878
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001879 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001880 // -- For a non-type template-parameter of type reference to
1881 // object, no conversions apply. The type referred to by the
1882 // reference may be more cv-qualified than the (otherwise
1883 // identical) type of the template-argument. The
1884 // template-parameter is bound directly to the
1885 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001886 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001887 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001888
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001889 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001890 Diag(Arg->getSourceRange().getBegin(),
1891 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001892 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001893 << Arg->getSourceRange();
1894 Diag(Param->getLocation(), diag::note_template_param_here);
1895 return true;
1896 }
1897
1898 unsigned ParamQuals
1899 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1900 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1901
1902 if ((ParamQuals | ArgQuals) != ParamQuals) {
1903 Diag(Arg->getSourceRange().getBegin(),
1904 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001905 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001906 << Arg->getSourceRange();
1907 Diag(Param->getLocation(), diag::note_template_param_here);
1908 return true;
1909 }
1910
Douglas Gregorad964b32009-02-17 01:05:43 +00001911 NamedDecl *Entity = 0;
1912 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1913 return true;
1914
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001915 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001916 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001917 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001918 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001919
1920 // -- For a non-type template-parameter of type pointer to data
1921 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001922 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001923 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1924
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001925 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001926 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001927 } else if (ArgType->isNullPtrType()) {
1928 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001929 } else if (IsQualificationConversion(ArgType, ParamType)) {
1930 ImpCastExprToType(Arg, ParamType);
1931 } else {
1932 // We can't perform this conversion.
1933 Diag(Arg->getSourceRange().getBegin(),
1934 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001935 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001936 Diag(Param->getLocation(), diag::note_template_param_here);
1937 return true;
1938 }
1939
Douglas Gregorad964b32009-02-17 01:05:43 +00001940 NamedDecl *Member = 0;
1941 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1942 return true;
1943
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001944 if (Member)
1945 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001946 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001947 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001948}
1949
1950/// \brief Check a template argument against its corresponding
1951/// template template parameter.
1952///
1953/// This routine implements the semantics of C++ [temp.arg.template].
1954/// It returns true if an error occurred, and false otherwise.
1955bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1956 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001957 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1958 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1959
1960 // C++ [temp.arg.template]p1:
1961 // A template-argument for a template template-parameter shall be
1962 // the name of a class template, expressed as id-expression. Only
1963 // primary class templates are considered when matching the
1964 // template template argument with the corresponding parameter;
1965 // partial specializations are not considered even if their
1966 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001967 //
1968 // Note that we also allow template template parameters here, which
1969 // will happen when we are dealing with, e.g., class template
1970 // partial specializations.
1971 if (!isa<ClassTemplateDecl>(Template) &&
1972 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001973 assert(isa<FunctionTemplateDecl>(Template) &&
1974 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001975 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1976 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001977 << Template;
1978 }
1979
1980 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1981 Param->getTemplateParameters(),
1982 true, true,
1983 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001984}
1985
Douglas Gregord406b032009-02-06 22:42:48 +00001986/// \brief Determine whether the given template parameter lists are
1987/// equivalent.
1988///
1989/// \param New The new template parameter list, typically written in the
1990/// source code as part of a new template declaration.
1991///
1992/// \param Old The old template parameter list, typically found via
1993/// name lookup of the template declared with this template parameter
1994/// list.
1995///
1996/// \param Complain If true, this routine will produce a diagnostic if
1997/// the template parameter lists are not equivalent.
1998///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001999/// \param IsTemplateTemplateParm If true, this routine is being
2000/// called to compare the template parameter lists of a template
2001/// template parameter.
2002///
2003/// \param TemplateArgLoc If this source location is valid, then we
2004/// are actually checking the template parameter list of a template
2005/// argument (New) against the template parameter list of its
2006/// corresponding template template parameter (Old). We produce
2007/// slightly different diagnostics in this scenario.
2008///
Douglas Gregord406b032009-02-06 22:42:48 +00002009/// \returns True if the template parameter lists are equal, false
2010/// otherwise.
2011bool
2012Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2013 TemplateParameterList *Old,
2014 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002015 bool IsTemplateTemplateParm,
2016 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00002017 if (Old->size() != New->size()) {
2018 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002019 unsigned NextDiag = diag::err_template_param_list_different_arity;
2020 if (TemplateArgLoc.isValid()) {
2021 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2022 NextDiag = diag::note_template_param_list_different_arity;
2023 }
2024 Diag(New->getTemplateLoc(), NextDiag)
2025 << (New->size() > Old->size())
2026 << IsTemplateTemplateParm
2027 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00002028 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2029 << IsTemplateTemplateParm
2030 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2031 }
2032
2033 return false;
2034 }
2035
2036 for (TemplateParameterList::iterator OldParm = Old->begin(),
2037 OldParmEnd = Old->end(), NewParm = New->begin();
2038 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2039 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00002040 if (Complain) {
2041 unsigned NextDiag = diag::err_template_param_different_kind;
2042 if (TemplateArgLoc.isValid()) {
2043 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2044 NextDiag = diag::note_template_param_different_kind;
2045 }
2046 Diag((*NewParm)->getLocation(), NextDiag)
2047 << IsTemplateTemplateParm;
2048 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2049 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00002050 }
Douglas Gregord406b032009-02-06 22:42:48 +00002051 return false;
2052 }
2053
2054 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2055 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00002056 // know we're at the same index).
2057#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00002058 // FIXME: Enable this code in debug mode *after* we properly go through
2059 // and "instantiate" the template parameter lists of template template
2060 // parameters. It's only after this instantiation that (1) any dependent
2061 // types within the template parameter list of the template template
2062 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00002063 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00002064 QualType OldParmType
2065 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2066 QualType NewParmType
2067 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2068 assert(Context.getCanonicalType(OldParmType) ==
2069 Context.getCanonicalType(NewParmType) &&
2070 "type parameter mismatch?");
2071#endif
2072 } else if (NonTypeTemplateParmDecl *OldNTTP
2073 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2074 // The types of non-type template parameters must agree.
2075 NonTypeTemplateParmDecl *NewNTTP
2076 = cast<NonTypeTemplateParmDecl>(*NewParm);
2077 if (Context.getCanonicalType(OldNTTP->getType()) !=
2078 Context.getCanonicalType(NewNTTP->getType())) {
2079 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002080 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2081 if (TemplateArgLoc.isValid()) {
2082 Diag(TemplateArgLoc,
2083 diag::err_template_arg_template_params_mismatch);
2084 NextDiag = diag::note_template_nontype_parm_different_type;
2085 }
2086 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002087 << NewNTTP->getType()
2088 << IsTemplateTemplateParm;
2089 Diag(OldNTTP->getLocation(),
2090 diag::note_template_nontype_parm_prev_declaration)
2091 << OldNTTP->getType();
2092 }
2093 return false;
2094 }
2095 } else {
2096 // The template parameter lists of template template
2097 // parameters must agree.
2098 // FIXME: Could we perform a faster "type" comparison here?
2099 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2100 "Only template template parameters handled here");
2101 TemplateTemplateParmDecl *OldTTP
2102 = cast<TemplateTemplateParmDecl>(*OldParm);
2103 TemplateTemplateParmDecl *NewTTP
2104 = cast<TemplateTemplateParmDecl>(*NewParm);
2105 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2106 OldTTP->getTemplateParameters(),
2107 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002108 /*IsTemplateTemplateParm=*/true,
2109 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002110 return false;
2111 }
2112 }
2113
2114 return true;
2115}
2116
2117/// \brief Check whether a template can be declared within this scope.
2118///
2119/// If the template declaration is valid in this scope, returns
2120/// false. Otherwise, issues a diagnostic and returns true.
2121bool
2122Sema::CheckTemplateDeclScope(Scope *S,
2123 MultiTemplateParamsArg &TemplateParameterLists) {
2124 assert(TemplateParameterLists.size() > 0 && "Not a template");
2125
2126 // Find the nearest enclosing declaration scope.
2127 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2128 (S->getFlags() & Scope::TemplateParamScope) != 0)
2129 S = S->getParent();
2130
2131 TemplateParameterList *TemplateParams =
2132 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2133 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2134 SourceRange TemplateRange
2135 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2136
2137 // C++ [temp]p2:
2138 // A template-declaration can appear only as a namespace scope or
2139 // class scope declaration.
2140 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2141 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2142 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2143 return Diag(TemplateLoc, diag::err_template_linkage)
2144 << TemplateRange;
2145
2146 Ctx = Ctx->getParent();
2147 }
2148
2149 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2150 return false;
2151
2152 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2153 << TemplateRange;
2154}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002155
Douglas Gregor90177912009-05-13 18:28:20 +00002156/// \brief Check whether a class template specialization or explicit
2157/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002158///
Douglas Gregor90177912009-05-13 18:28:20 +00002159/// This routine determines whether a class template specialization or
2160/// explicit instantiation can be declared in the current context
2161/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2162/// appropriate diagnostics if there was an error. It returns true if
2163// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002164bool
2165Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2166 ClassTemplateSpecializationDecl *PrevDecl,
2167 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002168 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002169 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002170 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002171 // C++ [temp.expl.spec]p2:
2172 // An explicit specialization shall be declared in the namespace
2173 // of which the template is a member, or, for member templates, in
2174 // the namespace of which the enclosing class or enclosing class
2175 // template is a member. An explicit specialization of a member
2176 // function, member class or static data member of a class
2177 // template shall be declared in the namespace of which the class
2178 // template is a member. Such a declaration may also be a
2179 // definition. If the declaration is not a definition, the
2180 // specialization may be defined later in the name- space in which
2181 // the explicit specialization was declared, or in a namespace
2182 // that encloses the one in which the explicit specialization was
2183 // declared.
2184 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002185 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002186 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002187 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002188 return true;
2189 }
2190
2191 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2192 DeclContext *TemplateContext
2193 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002194 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2195 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002196 // There is no prior declaration of this entity, so this
2197 // specialization must be in the same context as the template
2198 // itself.
2199 if (DC != TemplateContext) {
2200 if (isa<TranslationUnitDecl>(TemplateContext))
2201 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002202 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002203 << ClassTemplate << ScopeSpecifierRange;
2204 else if (isa<NamespaceDecl>(TemplateContext))
2205 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002206 << PartialSpecialization << ClassTemplate
2207 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002208
2209 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2210 }
2211
2212 return false;
2213 }
2214
2215 // We have a previous declaration of this entity. Make sure that
2216 // this redeclaration (or definition) occurs in an enclosing namespace.
2217 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002218 // FIXME: In C++98, we would like to turn these errors into warnings,
2219 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002220 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002221 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002222 if (isa<TranslationUnitDecl>(TemplateContext)) {
2223 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2224 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002225 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002226 else
2227 SuppressedDiag = true;
2228 } else if (isa<NamespaceDecl>(TemplateContext)) {
2229 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2230 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002231 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002232 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2233 else
2234 SuppressedDiag = true;
2235 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002236
Douglas Gregor90177912009-05-13 18:28:20 +00002237 if (!SuppressedDiag)
2238 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002239 }
2240
2241 return false;
2242}
2243
Douglas Gregor76e79952009-06-12 21:21:02 +00002244/// \brief Check the non-type template arguments of a class template
2245/// partial specialization according to C++ [temp.class.spec]p9.
2246///
Douglas Gregor42476442009-06-12 22:08:06 +00002247/// \param TemplateParams the template parameters of the primary class
2248/// template.
2249///
2250/// \param TemplateArg the template arguments of the class template
2251/// partial specialization.
2252///
2253/// \param MirrorsPrimaryTemplate will be set true if the class
2254/// template partial specialization arguments are identical to the
2255/// implicit template arguments of the primary template. This is not
2256/// necessarily an error (C++0x), and it is left to the caller to diagnose
2257/// this condition when it is an error.
2258///
Douglas Gregor76e79952009-06-12 21:21:02 +00002259/// \returns true if there was an error, false otherwise.
2260bool Sema::CheckClassTemplatePartialSpecializationArgs(
2261 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002262 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002263 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002264 // FIXME: the interface to this function will have to change to
2265 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002266 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002267
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002268 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002269
Douglas Gregor76e79952009-06-12 21:21:02 +00002270 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002271 // Determine whether the template argument list of the partial
2272 // specialization is identical to the implicit argument list of
2273 // the primary template. The caller may need to diagnostic this as
2274 // an error per C++ [temp.class.spec]p9b3.
2275 if (MirrorsPrimaryTemplate) {
2276 if (TemplateTypeParmDecl *TTP
2277 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2278 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002279 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002280 MirrorsPrimaryTemplate = false;
2281 } else if (TemplateTemplateParmDecl *TTP
2282 = dyn_cast<TemplateTemplateParmDecl>(
2283 TemplateParams->getParam(I))) {
2284 // FIXME: We should settle on either Declaration storage or
2285 // Expression storage for template template parameters.
2286 TemplateTemplateParmDecl *ArgDecl
2287 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002288 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002289 if (!ArgDecl)
2290 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002291 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002292 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2293
2294 if (!ArgDecl ||
2295 ArgDecl->getIndex() != TTP->getIndex() ||
2296 ArgDecl->getDepth() != TTP->getDepth())
2297 MirrorsPrimaryTemplate = false;
2298 }
2299 }
2300
Douglas Gregor76e79952009-06-12 21:21:02 +00002301 NonTypeTemplateParmDecl *Param
2302 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002303 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002304 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002305 }
2306
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002307 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002308 if (!ArgExpr) {
2309 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002310 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002311 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002312
2313 // C++ [temp.class.spec]p8:
2314 // A non-type argument is non-specialized if it is the name of a
2315 // non-type parameter. All other non-type arguments are
2316 // specialized.
2317 //
2318 // Below, we check the two conditions that only apply to
2319 // specialized non-type arguments, so skip any non-specialized
2320 // arguments.
2321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002322 if (NonTypeTemplateParmDecl *NTTP
2323 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2324 if (MirrorsPrimaryTemplate &&
2325 (Param->getIndex() != NTTP->getIndex() ||
2326 Param->getDepth() != NTTP->getDepth()))
2327 MirrorsPrimaryTemplate = false;
2328
Douglas Gregor76e79952009-06-12 21:21:02 +00002329 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002330 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002331
2332 // C++ [temp.class.spec]p9:
2333 // Within the argument list of a class template partial
2334 // specialization, the following restrictions apply:
2335 // -- A partially specialized non-type argument expression
2336 // shall not involve a template parameter of the partial
2337 // specialization except when the argument expression is a
2338 // simple identifier.
2339 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2340 Diag(ArgExpr->getLocStart(),
2341 diag::err_dependent_non_type_arg_in_partial_spec)
2342 << ArgExpr->getSourceRange();
2343 return true;
2344 }
2345
2346 // -- The type of a template parameter corresponding to a
2347 // specialized non-type argument shall not be dependent on a
2348 // parameter of the specialization.
2349 if (Param->getType()->isDependentType()) {
2350 Diag(ArgExpr->getLocStart(),
2351 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2352 << Param->getType()
2353 << ArgExpr->getSourceRange();
2354 Diag(Param->getLocation(), diag::note_template_param_here);
2355 return true;
2356 }
Douglas Gregor42476442009-06-12 22:08:06 +00002357
2358 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002359 }
2360
2361 return false;
2362}
2363
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002364Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002365Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2366 SourceLocation KWLoc,
2367 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002368 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002369 SourceLocation TemplateNameLoc,
2370 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002371 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002372 SourceLocation *TemplateArgLocs,
2373 SourceLocation RAngleLoc,
2374 AttributeList *Attr,
2375 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002376 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002377 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002378 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002379 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002380
Douglas Gregor58944ac2009-05-31 09:31:02 +00002381 bool isPartialSpecialization = false;
2382
Douglas Gregor0d93f692009-02-25 22:02:03 +00002383 // Check the validity of the template headers that introduce this
2384 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002385 // FIXME: Once we have member templates, we'll need to check
2386 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2387 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002388 if (TemplateParameterLists.size() == 0)
2389 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002390 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002391 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002392 TemplateParameterList *TemplateParams
2393 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002394 if (TemplateParameterLists.size() > 1) {
2395 Diag(TemplateParams->getTemplateLoc(),
2396 diag::err_template_spec_extra_headers);
2397 return true;
2398 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002399
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002400 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002401 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002402
2403 // C++ [temp.class.spec]p10:
2404 // The template parameter list of a specialization shall not
2405 // contain default template argument values.
2406 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2407 Decl *Param = TemplateParams->getParam(I);
2408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2409 if (TTP->hasDefaultArgument()) {
2410 Diag(TTP->getDefaultArgumentLoc(),
2411 diag::err_default_arg_in_partial_spec);
2412 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2413 }
2414 } else if (NonTypeTemplateParmDecl *NTTP
2415 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2416 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2417 Diag(NTTP->getDefaultArgumentLoc(),
2418 diag::err_default_arg_in_partial_spec)
2419 << DefArg->getSourceRange();
2420 NTTP->setDefaultArgument(0);
2421 DefArg->Destroy(Context);
2422 }
2423 } else {
2424 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2425 if (Expr *DefArg = TTP->getDefaultArgument()) {
2426 Diag(TTP->getDefaultArgumentLoc(),
2427 diag::err_default_arg_in_partial_spec)
2428 << DefArg->getSourceRange();
2429 TTP->setDefaultArgument(0);
2430 DefArg->Destroy(Context);
2431 }
2432 }
2433 }
2434 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002435 }
2436
Douglas Gregora08b6c72009-02-17 23:15:12 +00002437 // Check that the specialization uses the same tag kind as the
2438 // original template.
2439 TagDecl::TagKind Kind;
2440 switch (TagSpec) {
2441 default: assert(0 && "Unknown tag type!");
2442 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2443 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2444 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2445 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002446 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2447 Kind, KWLoc,
2448 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002449 Diag(KWLoc, diag::err_use_with_wrong_tag)
2450 << ClassTemplate
2451 << CodeModificationHint::CreateReplacement(KWLoc,
2452 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002453 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2454 diag::note_previous_use);
2455 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2456 }
2457
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002458 // Translate the parser's template argument list in our AST format.
2459 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2460 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2461
Douglas Gregora08b6c72009-02-17 23:15:12 +00002462 // Check that the template argument list is well-formed for this
2463 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002464 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2465 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002466 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002467 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002468 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002469 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002470
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002471 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002472 ClassTemplate->getTemplateParameters()->size()) &&
2473 "Converted template argument list is too short!");
2474
Douglas Gregor58944ac2009-05-31 09:31:02 +00002475 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002476 // corresponds to these arguments.
2477 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002478 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002479 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002480 if (CheckClassTemplatePartialSpecializationArgs(
2481 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002482 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002483 return true;
2484
Douglas Gregor42476442009-06-12 22:08:06 +00002485 if (MirrorsPrimaryTemplate) {
2486 // C++ [temp.class.spec]p9b3:
2487 //
2488 // -- The argument list of the specialization shall not be identical
2489 // to the implicit argument list of the primary template.
2490 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2491 << (TK == TK_Definition)
2492 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2493 RAngleLoc));
2494 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2495 ClassTemplate->getIdentifier(),
2496 TemplateNameLoc,
2497 Attr,
2498 move(TemplateParameterLists),
2499 AS_none);
2500 }
2501
Douglas Gregor58944ac2009-05-31 09:31:02 +00002502 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002503 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002504 Converted.getFlatArguments(),
2505 Converted.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002506 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002507 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002508 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002509 Converted.getFlatArguments(),
2510 Converted.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002511 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002512 ClassTemplateSpecializationDecl *PrevDecl = 0;
2513
2514 if (isPartialSpecialization)
2515 PrevDecl
2516 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2517 InsertPos);
2518 else
2519 PrevDecl
2520 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002521
2522 ClassTemplateSpecializationDecl *Specialization = 0;
2523
Douglas Gregor0d93f692009-02-25 22:02:03 +00002524 // Check whether we can declare a class template specialization in
2525 // the current scope.
2526 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2527 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002528 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002529 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002530 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002531 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002532
Douglas Gregora08b6c72009-02-17 23:15:12 +00002533 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2534 // Since the only prior class template specialization with these
2535 // arguments was referenced but not declared, reuse that
2536 // declaration node as our own, updating its source location to
2537 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002538 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002539 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002540 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002541 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002542 // Create a new class template partial specialization declaration node.
2543 TemplateParameterList *TemplateParams
2544 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2545 ClassTemplatePartialSpecializationDecl *PrevPartial
2546 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2547 ClassTemplatePartialSpecializationDecl *Partial
2548 = ClassTemplatePartialSpecializationDecl::Create(Context,
2549 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002550 TemplateNameLoc,
2551 TemplateParams,
2552 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002553 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002554 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002555
2556 if (PrevPartial) {
2557 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2558 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2559 } else {
2560 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2561 }
2562 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002563
2564 // Check that all of the template parameters of the class template
2565 // partial specialization are deducible from the template
2566 // arguments. If not, this class template partial specialization
2567 // will never be used.
2568 llvm::SmallVector<bool, 8> DeducibleParams;
2569 DeducibleParams.resize(TemplateParams->size());
2570 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2571 unsigned NumNonDeducible = 0;
2572 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2573 if (!DeducibleParams[I])
2574 ++NumNonDeducible;
2575
2576 if (NumNonDeducible) {
2577 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2578 << (NumNonDeducible > 1)
2579 << SourceRange(TemplateNameLoc, RAngleLoc);
2580 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2581 if (!DeducibleParams[I]) {
2582 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2583 if (Param->getDeclName())
2584 Diag(Param->getLocation(),
2585 diag::note_partial_spec_unused_parameter)
2586 << Param->getDeclName();
2587 else
2588 Diag(Param->getLocation(),
2589 diag::note_partial_spec_unused_parameter)
2590 << std::string("<anonymous>");
2591 }
2592 }
2593 }
2594
Douglas Gregora08b6c72009-02-17 23:15:12 +00002595 } else {
2596 // Create a new class template specialization declaration node for
2597 // this explicit specialization.
2598 Specialization
2599 = ClassTemplateSpecializationDecl::Create(Context,
2600 ClassTemplate->getDeclContext(),
2601 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002602 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002603 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002604 PrevDecl);
2605
2606 if (PrevDecl) {
2607 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2608 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2609 } else {
2610 ClassTemplate->getSpecializations().InsertNode(Specialization,
2611 InsertPos);
2612 }
2613 }
2614
2615 // Note that this is an explicit specialization.
2616 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2617
2618 // Check that this isn't a redefinition of this specialization.
2619 if (TK == TK_Definition) {
2620 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002621 // FIXME: Should also handle explicit specialization after implicit
2622 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002623 SourceRange Range(TemplateNameLoc, RAngleLoc);
2624 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002625 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002626 Diag(Def->getLocation(), diag::note_previous_definition);
2627 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002628 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002629 }
2630 }
2631
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002632 // Build the fully-sugared type for this class template
2633 // specialization as the user wrote in the specialization
2634 // itself. This means that we'll pretty-print the type retrieved
2635 // from the specialization's declaration the way that the user
2636 // actually wrote the specialization, rather than formatting the
2637 // name based on the "canonical" representation used to store the
2638 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002639 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002640 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002641 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002642 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002643 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002644 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002645 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002646
Douglas Gregor50113ca2009-02-25 22:18:32 +00002647 // C++ [temp.expl.spec]p9:
2648 // A template explicit specialization is in the scope of the
2649 // namespace in which the template was defined.
2650 //
2651 // We actually implement this paragraph where we set the semantic
2652 // context (in the creation of the ClassTemplateSpecializationDecl),
2653 // but we also maintain the lexical context where the actual
2654 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002655 Specialization->setLexicalDeclContext(CurContext);
2656
2657 // We may be starting the definition of this specialization.
2658 if (TK == TK_Definition)
2659 Specialization->startDefinition();
2660
2661 // Add the specialization into its lexical context, so that it can
2662 // be seen when iterating through the list of declarations in that
2663 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002664 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002665 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002666}
Douglas Gregord3022602009-03-27 23:10:48 +00002667
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002668Sema::DeclPtrTy
2669Sema::ActOnTemplateDeclarator(Scope *S,
2670 MultiTemplateParamsArg TemplateParameterLists,
2671 Declarator &D) {
2672 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2673}
2674
Douglas Gregor19d10652009-06-24 00:54:41 +00002675Sema::DeclPtrTy
2676Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2677 MultiTemplateParamsArg TemplateParameterLists,
2678 Declarator &D) {
2679 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2680 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2681 "Not a function declarator!");
2682 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2683
2684 if (FTI.hasPrototype) {
2685 // FIXME: Diagnose arguments without names in C.
2686 }
2687
2688 Scope *ParentScope = FnBodyScope->getParent();
2689
2690 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2691 move(TemplateParameterLists),
2692 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002693 if (FunctionTemplateDecl *FunctionTemplate
2694 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002695 return ActOnStartOfFunctionDef(FnBodyScope,
2696 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002697 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2698 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002699 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002700}
2701
Douglas Gregor96b6df92009-05-14 00:28:11 +00002702// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002703Sema::DeclResult
2704Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2705 unsigned TagSpec,
2706 SourceLocation KWLoc,
2707 const CXXScopeSpec &SS,
2708 TemplateTy TemplateD,
2709 SourceLocation TemplateNameLoc,
2710 SourceLocation LAngleLoc,
2711 ASTTemplateArgsPtr TemplateArgsIn,
2712 SourceLocation *TemplateArgLocs,
2713 SourceLocation RAngleLoc,
2714 AttributeList *Attr) {
2715 // Find the class template we're specializing
2716 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2717 ClassTemplateDecl *ClassTemplate
2718 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2719
2720 // Check that the specialization uses the same tag kind as the
2721 // original template.
2722 TagDecl::TagKind Kind;
2723 switch (TagSpec) {
2724 default: assert(0 && "Unknown tag type!");
2725 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2726 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2727 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2728 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002729 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2730 Kind, KWLoc,
2731 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002732 Diag(KWLoc, diag::err_use_with_wrong_tag)
2733 << ClassTemplate
2734 << CodeModificationHint::CreateReplacement(KWLoc,
2735 ClassTemplate->getTemplatedDecl()->getKindName());
2736 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2737 diag::note_previous_use);
2738 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2739 }
2740
Douglas Gregor90177912009-05-13 18:28:20 +00002741 // C++0x [temp.explicit]p2:
2742 // [...] An explicit instantiation shall appear in an enclosing
2743 // namespace of its template. [...]
2744 //
2745 // This is C++ DR 275.
2746 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2747 TemplateNameLoc,
2748 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002749 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002750 /*ExplicitInstantiation=*/true))
2751 return true;
2752
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002753 // Translate the parser's template argument list in our AST format.
2754 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2755 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2756
2757 // Check that the template argument list is well-formed for this
2758 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002759 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2760 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002761 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002762 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002763 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002764 return true;
2765
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002766 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002767 ClassTemplate->getTemplateParameters()->size()) &&
2768 "Converted template argument list is too short!");
2769
2770 // Find the class template specialization declaration that
2771 // corresponds to these arguments.
2772 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002773 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002774 Converted.getFlatArguments(),
2775 Converted.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002776 void *InsertPos = 0;
2777 ClassTemplateSpecializationDecl *PrevDecl
2778 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2779
2780 ClassTemplateSpecializationDecl *Specialization = 0;
2781
Douglas Gregor90177912009-05-13 18:28:20 +00002782 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002783 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002784 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002785 // This particular specialization has already been declared or
2786 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002787 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2788 << Context.getTypeDeclType(PrevDecl);
2789 Diag(PrevDecl->getLocation(),
2790 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002791 return DeclPtrTy::make(PrevDecl);
2792 }
2793
Douglas Gregor90177912009-05-13 18:28:20 +00002794 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002795 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002796 // For a given set of template parameters, if an explicit
2797 // instantiation of a template appears after a declaration of
2798 // an explicit specialization for that template, the explicit
2799 // instantiation has no effect.
2800 if (!getLangOptions().CPlusPlus0x) {
2801 Diag(TemplateNameLoc,
2802 diag::ext_explicit_instantiation_after_specialization)
2803 << Context.getTypeDeclType(PrevDecl);
2804 Diag(PrevDecl->getLocation(),
2805 diag::note_previous_template_specialization);
2806 }
2807
2808 // Create a new class template specialization declaration node
2809 // for this explicit specialization. This node is only used to
2810 // record the existence of this explicit instantiation for
2811 // accurate reproduction of the source code; we don't actually
2812 // use it for anything, since it is semantically irrelevant.
2813 Specialization
2814 = ClassTemplateSpecializationDecl::Create(Context,
2815 ClassTemplate->getDeclContext(),
2816 TemplateNameLoc,
2817 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002818 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002819 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002820 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002821 return DeclPtrTy::make(Specialization);
2822 }
2823
2824 // If we have already (implicitly) instantiated this
2825 // specialization, there is less work to do.
2826 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2827 SpecializationRequiresInstantiation = false;
2828
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002829 // Since the only prior class template specialization with these
2830 // arguments was referenced but not declared, reuse that
2831 // declaration node as our own, updating its source location to
2832 // reflect our new declaration.
2833 Specialization = PrevDecl;
2834 Specialization->setLocation(TemplateNameLoc);
2835 PrevDecl = 0;
2836 } else {
2837 // Create a new class template specialization declaration node for
2838 // this explicit specialization.
2839 Specialization
2840 = ClassTemplateSpecializationDecl::Create(Context,
2841 ClassTemplate->getDeclContext(),
2842 TemplateNameLoc,
2843 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002844 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002845
2846 ClassTemplate->getSpecializations().InsertNode(Specialization,
2847 InsertPos);
2848 }
2849
2850 // Build the fully-sugared type for this explicit instantiation as
2851 // the user wrote in the explicit instantiation itself. This means
2852 // that we'll pretty-print the type retrieved from the
2853 // specialization's declaration the way that the user actually wrote
2854 // the explicit instantiation, rather than formatting the name based
2855 // on the "canonical" representation used to store the template
2856 // arguments in the specialization.
2857 QualType WrittenTy
2858 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002859 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002860 TemplateArgs.size(),
2861 Context.getTypeDeclType(Specialization));
2862 Specialization->setTypeAsWritten(WrittenTy);
2863 TemplateArgsIn.release();
2864
2865 // Add the explicit instantiation into its lexical context. However,
2866 // since explicit instantiations are never found by name lookup, we
2867 // just put it into the declaration context directly.
2868 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002869 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002870
2871 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002872 // A definition of a class template or class member template
2873 // shall be in scope at the point of the explicit instantiation of
2874 // the class template or class member template.
2875 //
2876 // This check comes when we actually try to perform the
2877 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002878 if (SpecializationRequiresInstantiation)
2879 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002880 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002881 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002882
2883 return DeclPtrTy::make(Specialization);
2884}
2885
Douglas Gregor96b6df92009-05-14 00:28:11 +00002886// Explicit instantiation of a member class of a class template.
2887Sema::DeclResult
2888Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2889 unsigned TagSpec,
2890 SourceLocation KWLoc,
2891 const CXXScopeSpec &SS,
2892 IdentifierInfo *Name,
2893 SourceLocation NameLoc,
2894 AttributeList *Attr) {
2895
Douglas Gregor71f06032009-05-28 23:31:59 +00002896 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002897 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor84a20812009-07-22 23:48:44 +00002898 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2899 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002900 if (!TagD)
2901 return true;
2902
2903 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2904 if (Tag->isEnum()) {
2905 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2906 << Context.getTypeDeclType(Tag);
2907 return true;
2908 }
2909
Douglas Gregord769bfa2009-05-27 17:30:49 +00002910 if (Tag->isInvalidDecl())
2911 return true;
2912
Douglas Gregor96b6df92009-05-14 00:28:11 +00002913 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2914 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2915 if (!Pattern) {
2916 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2917 << Context.getTypeDeclType(Record);
2918 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2919 return true;
2920 }
2921
2922 // C++0x [temp.explicit]p2:
2923 // [...] An explicit instantiation shall appear in an enclosing
2924 // namespace of its template. [...]
2925 //
2926 // This is C++ DR 275.
2927 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002928 // FIXME: In C++98, we would like to turn these errors into warnings,
2929 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002930 DeclContext *PatternContext
2931 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2932 if (!CurContext->Encloses(PatternContext)) {
2933 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2934 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2935 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2936 }
2937 }
2938
Douglas Gregor96b6df92009-05-14 00:28:11 +00002939 if (!Record->getDefinition(Context)) {
2940 // If the class has a definition, instantiate it (and all of its
2941 // members, recursively).
2942 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2943 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002944 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002945 /*ExplicitInstantiation=*/true))
2946 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002947 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002948 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002949 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002950
Mike Stumpe127ae32009-05-16 07:39:55 +00002951 // FIXME: We don't have any representation for explicit instantiations of
2952 // member classes. Such a representation is not needed for compilation, but it
2953 // should be available for clients that want to see all of the declarations in
2954 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002955 return TagD;
2956}
2957
Douglas Gregord3022602009-03-27 23:10:48 +00002958Sema::TypeResult
2959Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2960 const IdentifierInfo &II, SourceLocation IdLoc) {
2961 NestedNameSpecifier *NNS
2962 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2963 if (!NNS)
2964 return true;
2965
2966 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002967 if (T.isNull())
2968 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002969 return T.getAsOpaquePtr();
2970}
2971
Douglas Gregor77da5802009-04-01 00:28:59 +00002972Sema::TypeResult
2973Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2974 SourceLocation TemplateLoc, TypeTy *Ty) {
2975 QualType T = QualType::getFromOpaquePtr(Ty);
2976 NestedNameSpecifier *NNS
2977 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2978 const TemplateSpecializationType *TemplateId
2979 = T->getAsTemplateSpecializationType();
2980 assert(TemplateId && "Expected a template specialization type");
2981
2982 if (NNS->isDependent())
2983 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2984
2985 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2986}
2987
Douglas Gregord3022602009-03-27 23:10:48 +00002988/// \brief Build the type that describes a C++ typename specifier,
2989/// e.g., "typename T::type".
2990QualType
2991Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2992 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002993 CXXRecordDecl *CurrentInstantiation = 0;
2994 if (NNS->isDependent()) {
2995 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002996
Douglas Gregor3eb20702009-05-11 19:58:34 +00002997 // If the nested-name-specifier does not refer to the current
2998 // instantiation, then build a typename type.
2999 if (!CurrentInstantiation)
3000 return Context.getTypenameType(NNS, &II);
3001 }
Douglas Gregord3022602009-03-27 23:10:48 +00003002
Douglas Gregor3eb20702009-05-11 19:58:34 +00003003 DeclContext *Ctx = 0;
3004
3005 if (CurrentInstantiation)
3006 Ctx = CurrentInstantiation;
3007 else {
3008 CXXScopeSpec SS;
3009 SS.setScopeRep(NNS);
3010 SS.setRange(Range);
3011 if (RequireCompleteDeclContext(SS))
3012 return QualType();
3013
3014 Ctx = computeDeclContext(SS);
3015 }
Douglas Gregord3022602009-03-27 23:10:48 +00003016 assert(Ctx && "No declaration context?");
3017
3018 DeclarationName Name(&II);
3019 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3020 false);
3021 unsigned DiagID = 0;
3022 Decl *Referenced = 0;
3023 switch (Result.getKind()) {
3024 case LookupResult::NotFound:
3025 if (Ctx->isTranslationUnit())
3026 DiagID = diag::err_typename_nested_not_found_global;
3027 else
3028 DiagID = diag::err_typename_nested_not_found;
3029 break;
3030
3031 case LookupResult::Found:
3032 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3033 // We found a type. Build a QualifiedNameType, since the
3034 // typename-specifier was just sugar. FIXME: Tell
3035 // QualifiedNameType that it has a "typename" prefix.
3036 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3037 }
3038
3039 DiagID = diag::err_typename_nested_not_type;
3040 Referenced = Result.getAsDecl();
3041 break;
3042
3043 case LookupResult::FoundOverloaded:
3044 DiagID = diag::err_typename_nested_not_type;
3045 Referenced = *Result.begin();
3046 break;
3047
3048 case LookupResult::AmbiguousBaseSubobjectTypes:
3049 case LookupResult::AmbiguousBaseSubobjects:
3050 case LookupResult::AmbiguousReference:
3051 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3052 return QualType();
3053 }
3054
3055 // If we get here, it's because name lookup did not find a
3056 // type. Emit an appropriate diagnostic and return an error.
3057 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3058 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3059 else
3060 Diag(Range.getEnd(), DiagID) << Range << Name;
3061 if (Referenced)
3062 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3063 << Name;
3064 return QualType();
3065}