blob: 78c1a9a97afb54db09f31bd3977936580685da4e [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
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000978/// \brief Check that the given template argument list is well-formed
979/// for specializing the given template.
980bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
981 SourceLocation TemplateLoc,
982 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000983 const TemplateArgument *TemplateArgs,
984 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000985 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +0000986 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000987 TemplateParameterList *Params = Template->getTemplateParameters();
988 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000989 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000990 bool Invalid = false;
991
992 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000993 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000994 // FIXME: point at either the first arg beyond what we can handle,
995 // or the '>', depending on whether we have too many or too few
996 // arguments.
997 SourceRange Range;
998 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000999 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001000 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1001 << (NumArgs > NumParams)
1002 << (isa<ClassTemplateDecl>(Template)? 0 :
1003 isa<FunctionTemplateDecl>(Template)? 1 :
1004 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1005 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001006 Diag(Template->getLocation(), diag::note_template_decl_here)
1007 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001008 Invalid = true;
1009 }
1010
1011 // C++ [temp.arg]p1:
1012 // [...] The type and form of each template-argument specified in
1013 // a template-id shall match the type and form specified for the
1014 // corresponding parameter declared by the template in its
1015 // template-parameter-list.
1016 unsigned ArgIdx = 0;
1017 for (TemplateParameterList::iterator Param = Params->begin(),
1018 ParamEnd = Params->end();
1019 Param != ParamEnd; ++Param, ++ArgIdx) {
1020 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001021 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001022 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001023 // Retrieve the default template argument from the template
1024 // parameter.
1025 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1026 if (!TTP->hasDefaultArgument())
1027 break;
1028
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001029 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001030
1031 // If the argument type is dependent, instantiate it now based
1032 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001033 if (ArgType->isDependentType()) {
1034 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001035 Template, Converted.getFlatArgumentList(),
1036 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001037 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001038
Anders Carlsson0233eb62009-06-05 04:47:51 +00001039 TemplateArgumentList TemplateArgs(Context, Converted,
1040 /*CopyArgs=*/false,
1041 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001042 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001043 TTP->getDefaultArgumentLoc(),
1044 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001045 }
Douglas Gregor74296542009-02-27 19:31:52 +00001046
1047 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001048 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001049
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001050 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001051 } else if (NonTypeTemplateParmDecl *NTTP
1052 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1053 if (!NTTP->hasDefaultArgument())
1054 break;
1055
Anders Carlsson0297caf2009-06-11 16:06:49 +00001056 InstantiatingTemplate Inst(*this, TemplateLoc,
1057 Template, Converted.getFlatArgumentList(),
1058 Converted.flatSize(),
1059 SourceRange(TemplateLoc, RAngleLoc));
1060
1061 TemplateArgumentList TemplateArgs(Context, Converted,
1062 /*CopyArgs=*/false,
1063 /*FlattenArgs=*/false);
1064
1065 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1066 TemplateArgs);
1067 if (E.isInvalid())
1068 return true;
1069
1070 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001071 } else {
1072 TemplateTemplateParmDecl *TempParm
1073 = cast<TemplateTemplateParmDecl>(*Param);
1074
1075 if (!TempParm->hasDefaultArgument())
1076 break;
1077
Douglas Gregored3a3982009-03-03 04:44:36 +00001078 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001079 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001080 }
1081 } else {
1082 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001083 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001084 }
1085
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001086
1087 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1088 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001089 if (Arg.getKind() == TemplateArgument::Type) {
1090 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001091 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001092
1093 // Add the converted template type argument.
1094 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001095 TemplateArgument(Arg.getLocation(),
1096 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001097 continue;
1098 }
1099
1100 // C++ [temp.arg.type]p1:
1101 // A template-argument for a template-parameter which is a
1102 // type shall be a type-id.
1103
1104 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001105 // is not a type.
1106 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001107 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001108 Invalid = true;
1109 } else if (NonTypeTemplateParmDecl *NTTP
1110 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1111 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001112
1113 // Instantiate the type of the non-type template parameter with
1114 // the template arguments we've seen thus far.
1115 QualType NTTPType = NTTP->getType();
1116 if (NTTPType->isDependentType()) {
1117 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001118 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001119 Template, Converted.getFlatArgumentList(),
1120 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001121 SourceRange(TemplateLoc, RAngleLoc));
1122
Anders Carlsson0233eb62009-06-05 04:47:51 +00001123 TemplateArgumentList TemplateArgs(Context, Converted,
1124 /*CopyArgs=*/false,
1125 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001126 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001127 NTTP->getLocation(),
1128 NTTP->getDeclName());
1129 // If that worked, check the non-type template parameter type
1130 // for validity.
1131 if (!NTTPType.isNull())
1132 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1133 NTTP->getLocation());
1134
1135 if (NTTPType.isNull()) {
1136 Invalid = true;
1137 break;
1138 }
1139 }
1140
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001141 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001142 case TemplateArgument::Null:
1143 assert(false && "Should never see a NULL template argument here");
1144 break;
1145
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001146 case TemplateArgument::Expression: {
1147 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001148 TemplateArgument Result;
1149 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001150 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001151 else
1152 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001153 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001154 }
1155
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001156 case TemplateArgument::Declaration:
1157 case TemplateArgument::Integral:
1158 // We've already checked this template argument, so just copy
1159 // it to the list of converted arguments.
1160 Converted.push_back(Arg);
1161 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001162
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001163 case TemplateArgument::Type:
1164 // We have a non-type template parameter but the template
1165 // argument is a type.
1166
1167 // C++ [temp.arg]p2:
1168 // In a template-argument, an ambiguity between a type-id and
1169 // an expression is resolved to a type-id, regardless of the
1170 // form of the corresponding template-parameter.
1171 //
1172 // We warn specifically about this case, since it can be rather
1173 // confusing for users.
1174 if (Arg.getAsType()->isFunctionType())
1175 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1176 << Arg.getAsType();
1177 else
1178 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1179 Diag((*Param)->getLocation(), diag::note_template_param_here);
1180 Invalid = true;
1181 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001182 } else {
1183 // Check template template parameters.
1184 TemplateTemplateParmDecl *TempParm
1185 = cast<TemplateTemplateParmDecl>(*Param);
1186
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001187 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001188 case TemplateArgument::Null:
1189 assert(false && "Should never see a NULL template argument here");
1190 break;
1191
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001192 case TemplateArgument::Expression: {
1193 Expr *ArgExpr = Arg.getAsExpr();
1194 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1195 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1196 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1197 Invalid = true;
1198
1199 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001200 Decl *D
1201 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1202 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001203 continue;
1204 }
1205 }
1206 // fall through
1207
1208 case TemplateArgument::Type: {
1209 // We have a template template parameter but the template
1210 // argument does not refer to a template.
1211 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1212 Invalid = true;
1213 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001214 }
1215
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001216 case TemplateArgument::Declaration:
1217 // We've already checked this template argument, so just copy
1218 // it to the list of converted arguments.
1219 Converted.push_back(Arg);
1220 break;
1221
1222 case TemplateArgument::Integral:
1223 assert(false && "Integral argument with template template parameter");
1224 break;
1225 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001226 }
1227 }
1228
1229 return Invalid;
1230}
1231
1232/// \brief Check a template argument against its corresponding
1233/// template type parameter.
1234///
1235/// This routine implements the semantics of C++ [temp.arg.type]. It
1236/// returns true if an error occurred, and false otherwise.
1237bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1238 QualType Arg, SourceLocation ArgLoc) {
1239 // C++ [temp.arg.type]p2:
1240 // A local type, a type with no linkage, an unnamed type or a type
1241 // compounded from any of these types shall not be used as a
1242 // template-argument for a template type-parameter.
1243 //
1244 // FIXME: Perform the recursive and no-linkage type checks.
1245 const TagType *Tag = 0;
1246 if (const EnumType *EnumT = Arg->getAsEnumType())
1247 Tag = EnumT;
1248 else if (const RecordType *RecordT = Arg->getAsRecordType())
1249 Tag = RecordT;
1250 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1251 return Diag(ArgLoc, diag::err_template_arg_local_type)
1252 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001253 else if (Tag && !Tag->getDecl()->getDeclName() &&
1254 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001255 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1256 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1257 return true;
1258 }
1259
1260 return false;
1261}
1262
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001263/// \brief Checks whether the given template argument is the address
1264/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001265bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1266 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001267 bool Invalid = false;
1268
1269 // See through any implicit casts we added to fix the type.
1270 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1271 Arg = Cast->getSubExpr();
1272
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001273 // C++0x allows nullptr, and there's no further checking to be done for that.
1274 if (Arg->getType()->isNullPtrType())
1275 return false;
1276
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001277 // C++ [temp.arg.nontype]p1:
1278 //
1279 // A template-argument for a non-type, non-template
1280 // template-parameter shall be one of: [...]
1281 //
1282 // -- the address of an object or function with external
1283 // linkage, including function templates and function
1284 // template-ids but excluding non-static class members,
1285 // expressed as & id-expression where the & is optional if
1286 // the name refers to a function or array, or if the
1287 // corresponding template-parameter is a reference; or
1288 DeclRefExpr *DRE = 0;
1289
1290 // Ignore (and complain about) any excess parentheses.
1291 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1292 if (!Invalid) {
1293 Diag(Arg->getSourceRange().getBegin(),
1294 diag::err_template_arg_extra_parens)
1295 << Arg->getSourceRange();
1296 Invalid = true;
1297 }
1298
1299 Arg = Parens->getSubExpr();
1300 }
1301
1302 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1303 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1304 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1305 } else
1306 DRE = dyn_cast<DeclRefExpr>(Arg);
1307
1308 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1309 return Diag(Arg->getSourceRange().getBegin(),
1310 diag::err_template_arg_not_object_or_func_form)
1311 << Arg->getSourceRange();
1312
1313 // Cannot refer to non-static data members
1314 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1315 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1316 << Field << Arg->getSourceRange();
1317
1318 // Cannot refer to non-static member functions
1319 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1320 if (!Method->isStatic())
1321 return Diag(Arg->getSourceRange().getBegin(),
1322 diag::err_template_arg_method)
1323 << Method << Arg->getSourceRange();
1324
1325 // Functions must have external linkage.
1326 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1327 if (Func->getStorageClass() == FunctionDecl::Static) {
1328 Diag(Arg->getSourceRange().getBegin(),
1329 diag::err_template_arg_function_not_extern)
1330 << Func << Arg->getSourceRange();
1331 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1332 << true;
1333 return true;
1334 }
1335
1336 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001337 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001338 return Invalid;
1339 }
1340
1341 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1342 if (!Var->hasGlobalStorage()) {
1343 Diag(Arg->getSourceRange().getBegin(),
1344 diag::err_template_arg_object_not_extern)
1345 << Var << Arg->getSourceRange();
1346 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1347 << true;
1348 return true;
1349 }
1350
1351 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001352 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001353 return Invalid;
1354 }
1355
1356 // We found something else, but we don't know specifically what it is.
1357 Diag(Arg->getSourceRange().getBegin(),
1358 diag::err_template_arg_not_object_or_func)
1359 << Arg->getSourceRange();
1360 Diag(DRE->getDecl()->getLocation(),
1361 diag::note_template_arg_refers_here);
1362 return true;
1363}
1364
1365/// \brief Checks whether the given template argument is a pointer to
1366/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001367bool
1368Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001369 bool Invalid = false;
1370
1371 // See through any implicit casts we added to fix the type.
1372 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1373 Arg = Cast->getSubExpr();
1374
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001375 // C++0x allows nullptr, and there's no further checking to be done for that.
1376 if (Arg->getType()->isNullPtrType())
1377 return false;
1378
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001379 // C++ [temp.arg.nontype]p1:
1380 //
1381 // A template-argument for a non-type, non-template
1382 // template-parameter shall be one of: [...]
1383 //
1384 // -- a pointer to member expressed as described in 5.3.1.
1385 QualifiedDeclRefExpr *DRE = 0;
1386
1387 // Ignore (and complain about) any excess parentheses.
1388 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1389 if (!Invalid) {
1390 Diag(Arg->getSourceRange().getBegin(),
1391 diag::err_template_arg_extra_parens)
1392 << Arg->getSourceRange();
1393 Invalid = true;
1394 }
1395
1396 Arg = Parens->getSubExpr();
1397 }
1398
1399 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1400 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1401 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1402
1403 if (!DRE)
1404 return Diag(Arg->getSourceRange().getBegin(),
1405 diag::err_template_arg_not_pointer_to_member_form)
1406 << Arg->getSourceRange();
1407
1408 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1409 assert((isa<FieldDecl>(DRE->getDecl()) ||
1410 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1411 "Only non-static member pointers can make it here");
1412
1413 // Okay: this is the address of a non-static member, and therefore
1414 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001415 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001416 return Invalid;
1417 }
1418
1419 // We found something else, but we don't know specifically what it is.
1420 Diag(Arg->getSourceRange().getBegin(),
1421 diag::err_template_arg_not_pointer_to_member_form)
1422 << Arg->getSourceRange();
1423 Diag(DRE->getDecl()->getLocation(),
1424 diag::note_template_arg_refers_here);
1425 return true;
1426}
1427
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001428/// \brief Check a template argument against its corresponding
1429/// non-type template parameter.
1430///
Douglas Gregored3a3982009-03-03 04:44:36 +00001431/// This routine implements the semantics of C++ [temp.arg.nontype].
1432/// It returns true if an error occurred, and false otherwise. \p
1433/// InstantiatedParamType is the type of the non-type template
1434/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001435///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001436/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001437bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001438 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001439 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001440 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1441
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001442 // If either the parameter has a dependent type or the argument is
1443 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001444 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001445 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1446 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001447 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001448 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001449 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001450
1451 // C++ [temp.arg.nontype]p5:
1452 // The following conversions are performed on each expression used
1453 // as a non-type template-argument. If a non-type
1454 // template-argument cannot be converted to the type of the
1455 // corresponding template-parameter then the program is
1456 // ill-formed.
1457 //
1458 // -- for a non-type template-parameter of integral or
1459 // enumeration type, integral promotions (4.5) and integral
1460 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001461 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001462 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001463 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001464 // C++ [temp.arg.nontype]p1:
1465 // A template-argument for a non-type, non-template
1466 // template-parameter shall be one of:
1467 //
1468 // -- an integral constant-expression of integral or enumeration
1469 // type; or
1470 // -- the name of a non-type template-parameter; or
1471 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001472 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001473 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1474 Diag(Arg->getSourceRange().getBegin(),
1475 diag::err_template_arg_not_integral_or_enumeral)
1476 << ArgType << Arg->getSourceRange();
1477 Diag(Param->getLocation(), diag::note_template_param_here);
1478 return true;
1479 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001480 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001481 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1482 << ArgType << Arg->getSourceRange();
1483 return true;
1484 }
1485
1486 // FIXME: We need some way to more easily get the unqualified form
1487 // of the types without going all the way to the
1488 // canonical type.
1489 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1490 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1491 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1492 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1493
1494 // Try to convert the argument to the parameter's type.
1495 if (ParamType == ArgType) {
1496 // Okay: no conversion necessary
1497 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1498 !ParamType->isEnumeralType()) {
1499 // This is an integral promotion or conversion.
1500 ImpCastExprToType(Arg, ParamType);
1501 } else {
1502 // We can't perform this conversion.
1503 Diag(Arg->getSourceRange().getBegin(),
1504 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001505 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001506 Diag(Param->getLocation(), diag::note_template_param_here);
1507 return true;
1508 }
1509
Douglas Gregorafc86942009-03-14 00:20:21 +00001510 QualType IntegerType = Context.getCanonicalType(ParamType);
1511 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001512 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001513
1514 if (!Arg->isValueDependent()) {
1515 // Check that an unsigned parameter does not receive a negative
1516 // value.
1517 if (IntegerType->isUnsignedIntegerType()
1518 && (Value.isSigned() && Value.isNegative())) {
1519 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1520 << Value.toString(10) << Param->getType()
1521 << Arg->getSourceRange();
1522 Diag(Param->getLocation(), diag::note_template_param_here);
1523 return true;
1524 }
1525
1526 // Check that we don't overflow the template parameter type.
1527 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1528 if (Value.getActiveBits() > AllowedBits) {
1529 Diag(Arg->getSourceRange().getBegin(),
1530 diag::err_template_arg_too_large)
1531 << Value.toString(10) << Param->getType()
1532 << Arg->getSourceRange();
1533 Diag(Param->getLocation(), diag::note_template_param_here);
1534 return true;
1535 }
1536
1537 if (Value.getBitWidth() != AllowedBits)
1538 Value.extOrTrunc(AllowedBits);
1539 Value.setIsSigned(IntegerType->isSignedIntegerType());
1540 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001541
Douglas Gregor8f378a92009-06-11 18:10:32 +00001542 // Add the value of this argument to the list of converted
1543 // arguments. We use the bitwidth and signedness of the template
1544 // parameter.
1545 if (Arg->isValueDependent()) {
1546 // The argument is value-dependent. Create a new
1547 // TemplateArgument with the converted expression.
1548 Converted = TemplateArgument(Arg);
1549 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001550 }
1551
Douglas Gregor8f378a92009-06-11 18:10:32 +00001552 Converted = TemplateArgument(StartLoc, Value,
1553 ParamType->isEnumeralType() ? ParamType
1554 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001555 return false;
1556 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001557
Douglas Gregor3f411962009-02-11 01:18:59 +00001558 // Handle pointer-to-function, reference-to-function, and
1559 // pointer-to-member-function all in (roughly) the same way.
1560 if (// -- For a non-type template-parameter of type pointer to
1561 // function, only the function-to-pointer conversion (4.3) is
1562 // applied. If the template-argument represents a set of
1563 // overloaded functions (or a pointer to such), the matching
1564 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001565 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001566 (ParamType->isPointerType() &&
1567 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1568 // -- For a non-type template-parameter of type reference to
1569 // function, no conversions apply. If the template-argument
1570 // represents a set of overloaded functions, the matching
1571 // function is selected from the set (13.4).
1572 (ParamType->isReferenceType() &&
1573 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1574 // -- For a non-type template-parameter of type pointer to
1575 // member function, no conversions apply. If the
1576 // template-argument represents a set of overloaded member
1577 // functions, the matching member function is selected from
1578 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001579 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001580 (ParamType->isMemberPointerType() &&
1581 ParamType->getAsMemberPointerType()->getPointeeType()
1582 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001583 if (Context.hasSameUnqualifiedType(ArgType,
1584 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001585 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001586 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1587 ParamType->isMemberPointerType())) {
1588 ArgType = ParamType;
1589 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001590 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001591 ArgType = Context.getPointerType(ArgType);
1592 ImpCastExprToType(Arg, ArgType);
1593 } else if (FunctionDecl *Fn
1594 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001595 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1596 return true;
1597
Douglas Gregor2eedd992009-02-11 00:19:33 +00001598 FixOverloadedFunctionReference(Arg, Fn);
1599 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001600 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001601 ArgType = Context.getPointerType(Arg->getType());
1602 ImpCastExprToType(Arg, ArgType);
1603 }
1604 }
1605
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001606 if (!Context.hasSameUnqualifiedType(ArgType,
1607 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001608 // We can't perform this conversion.
1609 Diag(Arg->getSourceRange().getBegin(),
1610 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001611 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001612 Diag(Param->getLocation(), diag::note_template_param_here);
1613 return true;
1614 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001615
Douglas Gregorad964b32009-02-17 01:05:43 +00001616 if (ParamType->isMemberPointerType()) {
1617 NamedDecl *Member = 0;
1618 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1619 return true;
1620
Douglas Gregor8f378a92009-06-11 18:10:32 +00001621 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1622 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001623 return false;
1624 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001625
Douglas Gregorad964b32009-02-17 01:05:43 +00001626 NamedDecl *Entity = 0;
1627 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1628 return true;
1629
Douglas Gregor8f378a92009-06-11 18:10:32 +00001630 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1631 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001632 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001633 }
1634
Chris Lattner320dff22009-02-20 21:37:53 +00001635 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001636 // -- for a non-type template-parameter of type pointer to
1637 // object, qualification conversions (4.4) and the
1638 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001639 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001640 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001641 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001642
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001643 if (ArgType->isNullPtrType()) {
1644 ArgType = ParamType;
1645 ImpCastExprToType(Arg, ParamType);
1646 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001647 ArgType = Context.getArrayDecayedType(ArgType);
1648 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001649 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001650
Douglas Gregor3f411962009-02-11 01:18:59 +00001651 if (IsQualificationConversion(ArgType, ParamType)) {
1652 ArgType = ParamType;
1653 ImpCastExprToType(Arg, ParamType);
1654 }
1655
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001656 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001657 // We can't perform this conversion.
1658 Diag(Arg->getSourceRange().getBegin(),
1659 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001660 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001661 Diag(Param->getLocation(), diag::note_template_param_here);
1662 return true;
1663 }
1664
Douglas Gregorad964b32009-02-17 01:05:43 +00001665 NamedDecl *Entity = 0;
1666 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1667 return true;
1668
Douglas Gregor8f378a92009-06-11 18:10:32 +00001669 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1670 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001671 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001672 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001673
1674 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1675 // -- For a non-type template-parameter of type reference to
1676 // object, no conversions apply. The type referred to by the
1677 // reference may be more cv-qualified than the (otherwise
1678 // identical) type of the template-argument. The
1679 // template-parameter is bound directly to the
1680 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001681 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001682 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001683
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001684 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001685 Diag(Arg->getSourceRange().getBegin(),
1686 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001687 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001688 << Arg->getSourceRange();
1689 Diag(Param->getLocation(), diag::note_template_param_here);
1690 return true;
1691 }
1692
1693 unsigned ParamQuals
1694 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1695 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1696
1697 if ((ParamQuals | ArgQuals) != ParamQuals) {
1698 Diag(Arg->getSourceRange().getBegin(),
1699 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001700 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001701 << Arg->getSourceRange();
1702 Diag(Param->getLocation(), diag::note_template_param_here);
1703 return true;
1704 }
1705
Douglas Gregorad964b32009-02-17 01:05:43 +00001706 NamedDecl *Entity = 0;
1707 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1708 return true;
1709
Douglas Gregor8f378a92009-06-11 18:10:32 +00001710 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1711 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001712 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001713 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001714
1715 // -- For a non-type template-parameter of type pointer to data
1716 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001717 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001718 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1719
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001720 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001721 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001722 } else if (ArgType->isNullPtrType()) {
1723 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001724 } else if (IsQualificationConversion(ArgType, ParamType)) {
1725 ImpCastExprToType(Arg, ParamType);
1726 } else {
1727 // We can't perform this conversion.
1728 Diag(Arg->getSourceRange().getBegin(),
1729 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001730 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001731 Diag(Param->getLocation(), diag::note_template_param_here);
1732 return true;
1733 }
1734
Douglas Gregorad964b32009-02-17 01:05:43 +00001735 NamedDecl *Member = 0;
1736 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1737 return true;
1738
Douglas Gregor8f378a92009-06-11 18:10:32 +00001739 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1740 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001741 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001742}
1743
1744/// \brief Check a template argument against its corresponding
1745/// template template parameter.
1746///
1747/// This routine implements the semantics of C++ [temp.arg.template].
1748/// It returns true if an error occurred, and false otherwise.
1749bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1750 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001751 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1752 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1753
1754 // C++ [temp.arg.template]p1:
1755 // A template-argument for a template template-parameter shall be
1756 // the name of a class template, expressed as id-expression. Only
1757 // primary class templates are considered when matching the
1758 // template template argument with the corresponding parameter;
1759 // partial specializations are not considered even if their
1760 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001761 //
1762 // Note that we also allow template template parameters here, which
1763 // will happen when we are dealing with, e.g., class template
1764 // partial specializations.
1765 if (!isa<ClassTemplateDecl>(Template) &&
1766 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001767 assert(isa<FunctionTemplateDecl>(Template) &&
1768 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001769 Diag(Arg->getSourceRange().getBegin(),
1770 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001771 << Template;
1772 }
1773
1774 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1775 Param->getTemplateParameters(),
1776 true, true,
1777 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001778}
1779
Douglas Gregord406b032009-02-06 22:42:48 +00001780/// \brief Determine whether the given template parameter lists are
1781/// equivalent.
1782///
1783/// \param New The new template parameter list, typically written in the
1784/// source code as part of a new template declaration.
1785///
1786/// \param Old The old template parameter list, typically found via
1787/// name lookup of the template declared with this template parameter
1788/// list.
1789///
1790/// \param Complain If true, this routine will produce a diagnostic if
1791/// the template parameter lists are not equivalent.
1792///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001793/// \param IsTemplateTemplateParm If true, this routine is being
1794/// called to compare the template parameter lists of a template
1795/// template parameter.
1796///
1797/// \param TemplateArgLoc If this source location is valid, then we
1798/// are actually checking the template parameter list of a template
1799/// argument (New) against the template parameter list of its
1800/// corresponding template template parameter (Old). We produce
1801/// slightly different diagnostics in this scenario.
1802///
Douglas Gregord406b032009-02-06 22:42:48 +00001803/// \returns True if the template parameter lists are equal, false
1804/// otherwise.
1805bool
1806Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1807 TemplateParameterList *Old,
1808 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001809 bool IsTemplateTemplateParm,
1810 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001811 if (Old->size() != New->size()) {
1812 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001813 unsigned NextDiag = diag::err_template_param_list_different_arity;
1814 if (TemplateArgLoc.isValid()) {
1815 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1816 NextDiag = diag::note_template_param_list_different_arity;
1817 }
1818 Diag(New->getTemplateLoc(), NextDiag)
1819 << (New->size() > Old->size())
1820 << IsTemplateTemplateParm
1821 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001822 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1823 << IsTemplateTemplateParm
1824 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1825 }
1826
1827 return false;
1828 }
1829
1830 for (TemplateParameterList::iterator OldParm = Old->begin(),
1831 OldParmEnd = Old->end(), NewParm = New->begin();
1832 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1833 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001834 unsigned NextDiag = diag::err_template_param_different_kind;
1835 if (TemplateArgLoc.isValid()) {
1836 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1837 NextDiag = diag::note_template_param_different_kind;
1838 }
1839 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001840 << IsTemplateTemplateParm;
1841 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1842 << IsTemplateTemplateParm;
1843 return false;
1844 }
1845
1846 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1847 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001848 // know we're at the same index).
1849#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001850 // FIXME: Enable this code in debug mode *after* we properly go through
1851 // and "instantiate" the template parameter lists of template template
1852 // parameters. It's only after this instantiation that (1) any dependent
1853 // types within the template parameter list of the template template
1854 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001855 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001856 QualType OldParmType
1857 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1858 QualType NewParmType
1859 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1860 assert(Context.getCanonicalType(OldParmType) ==
1861 Context.getCanonicalType(NewParmType) &&
1862 "type parameter mismatch?");
1863#endif
1864 } else if (NonTypeTemplateParmDecl *OldNTTP
1865 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1866 // The types of non-type template parameters must agree.
1867 NonTypeTemplateParmDecl *NewNTTP
1868 = cast<NonTypeTemplateParmDecl>(*NewParm);
1869 if (Context.getCanonicalType(OldNTTP->getType()) !=
1870 Context.getCanonicalType(NewNTTP->getType())) {
1871 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001872 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1873 if (TemplateArgLoc.isValid()) {
1874 Diag(TemplateArgLoc,
1875 diag::err_template_arg_template_params_mismatch);
1876 NextDiag = diag::note_template_nontype_parm_different_type;
1877 }
1878 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001879 << NewNTTP->getType()
1880 << IsTemplateTemplateParm;
1881 Diag(OldNTTP->getLocation(),
1882 diag::note_template_nontype_parm_prev_declaration)
1883 << OldNTTP->getType();
1884 }
1885 return false;
1886 }
1887 } else {
1888 // The template parameter lists of template template
1889 // parameters must agree.
1890 // FIXME: Could we perform a faster "type" comparison here?
1891 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1892 "Only template template parameters handled here");
1893 TemplateTemplateParmDecl *OldTTP
1894 = cast<TemplateTemplateParmDecl>(*OldParm);
1895 TemplateTemplateParmDecl *NewTTP
1896 = cast<TemplateTemplateParmDecl>(*NewParm);
1897 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1898 OldTTP->getTemplateParameters(),
1899 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001900 /*IsTemplateTemplateParm=*/true,
1901 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001902 return false;
1903 }
1904 }
1905
1906 return true;
1907}
1908
1909/// \brief Check whether a template can be declared within this scope.
1910///
1911/// If the template declaration is valid in this scope, returns
1912/// false. Otherwise, issues a diagnostic and returns true.
1913bool
1914Sema::CheckTemplateDeclScope(Scope *S,
1915 MultiTemplateParamsArg &TemplateParameterLists) {
1916 assert(TemplateParameterLists.size() > 0 && "Not a template");
1917
1918 // Find the nearest enclosing declaration scope.
1919 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1920 (S->getFlags() & Scope::TemplateParamScope) != 0)
1921 S = S->getParent();
1922
1923 TemplateParameterList *TemplateParams =
1924 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1925 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1926 SourceRange TemplateRange
1927 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1928
1929 // C++ [temp]p2:
1930 // A template-declaration can appear only as a namespace scope or
1931 // class scope declaration.
1932 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1933 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1934 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1935 return Diag(TemplateLoc, diag::err_template_linkage)
1936 << TemplateRange;
1937
1938 Ctx = Ctx->getParent();
1939 }
1940
1941 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1942 return false;
1943
1944 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1945 << TemplateRange;
1946}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001947
Douglas Gregor90177912009-05-13 18:28:20 +00001948/// \brief Check whether a class template specialization or explicit
1949/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001950///
Douglas Gregor90177912009-05-13 18:28:20 +00001951/// This routine determines whether a class template specialization or
1952/// explicit instantiation can be declared in the current context
1953/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1954/// appropriate diagnostics if there was an error. It returns true if
1955// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001956bool
1957Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1958 ClassTemplateSpecializationDecl *PrevDecl,
1959 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001960 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001961 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001962 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001963 // C++ [temp.expl.spec]p2:
1964 // An explicit specialization shall be declared in the namespace
1965 // of which the template is a member, or, for member templates, in
1966 // the namespace of which the enclosing class or enclosing class
1967 // template is a member. An explicit specialization of a member
1968 // function, member class or static data member of a class
1969 // template shall be declared in the namespace of which the class
1970 // template is a member. Such a declaration may also be a
1971 // definition. If the declaration is not a definition, the
1972 // specialization may be defined later in the name- space in which
1973 // the explicit specialization was declared, or in a namespace
1974 // that encloses the one in which the explicit specialization was
1975 // declared.
1976 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00001977 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001978 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001979 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001980 return true;
1981 }
1982
1983 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1984 DeclContext *TemplateContext
1985 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001986 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1987 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001988 // There is no prior declaration of this entity, so this
1989 // specialization must be in the same context as the template
1990 // itself.
1991 if (DC != TemplateContext) {
1992 if (isa<TranslationUnitDecl>(TemplateContext))
1993 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001994 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00001995 << ClassTemplate << ScopeSpecifierRange;
1996 else if (isa<NamespaceDecl>(TemplateContext))
1997 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001998 << PartialSpecialization << ClassTemplate
1999 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002000
2001 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2002 }
2003
2004 return false;
2005 }
2006
2007 // We have a previous declaration of this entity. Make sure that
2008 // this redeclaration (or definition) occurs in an enclosing namespace.
2009 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002010 // FIXME: In C++98, we would like to turn these errors into warnings,
2011 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002012 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002013 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002014 if (isa<TranslationUnitDecl>(TemplateContext)) {
2015 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2016 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002017 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002018 else
2019 SuppressedDiag = true;
2020 } else if (isa<NamespaceDecl>(TemplateContext)) {
2021 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2022 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002023 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002024 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2025 else
2026 SuppressedDiag = true;
2027 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002028
Douglas Gregor90177912009-05-13 18:28:20 +00002029 if (!SuppressedDiag)
2030 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002031 }
2032
2033 return false;
2034}
2035
Douglas Gregor76e79952009-06-12 21:21:02 +00002036/// \brief Check the non-type template arguments of a class template
2037/// partial specialization according to C++ [temp.class.spec]p9.
2038///
Douglas Gregor42476442009-06-12 22:08:06 +00002039/// \param TemplateParams the template parameters of the primary class
2040/// template.
2041///
2042/// \param TemplateArg the template arguments of the class template
2043/// partial specialization.
2044///
2045/// \param MirrorsPrimaryTemplate will be set true if the class
2046/// template partial specialization arguments are identical to the
2047/// implicit template arguments of the primary template. This is not
2048/// necessarily an error (C++0x), and it is left to the caller to diagnose
2049/// this condition when it is an error.
2050///
Douglas Gregor76e79952009-06-12 21:21:02 +00002051/// \returns true if there was an error, false otherwise.
2052bool Sema::CheckClassTemplatePartialSpecializationArgs(
2053 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002054 const TemplateArgument *TemplateArgs,
2055 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002056 // FIXME: the interface to this function will have to change to
2057 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002058 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002059 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002060 // Determine whether the template argument list of the partial
2061 // specialization is identical to the implicit argument list of
2062 // the primary template. The caller may need to diagnostic this as
2063 // an error per C++ [temp.class.spec]p9b3.
2064 if (MirrorsPrimaryTemplate) {
2065 if (TemplateTypeParmDecl *TTP
2066 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2067 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2068 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2069 MirrorsPrimaryTemplate = false;
2070 } else if (TemplateTemplateParmDecl *TTP
2071 = dyn_cast<TemplateTemplateParmDecl>(
2072 TemplateParams->getParam(I))) {
2073 // FIXME: We should settle on either Declaration storage or
2074 // Expression storage for template template parameters.
2075 TemplateTemplateParmDecl *ArgDecl
2076 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2077 TemplateArgs[I].getAsDecl());
2078 if (!ArgDecl)
2079 if (DeclRefExpr *DRE
2080 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2081 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2082
2083 if (!ArgDecl ||
2084 ArgDecl->getIndex() != TTP->getIndex() ||
2085 ArgDecl->getDepth() != TTP->getDepth())
2086 MirrorsPrimaryTemplate = false;
2087 }
2088 }
2089
Douglas Gregor76e79952009-06-12 21:21:02 +00002090 NonTypeTemplateParmDecl *Param
2091 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002092 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002093 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002094 }
2095
Douglas Gregor76e79952009-06-12 21:21:02 +00002096 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002097 if (!ArgExpr) {
2098 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002099 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002100 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002101
2102 // C++ [temp.class.spec]p8:
2103 // A non-type argument is non-specialized if it is the name of a
2104 // non-type parameter. All other non-type arguments are
2105 // specialized.
2106 //
2107 // Below, we check the two conditions that only apply to
2108 // specialized non-type arguments, so skip any non-specialized
2109 // arguments.
2110 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002111 if (NonTypeTemplateParmDecl *NTTP
2112 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2113 if (MirrorsPrimaryTemplate &&
2114 (Param->getIndex() != NTTP->getIndex() ||
2115 Param->getDepth() != NTTP->getDepth()))
2116 MirrorsPrimaryTemplate = false;
2117
Douglas Gregor76e79952009-06-12 21:21:02 +00002118 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002119 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002120
2121 // C++ [temp.class.spec]p9:
2122 // Within the argument list of a class template partial
2123 // specialization, the following restrictions apply:
2124 // -- A partially specialized non-type argument expression
2125 // shall not involve a template parameter of the partial
2126 // specialization except when the argument expression is a
2127 // simple identifier.
2128 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2129 Diag(ArgExpr->getLocStart(),
2130 diag::err_dependent_non_type_arg_in_partial_spec)
2131 << ArgExpr->getSourceRange();
2132 return true;
2133 }
2134
2135 // -- The type of a template parameter corresponding to a
2136 // specialized non-type argument shall not be dependent on a
2137 // parameter of the specialization.
2138 if (Param->getType()->isDependentType()) {
2139 Diag(ArgExpr->getLocStart(),
2140 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2141 << Param->getType()
2142 << ArgExpr->getSourceRange();
2143 Diag(Param->getLocation(), diag::note_template_param_here);
2144 return true;
2145 }
Douglas Gregor42476442009-06-12 22:08:06 +00002146
2147 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002148 }
2149
2150 return false;
2151}
2152
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002153Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002154Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2155 SourceLocation KWLoc,
2156 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002157 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002158 SourceLocation TemplateNameLoc,
2159 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002160 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002161 SourceLocation *TemplateArgLocs,
2162 SourceLocation RAngleLoc,
2163 AttributeList *Attr,
2164 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002165 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002166 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002167 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002168 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002169
Douglas Gregor58944ac2009-05-31 09:31:02 +00002170 bool isPartialSpecialization = false;
2171
Douglas Gregor0d93f692009-02-25 22:02:03 +00002172 // Check the validity of the template headers that introduce this
2173 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002174 // FIXME: Once we have member templates, we'll need to check
2175 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2176 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002177 if (TemplateParameterLists.size() == 0)
2178 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002179 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002180 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002181 TemplateParameterList *TemplateParams
2182 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002183 if (TemplateParameterLists.size() > 1) {
2184 Diag(TemplateParams->getTemplateLoc(),
2185 diag::err_template_spec_extra_headers);
2186 return true;
2187 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002188
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002189 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002190 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002191
2192 // C++ [temp.class.spec]p10:
2193 // The template parameter list of a specialization shall not
2194 // contain default template argument values.
2195 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2196 Decl *Param = TemplateParams->getParam(I);
2197 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2198 if (TTP->hasDefaultArgument()) {
2199 Diag(TTP->getDefaultArgumentLoc(),
2200 diag::err_default_arg_in_partial_spec);
2201 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2202 }
2203 } else if (NonTypeTemplateParmDecl *NTTP
2204 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2205 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2206 Diag(NTTP->getDefaultArgumentLoc(),
2207 diag::err_default_arg_in_partial_spec)
2208 << DefArg->getSourceRange();
2209 NTTP->setDefaultArgument(0);
2210 DefArg->Destroy(Context);
2211 }
2212 } else {
2213 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2214 if (Expr *DefArg = TTP->getDefaultArgument()) {
2215 Diag(TTP->getDefaultArgumentLoc(),
2216 diag::err_default_arg_in_partial_spec)
2217 << DefArg->getSourceRange();
2218 TTP->setDefaultArgument(0);
2219 DefArg->Destroy(Context);
2220 }
2221 }
2222 }
2223 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002224 }
2225
Douglas Gregora08b6c72009-02-17 23:15:12 +00002226 // Check that the specialization uses the same tag kind as the
2227 // original template.
2228 TagDecl::TagKind Kind;
2229 switch (TagSpec) {
2230 default: assert(0 && "Unknown tag type!");
2231 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2232 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2233 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2234 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002235 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2236 Kind, KWLoc,
2237 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002238 Diag(KWLoc, diag::err_use_with_wrong_tag)
2239 << ClassTemplate
2240 << CodeModificationHint::CreateReplacement(KWLoc,
2241 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002242 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2243 diag::note_previous_use);
2244 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2245 }
2246
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002247 // Translate the parser's template argument list in our AST format.
2248 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2249 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2250
Douglas Gregora08b6c72009-02-17 23:15:12 +00002251 // Check that the template argument list is well-formed for this
2252 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002253 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002254 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002255 &TemplateArgs[0], TemplateArgs.size(),
2256 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002257 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002258
2259 assert((ConvertedTemplateArgs.size() ==
2260 ClassTemplate->getTemplateParameters()->size()) &&
2261 "Converted template argument list is too short!");
2262
Douglas Gregor58944ac2009-05-31 09:31:02 +00002263 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002264 // corresponds to these arguments.
2265 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002266 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002267 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002268 if (CheckClassTemplatePartialSpecializationArgs(
2269 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002270 ConvertedTemplateArgs.getFlatArgumentList(),
2271 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002272 return true;
2273
Douglas Gregor42476442009-06-12 22:08:06 +00002274 if (MirrorsPrimaryTemplate) {
2275 // C++ [temp.class.spec]p9b3:
2276 //
2277 // -- The argument list of the specialization shall not be identical
2278 // to the implicit argument list of the primary template.
2279 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2280 << (TK == TK_Definition)
2281 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2282 RAngleLoc));
2283 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2284 ClassTemplate->getIdentifier(),
2285 TemplateNameLoc,
2286 Attr,
2287 move(TemplateParameterLists),
2288 AS_none);
2289 }
2290
Douglas Gregor58944ac2009-05-31 09:31:02 +00002291 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002292 ClassTemplatePartialSpecializationDecl::Profile(ID,
2293 ConvertedTemplateArgs.getFlatArgumentList(),
2294 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002295 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002296 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002297 ClassTemplateSpecializationDecl::Profile(ID,
2298 ConvertedTemplateArgs.getFlatArgumentList(),
2299 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002300 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002301 ClassTemplateSpecializationDecl *PrevDecl = 0;
2302
2303 if (isPartialSpecialization)
2304 PrevDecl
2305 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2306 InsertPos);
2307 else
2308 PrevDecl
2309 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002310
2311 ClassTemplateSpecializationDecl *Specialization = 0;
2312
Douglas Gregor0d93f692009-02-25 22:02:03 +00002313 // Check whether we can declare a class template specialization in
2314 // the current scope.
2315 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2316 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002317 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002318 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002319 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002320 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002321
Douglas Gregora08b6c72009-02-17 23:15:12 +00002322 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2323 // Since the only prior class template specialization with these
2324 // arguments was referenced but not declared, reuse that
2325 // declaration node as our own, updating its source location to
2326 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002327 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002328 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002329 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002330 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002331 // Create a new class template partial specialization declaration node.
2332 TemplateParameterList *TemplateParams
2333 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2334 ClassTemplatePartialSpecializationDecl *PrevPartial
2335 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2336 ClassTemplatePartialSpecializationDecl *Partial
2337 = ClassTemplatePartialSpecializationDecl::Create(Context,
2338 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002339 TemplateNameLoc,
2340 TemplateParams,
2341 ClassTemplate,
2342 ConvertedTemplateArgs,
2343 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002344
2345 if (PrevPartial) {
2346 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2347 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2348 } else {
2349 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2350 }
2351 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002352
2353 // Check that all of the template parameters of the class template
2354 // partial specialization are deducible from the template
2355 // arguments. If not, this class template partial specialization
2356 // will never be used.
2357 llvm::SmallVector<bool, 8> DeducibleParams;
2358 DeducibleParams.resize(TemplateParams->size());
2359 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2360 unsigned NumNonDeducible = 0;
2361 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2362 if (!DeducibleParams[I])
2363 ++NumNonDeducible;
2364
2365 if (NumNonDeducible) {
2366 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2367 << (NumNonDeducible > 1)
2368 << SourceRange(TemplateNameLoc, RAngleLoc);
2369 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2370 if (!DeducibleParams[I]) {
2371 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2372 if (Param->getDeclName())
2373 Diag(Param->getLocation(),
2374 diag::note_partial_spec_unused_parameter)
2375 << Param->getDeclName();
2376 else
2377 Diag(Param->getLocation(),
2378 diag::note_partial_spec_unused_parameter)
2379 << std::string("<anonymous>");
2380 }
2381 }
2382 }
2383
Douglas Gregora08b6c72009-02-17 23:15:12 +00002384 } else {
2385 // Create a new class template specialization declaration node for
2386 // this explicit specialization.
2387 Specialization
2388 = ClassTemplateSpecializationDecl::Create(Context,
2389 ClassTemplate->getDeclContext(),
2390 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002391 ClassTemplate,
2392 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002393 PrevDecl);
2394
2395 if (PrevDecl) {
2396 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2397 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2398 } else {
2399 ClassTemplate->getSpecializations().InsertNode(Specialization,
2400 InsertPos);
2401 }
2402 }
2403
2404 // Note that this is an explicit specialization.
2405 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2406
2407 // Check that this isn't a redefinition of this specialization.
2408 if (TK == TK_Definition) {
2409 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002410 // FIXME: Should also handle explicit specialization after implicit
2411 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002412 SourceRange Range(TemplateNameLoc, RAngleLoc);
2413 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002414 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002415 Diag(Def->getLocation(), diag::note_previous_definition);
2416 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002417 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002418 }
2419 }
2420
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002421 // Build the fully-sugared type for this class template
2422 // specialization as the user wrote in the specialization
2423 // itself. This means that we'll pretty-print the type retrieved
2424 // from the specialization's declaration the way that the user
2425 // actually wrote the specialization, rather than formatting the
2426 // name based on the "canonical" representation used to store the
2427 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002428 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002429 = Context.getTemplateSpecializationType(Name,
2430 &TemplateArgs[0],
2431 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002432 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002433 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002434 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002435
Douglas Gregor50113ca2009-02-25 22:18:32 +00002436 // C++ [temp.expl.spec]p9:
2437 // A template explicit specialization is in the scope of the
2438 // namespace in which the template was defined.
2439 //
2440 // We actually implement this paragraph where we set the semantic
2441 // context (in the creation of the ClassTemplateSpecializationDecl),
2442 // but we also maintain the lexical context where the actual
2443 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002444 Specialization->setLexicalDeclContext(CurContext);
2445
2446 // We may be starting the definition of this specialization.
2447 if (TK == TK_Definition)
2448 Specialization->startDefinition();
2449
2450 // Add the specialization into its lexical context, so that it can
2451 // be seen when iterating through the list of declarations in that
2452 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002453 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002454 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002455}
Douglas Gregord3022602009-03-27 23:10:48 +00002456
Douglas Gregor96b6df92009-05-14 00:28:11 +00002457// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002458Sema::DeclResult
2459Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2460 unsigned TagSpec,
2461 SourceLocation KWLoc,
2462 const CXXScopeSpec &SS,
2463 TemplateTy TemplateD,
2464 SourceLocation TemplateNameLoc,
2465 SourceLocation LAngleLoc,
2466 ASTTemplateArgsPtr TemplateArgsIn,
2467 SourceLocation *TemplateArgLocs,
2468 SourceLocation RAngleLoc,
2469 AttributeList *Attr) {
2470 // Find the class template we're specializing
2471 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2472 ClassTemplateDecl *ClassTemplate
2473 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2474
2475 // Check that the specialization uses the same tag kind as the
2476 // original template.
2477 TagDecl::TagKind Kind;
2478 switch (TagSpec) {
2479 default: assert(0 && "Unknown tag type!");
2480 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2481 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2482 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2483 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002484 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2485 Kind, KWLoc,
2486 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002487 Diag(KWLoc, diag::err_use_with_wrong_tag)
2488 << ClassTemplate
2489 << CodeModificationHint::CreateReplacement(KWLoc,
2490 ClassTemplate->getTemplatedDecl()->getKindName());
2491 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2492 diag::note_previous_use);
2493 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2494 }
2495
Douglas Gregor90177912009-05-13 18:28:20 +00002496 // C++0x [temp.explicit]p2:
2497 // [...] An explicit instantiation shall appear in an enclosing
2498 // namespace of its template. [...]
2499 //
2500 // This is C++ DR 275.
2501 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2502 TemplateNameLoc,
2503 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002504 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002505 /*ExplicitInstantiation=*/true))
2506 return true;
2507
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002508 // Translate the parser's template argument list in our AST format.
2509 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2510 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2511
2512 // Check that the template argument list is well-formed for this
2513 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002514 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002515 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002516 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002517 RAngleLoc, ConvertedTemplateArgs))
2518 return true;
2519
2520 assert((ConvertedTemplateArgs.size() ==
2521 ClassTemplate->getTemplateParameters()->size()) &&
2522 "Converted template argument list is too short!");
2523
2524 // Find the class template specialization declaration that
2525 // corresponds to these arguments.
2526 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002527 ClassTemplateSpecializationDecl::Profile(ID,
2528 ConvertedTemplateArgs.getFlatArgumentList(),
2529 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002530 void *InsertPos = 0;
2531 ClassTemplateSpecializationDecl *PrevDecl
2532 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2533
2534 ClassTemplateSpecializationDecl *Specialization = 0;
2535
Douglas Gregor90177912009-05-13 18:28:20 +00002536 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002537 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002538 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002539 // This particular specialization has already been declared or
2540 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002541 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2542 << Context.getTypeDeclType(PrevDecl);
2543 Diag(PrevDecl->getLocation(),
2544 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002545 return DeclPtrTy::make(PrevDecl);
2546 }
2547
Douglas Gregor90177912009-05-13 18:28:20 +00002548 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002549 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002550 // For a given set of template parameters, if an explicit
2551 // instantiation of a template appears after a declaration of
2552 // an explicit specialization for that template, the explicit
2553 // instantiation has no effect.
2554 if (!getLangOptions().CPlusPlus0x) {
2555 Diag(TemplateNameLoc,
2556 diag::ext_explicit_instantiation_after_specialization)
2557 << Context.getTypeDeclType(PrevDecl);
2558 Diag(PrevDecl->getLocation(),
2559 diag::note_previous_template_specialization);
2560 }
2561
2562 // Create a new class template specialization declaration node
2563 // for this explicit specialization. This node is only used to
2564 // record the existence of this explicit instantiation for
2565 // accurate reproduction of the source code; we don't actually
2566 // use it for anything, since it is semantically irrelevant.
2567 Specialization
2568 = ClassTemplateSpecializationDecl::Create(Context,
2569 ClassTemplate->getDeclContext(),
2570 TemplateNameLoc,
2571 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002572 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002573 Specialization->setLexicalDeclContext(CurContext);
2574 CurContext->addDecl(Context, Specialization);
2575 return DeclPtrTy::make(Specialization);
2576 }
2577
2578 // If we have already (implicitly) instantiated this
2579 // specialization, there is less work to do.
2580 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2581 SpecializationRequiresInstantiation = false;
2582
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002583 // Since the only prior class template specialization with these
2584 // arguments was referenced but not declared, reuse that
2585 // declaration node as our own, updating its source location to
2586 // reflect our new declaration.
2587 Specialization = PrevDecl;
2588 Specialization->setLocation(TemplateNameLoc);
2589 PrevDecl = 0;
2590 } else {
2591 // Create a new class template specialization declaration node for
2592 // this explicit specialization.
2593 Specialization
2594 = ClassTemplateSpecializationDecl::Create(Context,
2595 ClassTemplate->getDeclContext(),
2596 TemplateNameLoc,
2597 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002598 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002599
2600 ClassTemplate->getSpecializations().InsertNode(Specialization,
2601 InsertPos);
2602 }
2603
2604 // Build the fully-sugared type for this explicit instantiation as
2605 // the user wrote in the explicit instantiation itself. This means
2606 // that we'll pretty-print the type retrieved from the
2607 // specialization's declaration the way that the user actually wrote
2608 // the explicit instantiation, rather than formatting the name based
2609 // on the "canonical" representation used to store the template
2610 // arguments in the specialization.
2611 QualType WrittenTy
2612 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002613 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002614 TemplateArgs.size(),
2615 Context.getTypeDeclType(Specialization));
2616 Specialization->setTypeAsWritten(WrittenTy);
2617 TemplateArgsIn.release();
2618
2619 // Add the explicit instantiation into its lexical context. However,
2620 // since explicit instantiations are never found by name lookup, we
2621 // just put it into the declaration context directly.
2622 Specialization->setLexicalDeclContext(CurContext);
2623 CurContext->addDecl(Context, Specialization);
2624
2625 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002626 // A definition of a class template or class member template
2627 // shall be in scope at the point of the explicit instantiation of
2628 // the class template or class member template.
2629 //
2630 // This check comes when we actually try to perform the
2631 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002632 if (SpecializationRequiresInstantiation)
2633 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002634 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002635 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002636
2637 return DeclPtrTy::make(Specialization);
2638}
2639
Douglas Gregor96b6df92009-05-14 00:28:11 +00002640// Explicit instantiation of a member class of a class template.
2641Sema::DeclResult
2642Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2643 unsigned TagSpec,
2644 SourceLocation KWLoc,
2645 const CXXScopeSpec &SS,
2646 IdentifierInfo *Name,
2647 SourceLocation NameLoc,
2648 AttributeList *Attr) {
2649
Douglas Gregor71f06032009-05-28 23:31:59 +00002650 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002651 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002652 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002653 if (!TagD)
2654 return true;
2655
2656 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2657 if (Tag->isEnum()) {
2658 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2659 << Context.getTypeDeclType(Tag);
2660 return true;
2661 }
2662
Douglas Gregord769bfa2009-05-27 17:30:49 +00002663 if (Tag->isInvalidDecl())
2664 return true;
2665
Douglas Gregor96b6df92009-05-14 00:28:11 +00002666 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2667 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2668 if (!Pattern) {
2669 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2670 << Context.getTypeDeclType(Record);
2671 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2672 return true;
2673 }
2674
2675 // C++0x [temp.explicit]p2:
2676 // [...] An explicit instantiation shall appear in an enclosing
2677 // namespace of its template. [...]
2678 //
2679 // This is C++ DR 275.
2680 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002681 // FIXME: In C++98, we would like to turn these errors into warnings,
2682 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002683 DeclContext *PatternContext
2684 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2685 if (!CurContext->Encloses(PatternContext)) {
2686 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2687 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2688 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2689 }
2690 }
2691
Douglas Gregor96b6df92009-05-14 00:28:11 +00002692 if (!Record->getDefinition(Context)) {
2693 // If the class has a definition, instantiate it (and all of its
2694 // members, recursively).
2695 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2696 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002697 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002698 /*ExplicitInstantiation=*/true))
2699 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002700 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002701 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002702 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002703
Mike Stumpe127ae32009-05-16 07:39:55 +00002704 // FIXME: We don't have any representation for explicit instantiations of
2705 // member classes. Such a representation is not needed for compilation, but it
2706 // should be available for clients that want to see all of the declarations in
2707 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002708 return TagD;
2709}
2710
Douglas Gregord3022602009-03-27 23:10:48 +00002711Sema::TypeResult
2712Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2713 const IdentifierInfo &II, SourceLocation IdLoc) {
2714 NestedNameSpecifier *NNS
2715 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2716 if (!NNS)
2717 return true;
2718
2719 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002720 if (T.isNull())
2721 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002722 return T.getAsOpaquePtr();
2723}
2724
Douglas Gregor77da5802009-04-01 00:28:59 +00002725Sema::TypeResult
2726Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2727 SourceLocation TemplateLoc, TypeTy *Ty) {
2728 QualType T = QualType::getFromOpaquePtr(Ty);
2729 NestedNameSpecifier *NNS
2730 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2731 const TemplateSpecializationType *TemplateId
2732 = T->getAsTemplateSpecializationType();
2733 assert(TemplateId && "Expected a template specialization type");
2734
2735 if (NNS->isDependent())
2736 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2737
2738 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2739}
2740
Douglas Gregord3022602009-03-27 23:10:48 +00002741/// \brief Build the type that describes a C++ typename specifier,
2742/// e.g., "typename T::type".
2743QualType
2744Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2745 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002746 CXXRecordDecl *CurrentInstantiation = 0;
2747 if (NNS->isDependent()) {
2748 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002749
Douglas Gregor3eb20702009-05-11 19:58:34 +00002750 // If the nested-name-specifier does not refer to the current
2751 // instantiation, then build a typename type.
2752 if (!CurrentInstantiation)
2753 return Context.getTypenameType(NNS, &II);
2754 }
Douglas Gregord3022602009-03-27 23:10:48 +00002755
Douglas Gregor3eb20702009-05-11 19:58:34 +00002756 DeclContext *Ctx = 0;
2757
2758 if (CurrentInstantiation)
2759 Ctx = CurrentInstantiation;
2760 else {
2761 CXXScopeSpec SS;
2762 SS.setScopeRep(NNS);
2763 SS.setRange(Range);
2764 if (RequireCompleteDeclContext(SS))
2765 return QualType();
2766
2767 Ctx = computeDeclContext(SS);
2768 }
Douglas Gregord3022602009-03-27 23:10:48 +00002769 assert(Ctx && "No declaration context?");
2770
2771 DeclarationName Name(&II);
2772 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2773 false);
2774 unsigned DiagID = 0;
2775 Decl *Referenced = 0;
2776 switch (Result.getKind()) {
2777 case LookupResult::NotFound:
2778 if (Ctx->isTranslationUnit())
2779 DiagID = diag::err_typename_nested_not_found_global;
2780 else
2781 DiagID = diag::err_typename_nested_not_found;
2782 break;
2783
2784 case LookupResult::Found:
2785 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2786 // We found a type. Build a QualifiedNameType, since the
2787 // typename-specifier was just sugar. FIXME: Tell
2788 // QualifiedNameType that it has a "typename" prefix.
2789 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2790 }
2791
2792 DiagID = diag::err_typename_nested_not_type;
2793 Referenced = Result.getAsDecl();
2794 break;
2795
2796 case LookupResult::FoundOverloaded:
2797 DiagID = diag::err_typename_nested_not_type;
2798 Referenced = *Result.begin();
2799 break;
2800
2801 case LookupResult::AmbiguousBaseSubobjectTypes:
2802 case LookupResult::AmbiguousBaseSubobjects:
2803 case LookupResult::AmbiguousReference:
2804 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2805 return QualType();
2806 }
2807
2808 // If we get here, it's because name lookup did not find a
2809 // type. Emit an appropriate diagnostic and return an error.
2810 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2811 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2812 else
2813 Diag(Range.getEnd(), DiagID) << Range << Name;
2814 if (Referenced)
2815 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2816 << Name;
2817 return QualType();
2818}