blob: a55c956a2af586bf08530e7bb983bad8350b1b6b [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);
1083
1084 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1085 TemplateArgs.data(), TemplateArgs.size(),
1086 RAngleLoc);
1087}
1088
Douglas Gregoraabb8502009-03-31 00:43:58 +00001089/// \brief Form a dependent template name.
1090///
1091/// This action forms a dependent template name given the template
1092/// name and its (presumably dependent) scope specifier. For
1093/// example, given "MetaFun::template apply", the scope specifier \p
1094/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1095/// of the "template" keyword, and "apply" is the \p Name.
1096Sema::TemplateTy
1097Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1098 const IdentifierInfo &Name,
1099 SourceLocation NameLoc,
1100 const CXXScopeSpec &SS) {
1101 if (!SS.isSet() || SS.isInvalid())
1102 return TemplateTy();
1103
1104 NestedNameSpecifier *Qualifier
1105 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1106
1107 // FIXME: member of the current instantiation
1108
1109 if (!Qualifier->isDependent()) {
1110 // C++0x [temp.names]p5:
1111 // If a name prefixed by the keyword template is not the name of
1112 // a template, the program is ill-formed. [Note: the keyword
1113 // template may not be applied to non-template members of class
1114 // templates. -end note ] [ Note: as is the case with the
1115 // typename prefix, the template prefix is allowed in cases
1116 // where it is not strictly necessary; i.e., when the
1117 // nested-name-specifier or the expression on the left of the ->
1118 // or . is not dependent on a template-parameter, or the use
1119 // does not appear in the scope of a template. -end note]
1120 //
1121 // Note: C++03 was more strict here, because it banned the use of
1122 // the "template" keyword prior to a template-name that was not a
1123 // dependent name. C++ DR468 relaxed this requirement (the
1124 // "template" keyword is now permitted). We follow the C++0x
1125 // rules, even in C++03 mode, retroactively applying the DR.
1126 TemplateTy Template;
1127 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1128 if (TNK == TNK_Non_template) {
1129 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1130 << &Name;
1131 return TemplateTy();
1132 }
1133
1134 return Template;
1135 }
1136
1137 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1138}
1139
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001140bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1141 const TemplateArgument &Arg,
1142 TemplateArgumentListBuilder &Converted) {
1143 // Check template type parameter.
1144 if (Arg.getKind() != TemplateArgument::Type) {
1145 // C++ [temp.arg.type]p1:
1146 // A template-argument for a template-parameter which is a
1147 // type shall be a type-id.
1148
1149 // We have a template type parameter but the template argument
1150 // is not a type.
1151 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1152 Diag(Param->getLocation(), diag::note_template_param_here);
1153
1154 return true;
1155 }
1156
1157 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1158 return true;
1159
1160 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001161 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001162 TemplateArgument(Arg.getLocation(),
1163 Context.getCanonicalType(Arg.getAsType())));
1164 return false;
1165}
1166
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001167/// \brief Check that the given template argument list is well-formed
1168/// for specializing the given template.
1169bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1170 SourceLocation TemplateLoc,
1171 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001172 const TemplateArgument *TemplateArgs,
1173 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001174 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001175 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001176 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001177 TemplateParameterList *Params = Template->getTemplateParameters();
1178 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001179 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001180 bool Invalid = false;
1181
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001182 bool HasParameterPack =
1183 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1184
1185 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001186 (NumArgs < Params->getMinRequiredArguments() &&
1187 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001188 // FIXME: point at either the first arg beyond what we can handle,
1189 // or the '>', depending on whether we have too many or too few
1190 // arguments.
1191 SourceRange Range;
1192 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001193 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001194 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1195 << (NumArgs > NumParams)
1196 << (isa<ClassTemplateDecl>(Template)? 0 :
1197 isa<FunctionTemplateDecl>(Template)? 1 :
1198 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1199 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001200 Diag(Template->getLocation(), diag::note_template_decl_here)
1201 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001202 Invalid = true;
1203 }
1204
1205 // C++ [temp.arg]p1:
1206 // [...] The type and form of each template-argument specified in
1207 // a template-id shall match the type and form specified for the
1208 // corresponding parameter declared by the template in its
1209 // template-parameter-list.
1210 unsigned ArgIdx = 0;
1211 for (TemplateParameterList::iterator Param = Params->begin(),
1212 ParamEnd = Params->end();
1213 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001214 if (ArgIdx > NumArgs && PartialTemplateArgs)
1215 break;
1216
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001217 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001218 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001219 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001220 // Retrieve the default template argument from the template
1221 // parameter.
1222 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001223 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001224 // We have an empty argument pack.
1225 Converted.BeginPack();
1226 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001227 break;
1228 }
1229
Douglas Gregorad964b32009-02-17 01:05:43 +00001230 if (!TTP->hasDefaultArgument())
1231 break;
1232
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001233 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001234
1235 // If the argument type is dependent, instantiate it now based
1236 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001237 if (ArgType->isDependentType()) {
1238 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001239 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001240 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001241 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001242
Anders Carlsson0233eb62009-06-05 04:47:51 +00001243 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001244 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001245 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001246 TTP->getDefaultArgumentLoc(),
1247 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001248 }
Douglas Gregor74296542009-02-27 19:31:52 +00001249
1250 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001251 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001252
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001253 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001254 } else if (NonTypeTemplateParmDecl *NTTP
1255 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1256 if (!NTTP->hasDefaultArgument())
1257 break;
1258
Anders Carlsson0297caf2009-06-11 16:06:49 +00001259 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001260 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001261 Converted.flatSize(),
1262 SourceRange(TemplateLoc, RAngleLoc));
1263
1264 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001265 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001266
1267 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1268 TemplateArgs);
1269 if (E.isInvalid())
1270 return true;
1271
1272 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001273 } else {
1274 TemplateTemplateParmDecl *TempParm
1275 = cast<TemplateTemplateParmDecl>(*Param);
1276
1277 if (!TempParm->hasDefaultArgument())
1278 break;
1279
Douglas Gregored3a3982009-03-03 04:44:36 +00001280 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001281 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001282 }
1283 } else {
1284 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001285 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001286 }
1287
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001288
1289 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001290 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001291 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001292 // Check all the remaining arguments (if any).
1293 for (; ArgIdx < NumArgs; ++ArgIdx) {
1294 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1295 Invalid = true;
1296 }
1297
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001298 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001299 } else {
1300 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1301 Invalid = true;
1302 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001303 } else if (NonTypeTemplateParmDecl *NTTP
1304 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1305 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001306
1307 // Instantiate the type of the non-type template parameter with
1308 // the template arguments we've seen thus far.
1309 QualType NTTPType = NTTP->getType();
1310 if (NTTPType->isDependentType()) {
1311 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001312 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001313 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001314 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001315 SourceRange(TemplateLoc, RAngleLoc));
1316
Anders Carlsson0233eb62009-06-05 04:47:51 +00001317 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001318 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001319 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001320 NTTP->getLocation(),
1321 NTTP->getDeclName());
1322 // If that worked, check the non-type template parameter type
1323 // for validity.
1324 if (!NTTPType.isNull())
1325 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1326 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001327 if (NTTPType.isNull()) {
1328 Invalid = true;
1329 break;
1330 }
1331 }
1332
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001333 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001334 case TemplateArgument::Null:
1335 assert(false && "Should never see a NULL template argument here");
1336 break;
1337
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001338 case TemplateArgument::Expression: {
1339 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001340 TemplateArgument Result;
1341 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001342 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001343 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001344 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001345 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001346 }
1347
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001348 case TemplateArgument::Declaration:
1349 case TemplateArgument::Integral:
1350 // We've already checked this template argument, so just copy
1351 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001352 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001353 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001354
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001355 case TemplateArgument::Type:
1356 // We have a non-type template parameter but the template
1357 // argument is a type.
1358
1359 // C++ [temp.arg]p2:
1360 // In a template-argument, an ambiguity between a type-id and
1361 // an expression is resolved to a type-id, regardless of the
1362 // form of the corresponding template-parameter.
1363 //
1364 // We warn specifically about this case, since it can be rather
1365 // confusing for users.
1366 if (Arg.getAsType()->isFunctionType())
1367 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1368 << Arg.getAsType();
1369 else
1370 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1371 Diag((*Param)->getLocation(), diag::note_template_param_here);
1372 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001373 break;
1374
1375 case TemplateArgument::Pack:
1376 assert(0 && "FIXME: Implement!");
1377 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001378 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001379 } else {
1380 // Check template template parameters.
1381 TemplateTemplateParmDecl *TempParm
1382 = cast<TemplateTemplateParmDecl>(*Param);
1383
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001384 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001385 case TemplateArgument::Null:
1386 assert(false && "Should never see a NULL template argument here");
1387 break;
1388
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001389 case TemplateArgument::Expression: {
1390 Expr *ArgExpr = Arg.getAsExpr();
1391 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1392 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1393 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1394 Invalid = true;
1395
1396 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001397 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001398 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001399 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001400 continue;
1401 }
1402 }
1403 // fall through
1404
1405 case TemplateArgument::Type: {
1406 // We have a template template parameter but the template
1407 // argument does not refer to a template.
1408 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1409 Invalid = true;
1410 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001411 }
1412
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001413 case TemplateArgument::Declaration:
1414 // We've already checked this template argument, so just copy
1415 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001416 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001417 break;
1418
1419 case TemplateArgument::Integral:
1420 assert(false && "Integral argument with template template parameter");
1421 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001422
1423 case TemplateArgument::Pack:
1424 assert(0 && "FIXME: Implement!");
1425 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001426 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001427 }
1428 }
1429
1430 return Invalid;
1431}
1432
1433/// \brief Check a template argument against its corresponding
1434/// template type parameter.
1435///
1436/// This routine implements the semantics of C++ [temp.arg.type]. It
1437/// returns true if an error occurred, and false otherwise.
1438bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1439 QualType Arg, SourceLocation ArgLoc) {
1440 // C++ [temp.arg.type]p2:
1441 // A local type, a type with no linkage, an unnamed type or a type
1442 // compounded from any of these types shall not be used as a
1443 // template-argument for a template type-parameter.
1444 //
1445 // FIXME: Perform the recursive and no-linkage type checks.
1446 const TagType *Tag = 0;
1447 if (const EnumType *EnumT = Arg->getAsEnumType())
1448 Tag = EnumT;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001449 else if (const RecordType *RecordT = Arg->getAsRecordType())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001450 Tag = RecordT;
1451 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1452 return Diag(ArgLoc, diag::err_template_arg_local_type)
1453 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001454 else if (Tag && !Tag->getDecl()->getDeclName() &&
1455 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001456 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1457 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1458 return true;
1459 }
1460
1461 return false;
1462}
1463
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001464/// \brief Checks whether the given template argument is the address
1465/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001466bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1467 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001468 bool Invalid = false;
1469
1470 // See through any implicit casts we added to fix the type.
1471 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1472 Arg = Cast->getSubExpr();
1473
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001474 // C++0x allows nullptr, and there's no further checking to be done for that.
1475 if (Arg->getType()->isNullPtrType())
1476 return false;
1477
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001478 // C++ [temp.arg.nontype]p1:
1479 //
1480 // A template-argument for a non-type, non-template
1481 // template-parameter shall be one of: [...]
1482 //
1483 // -- the address of an object or function with external
1484 // linkage, including function templates and function
1485 // template-ids but excluding non-static class members,
1486 // expressed as & id-expression where the & is optional if
1487 // the name refers to a function or array, or if the
1488 // corresponding template-parameter is a reference; or
1489 DeclRefExpr *DRE = 0;
1490
1491 // Ignore (and complain about) any excess parentheses.
1492 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1493 if (!Invalid) {
1494 Diag(Arg->getSourceRange().getBegin(),
1495 diag::err_template_arg_extra_parens)
1496 << Arg->getSourceRange();
1497 Invalid = true;
1498 }
1499
1500 Arg = Parens->getSubExpr();
1501 }
1502
1503 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1504 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1505 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1506 } else
1507 DRE = dyn_cast<DeclRefExpr>(Arg);
1508
1509 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1510 return Diag(Arg->getSourceRange().getBegin(),
1511 diag::err_template_arg_not_object_or_func_form)
1512 << Arg->getSourceRange();
1513
1514 // Cannot refer to non-static data members
1515 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1516 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1517 << Field << Arg->getSourceRange();
1518
1519 // Cannot refer to non-static member functions
1520 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1521 if (!Method->isStatic())
1522 return Diag(Arg->getSourceRange().getBegin(),
1523 diag::err_template_arg_method)
1524 << Method << Arg->getSourceRange();
1525
1526 // Functions must have external linkage.
1527 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1528 if (Func->getStorageClass() == FunctionDecl::Static) {
1529 Diag(Arg->getSourceRange().getBegin(),
1530 diag::err_template_arg_function_not_extern)
1531 << Func << Arg->getSourceRange();
1532 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1533 << true;
1534 return true;
1535 }
1536
1537 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001538 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001539 return Invalid;
1540 }
1541
1542 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1543 if (!Var->hasGlobalStorage()) {
1544 Diag(Arg->getSourceRange().getBegin(),
1545 diag::err_template_arg_object_not_extern)
1546 << Var << Arg->getSourceRange();
1547 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1548 << true;
1549 return true;
1550 }
1551
1552 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001553 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001554 return Invalid;
1555 }
1556
1557 // We found something else, but we don't know specifically what it is.
1558 Diag(Arg->getSourceRange().getBegin(),
1559 diag::err_template_arg_not_object_or_func)
1560 << Arg->getSourceRange();
1561 Diag(DRE->getDecl()->getLocation(),
1562 diag::note_template_arg_refers_here);
1563 return true;
1564}
1565
1566/// \brief Checks whether the given template argument is a pointer to
1567/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001568bool
1569Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001570 bool Invalid = false;
1571
1572 // See through any implicit casts we added to fix the type.
1573 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1574 Arg = Cast->getSubExpr();
1575
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001576 // C++0x allows nullptr, and there's no further checking to be done for that.
1577 if (Arg->getType()->isNullPtrType())
1578 return false;
1579
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001580 // C++ [temp.arg.nontype]p1:
1581 //
1582 // A template-argument for a non-type, non-template
1583 // template-parameter shall be one of: [...]
1584 //
1585 // -- a pointer to member expressed as described in 5.3.1.
1586 QualifiedDeclRefExpr *DRE = 0;
1587
1588 // Ignore (and complain about) any excess parentheses.
1589 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1590 if (!Invalid) {
1591 Diag(Arg->getSourceRange().getBegin(),
1592 diag::err_template_arg_extra_parens)
1593 << Arg->getSourceRange();
1594 Invalid = true;
1595 }
1596
1597 Arg = Parens->getSubExpr();
1598 }
1599
1600 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1601 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1602 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1603
1604 if (!DRE)
1605 return Diag(Arg->getSourceRange().getBegin(),
1606 diag::err_template_arg_not_pointer_to_member_form)
1607 << Arg->getSourceRange();
1608
1609 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1610 assert((isa<FieldDecl>(DRE->getDecl()) ||
1611 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1612 "Only non-static member pointers can make it here");
1613
1614 // Okay: this is the address of a non-static member, and therefore
1615 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001616 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001617 return Invalid;
1618 }
1619
1620 // We found something else, but we don't know specifically what it is.
1621 Diag(Arg->getSourceRange().getBegin(),
1622 diag::err_template_arg_not_pointer_to_member_form)
1623 << Arg->getSourceRange();
1624 Diag(DRE->getDecl()->getLocation(),
1625 diag::note_template_arg_refers_here);
1626 return true;
1627}
1628
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001629/// \brief Check a template argument against its corresponding
1630/// non-type template parameter.
1631///
Douglas Gregored3a3982009-03-03 04:44:36 +00001632/// This routine implements the semantics of C++ [temp.arg.nontype].
1633/// It returns true if an error occurred, and false otherwise. \p
1634/// InstantiatedParamType is the type of the non-type template
1635/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001636///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001637/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001638bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001639 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001640 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001641 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1642
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001643 // If either the parameter has a dependent type or the argument is
1644 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001645 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001646 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1647 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001648 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001649 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001650 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001651
1652 // C++ [temp.arg.nontype]p5:
1653 // The following conversions are performed on each expression used
1654 // as a non-type template-argument. If a non-type
1655 // template-argument cannot be converted to the type of the
1656 // corresponding template-parameter then the program is
1657 // ill-formed.
1658 //
1659 // -- for a non-type template-parameter of integral or
1660 // enumeration type, integral promotions (4.5) and integral
1661 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001662 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001663 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001664 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001665 // C++ [temp.arg.nontype]p1:
1666 // A template-argument for a non-type, non-template
1667 // template-parameter shall be one of:
1668 //
1669 // -- an integral constant-expression of integral or enumeration
1670 // type; or
1671 // -- the name of a non-type template-parameter; or
1672 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001673 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001674 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1675 Diag(Arg->getSourceRange().getBegin(),
1676 diag::err_template_arg_not_integral_or_enumeral)
1677 << ArgType << Arg->getSourceRange();
1678 Diag(Param->getLocation(), diag::note_template_param_here);
1679 return true;
1680 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001681 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001682 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1683 << ArgType << Arg->getSourceRange();
1684 return true;
1685 }
1686
1687 // FIXME: We need some way to more easily get the unqualified form
1688 // of the types without going all the way to the
1689 // canonical type.
1690 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1691 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1692 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1693 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1694
1695 // Try to convert the argument to the parameter's type.
1696 if (ParamType == ArgType) {
1697 // Okay: no conversion necessary
1698 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1699 !ParamType->isEnumeralType()) {
1700 // This is an integral promotion or conversion.
1701 ImpCastExprToType(Arg, ParamType);
1702 } else {
1703 // We can't perform this conversion.
1704 Diag(Arg->getSourceRange().getBegin(),
1705 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001706 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001707 Diag(Param->getLocation(), diag::note_template_param_here);
1708 return true;
1709 }
1710
Douglas Gregorafc86942009-03-14 00:20:21 +00001711 QualType IntegerType = Context.getCanonicalType(ParamType);
1712 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001713 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001714
1715 if (!Arg->isValueDependent()) {
1716 // Check that an unsigned parameter does not receive a negative
1717 // value.
1718 if (IntegerType->isUnsignedIntegerType()
1719 && (Value.isSigned() && Value.isNegative())) {
1720 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1721 << Value.toString(10) << Param->getType()
1722 << Arg->getSourceRange();
1723 Diag(Param->getLocation(), diag::note_template_param_here);
1724 return true;
1725 }
1726
1727 // Check that we don't overflow the template parameter type.
1728 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1729 if (Value.getActiveBits() > AllowedBits) {
1730 Diag(Arg->getSourceRange().getBegin(),
1731 diag::err_template_arg_too_large)
1732 << Value.toString(10) << Param->getType()
1733 << Arg->getSourceRange();
1734 Diag(Param->getLocation(), diag::note_template_param_here);
1735 return true;
1736 }
1737
1738 if (Value.getBitWidth() != AllowedBits)
1739 Value.extOrTrunc(AllowedBits);
1740 Value.setIsSigned(IntegerType->isSignedIntegerType());
1741 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001742
Douglas Gregor8f378a92009-06-11 18:10:32 +00001743 // Add the value of this argument to the list of converted
1744 // arguments. We use the bitwidth and signedness of the template
1745 // parameter.
1746 if (Arg->isValueDependent()) {
1747 // The argument is value-dependent. Create a new
1748 // TemplateArgument with the converted expression.
1749 Converted = TemplateArgument(Arg);
1750 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001751 }
1752
Douglas Gregor8f378a92009-06-11 18:10:32 +00001753 Converted = TemplateArgument(StartLoc, Value,
1754 ParamType->isEnumeralType() ? ParamType
1755 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001756 return false;
1757 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001758
Douglas Gregor3f411962009-02-11 01:18:59 +00001759 // Handle pointer-to-function, reference-to-function, and
1760 // pointer-to-member-function all in (roughly) the same way.
1761 if (// -- For a non-type template-parameter of type pointer to
1762 // function, only the function-to-pointer conversion (4.3) is
1763 // applied. If the template-argument represents a set of
1764 // overloaded functions (or a pointer to such), the matching
1765 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001766 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001767 (ParamType->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001768 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001769 // -- For a non-type template-parameter of type reference to
1770 // function, no conversions apply. If the template-argument
1771 // represents a set of overloaded functions, the matching
1772 // function is selected from the set (13.4).
1773 (ParamType->isReferenceType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001774 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001775 // -- For a non-type template-parameter of type pointer to
1776 // member function, no conversions apply. If the
1777 // template-argument represents a set of overloaded member
1778 // functions, the matching member function is selected from
1779 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001780 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001781 (ParamType->isMemberPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001782 ParamType->getAsMemberPointerType()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001783 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001784 if (Context.hasSameUnqualifiedType(ArgType,
1785 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001786 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001787 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1788 ParamType->isMemberPointerType())) {
1789 ArgType = ParamType;
1790 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001791 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001792 ArgType = Context.getPointerType(ArgType);
1793 ImpCastExprToType(Arg, ArgType);
1794 } else if (FunctionDecl *Fn
1795 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001796 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1797 return true;
1798
Douglas Gregor2eedd992009-02-11 00:19:33 +00001799 FixOverloadedFunctionReference(Arg, Fn);
1800 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001801 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001802 ArgType = Context.getPointerType(Arg->getType());
1803 ImpCastExprToType(Arg, ArgType);
1804 }
1805 }
1806
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001807 if (!Context.hasSameUnqualifiedType(ArgType,
1808 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001809 // We can't perform this conversion.
1810 Diag(Arg->getSourceRange().getBegin(),
1811 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001812 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001813 Diag(Param->getLocation(), diag::note_template_param_here);
1814 return true;
1815 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001816
Douglas Gregorad964b32009-02-17 01:05:43 +00001817 if (ParamType->isMemberPointerType()) {
1818 NamedDecl *Member = 0;
1819 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1820 return true;
1821
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001822 if (Member)
1823 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001824 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001825 return false;
1826 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001827
Douglas Gregorad964b32009-02-17 01:05:43 +00001828 NamedDecl *Entity = 0;
1829 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1830 return true;
1831
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001832 if (Entity)
1833 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001834 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001835 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001836 }
1837
Chris Lattner320dff22009-02-20 21:37:53 +00001838 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001839 // -- for a non-type template-parameter of type pointer to
1840 // object, qualification conversions (4.4) and the
1841 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001842 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001843 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001844 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001845
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001846 if (ArgType->isNullPtrType()) {
1847 ArgType = ParamType;
1848 ImpCastExprToType(Arg, ParamType);
1849 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001850 ArgType = Context.getArrayDecayedType(ArgType);
1851 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001852 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001853
Douglas Gregor3f411962009-02-11 01:18:59 +00001854 if (IsQualificationConversion(ArgType, ParamType)) {
1855 ArgType = ParamType;
1856 ImpCastExprToType(Arg, ParamType);
1857 }
1858
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001859 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001860 // We can't perform this conversion.
1861 Diag(Arg->getSourceRange().getBegin(),
1862 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001863 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001864 Diag(Param->getLocation(), diag::note_template_param_here);
1865 return true;
1866 }
1867
Douglas Gregorad964b32009-02-17 01:05:43 +00001868 NamedDecl *Entity = 0;
1869 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1870 return true;
1871
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001872 if (Entity)
1873 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001874 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001875 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001876 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001877
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001878 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001879 // -- For a non-type template-parameter of type reference to
1880 // object, no conversions apply. The type referred to by the
1881 // reference may be more cv-qualified than the (otherwise
1882 // identical) type of the template-argument. The
1883 // template-parameter is bound directly to the
1884 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001885 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001886 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001887
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001888 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001889 Diag(Arg->getSourceRange().getBegin(),
1890 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001891 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001892 << Arg->getSourceRange();
1893 Diag(Param->getLocation(), diag::note_template_param_here);
1894 return true;
1895 }
1896
1897 unsigned ParamQuals
1898 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1899 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1900
1901 if ((ParamQuals | ArgQuals) != ParamQuals) {
1902 Diag(Arg->getSourceRange().getBegin(),
1903 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001904 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001905 << Arg->getSourceRange();
1906 Diag(Param->getLocation(), diag::note_template_param_here);
1907 return true;
1908 }
1909
Douglas Gregorad964b32009-02-17 01:05:43 +00001910 NamedDecl *Entity = 0;
1911 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1912 return true;
1913
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001914 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001915 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001916 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001917 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001918
1919 // -- For a non-type template-parameter of type pointer to data
1920 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001921 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001922 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1923
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001924 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001925 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001926 } else if (ArgType->isNullPtrType()) {
1927 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001928 } else if (IsQualificationConversion(ArgType, ParamType)) {
1929 ImpCastExprToType(Arg, ParamType);
1930 } else {
1931 // We can't perform this conversion.
1932 Diag(Arg->getSourceRange().getBegin(),
1933 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001934 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001935 Diag(Param->getLocation(), diag::note_template_param_here);
1936 return true;
1937 }
1938
Douglas Gregorad964b32009-02-17 01:05:43 +00001939 NamedDecl *Member = 0;
1940 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1941 return true;
1942
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001943 if (Member)
1944 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001945 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001946 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001947}
1948
1949/// \brief Check a template argument against its corresponding
1950/// template template parameter.
1951///
1952/// This routine implements the semantics of C++ [temp.arg.template].
1953/// It returns true if an error occurred, and false otherwise.
1954bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1955 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001956 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1957 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1958
1959 // C++ [temp.arg.template]p1:
1960 // A template-argument for a template template-parameter shall be
1961 // the name of a class template, expressed as id-expression. Only
1962 // primary class templates are considered when matching the
1963 // template template argument with the corresponding parameter;
1964 // partial specializations are not considered even if their
1965 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001966 //
1967 // Note that we also allow template template parameters here, which
1968 // will happen when we are dealing with, e.g., class template
1969 // partial specializations.
1970 if (!isa<ClassTemplateDecl>(Template) &&
1971 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001972 assert(isa<FunctionTemplateDecl>(Template) &&
1973 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001974 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1975 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001976 << Template;
1977 }
1978
1979 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1980 Param->getTemplateParameters(),
1981 true, true,
1982 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001983}
1984
Douglas Gregord406b032009-02-06 22:42:48 +00001985/// \brief Determine whether the given template parameter lists are
1986/// equivalent.
1987///
1988/// \param New The new template parameter list, typically written in the
1989/// source code as part of a new template declaration.
1990///
1991/// \param Old The old template parameter list, typically found via
1992/// name lookup of the template declared with this template parameter
1993/// list.
1994///
1995/// \param Complain If true, this routine will produce a diagnostic if
1996/// the template parameter lists are not equivalent.
1997///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001998/// \param IsTemplateTemplateParm If true, this routine is being
1999/// called to compare the template parameter lists of a template
2000/// template parameter.
2001///
2002/// \param TemplateArgLoc If this source location is valid, then we
2003/// are actually checking the template parameter list of a template
2004/// argument (New) against the template parameter list of its
2005/// corresponding template template parameter (Old). We produce
2006/// slightly different diagnostics in this scenario.
2007///
Douglas Gregord406b032009-02-06 22:42:48 +00002008/// \returns True if the template parameter lists are equal, false
2009/// otherwise.
2010bool
2011Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2012 TemplateParameterList *Old,
2013 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002014 bool IsTemplateTemplateParm,
2015 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00002016 if (Old->size() != New->size()) {
2017 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002018 unsigned NextDiag = diag::err_template_param_list_different_arity;
2019 if (TemplateArgLoc.isValid()) {
2020 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2021 NextDiag = diag::note_template_param_list_different_arity;
2022 }
2023 Diag(New->getTemplateLoc(), NextDiag)
2024 << (New->size() > Old->size())
2025 << IsTemplateTemplateParm
2026 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00002027 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2028 << IsTemplateTemplateParm
2029 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2030 }
2031
2032 return false;
2033 }
2034
2035 for (TemplateParameterList::iterator OldParm = Old->begin(),
2036 OldParmEnd = Old->end(), NewParm = New->begin();
2037 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2038 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00002039 if (Complain) {
2040 unsigned NextDiag = diag::err_template_param_different_kind;
2041 if (TemplateArgLoc.isValid()) {
2042 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2043 NextDiag = diag::note_template_param_different_kind;
2044 }
2045 Diag((*NewParm)->getLocation(), NextDiag)
2046 << IsTemplateTemplateParm;
2047 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2048 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00002049 }
Douglas Gregord406b032009-02-06 22:42:48 +00002050 return false;
2051 }
2052
2053 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2054 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00002055 // know we're at the same index).
2056#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00002057 // FIXME: Enable this code in debug mode *after* we properly go through
2058 // and "instantiate" the template parameter lists of template template
2059 // parameters. It's only after this instantiation that (1) any dependent
2060 // types within the template parameter list of the template template
2061 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00002062 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00002063 QualType OldParmType
2064 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2065 QualType NewParmType
2066 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2067 assert(Context.getCanonicalType(OldParmType) ==
2068 Context.getCanonicalType(NewParmType) &&
2069 "type parameter mismatch?");
2070#endif
2071 } else if (NonTypeTemplateParmDecl *OldNTTP
2072 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2073 // The types of non-type template parameters must agree.
2074 NonTypeTemplateParmDecl *NewNTTP
2075 = cast<NonTypeTemplateParmDecl>(*NewParm);
2076 if (Context.getCanonicalType(OldNTTP->getType()) !=
2077 Context.getCanonicalType(NewNTTP->getType())) {
2078 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002079 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2080 if (TemplateArgLoc.isValid()) {
2081 Diag(TemplateArgLoc,
2082 diag::err_template_arg_template_params_mismatch);
2083 NextDiag = diag::note_template_nontype_parm_different_type;
2084 }
2085 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002086 << NewNTTP->getType()
2087 << IsTemplateTemplateParm;
2088 Diag(OldNTTP->getLocation(),
2089 diag::note_template_nontype_parm_prev_declaration)
2090 << OldNTTP->getType();
2091 }
2092 return false;
2093 }
2094 } else {
2095 // The template parameter lists of template template
2096 // parameters must agree.
2097 // FIXME: Could we perform a faster "type" comparison here?
2098 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2099 "Only template template parameters handled here");
2100 TemplateTemplateParmDecl *OldTTP
2101 = cast<TemplateTemplateParmDecl>(*OldParm);
2102 TemplateTemplateParmDecl *NewTTP
2103 = cast<TemplateTemplateParmDecl>(*NewParm);
2104 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2105 OldTTP->getTemplateParameters(),
2106 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002107 /*IsTemplateTemplateParm=*/true,
2108 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002109 return false;
2110 }
2111 }
2112
2113 return true;
2114}
2115
2116/// \brief Check whether a template can be declared within this scope.
2117///
2118/// If the template declaration is valid in this scope, returns
2119/// false. Otherwise, issues a diagnostic and returns true.
2120bool
2121Sema::CheckTemplateDeclScope(Scope *S,
2122 MultiTemplateParamsArg &TemplateParameterLists) {
2123 assert(TemplateParameterLists.size() > 0 && "Not a template");
2124
2125 // Find the nearest enclosing declaration scope.
2126 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2127 (S->getFlags() & Scope::TemplateParamScope) != 0)
2128 S = S->getParent();
2129
2130 TemplateParameterList *TemplateParams =
2131 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2132 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2133 SourceRange TemplateRange
2134 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2135
2136 // C++ [temp]p2:
2137 // A template-declaration can appear only as a namespace scope or
2138 // class scope declaration.
2139 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2140 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2141 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2142 return Diag(TemplateLoc, diag::err_template_linkage)
2143 << TemplateRange;
2144
2145 Ctx = Ctx->getParent();
2146 }
2147
2148 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2149 return false;
2150
2151 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2152 << TemplateRange;
2153}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002154
Douglas Gregor90177912009-05-13 18:28:20 +00002155/// \brief Check whether a class template specialization or explicit
2156/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002157///
Douglas Gregor90177912009-05-13 18:28:20 +00002158/// This routine determines whether a class template specialization or
2159/// explicit instantiation can be declared in the current context
2160/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2161/// appropriate diagnostics if there was an error. It returns true if
2162// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002163bool
2164Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2165 ClassTemplateSpecializationDecl *PrevDecl,
2166 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002167 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002168 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002169 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002170 // C++ [temp.expl.spec]p2:
2171 // An explicit specialization shall be declared in the namespace
2172 // of which the template is a member, or, for member templates, in
2173 // the namespace of which the enclosing class or enclosing class
2174 // template is a member. An explicit specialization of a member
2175 // function, member class or static data member of a class
2176 // template shall be declared in the namespace of which the class
2177 // template is a member. Such a declaration may also be a
2178 // definition. If the declaration is not a definition, the
2179 // specialization may be defined later in the name- space in which
2180 // the explicit specialization was declared, or in a namespace
2181 // that encloses the one in which the explicit specialization was
2182 // declared.
2183 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002184 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002185 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002186 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002187 return true;
2188 }
2189
2190 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2191 DeclContext *TemplateContext
2192 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002193 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2194 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002195 // There is no prior declaration of this entity, so this
2196 // specialization must be in the same context as the template
2197 // itself.
2198 if (DC != TemplateContext) {
2199 if (isa<TranslationUnitDecl>(TemplateContext))
2200 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002201 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002202 << ClassTemplate << ScopeSpecifierRange;
2203 else if (isa<NamespaceDecl>(TemplateContext))
2204 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002205 << PartialSpecialization << ClassTemplate
2206 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002207
2208 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2209 }
2210
2211 return false;
2212 }
2213
2214 // We have a previous declaration of this entity. Make sure that
2215 // this redeclaration (or definition) occurs in an enclosing namespace.
2216 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002217 // FIXME: In C++98, we would like to turn these errors into warnings,
2218 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002219 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002220 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002221 if (isa<TranslationUnitDecl>(TemplateContext)) {
2222 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2223 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002224 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002225 else
2226 SuppressedDiag = true;
2227 } else if (isa<NamespaceDecl>(TemplateContext)) {
2228 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2229 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002230 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002231 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2232 else
2233 SuppressedDiag = true;
2234 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002235
Douglas Gregor90177912009-05-13 18:28:20 +00002236 if (!SuppressedDiag)
2237 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002238 }
2239
2240 return false;
2241}
2242
Douglas Gregor76e79952009-06-12 21:21:02 +00002243/// \brief Check the non-type template arguments of a class template
2244/// partial specialization according to C++ [temp.class.spec]p9.
2245///
Douglas Gregor42476442009-06-12 22:08:06 +00002246/// \param TemplateParams the template parameters of the primary class
2247/// template.
2248///
2249/// \param TemplateArg the template arguments of the class template
2250/// partial specialization.
2251///
2252/// \param MirrorsPrimaryTemplate will be set true if the class
2253/// template partial specialization arguments are identical to the
2254/// implicit template arguments of the primary template. This is not
2255/// necessarily an error (C++0x), and it is left to the caller to diagnose
2256/// this condition when it is an error.
2257///
Douglas Gregor76e79952009-06-12 21:21:02 +00002258/// \returns true if there was an error, false otherwise.
2259bool Sema::CheckClassTemplatePartialSpecializationArgs(
2260 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002261 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002262 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002263 // FIXME: the interface to this function will have to change to
2264 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002265 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002266
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002267 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002268
Douglas Gregor76e79952009-06-12 21:21:02 +00002269 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002270 // Determine whether the template argument list of the partial
2271 // specialization is identical to the implicit argument list of
2272 // the primary template. The caller may need to diagnostic this as
2273 // an error per C++ [temp.class.spec]p9b3.
2274 if (MirrorsPrimaryTemplate) {
2275 if (TemplateTypeParmDecl *TTP
2276 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2277 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002278 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002279 MirrorsPrimaryTemplate = false;
2280 } else if (TemplateTemplateParmDecl *TTP
2281 = dyn_cast<TemplateTemplateParmDecl>(
2282 TemplateParams->getParam(I))) {
2283 // FIXME: We should settle on either Declaration storage or
2284 // Expression storage for template template parameters.
2285 TemplateTemplateParmDecl *ArgDecl
2286 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002287 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002288 if (!ArgDecl)
2289 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002290 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002291 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2292
2293 if (!ArgDecl ||
2294 ArgDecl->getIndex() != TTP->getIndex() ||
2295 ArgDecl->getDepth() != TTP->getDepth())
2296 MirrorsPrimaryTemplate = false;
2297 }
2298 }
2299
Douglas Gregor76e79952009-06-12 21:21:02 +00002300 NonTypeTemplateParmDecl *Param
2301 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002302 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002303 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002304 }
2305
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002306 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002307 if (!ArgExpr) {
2308 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002309 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002310 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002311
2312 // C++ [temp.class.spec]p8:
2313 // A non-type argument is non-specialized if it is the name of a
2314 // non-type parameter. All other non-type arguments are
2315 // specialized.
2316 //
2317 // Below, we check the two conditions that only apply to
2318 // specialized non-type arguments, so skip any non-specialized
2319 // arguments.
2320 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002321 if (NonTypeTemplateParmDecl *NTTP
2322 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2323 if (MirrorsPrimaryTemplate &&
2324 (Param->getIndex() != NTTP->getIndex() ||
2325 Param->getDepth() != NTTP->getDepth()))
2326 MirrorsPrimaryTemplate = false;
2327
Douglas Gregor76e79952009-06-12 21:21:02 +00002328 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002329 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002330
2331 // C++ [temp.class.spec]p9:
2332 // Within the argument list of a class template partial
2333 // specialization, the following restrictions apply:
2334 // -- A partially specialized non-type argument expression
2335 // shall not involve a template parameter of the partial
2336 // specialization except when the argument expression is a
2337 // simple identifier.
2338 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2339 Diag(ArgExpr->getLocStart(),
2340 diag::err_dependent_non_type_arg_in_partial_spec)
2341 << ArgExpr->getSourceRange();
2342 return true;
2343 }
2344
2345 // -- The type of a template parameter corresponding to a
2346 // specialized non-type argument shall not be dependent on a
2347 // parameter of the specialization.
2348 if (Param->getType()->isDependentType()) {
2349 Diag(ArgExpr->getLocStart(),
2350 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2351 << Param->getType()
2352 << ArgExpr->getSourceRange();
2353 Diag(Param->getLocation(), diag::note_template_param_here);
2354 return true;
2355 }
Douglas Gregor42476442009-06-12 22:08:06 +00002356
2357 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002358 }
2359
2360 return false;
2361}
2362
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002363Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002364Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2365 SourceLocation KWLoc,
2366 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002367 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002368 SourceLocation TemplateNameLoc,
2369 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002370 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002371 SourceLocation *TemplateArgLocs,
2372 SourceLocation RAngleLoc,
2373 AttributeList *Attr,
2374 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002375 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002376 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002377 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002378 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002379
Douglas Gregor58944ac2009-05-31 09:31:02 +00002380 bool isPartialSpecialization = false;
2381
Douglas Gregor0d93f692009-02-25 22:02:03 +00002382 // Check the validity of the template headers that introduce this
2383 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002384 // FIXME: Once we have member templates, we'll need to check
2385 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2386 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002387 if (TemplateParameterLists.size() == 0)
2388 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002389 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002390 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002391 TemplateParameterList *TemplateParams
2392 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002393 if (TemplateParameterLists.size() > 1) {
2394 Diag(TemplateParams->getTemplateLoc(),
2395 diag::err_template_spec_extra_headers);
2396 return true;
2397 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002398
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002399 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002400 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002401
2402 // C++ [temp.class.spec]p10:
2403 // The template parameter list of a specialization shall not
2404 // contain default template argument values.
2405 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2406 Decl *Param = TemplateParams->getParam(I);
2407 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2408 if (TTP->hasDefaultArgument()) {
2409 Diag(TTP->getDefaultArgumentLoc(),
2410 diag::err_default_arg_in_partial_spec);
2411 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2412 }
2413 } else if (NonTypeTemplateParmDecl *NTTP
2414 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2415 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2416 Diag(NTTP->getDefaultArgumentLoc(),
2417 diag::err_default_arg_in_partial_spec)
2418 << DefArg->getSourceRange();
2419 NTTP->setDefaultArgument(0);
2420 DefArg->Destroy(Context);
2421 }
2422 } else {
2423 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2424 if (Expr *DefArg = TTP->getDefaultArgument()) {
2425 Diag(TTP->getDefaultArgumentLoc(),
2426 diag::err_default_arg_in_partial_spec)
2427 << DefArg->getSourceRange();
2428 TTP->setDefaultArgument(0);
2429 DefArg->Destroy(Context);
2430 }
2431 }
2432 }
2433 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002434 }
2435
Douglas Gregora08b6c72009-02-17 23:15:12 +00002436 // Check that the specialization uses the same tag kind as the
2437 // original template.
2438 TagDecl::TagKind Kind;
2439 switch (TagSpec) {
2440 default: assert(0 && "Unknown tag type!");
2441 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2442 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2443 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2444 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002445 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2446 Kind, KWLoc,
2447 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002448 Diag(KWLoc, diag::err_use_with_wrong_tag)
2449 << ClassTemplate
2450 << CodeModificationHint::CreateReplacement(KWLoc,
2451 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002452 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2453 diag::note_previous_use);
2454 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2455 }
2456
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002457 // Translate the parser's template argument list in our AST format.
2458 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2459 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2460
Douglas Gregora08b6c72009-02-17 23:15:12 +00002461 // Check that the template argument list is well-formed for this
2462 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002463 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2464 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002465 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002466 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002467 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002468 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002469
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002470 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002471 ClassTemplate->getTemplateParameters()->size()) &&
2472 "Converted template argument list is too short!");
2473
Douglas Gregor58944ac2009-05-31 09:31:02 +00002474 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002475 // corresponds to these arguments.
2476 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002477 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002478 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002479 if (CheckClassTemplatePartialSpecializationArgs(
2480 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002481 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002482 return true;
2483
Douglas Gregor42476442009-06-12 22:08:06 +00002484 if (MirrorsPrimaryTemplate) {
2485 // C++ [temp.class.spec]p9b3:
2486 //
2487 // -- The argument list of the specialization shall not be identical
2488 // to the implicit argument list of the primary template.
2489 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2490 << (TK == TK_Definition)
2491 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2492 RAngleLoc));
2493 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2494 ClassTemplate->getIdentifier(),
2495 TemplateNameLoc,
2496 Attr,
2497 move(TemplateParameterLists),
2498 AS_none);
2499 }
2500
Douglas Gregor58944ac2009-05-31 09:31:02 +00002501 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002502 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002503 Converted.getFlatArguments(),
2504 Converted.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002505 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002506 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002507 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002508 Converted.getFlatArguments(),
2509 Converted.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002510 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002511 ClassTemplateSpecializationDecl *PrevDecl = 0;
2512
2513 if (isPartialSpecialization)
2514 PrevDecl
2515 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2516 InsertPos);
2517 else
2518 PrevDecl
2519 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002520
2521 ClassTemplateSpecializationDecl *Specialization = 0;
2522
Douglas Gregor0d93f692009-02-25 22:02:03 +00002523 // Check whether we can declare a class template specialization in
2524 // the current scope.
2525 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2526 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002527 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002528 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002529 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002530 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002531
Douglas Gregora08b6c72009-02-17 23:15:12 +00002532 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2533 // Since the only prior class template specialization with these
2534 // arguments was referenced but not declared, reuse that
2535 // declaration node as our own, updating its source location to
2536 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002537 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002538 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002539 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002540 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002541 // Create a new class template partial specialization declaration node.
2542 TemplateParameterList *TemplateParams
2543 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2544 ClassTemplatePartialSpecializationDecl *PrevPartial
2545 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2546 ClassTemplatePartialSpecializationDecl *Partial
2547 = ClassTemplatePartialSpecializationDecl::Create(Context,
2548 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002549 TemplateNameLoc,
2550 TemplateParams,
2551 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002552 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002553 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002554
2555 if (PrevPartial) {
2556 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2557 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2558 } else {
2559 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2560 }
2561 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002562
2563 // Check that all of the template parameters of the class template
2564 // partial specialization are deducible from the template
2565 // arguments. If not, this class template partial specialization
2566 // will never be used.
2567 llvm::SmallVector<bool, 8> DeducibleParams;
2568 DeducibleParams.resize(TemplateParams->size());
2569 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2570 unsigned NumNonDeducible = 0;
2571 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2572 if (!DeducibleParams[I])
2573 ++NumNonDeducible;
2574
2575 if (NumNonDeducible) {
2576 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2577 << (NumNonDeducible > 1)
2578 << SourceRange(TemplateNameLoc, RAngleLoc);
2579 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2580 if (!DeducibleParams[I]) {
2581 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2582 if (Param->getDeclName())
2583 Diag(Param->getLocation(),
2584 diag::note_partial_spec_unused_parameter)
2585 << Param->getDeclName();
2586 else
2587 Diag(Param->getLocation(),
2588 diag::note_partial_spec_unused_parameter)
2589 << std::string("<anonymous>");
2590 }
2591 }
2592 }
2593
Douglas Gregora08b6c72009-02-17 23:15:12 +00002594 } else {
2595 // Create a new class template specialization declaration node for
2596 // this explicit specialization.
2597 Specialization
2598 = ClassTemplateSpecializationDecl::Create(Context,
2599 ClassTemplate->getDeclContext(),
2600 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002601 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002602 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002603 PrevDecl);
2604
2605 if (PrevDecl) {
2606 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2607 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2608 } else {
2609 ClassTemplate->getSpecializations().InsertNode(Specialization,
2610 InsertPos);
2611 }
2612 }
2613
2614 // Note that this is an explicit specialization.
2615 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2616
2617 // Check that this isn't a redefinition of this specialization.
2618 if (TK == TK_Definition) {
2619 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002620 // FIXME: Should also handle explicit specialization after implicit
2621 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002622 SourceRange Range(TemplateNameLoc, RAngleLoc);
2623 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002624 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002625 Diag(Def->getLocation(), diag::note_previous_definition);
2626 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002627 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002628 }
2629 }
2630
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002631 // Build the fully-sugared type for this class template
2632 // specialization as the user wrote in the specialization
2633 // itself. This means that we'll pretty-print the type retrieved
2634 // from the specialization's declaration the way that the user
2635 // actually wrote the specialization, rather than formatting the
2636 // name based on the "canonical" representation used to store the
2637 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002638 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002639 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002640 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002641 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002642 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002643 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002644 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002645
Douglas Gregor50113ca2009-02-25 22:18:32 +00002646 // C++ [temp.expl.spec]p9:
2647 // A template explicit specialization is in the scope of the
2648 // namespace in which the template was defined.
2649 //
2650 // We actually implement this paragraph where we set the semantic
2651 // context (in the creation of the ClassTemplateSpecializationDecl),
2652 // but we also maintain the lexical context where the actual
2653 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002654 Specialization->setLexicalDeclContext(CurContext);
2655
2656 // We may be starting the definition of this specialization.
2657 if (TK == TK_Definition)
2658 Specialization->startDefinition();
2659
2660 // Add the specialization into its lexical context, so that it can
2661 // be seen when iterating through the list of declarations in that
2662 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002663 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002664 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002665}
Douglas Gregord3022602009-03-27 23:10:48 +00002666
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002667Sema::DeclPtrTy
2668Sema::ActOnTemplateDeclarator(Scope *S,
2669 MultiTemplateParamsArg TemplateParameterLists,
2670 Declarator &D) {
2671 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2672}
2673
Douglas Gregor19d10652009-06-24 00:54:41 +00002674Sema::DeclPtrTy
2675Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2676 MultiTemplateParamsArg TemplateParameterLists,
2677 Declarator &D) {
2678 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2679 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2680 "Not a function declarator!");
2681 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2682
2683 if (FTI.hasPrototype) {
2684 // FIXME: Diagnose arguments without names in C.
2685 }
2686
2687 Scope *ParentScope = FnBodyScope->getParent();
2688
2689 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2690 move(TemplateParameterLists),
2691 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002692 if (FunctionTemplateDecl *FunctionTemplate
2693 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002694 return ActOnStartOfFunctionDef(FnBodyScope,
2695 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002696 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2697 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002698 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002699}
2700
Douglas Gregor96b6df92009-05-14 00:28:11 +00002701// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002702Sema::DeclResult
2703Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2704 unsigned TagSpec,
2705 SourceLocation KWLoc,
2706 const CXXScopeSpec &SS,
2707 TemplateTy TemplateD,
2708 SourceLocation TemplateNameLoc,
2709 SourceLocation LAngleLoc,
2710 ASTTemplateArgsPtr TemplateArgsIn,
2711 SourceLocation *TemplateArgLocs,
2712 SourceLocation RAngleLoc,
2713 AttributeList *Attr) {
2714 // Find the class template we're specializing
2715 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2716 ClassTemplateDecl *ClassTemplate
2717 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2718
2719 // Check that the specialization uses the same tag kind as the
2720 // original template.
2721 TagDecl::TagKind Kind;
2722 switch (TagSpec) {
2723 default: assert(0 && "Unknown tag type!");
2724 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2725 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2726 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2727 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002728 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2729 Kind, KWLoc,
2730 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002731 Diag(KWLoc, diag::err_use_with_wrong_tag)
2732 << ClassTemplate
2733 << CodeModificationHint::CreateReplacement(KWLoc,
2734 ClassTemplate->getTemplatedDecl()->getKindName());
2735 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2736 diag::note_previous_use);
2737 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2738 }
2739
Douglas Gregor90177912009-05-13 18:28:20 +00002740 // C++0x [temp.explicit]p2:
2741 // [...] An explicit instantiation shall appear in an enclosing
2742 // namespace of its template. [...]
2743 //
2744 // This is C++ DR 275.
2745 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2746 TemplateNameLoc,
2747 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002748 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002749 /*ExplicitInstantiation=*/true))
2750 return true;
2751
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002752 // Translate the parser's template argument list in our AST format.
2753 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2754 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2755
2756 // Check that the template argument list is well-formed for this
2757 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002758 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2759 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002760 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002761 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002762 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002763 return true;
2764
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002765 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002766 ClassTemplate->getTemplateParameters()->size()) &&
2767 "Converted template argument list is too short!");
2768
2769 // Find the class template specialization declaration that
2770 // corresponds to these arguments.
2771 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002772 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002773 Converted.getFlatArguments(),
2774 Converted.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002775 void *InsertPos = 0;
2776 ClassTemplateSpecializationDecl *PrevDecl
2777 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2778
2779 ClassTemplateSpecializationDecl *Specialization = 0;
2780
Douglas Gregor90177912009-05-13 18:28:20 +00002781 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002782 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002783 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002784 // This particular specialization has already been declared or
2785 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002786 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2787 << Context.getTypeDeclType(PrevDecl);
2788 Diag(PrevDecl->getLocation(),
2789 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002790 return DeclPtrTy::make(PrevDecl);
2791 }
2792
Douglas Gregor90177912009-05-13 18:28:20 +00002793 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002794 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002795 // For a given set of template parameters, if an explicit
2796 // instantiation of a template appears after a declaration of
2797 // an explicit specialization for that template, the explicit
2798 // instantiation has no effect.
2799 if (!getLangOptions().CPlusPlus0x) {
2800 Diag(TemplateNameLoc,
2801 diag::ext_explicit_instantiation_after_specialization)
2802 << Context.getTypeDeclType(PrevDecl);
2803 Diag(PrevDecl->getLocation(),
2804 diag::note_previous_template_specialization);
2805 }
2806
2807 // Create a new class template specialization declaration node
2808 // for this explicit specialization. This node is only used to
2809 // record the existence of this explicit instantiation for
2810 // accurate reproduction of the source code; we don't actually
2811 // use it for anything, since it is semantically irrelevant.
2812 Specialization
2813 = ClassTemplateSpecializationDecl::Create(Context,
2814 ClassTemplate->getDeclContext(),
2815 TemplateNameLoc,
2816 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002817 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002818 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002819 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002820 return DeclPtrTy::make(Specialization);
2821 }
2822
2823 // If we have already (implicitly) instantiated this
2824 // specialization, there is less work to do.
2825 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2826 SpecializationRequiresInstantiation = false;
2827
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002828 // Since the only prior class template specialization with these
2829 // arguments was referenced but not declared, reuse that
2830 // declaration node as our own, updating its source location to
2831 // reflect our new declaration.
2832 Specialization = PrevDecl;
2833 Specialization->setLocation(TemplateNameLoc);
2834 PrevDecl = 0;
2835 } else {
2836 // Create a new class template specialization declaration node for
2837 // this explicit specialization.
2838 Specialization
2839 = ClassTemplateSpecializationDecl::Create(Context,
2840 ClassTemplate->getDeclContext(),
2841 TemplateNameLoc,
2842 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002843 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002844
2845 ClassTemplate->getSpecializations().InsertNode(Specialization,
2846 InsertPos);
2847 }
2848
2849 // Build the fully-sugared type for this explicit instantiation as
2850 // the user wrote in the explicit instantiation itself. This means
2851 // that we'll pretty-print the type retrieved from the
2852 // specialization's declaration the way that the user actually wrote
2853 // the explicit instantiation, rather than formatting the name based
2854 // on the "canonical" representation used to store the template
2855 // arguments in the specialization.
2856 QualType WrittenTy
2857 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002858 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002859 TemplateArgs.size(),
2860 Context.getTypeDeclType(Specialization));
2861 Specialization->setTypeAsWritten(WrittenTy);
2862 TemplateArgsIn.release();
2863
2864 // Add the explicit instantiation into its lexical context. However,
2865 // since explicit instantiations are never found by name lookup, we
2866 // just put it into the declaration context directly.
2867 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002868 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002869
2870 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002871 // A definition of a class template or class member template
2872 // shall be in scope at the point of the explicit instantiation of
2873 // the class template or class member template.
2874 //
2875 // This check comes when we actually try to perform the
2876 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002877 if (SpecializationRequiresInstantiation)
2878 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002879 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002880 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002881
2882 return DeclPtrTy::make(Specialization);
2883}
2884
Douglas Gregor96b6df92009-05-14 00:28:11 +00002885// Explicit instantiation of a member class of a class template.
2886Sema::DeclResult
2887Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2888 unsigned TagSpec,
2889 SourceLocation KWLoc,
2890 const CXXScopeSpec &SS,
2891 IdentifierInfo *Name,
2892 SourceLocation NameLoc,
2893 AttributeList *Attr) {
2894
Douglas Gregor71f06032009-05-28 23:31:59 +00002895 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002896 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002897 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002898 if (!TagD)
2899 return true;
2900
2901 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2902 if (Tag->isEnum()) {
2903 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2904 << Context.getTypeDeclType(Tag);
2905 return true;
2906 }
2907
Douglas Gregord769bfa2009-05-27 17:30:49 +00002908 if (Tag->isInvalidDecl())
2909 return true;
2910
Douglas Gregor96b6df92009-05-14 00:28:11 +00002911 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2912 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2913 if (!Pattern) {
2914 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2915 << Context.getTypeDeclType(Record);
2916 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2917 return true;
2918 }
2919
2920 // C++0x [temp.explicit]p2:
2921 // [...] An explicit instantiation shall appear in an enclosing
2922 // namespace of its template. [...]
2923 //
2924 // This is C++ DR 275.
2925 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002926 // FIXME: In C++98, we would like to turn these errors into warnings,
2927 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002928 DeclContext *PatternContext
2929 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2930 if (!CurContext->Encloses(PatternContext)) {
2931 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2932 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2933 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2934 }
2935 }
2936
Douglas Gregor96b6df92009-05-14 00:28:11 +00002937 if (!Record->getDefinition(Context)) {
2938 // If the class has a definition, instantiate it (and all of its
2939 // members, recursively).
2940 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2941 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002942 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002943 /*ExplicitInstantiation=*/true))
2944 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002945 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002946 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002947 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002948
Mike Stumpe127ae32009-05-16 07:39:55 +00002949 // FIXME: We don't have any representation for explicit instantiations of
2950 // member classes. Such a representation is not needed for compilation, but it
2951 // should be available for clients that want to see all of the declarations in
2952 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002953 return TagD;
2954}
2955
Douglas Gregord3022602009-03-27 23:10:48 +00002956Sema::TypeResult
2957Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2958 const IdentifierInfo &II, SourceLocation IdLoc) {
2959 NestedNameSpecifier *NNS
2960 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2961 if (!NNS)
2962 return true;
2963
2964 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002965 if (T.isNull())
2966 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002967 return T.getAsOpaquePtr();
2968}
2969
Douglas Gregor77da5802009-04-01 00:28:59 +00002970Sema::TypeResult
2971Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2972 SourceLocation TemplateLoc, TypeTy *Ty) {
2973 QualType T = QualType::getFromOpaquePtr(Ty);
2974 NestedNameSpecifier *NNS
2975 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2976 const TemplateSpecializationType *TemplateId
2977 = T->getAsTemplateSpecializationType();
2978 assert(TemplateId && "Expected a template specialization type");
2979
2980 if (NNS->isDependent())
2981 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2982
2983 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2984}
2985
Douglas Gregord3022602009-03-27 23:10:48 +00002986/// \brief Build the type that describes a C++ typename specifier,
2987/// e.g., "typename T::type".
2988QualType
2989Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2990 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002991 CXXRecordDecl *CurrentInstantiation = 0;
2992 if (NNS->isDependent()) {
2993 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002994
Douglas Gregor3eb20702009-05-11 19:58:34 +00002995 // If the nested-name-specifier does not refer to the current
2996 // instantiation, then build a typename type.
2997 if (!CurrentInstantiation)
2998 return Context.getTypenameType(NNS, &II);
2999 }
Douglas Gregord3022602009-03-27 23:10:48 +00003000
Douglas Gregor3eb20702009-05-11 19:58:34 +00003001 DeclContext *Ctx = 0;
3002
3003 if (CurrentInstantiation)
3004 Ctx = CurrentInstantiation;
3005 else {
3006 CXXScopeSpec SS;
3007 SS.setScopeRep(NNS);
3008 SS.setRange(Range);
3009 if (RequireCompleteDeclContext(SS))
3010 return QualType();
3011
3012 Ctx = computeDeclContext(SS);
3013 }
Douglas Gregord3022602009-03-27 23:10:48 +00003014 assert(Ctx && "No declaration context?");
3015
3016 DeclarationName Name(&II);
3017 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3018 false);
3019 unsigned DiagID = 0;
3020 Decl *Referenced = 0;
3021 switch (Result.getKind()) {
3022 case LookupResult::NotFound:
3023 if (Ctx->isTranslationUnit())
3024 DiagID = diag::err_typename_nested_not_found_global;
3025 else
3026 DiagID = diag::err_typename_nested_not_found;
3027 break;
3028
3029 case LookupResult::Found:
3030 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3031 // We found a type. Build a QualifiedNameType, since the
3032 // typename-specifier was just sugar. FIXME: Tell
3033 // QualifiedNameType that it has a "typename" prefix.
3034 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3035 }
3036
3037 DiagID = diag::err_typename_nested_not_type;
3038 Referenced = Result.getAsDecl();
3039 break;
3040
3041 case LookupResult::FoundOverloaded:
3042 DiagID = diag::err_typename_nested_not_type;
3043 Referenced = *Result.begin();
3044 break;
3045
3046 case LookupResult::AmbiguousBaseSubobjectTypes:
3047 case LookupResult::AmbiguousBaseSubobjects:
3048 case LookupResult::AmbiguousReference:
3049 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3050 return QualType();
3051 }
3052
3053 // If we get here, it's because name lookup did not find a
3054 // type. Emit an appropriate diagnostic and return an error.
3055 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3056 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3057 else
3058 Diag(Range.getEnd(), DiagID) << Range << Name;
3059 if (Referenced)
3060 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3061 << Name;
3062 return QualType();
3063}