blob: f20bcd95ca14eca522feba3146ff35b5fc87b30d [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregord406b032009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000166 Depth, Position, ParamName, Typename,
167 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000168 if (Invalid)
169 Param->setInvalidDecl();
170
171 if (ParamName) {
172 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000173 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000174 IdResolver.AddDecl(Param);
175 }
176
Chris Lattner5261d0c2009-03-28 19:18:32 +0000177 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000178}
179
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000183 SourceLocation EqualLoc,
184 SourceLocation DefaultLoc,
185 TypeTy *DefaultT) {
186 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000187 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000188 QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
Anders Carlssona2333782009-06-12 22:30:13 +0000190 // C++0x [temp.param]p9:
191 // A default template-argument may be specified for any kind of
192 // template-parameter that is not a template parameter pack.
193 if (Parm->isParameterPack()) {
194 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000195 return;
196 }
197
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000198 // C++ [temp.param]p14:
199 // A template-parameter shall not be used in its own default argument.
200 // FIXME: Implement this check! Needs a recursive walk over the types.
201
202 // Check the template argument itself.
203 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
204 Parm->setInvalidDecl();
205 return;
206 }
207
208 Parm->setDefaultArgument(Default, DefaultLoc, false);
209}
210
Douglas Gregored3a3982009-03-03 04:44:36 +0000211/// \brief Check that the type of a non-type template parameter is
212/// well-formed.
213///
214/// \returns the (possibly-promoted) parameter type if valid;
215/// otherwise, produces a diagnostic and returns a NULL type.
216QualType
217Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
218 // C++ [temp.param]p4:
219 //
220 // A non-type template-parameter shall have one of the following
221 // (optionally cv-qualified) types:
222 //
223 // -- integral or enumeration type,
224 if (T->isIntegralType() || T->isEnumeralType() ||
225 // -- pointer to object or pointer to function,
226 (T->isPointerType() &&
227 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
228 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
229 // -- reference to object or reference to function,
230 T->isReferenceType() ||
231 // -- pointer to member.
232 T->isMemberPointerType() ||
233 // If T is a dependent type, we can't do the check now, so we
234 // assume that it is well-formed.
235 T->isDependentType())
236 return T;
237 // C++ [temp.param]p8:
238 //
239 // A non-type template-parameter of type "array of T" or
240 // "function returning T" is adjusted to be of type "pointer to
241 // T" or "pointer to function returning T", respectively.
242 else if (T->isArrayType())
243 // FIXME: Keep the type prior to promotion?
244 return Context.getArrayDecayedType(T);
245 else if (T->isFunctionType())
246 // FIXME: Keep the type prior to promotion?
247 return Context.getPointerType(T);
248
249 Diag(Loc, diag::err_template_nontype_parm_bad_type)
250 << T;
251
252 return QualType();
253}
254
Douglas Gregordd861062008-12-05 18:15:24 +0000255/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
256/// template parameter (e.g., "int Size" in "template<int Size>
257/// class Array") has been parsed. S is the current scope and D is
258/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000259Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
260 unsigned Depth,
261 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000262 QualType T = GetTypeForDeclarator(D, S);
263
Douglas Gregor279272e2009-02-04 19:02:06 +0000264 assert(S->isTemplateParamScope() &&
265 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000266 bool Invalid = false;
267
268 IdentifierInfo *ParamName = D.getIdentifier();
269 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000270 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000271 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000272 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000273 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000274 }
275
Douglas Gregored3a3982009-03-03 04:44:36 +0000276 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000277 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000278 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000279 Invalid = true;
280 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000281
Douglas Gregordd861062008-12-05 18:15:24 +0000282 NonTypeTemplateParmDecl *Param
283 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000284 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000285 if (Invalid)
286 Param->setInvalidDecl();
287
288 if (D.getIdentifier()) {
289 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000290 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000291 IdResolver.AddDecl(Param);
292 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000293 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000294}
Douglas Gregor52473432008-12-24 02:52:09 +0000295
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000296/// \brief Adds a default argument to the given non-type template
297/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000298void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000299 SourceLocation EqualLoc,
300 ExprArg DefaultE) {
301 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000302 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000303 Expr *Default = static_cast<Expr *>(DefaultE.get());
304
305 // C++ [temp.param]p14:
306 // A template-parameter shall not be used in its own default argument.
307 // FIXME: Implement this check! Needs a recursive walk over the types.
308
309 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000310 TemplateArgument Converted;
311 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
312 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000313 TemplateParm->setInvalidDecl();
314 return;
315 }
316
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000317 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000318}
319
Douglas Gregor279272e2009-02-04 19:02:06 +0000320
321/// ActOnTemplateTemplateParameter - Called when a C++ template template
322/// parameter (e.g. T in template <template <typename> class T> class array)
323/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000324Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
325 SourceLocation TmpLoc,
326 TemplateParamsTy *Params,
327 IdentifierInfo *Name,
328 SourceLocation NameLoc,
329 unsigned Depth,
330 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000331{
332 assert(S->isTemplateParamScope() &&
333 "Template template parameter not in template parameter scope!");
334
335 // Construct the parameter object.
336 TemplateTemplateParmDecl *Param =
337 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
338 Position, Name,
339 (TemplateParameterList*)Params);
340
341 // Make sure the parameter is valid.
342 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
343 // do anything yet. However, if the template parameter list or (eventual)
344 // default value is ever invalidated, that will propagate here.
345 bool Invalid = false;
346 if (Invalid) {
347 Param->setInvalidDecl();
348 }
349
350 // If the tt-param has a name, then link the identifier into the scope
351 // and lookup mechanisms.
352 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000353 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000354 IdResolver.AddDecl(Param);
355 }
356
Chris Lattner5261d0c2009-03-28 19:18:32 +0000357 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000358}
359
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000360/// \brief Adds a default argument to the given template template
361/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000362void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000363 SourceLocation EqualLoc,
364 ExprArg DefaultE) {
365 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000366 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000367
368 // Since a template-template parameter's default argument is an
369 // id-expression, it must be a DeclRefExpr.
370 DeclRefExpr *Default
371 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
372
373 // C++ [temp.param]p14:
374 // A template-parameter shall not be used in its own default argument.
375 // FIXME: Implement this check! Needs a recursive walk over the types.
376
377 // Check the well-formedness of the template argument.
378 if (!isa<TemplateDecl>(Default->getDecl())) {
379 Diag(Default->getSourceRange().getBegin(),
380 diag::err_template_arg_must_be_template)
381 << Default->getSourceRange();
382 TemplateParm->setInvalidDecl();
383 return;
384 }
385 if (CheckTemplateArgument(TemplateParm, Default)) {
386 TemplateParm->setInvalidDecl();
387 return;
388 }
389
390 DefaultE.release();
391 TemplateParm->setDefaultArgument(Default);
392}
393
Douglas Gregor52473432008-12-24 02:52:09 +0000394/// ActOnTemplateParameterList - Builds a TemplateParameterList that
395/// contains the template parameters in Params/NumParams.
396Sema::TemplateParamsTy *
397Sema::ActOnTemplateParameterList(unsigned Depth,
398 SourceLocation ExportLoc,
399 SourceLocation TemplateLoc,
400 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000401 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000402 SourceLocation RAngleLoc) {
403 if (ExportLoc.isValid())
404 Diag(ExportLoc, diag::note_template_export_unsupported);
405
Douglas Gregord406b032009-02-06 22:42:48 +0000406 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
407 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000408}
Douglas Gregor279272e2009-02-04 19:02:06 +0000409
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000410Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000411Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
412 SourceLocation KWLoc, const CXXScopeSpec &SS,
413 IdentifierInfo *Name, SourceLocation NameLoc,
414 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000415 MultiTemplateParamsArg TemplateParameterLists,
416 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000417 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
418 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000419 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000420
421 // Check that we can declare a template here.
422 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000423 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000424
425 TagDecl::TagKind Kind;
426 switch (TagSpec) {
427 default: assert(0 && "Unknown tag type!");
428 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
429 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
430 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
431 }
432
433 // There is no such thing as an unnamed class template.
434 if (!Name) {
435 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000436 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000437 }
438
439 // Find any previous declaration with this name.
440 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
441 true);
442 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
443 NamedDecl *PrevDecl = 0;
444 if (Previous.begin() != Previous.end())
445 PrevDecl = *Previous.begin();
446
447 DeclContext *SemanticContext = CurContext;
448 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000449 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000450
Mike Stumpe127ae32009-05-16 07:39:55 +0000451 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000452 }
453
454 // FIXME: member templates!
455 TemplateParameterList *TemplateParams
456 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
457
458 // If there is a previous declaration with the same name, check
459 // whether this is a valid redeclaration.
460 ClassTemplateDecl *PrevClassTemplate
461 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
462 if (PrevClassTemplate) {
463 // Ensure that the template parameter lists are compatible.
464 if (!TemplateParameterListsAreEqual(TemplateParams,
465 PrevClassTemplate->getTemplateParameters(),
466 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000467 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000468
469 // C++ [temp.class]p4:
470 // In a redeclaration, partial specialization, explicit
471 // specialization or explicit instantiation of a class template,
472 // the class-key shall agree in kind with the original class
473 // template declaration (7.1.5.3).
474 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000475 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000476 Diag(KWLoc, diag::err_use_with_wrong_tag)
477 << Name
478 << CodeModificationHint::CreateReplacement(KWLoc,
479 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000480 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000481 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000482 }
483
Douglas Gregord406b032009-02-06 22:42:48 +0000484 // Check for redefinition of this class template.
485 if (TK == TK_Definition) {
486 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
487 Diag(NameLoc, diag::err_redefinition) << Name;
488 Diag(Def->getLocation(), diag::note_previous_definition);
489 // FIXME: Would it make sense to try to "forget" the previous
490 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000491 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000492 }
493 }
494 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
495 // Maybe we will complain about the shadowed template parameter.
496 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
497 // Just pretend that we didn't see the previous declaration.
498 PrevDecl = 0;
499 } else if (PrevDecl) {
500 // C++ [temp]p5:
501 // A class template shall not have the same name as any other
502 // template, class, function, object, enumeration, enumerator,
503 // namespace, or type in the same scope (3.3), except as specified
504 // in (14.5.4).
505 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
506 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000507 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000508 }
509
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000510 // Check the template parameter list of this declaration, possibly
511 // merging in the template parameter list from the previous class
512 // template declaration.
513 if (CheckTemplateParameterList(TemplateParams,
514 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
515 Invalid = true;
516
Douglas Gregor9054f982009-05-10 22:57:19 +0000517 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000518 // declaration!
519
Douglas Gregor55216ac2009-03-26 00:10:35 +0000520 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000521 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
522 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000523 PrevClassTemplate->getTemplatedDecl() : 0,
524 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000525
526 ClassTemplateDecl *NewTemplate
527 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
528 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000529 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000530 NewClass->setDescribedClassTemplate(NewTemplate);
531
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000532 // Build the type for the class template declaration now.
533 QualType T =
534 Context.getTypeDeclType(NewClass,
535 PrevClassTemplate?
536 PrevClassTemplate->getTemplatedDecl() : 0);
537 assert(T->isDependentType() && "Class template type is not dependent?");
538 (void)T;
539
Anders Carlsson4ca43492009-03-26 01:24:28 +0000540 // Set the access specifier.
541 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
542
Douglas Gregord406b032009-02-06 22:42:48 +0000543 // Set the lexical context of these templates
544 NewClass->setLexicalDeclContext(CurContext);
545 NewTemplate->setLexicalDeclContext(CurContext);
546
547 if (TK == TK_Definition)
548 NewClass->startDefinition();
549
550 if (Attr)
551 ProcessDeclAttributeList(NewClass, Attr);
552
553 PushOnScopeChains(NewTemplate, S);
554
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000555 if (Invalid) {
556 NewTemplate->setInvalidDecl();
557 NewClass->setInvalidDecl();
558 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000559 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000560}
561
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000562/// \brief Checks the validity of a template parameter list, possibly
563/// considering the template parameter list from a previous
564/// declaration.
565///
566/// If an "old" template parameter list is provided, it must be
567/// equivalent (per TemplateParameterListsAreEqual) to the "new"
568/// template parameter list.
569///
570/// \param NewParams Template parameter list for a new template
571/// declaration. This template parameter list will be updated with any
572/// default arguments that are carried through from the previous
573/// template parameter list.
574///
575/// \param OldParams If provided, template parameter list from a
576/// previous declaration of the same template. Default template
577/// arguments will be merged from the old template parameter list to
578/// the new template parameter list.
579///
580/// \returns true if an error occurred, false otherwise.
581bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
582 TemplateParameterList *OldParams) {
583 bool Invalid = false;
584
585 // C++ [temp.param]p10:
586 // The set of default template-arguments available for use with a
587 // template declaration or definition is obtained by merging the
588 // default arguments from the definition (if in scope) and all
589 // declarations in scope in the same way default function
590 // arguments are (8.3.6).
591 bool SawDefaultArgument = false;
592 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000593
Anders Carlssonb1929502009-06-12 23:20:15 +0000594 bool SawParameterPack = false;
595 SourceLocation ParameterPackLoc;
596
Mike Stumpe0b7e032009-02-11 23:03:27 +0000597 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000598 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000599 if (OldParams)
600 OldParam = OldParams->begin();
601
602 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
603 NewParamEnd = NewParams->end();
604 NewParam != NewParamEnd; ++NewParam) {
605 // Variables used to diagnose redundant default arguments
606 bool RedundantDefaultArg = false;
607 SourceLocation OldDefaultLoc;
608 SourceLocation NewDefaultLoc;
609
610 // Variables used to diagnose missing default arguments
611 bool MissingDefaultArg = false;
612
Anders Carlssonb1929502009-06-12 23:20:15 +0000613 // C++0x [temp.param]p11:
614 // If a template parameter of a class template is a template parameter pack,
615 // it must be the last template parameter.
616 if (SawParameterPack) {
617 Diag(ParameterPackLoc,
618 diag::err_template_param_pack_must_be_last_template_parameter);
619 Invalid = true;
620 }
621
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000622 // Merge default arguments for template type parameters.
623 if (TemplateTypeParmDecl *NewTypeParm
624 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
625 TemplateTypeParmDecl *OldTypeParm
626 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
627
Anders Carlssonb1929502009-06-12 23:20:15 +0000628 if (NewTypeParm->isParameterPack()) {
629 assert(!NewTypeParm->hasDefaultArgument() &&
630 "Parameter packs can't have a default argument!");
631 SawParameterPack = true;
632 ParameterPackLoc = NewTypeParm->getLocation();
633 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000634 NewTypeParm->hasDefaultArgument()) {
635 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
636 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
637 SawDefaultArgument = true;
638 RedundantDefaultArg = true;
639 PreviousDefaultArgLoc = NewDefaultLoc;
640 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
641 // Merge the default argument from the old declaration to the
642 // new declaration.
643 SawDefaultArgument = true;
644 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
645 OldTypeParm->getDefaultArgumentLoc(),
646 true);
647 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
648 } else if (NewTypeParm->hasDefaultArgument()) {
649 SawDefaultArgument = true;
650 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
651 } else if (SawDefaultArgument)
652 MissingDefaultArg = true;
653 }
654 // Merge default arguments for non-type template parameters
655 else if (NonTypeTemplateParmDecl *NewNonTypeParm
656 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
657 NonTypeTemplateParmDecl *OldNonTypeParm
658 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
659 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
660 NewNonTypeParm->hasDefaultArgument()) {
661 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
662 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
663 SawDefaultArgument = true;
664 RedundantDefaultArg = true;
665 PreviousDefaultArgLoc = NewDefaultLoc;
666 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
667 // Merge the default argument from the old declaration to the
668 // new declaration.
669 SawDefaultArgument = true;
670 // FIXME: We need to create a new kind of "default argument"
671 // expression that points to a previous template template
672 // parameter.
673 NewNonTypeParm->setDefaultArgument(
674 OldNonTypeParm->getDefaultArgument());
675 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
676 } else if (NewNonTypeParm->hasDefaultArgument()) {
677 SawDefaultArgument = true;
678 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
679 } else if (SawDefaultArgument)
680 MissingDefaultArg = true;
681 }
682 // Merge default arguments for template template parameters
683 else {
684 TemplateTemplateParmDecl *NewTemplateParm
685 = cast<TemplateTemplateParmDecl>(*NewParam);
686 TemplateTemplateParmDecl *OldTemplateParm
687 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
688 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
689 NewTemplateParm->hasDefaultArgument()) {
690 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
691 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
692 SawDefaultArgument = true;
693 RedundantDefaultArg = true;
694 PreviousDefaultArgLoc = NewDefaultLoc;
695 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
696 // Merge the default argument from the old declaration to the
697 // new declaration.
698 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000699 // FIXME: We need to create a new kind of "default argument" expression
700 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000701 NewTemplateParm->setDefaultArgument(
702 OldTemplateParm->getDefaultArgument());
703 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
704 } else if (NewTemplateParm->hasDefaultArgument()) {
705 SawDefaultArgument = true;
706 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
707 } else if (SawDefaultArgument)
708 MissingDefaultArg = true;
709 }
710
711 if (RedundantDefaultArg) {
712 // C++ [temp.param]p12:
713 // A template-parameter shall not be given default arguments
714 // by two different declarations in the same scope.
715 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
716 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
717 Invalid = true;
718 } else if (MissingDefaultArg) {
719 // C++ [temp.param]p11:
720 // If a template-parameter has a default template-argument,
721 // all subsequent template-parameters shall have a default
722 // template-argument supplied.
723 Diag((*NewParam)->getLocation(),
724 diag::err_template_param_default_arg_missing);
725 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
726 Invalid = true;
727 }
728
729 // If we have an old template parameter list that we're merging
730 // in, move on to the next parameter.
731 if (OldParams)
732 ++OldParam;
733 }
734
735 return Invalid;
736}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000737
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000738/// \brief Translates template arguments as provided by the parser
739/// into template arguments used by semantic analysis.
740static void
741translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
742 SourceLocation *TemplateArgLocs,
743 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
744 TemplateArgs.reserve(TemplateArgsIn.size());
745
746 void **Args = TemplateArgsIn.getArgs();
747 bool *ArgIsType = TemplateArgsIn.getArgIsType();
748 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
749 TemplateArgs.push_back(
750 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
751 QualType::getFromOpaquePtr(Args[Arg]))
752 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
753 }
754}
755
Douglas Gregoraabb8502009-03-31 00:43:58 +0000756/// \brief Build a canonical version of a template argument list.
757///
758/// This function builds a canonical version of the given template
759/// argument list, where each of the template arguments has been
760/// converted into its canonical form. This routine is typically used
761/// to canonicalize a template argument list when the template name
762/// itself is dependent. When the template name refers to an actual
763/// template declaration, Sema::CheckTemplateArgumentList should be
764/// used to check and canonicalize the template arguments.
765///
766/// \param TemplateArgs The incoming template arguments.
767///
768/// \param NumTemplateArgs The number of template arguments in \p
769/// TemplateArgs.
770///
771/// \param Canonical A vector to be filled with the canonical versions
772/// of the template arguments.
773///
774/// \param Context The ASTContext in which the template arguments live.
775static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
776 unsigned NumTemplateArgs,
777 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
778 ASTContext &Context) {
779 Canonical.reserve(NumTemplateArgs);
780 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
781 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000782 case TemplateArgument::Null:
783 assert(false && "Should never see a NULL template argument here");
784 break;
785
Douglas Gregoraabb8502009-03-31 00:43:58 +0000786 case TemplateArgument::Expression:
787 // FIXME: Build canonical expression (!)
788 Canonical.push_back(TemplateArgs[Idx]);
789 break;
790
791 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000792 Canonical.push_back(
793 TemplateArgument(SourceLocation(),
794 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000795 break;
796
797 case TemplateArgument::Integral:
798 Canonical.push_back(TemplateArgument(SourceLocation(),
799 *TemplateArgs[Idx].getAsIntegral(),
800 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000801 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000802
803 case TemplateArgument::Type: {
804 QualType CanonType
805 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
806 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000807 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000808 }
809 }
810 }
811}
812
Douglas Gregordd13e842009-03-30 22:58:21 +0000813QualType Sema::CheckTemplateIdType(TemplateName Name,
814 SourceLocation TemplateLoc,
815 SourceLocation LAngleLoc,
816 const TemplateArgument *TemplateArgs,
817 unsigned NumTemplateArgs,
818 SourceLocation RAngleLoc) {
819 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000820 if (!Template) {
821 // The template name does not resolve to a template, so we just
822 // build a dependent template-id type.
823
824 // Canonicalize the template arguments to build the canonical
825 // template-id type.
826 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
827 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
828 CanonicalTemplateArgs, Context);
829
Douglas Gregor905406b2009-05-07 06:49:52 +0000830 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000831 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000832 = Context.getTemplateSpecializationType(CanonName,
833 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000834 CanonicalTemplateArgs.size());
835
836 // Build the dependent template-id type.
837 return Context.getTemplateSpecializationType(Name, TemplateArgs,
838 NumTemplateArgs, CanonType);
839 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000840
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000841 // Check that the template argument list is well-formed for this
842 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000843 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000844 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000845 TemplateArgs, NumTemplateArgs, RAngleLoc,
846 ConvertedTemplateArgs))
847 return QualType();
848
849 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000850 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000851 "Converted template argument list is too short!");
852
853 QualType CanonType;
854
Douglas Gregordd13e842009-03-30 22:58:21 +0000855 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000856 TemplateArgs,
857 NumTemplateArgs)) {
858 // This class template specialization is a dependent
859 // type. Therefore, its canonical type is another class template
860 // specialization type that contains all of the converted
861 // arguments in canonical form. This ensures that, e.g., A<T> and
862 // A<T, T> have identical types when A is declared as:
863 //
864 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000865 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
866 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000867 ConvertedTemplateArgs.getFlatArgumentList(),
868 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000869 } else if (ClassTemplateDecl *ClassTemplate
870 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000871 // Find the class template specialization declaration that
872 // corresponds to these arguments.
873 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000874 ClassTemplateSpecializationDecl::Profile(ID,
875 ConvertedTemplateArgs.getFlatArgumentList(),
876 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000877 void *InsertPos = 0;
878 ClassTemplateSpecializationDecl *Decl
879 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
880 if (!Decl) {
881 // This is the first time we have referenced this class template
882 // specialization. Create the canonical declaration and add it to
883 // the set of specializations.
884 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000885 ClassTemplate->getDeclContext(),
886 TemplateLoc,
887 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000888 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000889 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
890 Decl->setLexicalDeclContext(CurContext);
891 }
892
893 CanonType = Context.getTypeDeclType(Decl);
894 }
895
896 // Build the fully-sugared type for this class template
897 // specialization, which refers back to the class template
898 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000899 return Context.getTemplateSpecializationType(Name, TemplateArgs,
900 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000901}
902
Douglas Gregora08b6c72009-02-17 23:15:12 +0000903Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000904Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
905 SourceLocation LAngleLoc,
906 ASTTemplateArgsPtr TemplateArgsIn,
907 SourceLocation *TemplateArgLocs,
908 SourceLocation RAngleLoc) {
909 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000910
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000911 // Translate the parser's template argument list in our AST format.
912 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
913 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000914
Douglas Gregordd13e842009-03-30 22:58:21 +0000915 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000916 TemplateArgs.data(),
917 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000918 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000919 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000920
921 if (Result.isNull())
922 return true;
923
Douglas Gregor6f37b582009-02-09 19:34:22 +0000924 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000925}
926
Douglas Gregoraabb8502009-03-31 00:43:58 +0000927/// \brief Form a dependent template name.
928///
929/// This action forms a dependent template name given the template
930/// name and its (presumably dependent) scope specifier. For
931/// example, given "MetaFun::template apply", the scope specifier \p
932/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
933/// of the "template" keyword, and "apply" is the \p Name.
934Sema::TemplateTy
935Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
936 const IdentifierInfo &Name,
937 SourceLocation NameLoc,
938 const CXXScopeSpec &SS) {
939 if (!SS.isSet() || SS.isInvalid())
940 return TemplateTy();
941
942 NestedNameSpecifier *Qualifier
943 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
944
945 // FIXME: member of the current instantiation
946
947 if (!Qualifier->isDependent()) {
948 // C++0x [temp.names]p5:
949 // If a name prefixed by the keyword template is not the name of
950 // a template, the program is ill-formed. [Note: the keyword
951 // template may not be applied to non-template members of class
952 // templates. -end note ] [ Note: as is the case with the
953 // typename prefix, the template prefix is allowed in cases
954 // where it is not strictly necessary; i.e., when the
955 // nested-name-specifier or the expression on the left of the ->
956 // or . is not dependent on a template-parameter, or the use
957 // does not appear in the scope of a template. -end note]
958 //
959 // Note: C++03 was more strict here, because it banned the use of
960 // the "template" keyword prior to a template-name that was not a
961 // dependent name. C++ DR468 relaxed this requirement (the
962 // "template" keyword is now permitted). We follow the C++0x
963 // rules, even in C++03 mode, retroactively applying the DR.
964 TemplateTy Template;
965 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
966 if (TNK == TNK_Non_template) {
967 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
968 << &Name;
969 return TemplateTy();
970 }
971
972 return Template;
973 }
974
975 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
976}
977
Anders Carlssonfdd33cc2009-06-13 00:33:33 +0000978bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
979 const TemplateArgument &Arg,
980 TemplateArgumentListBuilder &Converted) {
981 // Check template type parameter.
982 if (Arg.getKind() != TemplateArgument::Type) {
983 // C++ [temp.arg.type]p1:
984 // A template-argument for a template-parameter which is a
985 // type shall be a type-id.
986
987 // We have a template type parameter but the template argument
988 // is not a type.
989 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
990 Diag(Param->getLocation(), diag::note_template_param_here);
991
992 return true;
993 }
994
995 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
996 return true;
997
998 // Add the converted template type argument.
999 Converted.push_back(
1000 TemplateArgument(Arg.getLocation(),
1001 Context.getCanonicalType(Arg.getAsType())));
1002 return false;
1003}
1004
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001005/// \brief Check that the given template argument list is well-formed
1006/// for specializing the given template.
1007bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1008 SourceLocation TemplateLoc,
1009 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001010 const TemplateArgument *TemplateArgs,
1011 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001012 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001013 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001014 TemplateParameterList *Params = Template->getTemplateParameters();
1015 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001016 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001017 bool Invalid = false;
1018
1019 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001020 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001021 // FIXME: point at either the first arg beyond what we can handle,
1022 // or the '>', depending on whether we have too many or too few
1023 // arguments.
1024 SourceRange Range;
1025 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001026 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001027 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1028 << (NumArgs > NumParams)
1029 << (isa<ClassTemplateDecl>(Template)? 0 :
1030 isa<FunctionTemplateDecl>(Template)? 1 :
1031 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1032 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001033 Diag(Template->getLocation(), diag::note_template_decl_here)
1034 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001035 Invalid = true;
1036 }
1037
1038 // C++ [temp.arg]p1:
1039 // [...] The type and form of each template-argument specified in
1040 // a template-id shall match the type and form specified for the
1041 // corresponding parameter declared by the template in its
1042 // template-parameter-list.
1043 unsigned ArgIdx = 0;
1044 for (TemplateParameterList::iterator Param = Params->begin(),
1045 ParamEnd = Params->end();
1046 Param != ParamEnd; ++Param, ++ArgIdx) {
1047 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001048 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001049 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001050 // Retrieve the default template argument from the template
1051 // parameter.
1052 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1053 if (!TTP->hasDefaultArgument())
1054 break;
1055
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001056 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001057
1058 // If the argument type is dependent, instantiate it now based
1059 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001060 if (ArgType->isDependentType()) {
1061 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001062 Template, Converted.getFlatArgumentList(),
1063 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001064 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001065
Anders Carlsson0233eb62009-06-05 04:47:51 +00001066 TemplateArgumentList TemplateArgs(Context, Converted,
1067 /*CopyArgs=*/false,
1068 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001069 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001070 TTP->getDefaultArgumentLoc(),
1071 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001072 }
Douglas Gregor74296542009-02-27 19:31:52 +00001073
1074 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001075 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001076
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001077 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001078 } else if (NonTypeTemplateParmDecl *NTTP
1079 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1080 if (!NTTP->hasDefaultArgument())
1081 break;
1082
Anders Carlsson0297caf2009-06-11 16:06:49 +00001083 InstantiatingTemplate Inst(*this, TemplateLoc,
1084 Template, Converted.getFlatArgumentList(),
1085 Converted.flatSize(),
1086 SourceRange(TemplateLoc, RAngleLoc));
1087
1088 TemplateArgumentList TemplateArgs(Context, Converted,
1089 /*CopyArgs=*/false,
1090 /*FlattenArgs=*/false);
1091
1092 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1093 TemplateArgs);
1094 if (E.isInvalid())
1095 return true;
1096
1097 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001098 } else {
1099 TemplateTemplateParmDecl *TempParm
1100 = cast<TemplateTemplateParmDecl>(*Param);
1101
1102 if (!TempParm->hasDefaultArgument())
1103 break;
1104
Douglas Gregored3a3982009-03-03 04:44:36 +00001105 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001106 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001107 }
1108 } else {
1109 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001110 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001111 }
1112
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001113
1114 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001115 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1116 Invalid = true;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001117 } else if (NonTypeTemplateParmDecl *NTTP
1118 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1119 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001120
1121 // Instantiate the type of the non-type template parameter with
1122 // the template arguments we've seen thus far.
1123 QualType NTTPType = NTTP->getType();
1124 if (NTTPType->isDependentType()) {
1125 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001126 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001127 Template, Converted.getFlatArgumentList(),
1128 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001129 SourceRange(TemplateLoc, RAngleLoc));
1130
Anders Carlsson0233eb62009-06-05 04:47:51 +00001131 TemplateArgumentList TemplateArgs(Context, Converted,
1132 /*CopyArgs=*/false,
1133 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001134 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001135 NTTP->getLocation(),
1136 NTTP->getDeclName());
1137 // If that worked, check the non-type template parameter type
1138 // for validity.
1139 if (!NTTPType.isNull())
1140 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1141 NTTP->getLocation());
1142
1143 if (NTTPType.isNull()) {
1144 Invalid = true;
1145 break;
1146 }
1147 }
1148
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001149 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001150 case TemplateArgument::Null:
1151 assert(false && "Should never see a NULL template argument here");
1152 break;
1153
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001154 case TemplateArgument::Expression: {
1155 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001156 TemplateArgument Result;
1157 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001158 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001159 else
1160 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001161 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001162 }
1163
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001164 case TemplateArgument::Declaration:
1165 case TemplateArgument::Integral:
1166 // We've already checked this template argument, so just copy
1167 // it to the list of converted arguments.
1168 Converted.push_back(Arg);
1169 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001170
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001171 case TemplateArgument::Type:
1172 // We have a non-type template parameter but the template
1173 // argument is a type.
1174
1175 // C++ [temp.arg]p2:
1176 // In a template-argument, an ambiguity between a type-id and
1177 // an expression is resolved to a type-id, regardless of the
1178 // form of the corresponding template-parameter.
1179 //
1180 // We warn specifically about this case, since it can be rather
1181 // confusing for users.
1182 if (Arg.getAsType()->isFunctionType())
1183 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1184 << Arg.getAsType();
1185 else
1186 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1187 Diag((*Param)->getLocation(), diag::note_template_param_here);
1188 Invalid = true;
1189 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001190 } else {
1191 // Check template template parameters.
1192 TemplateTemplateParmDecl *TempParm
1193 = cast<TemplateTemplateParmDecl>(*Param);
1194
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001195 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001196 case TemplateArgument::Null:
1197 assert(false && "Should never see a NULL template argument here");
1198 break;
1199
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001200 case TemplateArgument::Expression: {
1201 Expr *ArgExpr = Arg.getAsExpr();
1202 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1203 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1204 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1205 Invalid = true;
1206
1207 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001208 Decl *D
1209 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1210 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001211 continue;
1212 }
1213 }
1214 // fall through
1215
1216 case TemplateArgument::Type: {
1217 // We have a template template parameter but the template
1218 // argument does not refer to a template.
1219 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1220 Invalid = true;
1221 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001222 }
1223
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001224 case TemplateArgument::Declaration:
1225 // We've already checked this template argument, so just copy
1226 // it to the list of converted arguments.
1227 Converted.push_back(Arg);
1228 break;
1229
1230 case TemplateArgument::Integral:
1231 assert(false && "Integral argument with template template parameter");
1232 break;
1233 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001234 }
1235 }
1236
1237 return Invalid;
1238}
1239
1240/// \brief Check a template argument against its corresponding
1241/// template type parameter.
1242///
1243/// This routine implements the semantics of C++ [temp.arg.type]. It
1244/// returns true if an error occurred, and false otherwise.
1245bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1246 QualType Arg, SourceLocation ArgLoc) {
1247 // C++ [temp.arg.type]p2:
1248 // A local type, a type with no linkage, an unnamed type or a type
1249 // compounded from any of these types shall not be used as a
1250 // template-argument for a template type-parameter.
1251 //
1252 // FIXME: Perform the recursive and no-linkage type checks.
1253 const TagType *Tag = 0;
1254 if (const EnumType *EnumT = Arg->getAsEnumType())
1255 Tag = EnumT;
1256 else if (const RecordType *RecordT = Arg->getAsRecordType())
1257 Tag = RecordT;
1258 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1259 return Diag(ArgLoc, diag::err_template_arg_local_type)
1260 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001261 else if (Tag && !Tag->getDecl()->getDeclName() &&
1262 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001263 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1264 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1265 return true;
1266 }
1267
1268 return false;
1269}
1270
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001271/// \brief Checks whether the given template argument is the address
1272/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001273bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1274 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001275 bool Invalid = false;
1276
1277 // See through any implicit casts we added to fix the type.
1278 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1279 Arg = Cast->getSubExpr();
1280
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001281 // C++0x allows nullptr, and there's no further checking to be done for that.
1282 if (Arg->getType()->isNullPtrType())
1283 return false;
1284
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001285 // C++ [temp.arg.nontype]p1:
1286 //
1287 // A template-argument for a non-type, non-template
1288 // template-parameter shall be one of: [...]
1289 //
1290 // -- the address of an object or function with external
1291 // linkage, including function templates and function
1292 // template-ids but excluding non-static class members,
1293 // expressed as & id-expression where the & is optional if
1294 // the name refers to a function or array, or if the
1295 // corresponding template-parameter is a reference; or
1296 DeclRefExpr *DRE = 0;
1297
1298 // Ignore (and complain about) any excess parentheses.
1299 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1300 if (!Invalid) {
1301 Diag(Arg->getSourceRange().getBegin(),
1302 diag::err_template_arg_extra_parens)
1303 << Arg->getSourceRange();
1304 Invalid = true;
1305 }
1306
1307 Arg = Parens->getSubExpr();
1308 }
1309
1310 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1311 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1312 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1313 } else
1314 DRE = dyn_cast<DeclRefExpr>(Arg);
1315
1316 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1317 return Diag(Arg->getSourceRange().getBegin(),
1318 diag::err_template_arg_not_object_or_func_form)
1319 << Arg->getSourceRange();
1320
1321 // Cannot refer to non-static data members
1322 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1323 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1324 << Field << Arg->getSourceRange();
1325
1326 // Cannot refer to non-static member functions
1327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1328 if (!Method->isStatic())
1329 return Diag(Arg->getSourceRange().getBegin(),
1330 diag::err_template_arg_method)
1331 << Method << Arg->getSourceRange();
1332
1333 // Functions must have external linkage.
1334 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1335 if (Func->getStorageClass() == FunctionDecl::Static) {
1336 Diag(Arg->getSourceRange().getBegin(),
1337 diag::err_template_arg_function_not_extern)
1338 << Func << Arg->getSourceRange();
1339 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1340 << true;
1341 return true;
1342 }
1343
1344 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001345 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001346 return Invalid;
1347 }
1348
1349 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1350 if (!Var->hasGlobalStorage()) {
1351 Diag(Arg->getSourceRange().getBegin(),
1352 diag::err_template_arg_object_not_extern)
1353 << Var << Arg->getSourceRange();
1354 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1355 << true;
1356 return true;
1357 }
1358
1359 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001360 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001361 return Invalid;
1362 }
1363
1364 // We found something else, but we don't know specifically what it is.
1365 Diag(Arg->getSourceRange().getBegin(),
1366 diag::err_template_arg_not_object_or_func)
1367 << Arg->getSourceRange();
1368 Diag(DRE->getDecl()->getLocation(),
1369 diag::note_template_arg_refers_here);
1370 return true;
1371}
1372
1373/// \brief Checks whether the given template argument is a pointer to
1374/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001375bool
1376Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001377 bool Invalid = false;
1378
1379 // See through any implicit casts we added to fix the type.
1380 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1381 Arg = Cast->getSubExpr();
1382
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001383 // C++0x allows nullptr, and there's no further checking to be done for that.
1384 if (Arg->getType()->isNullPtrType())
1385 return false;
1386
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001387 // C++ [temp.arg.nontype]p1:
1388 //
1389 // A template-argument for a non-type, non-template
1390 // template-parameter shall be one of: [...]
1391 //
1392 // -- a pointer to member expressed as described in 5.3.1.
1393 QualifiedDeclRefExpr *DRE = 0;
1394
1395 // Ignore (and complain about) any excess parentheses.
1396 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1397 if (!Invalid) {
1398 Diag(Arg->getSourceRange().getBegin(),
1399 diag::err_template_arg_extra_parens)
1400 << Arg->getSourceRange();
1401 Invalid = true;
1402 }
1403
1404 Arg = Parens->getSubExpr();
1405 }
1406
1407 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1408 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1409 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1410
1411 if (!DRE)
1412 return Diag(Arg->getSourceRange().getBegin(),
1413 diag::err_template_arg_not_pointer_to_member_form)
1414 << Arg->getSourceRange();
1415
1416 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1417 assert((isa<FieldDecl>(DRE->getDecl()) ||
1418 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1419 "Only non-static member pointers can make it here");
1420
1421 // Okay: this is the address of a non-static member, and therefore
1422 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001423 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001424 return Invalid;
1425 }
1426
1427 // We found something else, but we don't know specifically what it is.
1428 Diag(Arg->getSourceRange().getBegin(),
1429 diag::err_template_arg_not_pointer_to_member_form)
1430 << Arg->getSourceRange();
1431 Diag(DRE->getDecl()->getLocation(),
1432 diag::note_template_arg_refers_here);
1433 return true;
1434}
1435
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001436/// \brief Check a template argument against its corresponding
1437/// non-type template parameter.
1438///
Douglas Gregored3a3982009-03-03 04:44:36 +00001439/// This routine implements the semantics of C++ [temp.arg.nontype].
1440/// It returns true if an error occurred, and false otherwise. \p
1441/// InstantiatedParamType is the type of the non-type template
1442/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001443///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001444/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001445bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001446 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001447 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001448 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1449
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001450 // If either the parameter has a dependent type or the argument is
1451 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001452 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001453 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1454 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001455 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001456 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001457 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001458
1459 // C++ [temp.arg.nontype]p5:
1460 // The following conversions are performed on each expression used
1461 // as a non-type template-argument. If a non-type
1462 // template-argument cannot be converted to the type of the
1463 // corresponding template-parameter then the program is
1464 // ill-formed.
1465 //
1466 // -- for a non-type template-parameter of integral or
1467 // enumeration type, integral promotions (4.5) and integral
1468 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001469 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001470 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001471 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001472 // C++ [temp.arg.nontype]p1:
1473 // A template-argument for a non-type, non-template
1474 // template-parameter shall be one of:
1475 //
1476 // -- an integral constant-expression of integral or enumeration
1477 // type; or
1478 // -- the name of a non-type template-parameter; or
1479 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001480 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001481 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1482 Diag(Arg->getSourceRange().getBegin(),
1483 diag::err_template_arg_not_integral_or_enumeral)
1484 << ArgType << Arg->getSourceRange();
1485 Diag(Param->getLocation(), diag::note_template_param_here);
1486 return true;
1487 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001488 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001489 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1490 << ArgType << Arg->getSourceRange();
1491 return true;
1492 }
1493
1494 // FIXME: We need some way to more easily get the unqualified form
1495 // of the types without going all the way to the
1496 // canonical type.
1497 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1498 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1499 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1500 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1501
1502 // Try to convert the argument to the parameter's type.
1503 if (ParamType == ArgType) {
1504 // Okay: no conversion necessary
1505 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1506 !ParamType->isEnumeralType()) {
1507 // This is an integral promotion or conversion.
1508 ImpCastExprToType(Arg, ParamType);
1509 } else {
1510 // We can't perform this conversion.
1511 Diag(Arg->getSourceRange().getBegin(),
1512 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001513 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001514 Diag(Param->getLocation(), diag::note_template_param_here);
1515 return true;
1516 }
1517
Douglas Gregorafc86942009-03-14 00:20:21 +00001518 QualType IntegerType = Context.getCanonicalType(ParamType);
1519 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001520 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001521
1522 if (!Arg->isValueDependent()) {
1523 // Check that an unsigned parameter does not receive a negative
1524 // value.
1525 if (IntegerType->isUnsignedIntegerType()
1526 && (Value.isSigned() && Value.isNegative())) {
1527 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1528 << Value.toString(10) << Param->getType()
1529 << Arg->getSourceRange();
1530 Diag(Param->getLocation(), diag::note_template_param_here);
1531 return true;
1532 }
1533
1534 // Check that we don't overflow the template parameter type.
1535 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1536 if (Value.getActiveBits() > AllowedBits) {
1537 Diag(Arg->getSourceRange().getBegin(),
1538 diag::err_template_arg_too_large)
1539 << Value.toString(10) << Param->getType()
1540 << Arg->getSourceRange();
1541 Diag(Param->getLocation(), diag::note_template_param_here);
1542 return true;
1543 }
1544
1545 if (Value.getBitWidth() != AllowedBits)
1546 Value.extOrTrunc(AllowedBits);
1547 Value.setIsSigned(IntegerType->isSignedIntegerType());
1548 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001549
Douglas Gregor8f378a92009-06-11 18:10:32 +00001550 // Add the value of this argument to the list of converted
1551 // arguments. We use the bitwidth and signedness of the template
1552 // parameter.
1553 if (Arg->isValueDependent()) {
1554 // The argument is value-dependent. Create a new
1555 // TemplateArgument with the converted expression.
1556 Converted = TemplateArgument(Arg);
1557 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001558 }
1559
Douglas Gregor8f378a92009-06-11 18:10:32 +00001560 Converted = TemplateArgument(StartLoc, Value,
1561 ParamType->isEnumeralType() ? ParamType
1562 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001563 return false;
1564 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001565
Douglas Gregor3f411962009-02-11 01:18:59 +00001566 // Handle pointer-to-function, reference-to-function, and
1567 // pointer-to-member-function all in (roughly) the same way.
1568 if (// -- For a non-type template-parameter of type pointer to
1569 // function, only the function-to-pointer conversion (4.3) is
1570 // applied. If the template-argument represents a set of
1571 // overloaded functions (or a pointer to such), the matching
1572 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001573 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001574 (ParamType->isPointerType() &&
1575 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1576 // -- For a non-type template-parameter of type reference to
1577 // function, no conversions apply. If the template-argument
1578 // represents a set of overloaded functions, the matching
1579 // function is selected from the set (13.4).
1580 (ParamType->isReferenceType() &&
1581 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1582 // -- For a non-type template-parameter of type pointer to
1583 // member function, no conversions apply. If the
1584 // template-argument represents a set of overloaded member
1585 // functions, the matching member function is selected from
1586 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001587 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001588 (ParamType->isMemberPointerType() &&
1589 ParamType->getAsMemberPointerType()->getPointeeType()
1590 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001591 if (Context.hasSameUnqualifiedType(ArgType,
1592 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001593 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001594 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1595 ParamType->isMemberPointerType())) {
1596 ArgType = ParamType;
1597 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001598 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001599 ArgType = Context.getPointerType(ArgType);
1600 ImpCastExprToType(Arg, ArgType);
1601 } else if (FunctionDecl *Fn
1602 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001603 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1604 return true;
1605
Douglas Gregor2eedd992009-02-11 00:19:33 +00001606 FixOverloadedFunctionReference(Arg, Fn);
1607 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001608 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001609 ArgType = Context.getPointerType(Arg->getType());
1610 ImpCastExprToType(Arg, ArgType);
1611 }
1612 }
1613
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001614 if (!Context.hasSameUnqualifiedType(ArgType,
1615 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001616 // We can't perform this conversion.
1617 Diag(Arg->getSourceRange().getBegin(),
1618 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001619 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001620 Diag(Param->getLocation(), diag::note_template_param_here);
1621 return true;
1622 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001623
Douglas Gregorad964b32009-02-17 01:05:43 +00001624 if (ParamType->isMemberPointerType()) {
1625 NamedDecl *Member = 0;
1626 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1627 return true;
1628
Douglas Gregor8f378a92009-06-11 18:10:32 +00001629 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1630 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001631 return false;
1632 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001633
Douglas Gregorad964b32009-02-17 01:05:43 +00001634 NamedDecl *Entity = 0;
1635 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1636 return true;
1637
Douglas Gregor8f378a92009-06-11 18:10:32 +00001638 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1639 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001640 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001641 }
1642
Chris Lattner320dff22009-02-20 21:37:53 +00001643 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001644 // -- for a non-type template-parameter of type pointer to
1645 // object, qualification conversions (4.4) and the
1646 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001647 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001648 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001649 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001650
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001651 if (ArgType->isNullPtrType()) {
1652 ArgType = ParamType;
1653 ImpCastExprToType(Arg, ParamType);
1654 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001655 ArgType = Context.getArrayDecayedType(ArgType);
1656 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001657 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001658
Douglas Gregor3f411962009-02-11 01:18:59 +00001659 if (IsQualificationConversion(ArgType, ParamType)) {
1660 ArgType = ParamType;
1661 ImpCastExprToType(Arg, ParamType);
1662 }
1663
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001664 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001665 // We can't perform this conversion.
1666 Diag(Arg->getSourceRange().getBegin(),
1667 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001668 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001669 Diag(Param->getLocation(), diag::note_template_param_here);
1670 return true;
1671 }
1672
Douglas Gregorad964b32009-02-17 01:05:43 +00001673 NamedDecl *Entity = 0;
1674 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1675 return true;
1676
Douglas Gregor8f378a92009-06-11 18:10:32 +00001677 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1678 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001679 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001680 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001681
1682 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1683 // -- For a non-type template-parameter of type reference to
1684 // object, no conversions apply. The type referred to by the
1685 // reference may be more cv-qualified than the (otherwise
1686 // identical) type of the template-argument. The
1687 // template-parameter is bound directly to the
1688 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001689 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001690 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001691
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001692 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001693 Diag(Arg->getSourceRange().getBegin(),
1694 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001695 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001696 << Arg->getSourceRange();
1697 Diag(Param->getLocation(), diag::note_template_param_here);
1698 return true;
1699 }
1700
1701 unsigned ParamQuals
1702 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1703 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1704
1705 if ((ParamQuals | ArgQuals) != ParamQuals) {
1706 Diag(Arg->getSourceRange().getBegin(),
1707 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001708 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001709 << Arg->getSourceRange();
1710 Diag(Param->getLocation(), diag::note_template_param_here);
1711 return true;
1712 }
1713
Douglas Gregorad964b32009-02-17 01:05:43 +00001714 NamedDecl *Entity = 0;
1715 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1716 return true;
1717
Douglas Gregor8f378a92009-06-11 18:10:32 +00001718 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1719 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001720 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001721 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001722
1723 // -- For a non-type template-parameter of type pointer to data
1724 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001725 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001726 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1727
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001728 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001729 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001730 } else if (ArgType->isNullPtrType()) {
1731 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001732 } else if (IsQualificationConversion(ArgType, ParamType)) {
1733 ImpCastExprToType(Arg, ParamType);
1734 } else {
1735 // We can't perform this conversion.
1736 Diag(Arg->getSourceRange().getBegin(),
1737 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001738 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001739 Diag(Param->getLocation(), diag::note_template_param_here);
1740 return true;
1741 }
1742
Douglas Gregorad964b32009-02-17 01:05:43 +00001743 NamedDecl *Member = 0;
1744 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1745 return true;
1746
Douglas Gregor8f378a92009-06-11 18:10:32 +00001747 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1748 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001749 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001750}
1751
1752/// \brief Check a template argument against its corresponding
1753/// template template parameter.
1754///
1755/// This routine implements the semantics of C++ [temp.arg.template].
1756/// It returns true if an error occurred, and false otherwise.
1757bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1758 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001759 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1760 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1761
1762 // C++ [temp.arg.template]p1:
1763 // A template-argument for a template template-parameter shall be
1764 // the name of a class template, expressed as id-expression. Only
1765 // primary class templates are considered when matching the
1766 // template template argument with the corresponding parameter;
1767 // partial specializations are not considered even if their
1768 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001769 //
1770 // Note that we also allow template template parameters here, which
1771 // will happen when we are dealing with, e.g., class template
1772 // partial specializations.
1773 if (!isa<ClassTemplateDecl>(Template) &&
1774 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001775 assert(isa<FunctionTemplateDecl>(Template) &&
1776 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001777 Diag(Arg->getSourceRange().getBegin(),
1778 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001779 << Template;
1780 }
1781
1782 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1783 Param->getTemplateParameters(),
1784 true, true,
1785 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001786}
1787
Douglas Gregord406b032009-02-06 22:42:48 +00001788/// \brief Determine whether the given template parameter lists are
1789/// equivalent.
1790///
1791/// \param New The new template parameter list, typically written in the
1792/// source code as part of a new template declaration.
1793///
1794/// \param Old The old template parameter list, typically found via
1795/// name lookup of the template declared with this template parameter
1796/// list.
1797///
1798/// \param Complain If true, this routine will produce a diagnostic if
1799/// the template parameter lists are not equivalent.
1800///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001801/// \param IsTemplateTemplateParm If true, this routine is being
1802/// called to compare the template parameter lists of a template
1803/// template parameter.
1804///
1805/// \param TemplateArgLoc If this source location is valid, then we
1806/// are actually checking the template parameter list of a template
1807/// argument (New) against the template parameter list of its
1808/// corresponding template template parameter (Old). We produce
1809/// slightly different diagnostics in this scenario.
1810///
Douglas Gregord406b032009-02-06 22:42:48 +00001811/// \returns True if the template parameter lists are equal, false
1812/// otherwise.
1813bool
1814Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1815 TemplateParameterList *Old,
1816 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001817 bool IsTemplateTemplateParm,
1818 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001819 if (Old->size() != New->size()) {
1820 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001821 unsigned NextDiag = diag::err_template_param_list_different_arity;
1822 if (TemplateArgLoc.isValid()) {
1823 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1824 NextDiag = diag::note_template_param_list_different_arity;
1825 }
1826 Diag(New->getTemplateLoc(), NextDiag)
1827 << (New->size() > Old->size())
1828 << IsTemplateTemplateParm
1829 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001830 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1831 << IsTemplateTemplateParm
1832 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1833 }
1834
1835 return false;
1836 }
1837
1838 for (TemplateParameterList::iterator OldParm = Old->begin(),
1839 OldParmEnd = Old->end(), NewParm = New->begin();
1840 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1841 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001842 unsigned NextDiag = diag::err_template_param_different_kind;
1843 if (TemplateArgLoc.isValid()) {
1844 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1845 NextDiag = diag::note_template_param_different_kind;
1846 }
1847 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001848 << IsTemplateTemplateParm;
1849 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1850 << IsTemplateTemplateParm;
1851 return false;
1852 }
1853
1854 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1855 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001856 // know we're at the same index).
1857#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001858 // FIXME: Enable this code in debug mode *after* we properly go through
1859 // and "instantiate" the template parameter lists of template template
1860 // parameters. It's only after this instantiation that (1) any dependent
1861 // types within the template parameter list of the template template
1862 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001863 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001864 QualType OldParmType
1865 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1866 QualType NewParmType
1867 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1868 assert(Context.getCanonicalType(OldParmType) ==
1869 Context.getCanonicalType(NewParmType) &&
1870 "type parameter mismatch?");
1871#endif
1872 } else if (NonTypeTemplateParmDecl *OldNTTP
1873 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1874 // The types of non-type template parameters must agree.
1875 NonTypeTemplateParmDecl *NewNTTP
1876 = cast<NonTypeTemplateParmDecl>(*NewParm);
1877 if (Context.getCanonicalType(OldNTTP->getType()) !=
1878 Context.getCanonicalType(NewNTTP->getType())) {
1879 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001880 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1881 if (TemplateArgLoc.isValid()) {
1882 Diag(TemplateArgLoc,
1883 diag::err_template_arg_template_params_mismatch);
1884 NextDiag = diag::note_template_nontype_parm_different_type;
1885 }
1886 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001887 << NewNTTP->getType()
1888 << IsTemplateTemplateParm;
1889 Diag(OldNTTP->getLocation(),
1890 diag::note_template_nontype_parm_prev_declaration)
1891 << OldNTTP->getType();
1892 }
1893 return false;
1894 }
1895 } else {
1896 // The template parameter lists of template template
1897 // parameters must agree.
1898 // FIXME: Could we perform a faster "type" comparison here?
1899 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1900 "Only template template parameters handled here");
1901 TemplateTemplateParmDecl *OldTTP
1902 = cast<TemplateTemplateParmDecl>(*OldParm);
1903 TemplateTemplateParmDecl *NewTTP
1904 = cast<TemplateTemplateParmDecl>(*NewParm);
1905 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1906 OldTTP->getTemplateParameters(),
1907 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001908 /*IsTemplateTemplateParm=*/true,
1909 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001910 return false;
1911 }
1912 }
1913
1914 return true;
1915}
1916
1917/// \brief Check whether a template can be declared within this scope.
1918///
1919/// If the template declaration is valid in this scope, returns
1920/// false. Otherwise, issues a diagnostic and returns true.
1921bool
1922Sema::CheckTemplateDeclScope(Scope *S,
1923 MultiTemplateParamsArg &TemplateParameterLists) {
1924 assert(TemplateParameterLists.size() > 0 && "Not a template");
1925
1926 // Find the nearest enclosing declaration scope.
1927 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1928 (S->getFlags() & Scope::TemplateParamScope) != 0)
1929 S = S->getParent();
1930
1931 TemplateParameterList *TemplateParams =
1932 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1933 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1934 SourceRange TemplateRange
1935 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1936
1937 // C++ [temp]p2:
1938 // A template-declaration can appear only as a namespace scope or
1939 // class scope declaration.
1940 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1941 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1942 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1943 return Diag(TemplateLoc, diag::err_template_linkage)
1944 << TemplateRange;
1945
1946 Ctx = Ctx->getParent();
1947 }
1948
1949 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1950 return false;
1951
1952 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1953 << TemplateRange;
1954}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001955
Douglas Gregor90177912009-05-13 18:28:20 +00001956/// \brief Check whether a class template specialization or explicit
1957/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001958///
Douglas Gregor90177912009-05-13 18:28:20 +00001959/// This routine determines whether a class template specialization or
1960/// explicit instantiation can be declared in the current context
1961/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1962/// appropriate diagnostics if there was an error. It returns true if
1963// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001964bool
1965Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1966 ClassTemplateSpecializationDecl *PrevDecl,
1967 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001968 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001969 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001970 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001971 // C++ [temp.expl.spec]p2:
1972 // An explicit specialization shall be declared in the namespace
1973 // of which the template is a member, or, for member templates, in
1974 // the namespace of which the enclosing class or enclosing class
1975 // template is a member. An explicit specialization of a member
1976 // function, member class or static data member of a class
1977 // template shall be declared in the namespace of which the class
1978 // template is a member. Such a declaration may also be a
1979 // definition. If the declaration is not a definition, the
1980 // specialization may be defined later in the name- space in which
1981 // the explicit specialization was declared, or in a namespace
1982 // that encloses the one in which the explicit specialization was
1983 // declared.
1984 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00001985 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001986 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001987 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001988 return true;
1989 }
1990
1991 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1992 DeclContext *TemplateContext
1993 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001994 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1995 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001996 // There is no prior declaration of this entity, so this
1997 // specialization must be in the same context as the template
1998 // itself.
1999 if (DC != TemplateContext) {
2000 if (isa<TranslationUnitDecl>(TemplateContext))
2001 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002002 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002003 << ClassTemplate << ScopeSpecifierRange;
2004 else if (isa<NamespaceDecl>(TemplateContext))
2005 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002006 << PartialSpecialization << ClassTemplate
2007 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002008
2009 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2010 }
2011
2012 return false;
2013 }
2014
2015 // We have a previous declaration of this entity. Make sure that
2016 // this redeclaration (or definition) occurs in an enclosing namespace.
2017 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002018 // FIXME: In C++98, we would like to turn these errors into warnings,
2019 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002020 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002021 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002022 if (isa<TranslationUnitDecl>(TemplateContext)) {
2023 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2024 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002025 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002026 else
2027 SuppressedDiag = true;
2028 } else if (isa<NamespaceDecl>(TemplateContext)) {
2029 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2030 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002031 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002032 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2033 else
2034 SuppressedDiag = true;
2035 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002036
Douglas Gregor90177912009-05-13 18:28:20 +00002037 if (!SuppressedDiag)
2038 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002039 }
2040
2041 return false;
2042}
2043
Douglas Gregor76e79952009-06-12 21:21:02 +00002044/// \brief Check the non-type template arguments of a class template
2045/// partial specialization according to C++ [temp.class.spec]p9.
2046///
Douglas Gregor42476442009-06-12 22:08:06 +00002047/// \param TemplateParams the template parameters of the primary class
2048/// template.
2049///
2050/// \param TemplateArg the template arguments of the class template
2051/// partial specialization.
2052///
2053/// \param MirrorsPrimaryTemplate will be set true if the class
2054/// template partial specialization arguments are identical to the
2055/// implicit template arguments of the primary template. This is not
2056/// necessarily an error (C++0x), and it is left to the caller to diagnose
2057/// this condition when it is an error.
2058///
Douglas Gregor76e79952009-06-12 21:21:02 +00002059/// \returns true if there was an error, false otherwise.
2060bool Sema::CheckClassTemplatePartialSpecializationArgs(
2061 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002062 const TemplateArgument *TemplateArgs,
2063 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002064 // FIXME: the interface to this function will have to change to
2065 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002066 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002067 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002068 // Determine whether the template argument list of the partial
2069 // specialization is identical to the implicit argument list of
2070 // the primary template. The caller may need to diagnostic this as
2071 // an error per C++ [temp.class.spec]p9b3.
2072 if (MirrorsPrimaryTemplate) {
2073 if (TemplateTypeParmDecl *TTP
2074 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2075 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2076 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2077 MirrorsPrimaryTemplate = false;
2078 } else if (TemplateTemplateParmDecl *TTP
2079 = dyn_cast<TemplateTemplateParmDecl>(
2080 TemplateParams->getParam(I))) {
2081 // FIXME: We should settle on either Declaration storage or
2082 // Expression storage for template template parameters.
2083 TemplateTemplateParmDecl *ArgDecl
2084 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2085 TemplateArgs[I].getAsDecl());
2086 if (!ArgDecl)
2087 if (DeclRefExpr *DRE
2088 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2089 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2090
2091 if (!ArgDecl ||
2092 ArgDecl->getIndex() != TTP->getIndex() ||
2093 ArgDecl->getDepth() != TTP->getDepth())
2094 MirrorsPrimaryTemplate = false;
2095 }
2096 }
2097
Douglas Gregor76e79952009-06-12 21:21:02 +00002098 NonTypeTemplateParmDecl *Param
2099 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002100 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002101 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002102 }
2103
Douglas Gregor76e79952009-06-12 21:21:02 +00002104 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002105 if (!ArgExpr) {
2106 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002107 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002108 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002109
2110 // C++ [temp.class.spec]p8:
2111 // A non-type argument is non-specialized if it is the name of a
2112 // non-type parameter. All other non-type arguments are
2113 // specialized.
2114 //
2115 // Below, we check the two conditions that only apply to
2116 // specialized non-type arguments, so skip any non-specialized
2117 // arguments.
2118 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002119 if (NonTypeTemplateParmDecl *NTTP
2120 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2121 if (MirrorsPrimaryTemplate &&
2122 (Param->getIndex() != NTTP->getIndex() ||
2123 Param->getDepth() != NTTP->getDepth()))
2124 MirrorsPrimaryTemplate = false;
2125
Douglas Gregor76e79952009-06-12 21:21:02 +00002126 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002127 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002128
2129 // C++ [temp.class.spec]p9:
2130 // Within the argument list of a class template partial
2131 // specialization, the following restrictions apply:
2132 // -- A partially specialized non-type argument expression
2133 // shall not involve a template parameter of the partial
2134 // specialization except when the argument expression is a
2135 // simple identifier.
2136 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2137 Diag(ArgExpr->getLocStart(),
2138 diag::err_dependent_non_type_arg_in_partial_spec)
2139 << ArgExpr->getSourceRange();
2140 return true;
2141 }
2142
2143 // -- The type of a template parameter corresponding to a
2144 // specialized non-type argument shall not be dependent on a
2145 // parameter of the specialization.
2146 if (Param->getType()->isDependentType()) {
2147 Diag(ArgExpr->getLocStart(),
2148 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2149 << Param->getType()
2150 << ArgExpr->getSourceRange();
2151 Diag(Param->getLocation(), diag::note_template_param_here);
2152 return true;
2153 }
Douglas Gregor42476442009-06-12 22:08:06 +00002154
2155 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002156 }
2157
2158 return false;
2159}
2160
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002161Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002162Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2163 SourceLocation KWLoc,
2164 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002165 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002166 SourceLocation TemplateNameLoc,
2167 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002168 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002169 SourceLocation *TemplateArgLocs,
2170 SourceLocation RAngleLoc,
2171 AttributeList *Attr,
2172 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002173 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002174 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002175 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002176 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002177
Douglas Gregor58944ac2009-05-31 09:31:02 +00002178 bool isPartialSpecialization = false;
2179
Douglas Gregor0d93f692009-02-25 22:02:03 +00002180 // Check the validity of the template headers that introduce this
2181 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002182 // FIXME: Once we have member templates, we'll need to check
2183 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2184 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002185 if (TemplateParameterLists.size() == 0)
2186 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002187 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002188 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002189 TemplateParameterList *TemplateParams
2190 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002191 if (TemplateParameterLists.size() > 1) {
2192 Diag(TemplateParams->getTemplateLoc(),
2193 diag::err_template_spec_extra_headers);
2194 return true;
2195 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002196
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002197 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002198 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002199
2200 // C++ [temp.class.spec]p10:
2201 // The template parameter list of a specialization shall not
2202 // contain default template argument values.
2203 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2204 Decl *Param = TemplateParams->getParam(I);
2205 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2206 if (TTP->hasDefaultArgument()) {
2207 Diag(TTP->getDefaultArgumentLoc(),
2208 diag::err_default_arg_in_partial_spec);
2209 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2210 }
2211 } else if (NonTypeTemplateParmDecl *NTTP
2212 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2213 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2214 Diag(NTTP->getDefaultArgumentLoc(),
2215 diag::err_default_arg_in_partial_spec)
2216 << DefArg->getSourceRange();
2217 NTTP->setDefaultArgument(0);
2218 DefArg->Destroy(Context);
2219 }
2220 } else {
2221 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2222 if (Expr *DefArg = TTP->getDefaultArgument()) {
2223 Diag(TTP->getDefaultArgumentLoc(),
2224 diag::err_default_arg_in_partial_spec)
2225 << DefArg->getSourceRange();
2226 TTP->setDefaultArgument(0);
2227 DefArg->Destroy(Context);
2228 }
2229 }
2230 }
2231 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002232 }
2233
Douglas Gregora08b6c72009-02-17 23:15:12 +00002234 // Check that the specialization uses the same tag kind as the
2235 // original template.
2236 TagDecl::TagKind Kind;
2237 switch (TagSpec) {
2238 default: assert(0 && "Unknown tag type!");
2239 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2240 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2241 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2242 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002243 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2244 Kind, KWLoc,
2245 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002246 Diag(KWLoc, diag::err_use_with_wrong_tag)
2247 << ClassTemplate
2248 << CodeModificationHint::CreateReplacement(KWLoc,
2249 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002250 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2251 diag::note_previous_use);
2252 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2253 }
2254
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002255 // Translate the parser's template argument list in our AST format.
2256 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2257 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2258
Douglas Gregora08b6c72009-02-17 23:15:12 +00002259 // Check that the template argument list is well-formed for this
2260 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002261 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002262 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002263 &TemplateArgs[0], TemplateArgs.size(),
2264 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002265 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002266
2267 assert((ConvertedTemplateArgs.size() ==
2268 ClassTemplate->getTemplateParameters()->size()) &&
2269 "Converted template argument list is too short!");
2270
Douglas Gregor58944ac2009-05-31 09:31:02 +00002271 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002272 // corresponds to these arguments.
2273 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002274 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002275 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002276 if (CheckClassTemplatePartialSpecializationArgs(
2277 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002278 ConvertedTemplateArgs.getFlatArgumentList(),
2279 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002280 return true;
2281
Douglas Gregor42476442009-06-12 22:08:06 +00002282 if (MirrorsPrimaryTemplate) {
2283 // C++ [temp.class.spec]p9b3:
2284 //
2285 // -- The argument list of the specialization shall not be identical
2286 // to the implicit argument list of the primary template.
2287 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2288 << (TK == TK_Definition)
2289 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2290 RAngleLoc));
2291 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2292 ClassTemplate->getIdentifier(),
2293 TemplateNameLoc,
2294 Attr,
2295 move(TemplateParameterLists),
2296 AS_none);
2297 }
2298
Douglas Gregor58944ac2009-05-31 09:31:02 +00002299 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002300 ClassTemplatePartialSpecializationDecl::Profile(ID,
2301 ConvertedTemplateArgs.getFlatArgumentList(),
2302 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002303 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002304 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002305 ClassTemplateSpecializationDecl::Profile(ID,
2306 ConvertedTemplateArgs.getFlatArgumentList(),
2307 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002308 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002309 ClassTemplateSpecializationDecl *PrevDecl = 0;
2310
2311 if (isPartialSpecialization)
2312 PrevDecl
2313 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2314 InsertPos);
2315 else
2316 PrevDecl
2317 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002318
2319 ClassTemplateSpecializationDecl *Specialization = 0;
2320
Douglas Gregor0d93f692009-02-25 22:02:03 +00002321 // Check whether we can declare a class template specialization in
2322 // the current scope.
2323 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2324 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002325 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002326 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002327 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002328 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002329
Douglas Gregora08b6c72009-02-17 23:15:12 +00002330 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2331 // Since the only prior class template specialization with these
2332 // arguments was referenced but not declared, reuse that
2333 // declaration node as our own, updating its source location to
2334 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002335 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002336 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002337 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002338 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002339 // Create a new class template partial specialization declaration node.
2340 TemplateParameterList *TemplateParams
2341 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2342 ClassTemplatePartialSpecializationDecl *PrevPartial
2343 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2344 ClassTemplatePartialSpecializationDecl *Partial
2345 = ClassTemplatePartialSpecializationDecl::Create(Context,
2346 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002347 TemplateNameLoc,
2348 TemplateParams,
2349 ClassTemplate,
2350 ConvertedTemplateArgs,
2351 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002352
2353 if (PrevPartial) {
2354 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2355 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2356 } else {
2357 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2358 }
2359 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002360
2361 // Check that all of the template parameters of the class template
2362 // partial specialization are deducible from the template
2363 // arguments. If not, this class template partial specialization
2364 // will never be used.
2365 llvm::SmallVector<bool, 8> DeducibleParams;
2366 DeducibleParams.resize(TemplateParams->size());
2367 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2368 unsigned NumNonDeducible = 0;
2369 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2370 if (!DeducibleParams[I])
2371 ++NumNonDeducible;
2372
2373 if (NumNonDeducible) {
2374 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2375 << (NumNonDeducible > 1)
2376 << SourceRange(TemplateNameLoc, RAngleLoc);
2377 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2378 if (!DeducibleParams[I]) {
2379 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2380 if (Param->getDeclName())
2381 Diag(Param->getLocation(),
2382 diag::note_partial_spec_unused_parameter)
2383 << Param->getDeclName();
2384 else
2385 Diag(Param->getLocation(),
2386 diag::note_partial_spec_unused_parameter)
2387 << std::string("<anonymous>");
2388 }
2389 }
2390 }
2391
Douglas Gregora08b6c72009-02-17 23:15:12 +00002392 } else {
2393 // Create a new class template specialization declaration node for
2394 // this explicit specialization.
2395 Specialization
2396 = ClassTemplateSpecializationDecl::Create(Context,
2397 ClassTemplate->getDeclContext(),
2398 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002399 ClassTemplate,
2400 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002401 PrevDecl);
2402
2403 if (PrevDecl) {
2404 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2405 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2406 } else {
2407 ClassTemplate->getSpecializations().InsertNode(Specialization,
2408 InsertPos);
2409 }
2410 }
2411
2412 // Note that this is an explicit specialization.
2413 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2414
2415 // Check that this isn't a redefinition of this specialization.
2416 if (TK == TK_Definition) {
2417 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002418 // FIXME: Should also handle explicit specialization after implicit
2419 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002420 SourceRange Range(TemplateNameLoc, RAngleLoc);
2421 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002422 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002423 Diag(Def->getLocation(), diag::note_previous_definition);
2424 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002425 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002426 }
2427 }
2428
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002429 // Build the fully-sugared type for this class template
2430 // specialization as the user wrote in the specialization
2431 // itself. This means that we'll pretty-print the type retrieved
2432 // from the specialization's declaration the way that the user
2433 // actually wrote the specialization, rather than formatting the
2434 // name based on the "canonical" representation used to store the
2435 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002436 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002437 = Context.getTemplateSpecializationType(Name,
2438 &TemplateArgs[0],
2439 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002440 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002441 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002442 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002443
Douglas Gregor50113ca2009-02-25 22:18:32 +00002444 // C++ [temp.expl.spec]p9:
2445 // A template explicit specialization is in the scope of the
2446 // namespace in which the template was defined.
2447 //
2448 // We actually implement this paragraph where we set the semantic
2449 // context (in the creation of the ClassTemplateSpecializationDecl),
2450 // but we also maintain the lexical context where the actual
2451 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002452 Specialization->setLexicalDeclContext(CurContext);
2453
2454 // We may be starting the definition of this specialization.
2455 if (TK == TK_Definition)
2456 Specialization->startDefinition();
2457
2458 // Add the specialization into its lexical context, so that it can
2459 // be seen when iterating through the list of declarations in that
2460 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002461 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002462 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002463}
Douglas Gregord3022602009-03-27 23:10:48 +00002464
Douglas Gregor96b6df92009-05-14 00:28:11 +00002465// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002466Sema::DeclResult
2467Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2468 unsigned TagSpec,
2469 SourceLocation KWLoc,
2470 const CXXScopeSpec &SS,
2471 TemplateTy TemplateD,
2472 SourceLocation TemplateNameLoc,
2473 SourceLocation LAngleLoc,
2474 ASTTemplateArgsPtr TemplateArgsIn,
2475 SourceLocation *TemplateArgLocs,
2476 SourceLocation RAngleLoc,
2477 AttributeList *Attr) {
2478 // Find the class template we're specializing
2479 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2480 ClassTemplateDecl *ClassTemplate
2481 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2482
2483 // Check that the specialization uses the same tag kind as the
2484 // original template.
2485 TagDecl::TagKind Kind;
2486 switch (TagSpec) {
2487 default: assert(0 && "Unknown tag type!");
2488 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2489 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2490 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2491 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002492 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2493 Kind, KWLoc,
2494 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002495 Diag(KWLoc, diag::err_use_with_wrong_tag)
2496 << ClassTemplate
2497 << CodeModificationHint::CreateReplacement(KWLoc,
2498 ClassTemplate->getTemplatedDecl()->getKindName());
2499 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2500 diag::note_previous_use);
2501 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2502 }
2503
Douglas Gregor90177912009-05-13 18:28:20 +00002504 // C++0x [temp.explicit]p2:
2505 // [...] An explicit instantiation shall appear in an enclosing
2506 // namespace of its template. [...]
2507 //
2508 // This is C++ DR 275.
2509 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2510 TemplateNameLoc,
2511 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002512 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002513 /*ExplicitInstantiation=*/true))
2514 return true;
2515
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002516 // Translate the parser's template argument list in our AST format.
2517 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2518 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2519
2520 // Check that the template argument list is well-formed for this
2521 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002522 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002523 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002524 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002525 RAngleLoc, ConvertedTemplateArgs))
2526 return true;
2527
2528 assert((ConvertedTemplateArgs.size() ==
2529 ClassTemplate->getTemplateParameters()->size()) &&
2530 "Converted template argument list is too short!");
2531
2532 // Find the class template specialization declaration that
2533 // corresponds to these arguments.
2534 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002535 ClassTemplateSpecializationDecl::Profile(ID,
2536 ConvertedTemplateArgs.getFlatArgumentList(),
2537 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002538 void *InsertPos = 0;
2539 ClassTemplateSpecializationDecl *PrevDecl
2540 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2541
2542 ClassTemplateSpecializationDecl *Specialization = 0;
2543
Douglas Gregor90177912009-05-13 18:28:20 +00002544 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002545 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002546 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002547 // This particular specialization has already been declared or
2548 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002549 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2550 << Context.getTypeDeclType(PrevDecl);
2551 Diag(PrevDecl->getLocation(),
2552 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002553 return DeclPtrTy::make(PrevDecl);
2554 }
2555
Douglas Gregor90177912009-05-13 18:28:20 +00002556 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002557 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002558 // For a given set of template parameters, if an explicit
2559 // instantiation of a template appears after a declaration of
2560 // an explicit specialization for that template, the explicit
2561 // instantiation has no effect.
2562 if (!getLangOptions().CPlusPlus0x) {
2563 Diag(TemplateNameLoc,
2564 diag::ext_explicit_instantiation_after_specialization)
2565 << Context.getTypeDeclType(PrevDecl);
2566 Diag(PrevDecl->getLocation(),
2567 diag::note_previous_template_specialization);
2568 }
2569
2570 // Create a new class template specialization declaration node
2571 // for this explicit specialization. This node is only used to
2572 // record the existence of this explicit instantiation for
2573 // accurate reproduction of the source code; we don't actually
2574 // use it for anything, since it is semantically irrelevant.
2575 Specialization
2576 = ClassTemplateSpecializationDecl::Create(Context,
2577 ClassTemplate->getDeclContext(),
2578 TemplateNameLoc,
2579 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002580 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002581 Specialization->setLexicalDeclContext(CurContext);
2582 CurContext->addDecl(Context, Specialization);
2583 return DeclPtrTy::make(Specialization);
2584 }
2585
2586 // If we have already (implicitly) instantiated this
2587 // specialization, there is less work to do.
2588 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2589 SpecializationRequiresInstantiation = false;
2590
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002591 // Since the only prior class template specialization with these
2592 // arguments was referenced but not declared, reuse that
2593 // declaration node as our own, updating its source location to
2594 // reflect our new declaration.
2595 Specialization = PrevDecl;
2596 Specialization->setLocation(TemplateNameLoc);
2597 PrevDecl = 0;
2598 } else {
2599 // Create a new class template specialization declaration node for
2600 // this explicit specialization.
2601 Specialization
2602 = ClassTemplateSpecializationDecl::Create(Context,
2603 ClassTemplate->getDeclContext(),
2604 TemplateNameLoc,
2605 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002606 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002607
2608 ClassTemplate->getSpecializations().InsertNode(Specialization,
2609 InsertPos);
2610 }
2611
2612 // Build the fully-sugared type for this explicit instantiation as
2613 // the user wrote in the explicit instantiation itself. This means
2614 // that we'll pretty-print the type retrieved from the
2615 // specialization's declaration the way that the user actually wrote
2616 // the explicit instantiation, rather than formatting the name based
2617 // on the "canonical" representation used to store the template
2618 // arguments in the specialization.
2619 QualType WrittenTy
2620 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002621 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002622 TemplateArgs.size(),
2623 Context.getTypeDeclType(Specialization));
2624 Specialization->setTypeAsWritten(WrittenTy);
2625 TemplateArgsIn.release();
2626
2627 // Add the explicit instantiation into its lexical context. However,
2628 // since explicit instantiations are never found by name lookup, we
2629 // just put it into the declaration context directly.
2630 Specialization->setLexicalDeclContext(CurContext);
2631 CurContext->addDecl(Context, Specialization);
2632
2633 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002634 // A definition of a class template or class member template
2635 // shall be in scope at the point of the explicit instantiation of
2636 // the class template or class member template.
2637 //
2638 // This check comes when we actually try to perform the
2639 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002640 if (SpecializationRequiresInstantiation)
2641 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002642 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002643 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002644
2645 return DeclPtrTy::make(Specialization);
2646}
2647
Douglas Gregor96b6df92009-05-14 00:28:11 +00002648// Explicit instantiation of a member class of a class template.
2649Sema::DeclResult
2650Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2651 unsigned TagSpec,
2652 SourceLocation KWLoc,
2653 const CXXScopeSpec &SS,
2654 IdentifierInfo *Name,
2655 SourceLocation NameLoc,
2656 AttributeList *Attr) {
2657
Douglas Gregor71f06032009-05-28 23:31:59 +00002658 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002659 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002660 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002661 if (!TagD)
2662 return true;
2663
2664 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2665 if (Tag->isEnum()) {
2666 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2667 << Context.getTypeDeclType(Tag);
2668 return true;
2669 }
2670
Douglas Gregord769bfa2009-05-27 17:30:49 +00002671 if (Tag->isInvalidDecl())
2672 return true;
2673
Douglas Gregor96b6df92009-05-14 00:28:11 +00002674 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2675 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2676 if (!Pattern) {
2677 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2678 << Context.getTypeDeclType(Record);
2679 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2680 return true;
2681 }
2682
2683 // C++0x [temp.explicit]p2:
2684 // [...] An explicit instantiation shall appear in an enclosing
2685 // namespace of its template. [...]
2686 //
2687 // This is C++ DR 275.
2688 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002689 // FIXME: In C++98, we would like to turn these errors into warnings,
2690 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002691 DeclContext *PatternContext
2692 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2693 if (!CurContext->Encloses(PatternContext)) {
2694 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2695 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2696 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2697 }
2698 }
2699
Douglas Gregor96b6df92009-05-14 00:28:11 +00002700 if (!Record->getDefinition(Context)) {
2701 // If the class has a definition, instantiate it (and all of its
2702 // members, recursively).
2703 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2704 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002705 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002706 /*ExplicitInstantiation=*/true))
2707 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002708 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002709 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002710 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002711
Mike Stumpe127ae32009-05-16 07:39:55 +00002712 // FIXME: We don't have any representation for explicit instantiations of
2713 // member classes. Such a representation is not needed for compilation, but it
2714 // should be available for clients that want to see all of the declarations in
2715 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002716 return TagD;
2717}
2718
Douglas Gregord3022602009-03-27 23:10:48 +00002719Sema::TypeResult
2720Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2721 const IdentifierInfo &II, SourceLocation IdLoc) {
2722 NestedNameSpecifier *NNS
2723 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2724 if (!NNS)
2725 return true;
2726
2727 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002728 if (T.isNull())
2729 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002730 return T.getAsOpaquePtr();
2731}
2732
Douglas Gregor77da5802009-04-01 00:28:59 +00002733Sema::TypeResult
2734Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2735 SourceLocation TemplateLoc, TypeTy *Ty) {
2736 QualType T = QualType::getFromOpaquePtr(Ty);
2737 NestedNameSpecifier *NNS
2738 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2739 const TemplateSpecializationType *TemplateId
2740 = T->getAsTemplateSpecializationType();
2741 assert(TemplateId && "Expected a template specialization type");
2742
2743 if (NNS->isDependent())
2744 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2745
2746 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2747}
2748
Douglas Gregord3022602009-03-27 23:10:48 +00002749/// \brief Build the type that describes a C++ typename specifier,
2750/// e.g., "typename T::type".
2751QualType
2752Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2753 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002754 CXXRecordDecl *CurrentInstantiation = 0;
2755 if (NNS->isDependent()) {
2756 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002757
Douglas Gregor3eb20702009-05-11 19:58:34 +00002758 // If the nested-name-specifier does not refer to the current
2759 // instantiation, then build a typename type.
2760 if (!CurrentInstantiation)
2761 return Context.getTypenameType(NNS, &II);
2762 }
Douglas Gregord3022602009-03-27 23:10:48 +00002763
Douglas Gregor3eb20702009-05-11 19:58:34 +00002764 DeclContext *Ctx = 0;
2765
2766 if (CurrentInstantiation)
2767 Ctx = CurrentInstantiation;
2768 else {
2769 CXXScopeSpec SS;
2770 SS.setScopeRep(NNS);
2771 SS.setRange(Range);
2772 if (RequireCompleteDeclContext(SS))
2773 return QualType();
2774
2775 Ctx = computeDeclContext(SS);
2776 }
Douglas Gregord3022602009-03-27 23:10:48 +00002777 assert(Ctx && "No declaration context?");
2778
2779 DeclarationName Name(&II);
2780 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2781 false);
2782 unsigned DiagID = 0;
2783 Decl *Referenced = 0;
2784 switch (Result.getKind()) {
2785 case LookupResult::NotFound:
2786 if (Ctx->isTranslationUnit())
2787 DiagID = diag::err_typename_nested_not_found_global;
2788 else
2789 DiagID = diag::err_typename_nested_not_found;
2790 break;
2791
2792 case LookupResult::Found:
2793 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2794 // We found a type. Build a QualifiedNameType, since the
2795 // typename-specifier was just sugar. FIXME: Tell
2796 // QualifiedNameType that it has a "typename" prefix.
2797 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2798 }
2799
2800 DiagID = diag::err_typename_nested_not_type;
2801 Referenced = Result.getAsDecl();
2802 break;
2803
2804 case LookupResult::FoundOverloaded:
2805 DiagID = diag::err_typename_nested_not_type;
2806 Referenced = *Result.begin();
2807 break;
2808
2809 case LookupResult::AmbiguousBaseSubobjectTypes:
2810 case LookupResult::AmbiguousBaseSubobjects:
2811 case LookupResult::AmbiguousReference:
2812 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2813 return QualType();
2814 }
2815
2816 // If we get here, it's because name lookup did not find a
2817 // type. Emit an appropriate diagnostic and return an error.
2818 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2819 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2820 else
2821 Diag(Range.getEnd(), DiagID) << Range << Name;
2822 if (Referenced)
2823 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2824 << Name;
2825 return QualType();
2826}