blob: 00d8c769bd22f2824481abbcf23921a02ee86ffc [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
Douglas Gregordd13e842009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregor2fa10442008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregordd13e842009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000068 }
Douglas Gregor279272e2009-02-04 19:02:06 +000069
Douglas Gregor8e458f42009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor8e458f42009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregordd13e842009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor8e458f42009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000085 }
86 }
Douglas Gregordd13e842009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000099 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000101}
102
Douglas Gregordd861062008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregored3a3982009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregordd861062008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregord406b032009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregordd861062008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000166 Depth, Position, ParamName, Typename,
167 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000168 if (Invalid)
169 Param->setInvalidDecl();
170
171 if (ParamName) {
172 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000173 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000174 IdResolver.AddDecl(Param);
175 }
176
Chris Lattner5261d0c2009-03-28 19:18:32 +0000177 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000178}
179
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000183 SourceLocation EqualLoc,
184 SourceLocation DefaultLoc,
185 TypeTy *DefaultT) {
186 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000187 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000188 QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
Anders Carlssona2333782009-06-12 22:30:13 +0000190 // C++0x [temp.param]p9:
191 // A default template-argument may be specified for any kind of
192 // template-parameter that is not a template parameter pack.
193 if (Parm->isParameterPack()) {
194 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000195 return;
196 }
197
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000198 // C++ [temp.param]p14:
199 // A template-parameter shall not be used in its own default argument.
200 // FIXME: Implement this check! Needs a recursive walk over the types.
201
202 // Check the template argument itself.
203 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
204 Parm->setInvalidDecl();
205 return;
206 }
207
208 Parm->setDefaultArgument(Default, DefaultLoc, false);
209}
210
Douglas Gregored3a3982009-03-03 04:44:36 +0000211/// \brief Check that the type of a non-type template parameter is
212/// well-formed.
213///
214/// \returns the (possibly-promoted) parameter type if valid;
215/// otherwise, produces a diagnostic and returns a NULL type.
216QualType
217Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
218 // C++ [temp.param]p4:
219 //
220 // A non-type template-parameter shall have one of the following
221 // (optionally cv-qualified) types:
222 //
223 // -- integral or enumeration type,
224 if (T->isIntegralType() || T->isEnumeralType() ||
225 // -- pointer to object or pointer to function,
226 (T->isPointerType() &&
227 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
228 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
229 // -- reference to object or reference to function,
230 T->isReferenceType() ||
231 // -- pointer to member.
232 T->isMemberPointerType() ||
233 // If T is a dependent type, we can't do the check now, so we
234 // assume that it is well-formed.
235 T->isDependentType())
236 return T;
237 // C++ [temp.param]p8:
238 //
239 // A non-type template-parameter of type "array of T" or
240 // "function returning T" is adjusted to be of type "pointer to
241 // T" or "pointer to function returning T", respectively.
242 else if (T->isArrayType())
243 // FIXME: Keep the type prior to promotion?
244 return Context.getArrayDecayedType(T);
245 else if (T->isFunctionType())
246 // FIXME: Keep the type prior to promotion?
247 return Context.getPointerType(T);
248
249 Diag(Loc, diag::err_template_nontype_parm_bad_type)
250 << T;
251
252 return QualType();
253}
254
Douglas Gregordd861062008-12-05 18:15:24 +0000255/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
256/// template parameter (e.g., "int Size" in "template<int Size>
257/// class Array") has been parsed. S is the current scope and D is
258/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000259Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
260 unsigned Depth,
261 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000262 QualType T = GetTypeForDeclarator(D, S);
263
Douglas Gregor279272e2009-02-04 19:02:06 +0000264 assert(S->isTemplateParamScope() &&
265 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000266 bool Invalid = false;
267
268 IdentifierInfo *ParamName = D.getIdentifier();
269 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000270 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000271 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000272 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000273 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000274 }
275
Douglas Gregored3a3982009-03-03 04:44:36 +0000276 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000277 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000278 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000279 Invalid = true;
280 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000281
Douglas Gregordd861062008-12-05 18:15:24 +0000282 NonTypeTemplateParmDecl *Param
283 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000284 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000285 if (Invalid)
286 Param->setInvalidDecl();
287
288 if (D.getIdentifier()) {
289 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000290 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000291 IdResolver.AddDecl(Param);
292 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000293 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000294}
Douglas Gregor52473432008-12-24 02:52:09 +0000295
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000296/// \brief Adds a default argument to the given non-type template
297/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000298void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000299 SourceLocation EqualLoc,
300 ExprArg DefaultE) {
301 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000302 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000303 Expr *Default = static_cast<Expr *>(DefaultE.get());
304
305 // C++ [temp.param]p14:
306 // A template-parameter shall not be used in its own default argument.
307 // FIXME: Implement this check! Needs a recursive walk over the types.
308
309 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000310 TemplateArgument Converted;
311 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
312 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000313 TemplateParm->setInvalidDecl();
314 return;
315 }
316
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000317 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000318}
319
Douglas Gregor279272e2009-02-04 19:02:06 +0000320
321/// ActOnTemplateTemplateParameter - Called when a C++ template template
322/// parameter (e.g. T in template <template <typename> class T> class array)
323/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000324Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
325 SourceLocation TmpLoc,
326 TemplateParamsTy *Params,
327 IdentifierInfo *Name,
328 SourceLocation NameLoc,
329 unsigned Depth,
330 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000331{
332 assert(S->isTemplateParamScope() &&
333 "Template template parameter not in template parameter scope!");
334
335 // Construct the parameter object.
336 TemplateTemplateParmDecl *Param =
337 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
338 Position, Name,
339 (TemplateParameterList*)Params);
340
341 // Make sure the parameter is valid.
342 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
343 // do anything yet. However, if the template parameter list or (eventual)
344 // default value is ever invalidated, that will propagate here.
345 bool Invalid = false;
346 if (Invalid) {
347 Param->setInvalidDecl();
348 }
349
350 // If the tt-param has a name, then link the identifier into the scope
351 // and lookup mechanisms.
352 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000353 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000354 IdResolver.AddDecl(Param);
355 }
356
Chris Lattner5261d0c2009-03-28 19:18:32 +0000357 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000358}
359
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000360/// \brief Adds a default argument to the given template template
361/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000362void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000363 SourceLocation EqualLoc,
364 ExprArg DefaultE) {
365 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000366 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000367
368 // Since a template-template parameter's default argument is an
369 // id-expression, it must be a DeclRefExpr.
370 DeclRefExpr *Default
371 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
372
373 // C++ [temp.param]p14:
374 // A template-parameter shall not be used in its own default argument.
375 // FIXME: Implement this check! Needs a recursive walk over the types.
376
377 // Check the well-formedness of the template argument.
378 if (!isa<TemplateDecl>(Default->getDecl())) {
379 Diag(Default->getSourceRange().getBegin(),
380 diag::err_template_arg_must_be_template)
381 << Default->getSourceRange();
382 TemplateParm->setInvalidDecl();
383 return;
384 }
385 if (CheckTemplateArgument(TemplateParm, Default)) {
386 TemplateParm->setInvalidDecl();
387 return;
388 }
389
390 DefaultE.release();
391 TemplateParm->setDefaultArgument(Default);
392}
393
Douglas Gregor52473432008-12-24 02:52:09 +0000394/// ActOnTemplateParameterList - Builds a TemplateParameterList that
395/// contains the template parameters in Params/NumParams.
396Sema::TemplateParamsTy *
397Sema::ActOnTemplateParameterList(unsigned Depth,
398 SourceLocation ExportLoc,
399 SourceLocation TemplateLoc,
400 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000401 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000402 SourceLocation RAngleLoc) {
403 if (ExportLoc.isValid())
404 Diag(ExportLoc, diag::note_template_export_unsupported);
405
Douglas Gregord406b032009-02-06 22:42:48 +0000406 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
407 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000408}
Douglas Gregor279272e2009-02-04 19:02:06 +0000409
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000410Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000411Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
412 SourceLocation KWLoc, const CXXScopeSpec &SS,
413 IdentifierInfo *Name, SourceLocation NameLoc,
414 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000415 MultiTemplateParamsArg TemplateParameterLists,
416 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000417 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
418 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000419 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000420
421 // Check that we can declare a template here.
422 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000423 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000424
425 TagDecl::TagKind Kind;
426 switch (TagSpec) {
427 default: assert(0 && "Unknown tag type!");
428 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
429 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
430 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
431 }
432
433 // There is no such thing as an unnamed class template.
434 if (!Name) {
435 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000436 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000437 }
438
439 // Find any previous declaration with this name.
440 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
441 true);
442 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
443 NamedDecl *PrevDecl = 0;
444 if (Previous.begin() != Previous.end())
445 PrevDecl = *Previous.begin();
446
447 DeclContext *SemanticContext = CurContext;
448 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000449 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000450
Mike Stumpe127ae32009-05-16 07:39:55 +0000451 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000452 }
453
454 // FIXME: member templates!
455 TemplateParameterList *TemplateParams
456 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
457
458 // If there is a previous declaration with the same name, check
459 // whether this is a valid redeclaration.
460 ClassTemplateDecl *PrevClassTemplate
461 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
462 if (PrevClassTemplate) {
463 // Ensure that the template parameter lists are compatible.
464 if (!TemplateParameterListsAreEqual(TemplateParams,
465 PrevClassTemplate->getTemplateParameters(),
466 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000467 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000468
469 // C++ [temp.class]p4:
470 // In a redeclaration, partial specialization, explicit
471 // specialization or explicit instantiation of a class template,
472 // the class-key shall agree in kind with the original class
473 // template declaration (7.1.5.3).
474 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000475 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000476 Diag(KWLoc, diag::err_use_with_wrong_tag)
477 << Name
478 << CodeModificationHint::CreateReplacement(KWLoc,
479 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000480 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000481 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000482 }
483
Douglas Gregord406b032009-02-06 22:42:48 +0000484 // Check for redefinition of this class template.
485 if (TK == TK_Definition) {
486 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
487 Diag(NameLoc, diag::err_redefinition) << Name;
488 Diag(Def->getLocation(), diag::note_previous_definition);
489 // FIXME: Would it make sense to try to "forget" the previous
490 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000491 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000492 }
493 }
494 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
495 // Maybe we will complain about the shadowed template parameter.
496 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
497 // Just pretend that we didn't see the previous declaration.
498 PrevDecl = 0;
499 } else if (PrevDecl) {
500 // C++ [temp]p5:
501 // A class template shall not have the same name as any other
502 // template, class, function, object, enumeration, enumerator,
503 // namespace, or type in the same scope (3.3), except as specified
504 // in (14.5.4).
505 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
506 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000507 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000508 }
509
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000510 // Check the template parameter list of this declaration, possibly
511 // merging in the template parameter list from the previous class
512 // template declaration.
513 if (CheckTemplateParameterList(TemplateParams,
514 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
515 Invalid = true;
516
Douglas Gregor9054f982009-05-10 22:57:19 +0000517 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000518 // declaration!
519
Douglas Gregor55216ac2009-03-26 00:10:35 +0000520 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000521 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
522 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000523 PrevClassTemplate->getTemplatedDecl() : 0,
524 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000525
526 ClassTemplateDecl *NewTemplate
527 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
528 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000529 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000530 NewClass->setDescribedClassTemplate(NewTemplate);
531
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000532 // Build the type for the class template declaration now.
533 QualType T =
534 Context.getTypeDeclType(NewClass,
535 PrevClassTemplate?
536 PrevClassTemplate->getTemplatedDecl() : 0);
537 assert(T->isDependentType() && "Class template type is not dependent?");
538 (void)T;
539
Anders Carlsson4ca43492009-03-26 01:24:28 +0000540 // Set the access specifier.
541 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
542
Douglas Gregord406b032009-02-06 22:42:48 +0000543 // Set the lexical context of these templates
544 NewClass->setLexicalDeclContext(CurContext);
545 NewTemplate->setLexicalDeclContext(CurContext);
546
547 if (TK == TK_Definition)
548 NewClass->startDefinition();
549
550 if (Attr)
551 ProcessDeclAttributeList(NewClass, Attr);
552
553 PushOnScopeChains(NewTemplate, S);
554
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000555 if (Invalid) {
556 NewTemplate->setInvalidDecl();
557 NewClass->setInvalidDecl();
558 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000559 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000560}
561
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000562/// \brief Checks the validity of a template parameter list, possibly
563/// considering the template parameter list from a previous
564/// declaration.
565///
566/// If an "old" template parameter list is provided, it must be
567/// equivalent (per TemplateParameterListsAreEqual) to the "new"
568/// template parameter list.
569///
570/// \param NewParams Template parameter list for a new template
571/// declaration. This template parameter list will be updated with any
572/// default arguments that are carried through from the previous
573/// template parameter list.
574///
575/// \param OldParams If provided, template parameter list from a
576/// previous declaration of the same template. Default template
577/// arguments will be merged from the old template parameter list to
578/// the new template parameter list.
579///
580/// \returns true if an error occurred, false otherwise.
581bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
582 TemplateParameterList *OldParams) {
583 bool Invalid = false;
584
585 // C++ [temp.param]p10:
586 // The set of default template-arguments available for use with a
587 // template declaration or definition is obtained by merging the
588 // default arguments from the definition (if in scope) and all
589 // declarations in scope in the same way default function
590 // arguments are (8.3.6).
591 bool SawDefaultArgument = false;
592 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000593
Anders Carlssonb1929502009-06-12 23:20:15 +0000594 bool SawParameterPack = false;
595 SourceLocation ParameterPackLoc;
596
Mike Stumpe0b7e032009-02-11 23:03:27 +0000597 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000598 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000599 if (OldParams)
600 OldParam = OldParams->begin();
601
602 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
603 NewParamEnd = NewParams->end();
604 NewParam != NewParamEnd; ++NewParam) {
605 // Variables used to diagnose redundant default arguments
606 bool RedundantDefaultArg = false;
607 SourceLocation OldDefaultLoc;
608 SourceLocation NewDefaultLoc;
609
610 // Variables used to diagnose missing default arguments
611 bool MissingDefaultArg = false;
612
Anders Carlssonb1929502009-06-12 23:20:15 +0000613 // C++0x [temp.param]p11:
614 // If a template parameter of a class template is a template parameter pack,
615 // it must be the last template parameter.
616 if (SawParameterPack) {
617 Diag(ParameterPackLoc,
618 diag::err_template_param_pack_must_be_last_template_parameter);
619 Invalid = true;
620 }
621
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000622 // Merge default arguments for template type parameters.
623 if (TemplateTypeParmDecl *NewTypeParm
624 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
625 TemplateTypeParmDecl *OldTypeParm
626 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
627
Anders Carlssonb1929502009-06-12 23:20:15 +0000628 if (NewTypeParm->isParameterPack()) {
629 assert(!NewTypeParm->hasDefaultArgument() &&
630 "Parameter packs can't have a default argument!");
631 SawParameterPack = true;
632 ParameterPackLoc = NewTypeParm->getLocation();
633 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000634 NewTypeParm->hasDefaultArgument()) {
635 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
636 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
637 SawDefaultArgument = true;
638 RedundantDefaultArg = true;
639 PreviousDefaultArgLoc = NewDefaultLoc;
640 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
641 // Merge the default argument from the old declaration to the
642 // new declaration.
643 SawDefaultArgument = true;
644 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
645 OldTypeParm->getDefaultArgumentLoc(),
646 true);
647 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
648 } else if (NewTypeParm->hasDefaultArgument()) {
649 SawDefaultArgument = true;
650 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
651 } else if (SawDefaultArgument)
652 MissingDefaultArg = true;
653 }
654 // Merge default arguments for non-type template parameters
655 else if (NonTypeTemplateParmDecl *NewNonTypeParm
656 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
657 NonTypeTemplateParmDecl *OldNonTypeParm
658 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
659 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
660 NewNonTypeParm->hasDefaultArgument()) {
661 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
662 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
663 SawDefaultArgument = true;
664 RedundantDefaultArg = true;
665 PreviousDefaultArgLoc = NewDefaultLoc;
666 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
667 // Merge the default argument from the old declaration to the
668 // new declaration.
669 SawDefaultArgument = true;
670 // FIXME: We need to create a new kind of "default argument"
671 // expression that points to a previous template template
672 // parameter.
673 NewNonTypeParm->setDefaultArgument(
674 OldNonTypeParm->getDefaultArgument());
675 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
676 } else if (NewNonTypeParm->hasDefaultArgument()) {
677 SawDefaultArgument = true;
678 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
679 } else if (SawDefaultArgument)
680 MissingDefaultArg = true;
681 }
682 // Merge default arguments for template template parameters
683 else {
684 TemplateTemplateParmDecl *NewTemplateParm
685 = cast<TemplateTemplateParmDecl>(*NewParam);
686 TemplateTemplateParmDecl *OldTemplateParm
687 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
688 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
689 NewTemplateParm->hasDefaultArgument()) {
690 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
691 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
692 SawDefaultArgument = true;
693 RedundantDefaultArg = true;
694 PreviousDefaultArgLoc = NewDefaultLoc;
695 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
696 // Merge the default argument from the old declaration to the
697 // new declaration.
698 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000699 // FIXME: We need to create a new kind of "default argument" expression
700 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000701 NewTemplateParm->setDefaultArgument(
702 OldTemplateParm->getDefaultArgument());
703 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
704 } else if (NewTemplateParm->hasDefaultArgument()) {
705 SawDefaultArgument = true;
706 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
707 } else if (SawDefaultArgument)
708 MissingDefaultArg = true;
709 }
710
711 if (RedundantDefaultArg) {
712 // C++ [temp.param]p12:
713 // A template-parameter shall not be given default arguments
714 // by two different declarations in the same scope.
715 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
716 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
717 Invalid = true;
718 } else if (MissingDefaultArg) {
719 // C++ [temp.param]p11:
720 // If a template-parameter has a default template-argument,
721 // all subsequent template-parameters shall have a default
722 // template-argument supplied.
723 Diag((*NewParam)->getLocation(),
724 diag::err_template_param_default_arg_missing);
725 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
726 Invalid = true;
727 }
728
729 // If we have an old template parameter list that we're merging
730 // in, move on to the next parameter.
731 if (OldParams)
732 ++OldParam;
733 }
734
735 return Invalid;
736}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000737
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000738/// \brief Translates template arguments as provided by the parser
739/// into template arguments used by semantic analysis.
740static void
741translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
742 SourceLocation *TemplateArgLocs,
743 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
744 TemplateArgs.reserve(TemplateArgsIn.size());
745
746 void **Args = TemplateArgsIn.getArgs();
747 bool *ArgIsType = TemplateArgsIn.getArgIsType();
748 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
749 TemplateArgs.push_back(
750 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
751 QualType::getFromOpaquePtr(Args[Arg]))
752 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
753 }
754}
755
Douglas Gregoraabb8502009-03-31 00:43:58 +0000756/// \brief Build a canonical version of a template argument list.
757///
758/// This function builds a canonical version of the given template
759/// argument list, where each of the template arguments has been
760/// converted into its canonical form. This routine is typically used
761/// to canonicalize a template argument list when the template name
762/// itself is dependent. When the template name refers to an actual
763/// template declaration, Sema::CheckTemplateArgumentList should be
764/// used to check and canonicalize the template arguments.
765///
766/// \param TemplateArgs The incoming template arguments.
767///
768/// \param NumTemplateArgs The number of template arguments in \p
769/// TemplateArgs.
770///
771/// \param Canonical A vector to be filled with the canonical versions
772/// of the template arguments.
773///
774/// \param Context The ASTContext in which the template arguments live.
775static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
776 unsigned NumTemplateArgs,
777 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
778 ASTContext &Context) {
779 Canonical.reserve(NumTemplateArgs);
780 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
781 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000782 case TemplateArgument::Null:
783 assert(false && "Should never see a NULL template argument here");
784 break;
785
Douglas Gregoraabb8502009-03-31 00:43:58 +0000786 case TemplateArgument::Expression:
787 // FIXME: Build canonical expression (!)
788 Canonical.push_back(TemplateArgs[Idx]);
789 break;
790
791 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000792 Canonical.push_back(
793 TemplateArgument(SourceLocation(),
794 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000795 break;
796
797 case TemplateArgument::Integral:
798 Canonical.push_back(TemplateArgument(SourceLocation(),
799 *TemplateArgs[Idx].getAsIntegral(),
800 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000801 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000802
803 case TemplateArgument::Type: {
804 QualType CanonType
805 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
806 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000807 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000808 }
809 }
810 }
811}
812
Douglas Gregordd13e842009-03-30 22:58:21 +0000813QualType Sema::CheckTemplateIdType(TemplateName Name,
814 SourceLocation TemplateLoc,
815 SourceLocation LAngleLoc,
816 const TemplateArgument *TemplateArgs,
817 unsigned NumTemplateArgs,
818 SourceLocation RAngleLoc) {
819 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000820 if (!Template) {
821 // The template name does not resolve to a template, so we just
822 // build a dependent template-id type.
823
824 // Canonicalize the template arguments to build the canonical
825 // template-id type.
826 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
827 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
828 CanonicalTemplateArgs, Context);
829
Douglas Gregor905406b2009-05-07 06:49:52 +0000830 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000831 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000832 = Context.getTemplateSpecializationType(CanonName,
833 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000834 CanonicalTemplateArgs.size());
835
836 // Build the dependent template-id type.
837 return Context.getTemplateSpecializationType(Name, TemplateArgs,
838 NumTemplateArgs, CanonType);
839 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000840
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000841 // Check that the template argument list is well-formed for this
842 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000843 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000844 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000845 TemplateArgs, NumTemplateArgs, RAngleLoc,
846 ConvertedTemplateArgs))
847 return QualType();
848
849 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000850 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000851 "Converted template argument list is too short!");
852
853 QualType CanonType;
854
Douglas Gregordd13e842009-03-30 22:58:21 +0000855 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000856 TemplateArgs,
857 NumTemplateArgs)) {
858 // This class template specialization is a dependent
859 // type. Therefore, its canonical type is another class template
860 // specialization type that contains all of the converted
861 // arguments in canonical form. This ensures that, e.g., A<T> and
862 // A<T, T> have identical types when A is declared as:
863 //
864 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000865 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
866 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000867 ConvertedTemplateArgs.getFlatArgumentList(),
868 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000869 } else if (ClassTemplateDecl *ClassTemplate
870 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000871 // Find the class template specialization declaration that
872 // corresponds to these arguments.
873 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000874 ClassTemplateSpecializationDecl::Profile(ID,
875 ConvertedTemplateArgs.getFlatArgumentList(),
876 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000877 void *InsertPos = 0;
878 ClassTemplateSpecializationDecl *Decl
879 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
880 if (!Decl) {
881 // This is the first time we have referenced this class template
882 // specialization. Create the canonical declaration and add it to
883 // the set of specializations.
884 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000885 ClassTemplate->getDeclContext(),
886 TemplateLoc,
887 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000888 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000889 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
890 Decl->setLexicalDeclContext(CurContext);
891 }
892
893 CanonType = Context.getTypeDeclType(Decl);
894 }
895
896 // Build the fully-sugared type for this class template
897 // specialization, which refers back to the class template
898 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000899 return Context.getTemplateSpecializationType(Name, TemplateArgs,
900 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000901}
902
Douglas Gregora08b6c72009-02-17 23:15:12 +0000903Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000904Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
905 SourceLocation LAngleLoc,
906 ASTTemplateArgsPtr TemplateArgsIn,
907 SourceLocation *TemplateArgLocs,
908 SourceLocation RAngleLoc) {
909 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000910
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000911 // Translate the parser's template argument list in our AST format.
912 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
913 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000914
Douglas Gregordd13e842009-03-30 22:58:21 +0000915 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000916 TemplateArgs.data(),
917 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000918 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000919 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000920
921 if (Result.isNull())
922 return true;
923
Douglas Gregor6f37b582009-02-09 19:34:22 +0000924 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000925}
926
Douglas Gregoraabb8502009-03-31 00:43:58 +0000927/// \brief Form a dependent template name.
928///
929/// This action forms a dependent template name given the template
930/// name and its (presumably dependent) scope specifier. For
931/// example, given "MetaFun::template apply", the scope specifier \p
932/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
933/// of the "template" keyword, and "apply" is the \p Name.
934Sema::TemplateTy
935Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
936 const IdentifierInfo &Name,
937 SourceLocation NameLoc,
938 const CXXScopeSpec &SS) {
939 if (!SS.isSet() || SS.isInvalid())
940 return TemplateTy();
941
942 NestedNameSpecifier *Qualifier
943 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
944
945 // FIXME: member of the current instantiation
946
947 if (!Qualifier->isDependent()) {
948 // C++0x [temp.names]p5:
949 // If a name prefixed by the keyword template is not the name of
950 // a template, the program is ill-formed. [Note: the keyword
951 // template may not be applied to non-template members of class
952 // templates. -end note ] [ Note: as is the case with the
953 // typename prefix, the template prefix is allowed in cases
954 // where it is not strictly necessary; i.e., when the
955 // nested-name-specifier or the expression on the left of the ->
956 // or . is not dependent on a template-parameter, or the use
957 // does not appear in the scope of a template. -end note]
958 //
959 // Note: C++03 was more strict here, because it banned the use of
960 // the "template" keyword prior to a template-name that was not a
961 // dependent name. C++ DR468 relaxed this requirement (the
962 // "template" keyword is now permitted). We follow the C++0x
963 // rules, even in C++03 mode, retroactively applying the DR.
964 TemplateTy Template;
965 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
966 if (TNK == TNK_Non_template) {
967 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
968 << &Name;
969 return TemplateTy();
970 }
971
972 return Template;
973 }
974
975 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
976}
977
Anders Carlssonfdd33cc2009-06-13 00:33:33 +0000978bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
979 const TemplateArgument &Arg,
980 TemplateArgumentListBuilder &Converted) {
981 // Check template type parameter.
982 if (Arg.getKind() != TemplateArgument::Type) {
983 // C++ [temp.arg.type]p1:
984 // A template-argument for a template-parameter which is a
985 // type shall be a type-id.
986
987 // We have a template type parameter but the template argument
988 // is not a type.
989 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
990 Diag(Param->getLocation(), diag::note_template_param_here);
991
992 return true;
993 }
994
995 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
996 return true;
997
998 // Add the converted template type argument.
999 Converted.push_back(
1000 TemplateArgument(Arg.getLocation(),
1001 Context.getCanonicalType(Arg.getAsType())));
1002 return false;
1003}
1004
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001005/// \brief Check that the given template argument list is well-formed
1006/// for specializing the given template.
1007bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1008 SourceLocation TemplateLoc,
1009 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001010 const TemplateArgument *TemplateArgs,
1011 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001012 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001013 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001014 TemplateParameterList *Params = Template->getTemplateParameters();
1015 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001016 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001017 bool Invalid = false;
1018
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001019 bool HasParameterPack =
1020 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1021
1022 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001023 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001024 // FIXME: point at either the first arg beyond what we can handle,
1025 // or the '>', depending on whether we have too many or too few
1026 // arguments.
1027 SourceRange Range;
1028 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001029 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001030 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1031 << (NumArgs > NumParams)
1032 << (isa<ClassTemplateDecl>(Template)? 0 :
1033 isa<FunctionTemplateDecl>(Template)? 1 :
1034 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1035 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001036 Diag(Template->getLocation(), diag::note_template_decl_here)
1037 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001038 Invalid = true;
1039 }
1040
1041 // C++ [temp.arg]p1:
1042 // [...] The type and form of each template-argument specified in
1043 // a template-id shall match the type and form specified for the
1044 // corresponding parameter declared by the template in its
1045 // template-parameter-list.
1046 unsigned ArgIdx = 0;
1047 for (TemplateParameterList::iterator Param = Params->begin(),
1048 ParamEnd = Params->end();
1049 Param != ParamEnd; ++Param, ++ArgIdx) {
1050 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001051 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001052 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001053 // Retrieve the default template argument from the template
1054 // parameter.
1055 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001056 if (TTP->isParameterPack()) {
1057 // We have an empty parameter pack.
1058 Converted.BeginParameterPack();
1059 Converted.EndParameterPack();
1060 break;
1061 }
1062
Douglas Gregorad964b32009-02-17 01:05:43 +00001063 if (!TTP->hasDefaultArgument())
1064 break;
1065
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001066 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001067
1068 // If the argument type is dependent, instantiate it now based
1069 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001070 if (ArgType->isDependentType()) {
1071 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001072 Template, Converted.getFlatArgumentList(),
1073 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001074 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001075
Anders Carlsson0233eb62009-06-05 04:47:51 +00001076 TemplateArgumentList TemplateArgs(Context, Converted,
1077 /*CopyArgs=*/false,
1078 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001079 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001080 TTP->getDefaultArgumentLoc(),
1081 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001082 }
Douglas Gregor74296542009-02-27 19:31:52 +00001083
1084 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001085 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001086
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001087 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001088 } else if (NonTypeTemplateParmDecl *NTTP
1089 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1090 if (!NTTP->hasDefaultArgument())
1091 break;
1092
Anders Carlsson0297caf2009-06-11 16:06:49 +00001093 InstantiatingTemplate Inst(*this, TemplateLoc,
1094 Template, Converted.getFlatArgumentList(),
1095 Converted.flatSize(),
1096 SourceRange(TemplateLoc, RAngleLoc));
1097
1098 TemplateArgumentList TemplateArgs(Context, Converted,
1099 /*CopyArgs=*/false,
1100 /*FlattenArgs=*/false);
1101
1102 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1103 TemplateArgs);
1104 if (E.isInvalid())
1105 return true;
1106
1107 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001108 } else {
1109 TemplateTemplateParmDecl *TempParm
1110 = cast<TemplateTemplateParmDecl>(*Param);
1111
1112 if (!TempParm->hasDefaultArgument())
1113 break;
1114
Douglas Gregored3a3982009-03-03 04:44:36 +00001115 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001116 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001117 }
1118 } else {
1119 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001120 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001121 }
1122
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001123
1124 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001125 if (TTP->isParameterPack()) {
1126 Converted.BeginParameterPack();
1127 // Check all the remaining arguments (if any).
1128 for (; ArgIdx < NumArgs; ++ArgIdx) {
1129 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1130 Invalid = true;
1131 }
1132
1133 Converted.EndParameterPack();
1134 } else {
1135 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1136 Invalid = true;
1137 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001138 } else if (NonTypeTemplateParmDecl *NTTP
1139 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1140 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001141
1142 // Instantiate the type of the non-type template parameter with
1143 // the template arguments we've seen thus far.
1144 QualType NTTPType = NTTP->getType();
1145 if (NTTPType->isDependentType()) {
1146 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001147 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001148 Template, Converted.getFlatArgumentList(),
1149 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001150 SourceRange(TemplateLoc, RAngleLoc));
1151
Anders Carlsson0233eb62009-06-05 04:47:51 +00001152 TemplateArgumentList TemplateArgs(Context, Converted,
1153 /*CopyArgs=*/false,
1154 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001155 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001156 NTTP->getLocation(),
1157 NTTP->getDeclName());
1158 // If that worked, check the non-type template parameter type
1159 // for validity.
1160 if (!NTTPType.isNull())
1161 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1162 NTTP->getLocation());
1163
1164 if (NTTPType.isNull()) {
1165 Invalid = true;
1166 break;
1167 }
1168 }
1169
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001170 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001171 case TemplateArgument::Null:
1172 assert(false && "Should never see a NULL template argument here");
1173 break;
1174
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001175 case TemplateArgument::Expression: {
1176 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001177 TemplateArgument Result;
1178 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001179 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001180 else
1181 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001182 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001183 }
1184
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001185 case TemplateArgument::Declaration:
1186 case TemplateArgument::Integral:
1187 // We've already checked this template argument, so just copy
1188 // it to the list of converted arguments.
1189 Converted.push_back(Arg);
1190 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001191
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001192 case TemplateArgument::Type:
1193 // We have a non-type template parameter but the template
1194 // argument is a type.
1195
1196 // C++ [temp.arg]p2:
1197 // In a template-argument, an ambiguity between a type-id and
1198 // an expression is resolved to a type-id, regardless of the
1199 // form of the corresponding template-parameter.
1200 //
1201 // We warn specifically about this case, since it can be rather
1202 // confusing for users.
1203 if (Arg.getAsType()->isFunctionType())
1204 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1205 << Arg.getAsType();
1206 else
1207 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1208 Diag((*Param)->getLocation(), diag::note_template_param_here);
1209 Invalid = true;
1210 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001211 } else {
1212 // Check template template parameters.
1213 TemplateTemplateParmDecl *TempParm
1214 = cast<TemplateTemplateParmDecl>(*Param);
1215
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001216 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001217 case TemplateArgument::Null:
1218 assert(false && "Should never see a NULL template argument here");
1219 break;
1220
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001221 case TemplateArgument::Expression: {
1222 Expr *ArgExpr = Arg.getAsExpr();
1223 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1224 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1225 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1226 Invalid = true;
1227
1228 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001229 Decl *D
1230 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1231 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001232 continue;
1233 }
1234 }
1235 // fall through
1236
1237 case TemplateArgument::Type: {
1238 // We have a template template parameter but the template
1239 // argument does not refer to a template.
1240 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1241 Invalid = true;
1242 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001243 }
1244
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001245 case TemplateArgument::Declaration:
1246 // We've already checked this template argument, so just copy
1247 // it to the list of converted arguments.
1248 Converted.push_back(Arg);
1249 break;
1250
1251 case TemplateArgument::Integral:
1252 assert(false && "Integral argument with template template parameter");
1253 break;
1254 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001255 }
1256 }
1257
1258 return Invalid;
1259}
1260
1261/// \brief Check a template argument against its corresponding
1262/// template type parameter.
1263///
1264/// This routine implements the semantics of C++ [temp.arg.type]. It
1265/// returns true if an error occurred, and false otherwise.
1266bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1267 QualType Arg, SourceLocation ArgLoc) {
1268 // C++ [temp.arg.type]p2:
1269 // A local type, a type with no linkage, an unnamed type or a type
1270 // compounded from any of these types shall not be used as a
1271 // template-argument for a template type-parameter.
1272 //
1273 // FIXME: Perform the recursive and no-linkage type checks.
1274 const TagType *Tag = 0;
1275 if (const EnumType *EnumT = Arg->getAsEnumType())
1276 Tag = EnumT;
1277 else if (const RecordType *RecordT = Arg->getAsRecordType())
1278 Tag = RecordT;
1279 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1280 return Diag(ArgLoc, diag::err_template_arg_local_type)
1281 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001282 else if (Tag && !Tag->getDecl()->getDeclName() &&
1283 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001284 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1285 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1286 return true;
1287 }
1288
1289 return false;
1290}
1291
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001292/// \brief Checks whether the given template argument is the address
1293/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001294bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1295 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001296 bool Invalid = false;
1297
1298 // See through any implicit casts we added to fix the type.
1299 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1300 Arg = Cast->getSubExpr();
1301
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001302 // C++0x allows nullptr, and there's no further checking to be done for that.
1303 if (Arg->getType()->isNullPtrType())
1304 return false;
1305
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001306 // C++ [temp.arg.nontype]p1:
1307 //
1308 // A template-argument for a non-type, non-template
1309 // template-parameter shall be one of: [...]
1310 //
1311 // -- the address of an object or function with external
1312 // linkage, including function templates and function
1313 // template-ids but excluding non-static class members,
1314 // expressed as & id-expression where the & is optional if
1315 // the name refers to a function or array, or if the
1316 // corresponding template-parameter is a reference; or
1317 DeclRefExpr *DRE = 0;
1318
1319 // Ignore (and complain about) any excess parentheses.
1320 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1321 if (!Invalid) {
1322 Diag(Arg->getSourceRange().getBegin(),
1323 diag::err_template_arg_extra_parens)
1324 << Arg->getSourceRange();
1325 Invalid = true;
1326 }
1327
1328 Arg = Parens->getSubExpr();
1329 }
1330
1331 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1332 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1333 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1334 } else
1335 DRE = dyn_cast<DeclRefExpr>(Arg);
1336
1337 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1338 return Diag(Arg->getSourceRange().getBegin(),
1339 diag::err_template_arg_not_object_or_func_form)
1340 << Arg->getSourceRange();
1341
1342 // Cannot refer to non-static data members
1343 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1344 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1345 << Field << Arg->getSourceRange();
1346
1347 // Cannot refer to non-static member functions
1348 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1349 if (!Method->isStatic())
1350 return Diag(Arg->getSourceRange().getBegin(),
1351 diag::err_template_arg_method)
1352 << Method << Arg->getSourceRange();
1353
1354 // Functions must have external linkage.
1355 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1356 if (Func->getStorageClass() == FunctionDecl::Static) {
1357 Diag(Arg->getSourceRange().getBegin(),
1358 diag::err_template_arg_function_not_extern)
1359 << Func << Arg->getSourceRange();
1360 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1361 << true;
1362 return true;
1363 }
1364
1365 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001366 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001367 return Invalid;
1368 }
1369
1370 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1371 if (!Var->hasGlobalStorage()) {
1372 Diag(Arg->getSourceRange().getBegin(),
1373 diag::err_template_arg_object_not_extern)
1374 << Var << Arg->getSourceRange();
1375 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1376 << true;
1377 return true;
1378 }
1379
1380 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001381 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001382 return Invalid;
1383 }
1384
1385 // We found something else, but we don't know specifically what it is.
1386 Diag(Arg->getSourceRange().getBegin(),
1387 diag::err_template_arg_not_object_or_func)
1388 << Arg->getSourceRange();
1389 Diag(DRE->getDecl()->getLocation(),
1390 diag::note_template_arg_refers_here);
1391 return true;
1392}
1393
1394/// \brief Checks whether the given template argument is a pointer to
1395/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001396bool
1397Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001398 bool Invalid = false;
1399
1400 // See through any implicit casts we added to fix the type.
1401 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1402 Arg = Cast->getSubExpr();
1403
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001404 // C++0x allows nullptr, and there's no further checking to be done for that.
1405 if (Arg->getType()->isNullPtrType())
1406 return false;
1407
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001408 // C++ [temp.arg.nontype]p1:
1409 //
1410 // A template-argument for a non-type, non-template
1411 // template-parameter shall be one of: [...]
1412 //
1413 // -- a pointer to member expressed as described in 5.3.1.
1414 QualifiedDeclRefExpr *DRE = 0;
1415
1416 // Ignore (and complain about) any excess parentheses.
1417 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1418 if (!Invalid) {
1419 Diag(Arg->getSourceRange().getBegin(),
1420 diag::err_template_arg_extra_parens)
1421 << Arg->getSourceRange();
1422 Invalid = true;
1423 }
1424
1425 Arg = Parens->getSubExpr();
1426 }
1427
1428 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1429 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1430 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1431
1432 if (!DRE)
1433 return Diag(Arg->getSourceRange().getBegin(),
1434 diag::err_template_arg_not_pointer_to_member_form)
1435 << Arg->getSourceRange();
1436
1437 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1438 assert((isa<FieldDecl>(DRE->getDecl()) ||
1439 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1440 "Only non-static member pointers can make it here");
1441
1442 // Okay: this is the address of a non-static member, and therefore
1443 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001444 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001445 return Invalid;
1446 }
1447
1448 // We found something else, but we don't know specifically what it is.
1449 Diag(Arg->getSourceRange().getBegin(),
1450 diag::err_template_arg_not_pointer_to_member_form)
1451 << Arg->getSourceRange();
1452 Diag(DRE->getDecl()->getLocation(),
1453 diag::note_template_arg_refers_here);
1454 return true;
1455}
1456
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001457/// \brief Check a template argument against its corresponding
1458/// non-type template parameter.
1459///
Douglas Gregored3a3982009-03-03 04:44:36 +00001460/// This routine implements the semantics of C++ [temp.arg.nontype].
1461/// It returns true if an error occurred, and false otherwise. \p
1462/// InstantiatedParamType is the type of the non-type template
1463/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001464///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001465/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001466bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001467 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001468 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001469 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1470
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001471 // If either the parameter has a dependent type or the argument is
1472 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001473 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001474 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1475 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001476 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001477 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001478 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001479
1480 // C++ [temp.arg.nontype]p5:
1481 // The following conversions are performed on each expression used
1482 // as a non-type template-argument. If a non-type
1483 // template-argument cannot be converted to the type of the
1484 // corresponding template-parameter then the program is
1485 // ill-formed.
1486 //
1487 // -- for a non-type template-parameter of integral or
1488 // enumeration type, integral promotions (4.5) and integral
1489 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001490 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001491 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001492 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001493 // C++ [temp.arg.nontype]p1:
1494 // A template-argument for a non-type, non-template
1495 // template-parameter shall be one of:
1496 //
1497 // -- an integral constant-expression of integral or enumeration
1498 // type; or
1499 // -- the name of a non-type template-parameter; or
1500 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001501 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001502 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1503 Diag(Arg->getSourceRange().getBegin(),
1504 diag::err_template_arg_not_integral_or_enumeral)
1505 << ArgType << Arg->getSourceRange();
1506 Diag(Param->getLocation(), diag::note_template_param_here);
1507 return true;
1508 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001509 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001510 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1511 << ArgType << Arg->getSourceRange();
1512 return true;
1513 }
1514
1515 // FIXME: We need some way to more easily get the unqualified form
1516 // of the types without going all the way to the
1517 // canonical type.
1518 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1519 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1520 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1521 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1522
1523 // Try to convert the argument to the parameter's type.
1524 if (ParamType == ArgType) {
1525 // Okay: no conversion necessary
1526 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1527 !ParamType->isEnumeralType()) {
1528 // This is an integral promotion or conversion.
1529 ImpCastExprToType(Arg, ParamType);
1530 } else {
1531 // We can't perform this conversion.
1532 Diag(Arg->getSourceRange().getBegin(),
1533 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001534 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001535 Diag(Param->getLocation(), diag::note_template_param_here);
1536 return true;
1537 }
1538
Douglas Gregorafc86942009-03-14 00:20:21 +00001539 QualType IntegerType = Context.getCanonicalType(ParamType);
1540 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001541 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001542
1543 if (!Arg->isValueDependent()) {
1544 // Check that an unsigned parameter does not receive a negative
1545 // value.
1546 if (IntegerType->isUnsignedIntegerType()
1547 && (Value.isSigned() && Value.isNegative())) {
1548 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1549 << Value.toString(10) << Param->getType()
1550 << Arg->getSourceRange();
1551 Diag(Param->getLocation(), diag::note_template_param_here);
1552 return true;
1553 }
1554
1555 // Check that we don't overflow the template parameter type.
1556 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1557 if (Value.getActiveBits() > AllowedBits) {
1558 Diag(Arg->getSourceRange().getBegin(),
1559 diag::err_template_arg_too_large)
1560 << Value.toString(10) << Param->getType()
1561 << Arg->getSourceRange();
1562 Diag(Param->getLocation(), diag::note_template_param_here);
1563 return true;
1564 }
1565
1566 if (Value.getBitWidth() != AllowedBits)
1567 Value.extOrTrunc(AllowedBits);
1568 Value.setIsSigned(IntegerType->isSignedIntegerType());
1569 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001570
Douglas Gregor8f378a92009-06-11 18:10:32 +00001571 // Add the value of this argument to the list of converted
1572 // arguments. We use the bitwidth and signedness of the template
1573 // parameter.
1574 if (Arg->isValueDependent()) {
1575 // The argument is value-dependent. Create a new
1576 // TemplateArgument with the converted expression.
1577 Converted = TemplateArgument(Arg);
1578 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001579 }
1580
Douglas Gregor8f378a92009-06-11 18:10:32 +00001581 Converted = TemplateArgument(StartLoc, Value,
1582 ParamType->isEnumeralType() ? ParamType
1583 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001584 return false;
1585 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001586
Douglas Gregor3f411962009-02-11 01:18:59 +00001587 // Handle pointer-to-function, reference-to-function, and
1588 // pointer-to-member-function all in (roughly) the same way.
1589 if (// -- For a non-type template-parameter of type pointer to
1590 // function, only the function-to-pointer conversion (4.3) is
1591 // applied. If the template-argument represents a set of
1592 // overloaded functions (or a pointer to such), the matching
1593 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001594 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001595 (ParamType->isPointerType() &&
1596 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1597 // -- For a non-type template-parameter of type reference to
1598 // function, no conversions apply. If the template-argument
1599 // represents a set of overloaded functions, the matching
1600 // function is selected from the set (13.4).
1601 (ParamType->isReferenceType() &&
1602 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1603 // -- For a non-type template-parameter of type pointer to
1604 // member function, no conversions apply. If the
1605 // template-argument represents a set of overloaded member
1606 // functions, the matching member function is selected from
1607 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001608 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001609 (ParamType->isMemberPointerType() &&
1610 ParamType->getAsMemberPointerType()->getPointeeType()
1611 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001612 if (Context.hasSameUnqualifiedType(ArgType,
1613 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001614 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001615 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1616 ParamType->isMemberPointerType())) {
1617 ArgType = ParamType;
1618 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001619 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001620 ArgType = Context.getPointerType(ArgType);
1621 ImpCastExprToType(Arg, ArgType);
1622 } else if (FunctionDecl *Fn
1623 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001624 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1625 return true;
1626
Douglas Gregor2eedd992009-02-11 00:19:33 +00001627 FixOverloadedFunctionReference(Arg, Fn);
1628 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001629 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001630 ArgType = Context.getPointerType(Arg->getType());
1631 ImpCastExprToType(Arg, ArgType);
1632 }
1633 }
1634
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001635 if (!Context.hasSameUnqualifiedType(ArgType,
1636 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001637 // We can't perform this conversion.
1638 Diag(Arg->getSourceRange().getBegin(),
1639 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001640 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001641 Diag(Param->getLocation(), diag::note_template_param_here);
1642 return true;
1643 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001644
Douglas Gregorad964b32009-02-17 01:05:43 +00001645 if (ParamType->isMemberPointerType()) {
1646 NamedDecl *Member = 0;
1647 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1648 return true;
1649
Douglas Gregor8f378a92009-06-11 18:10:32 +00001650 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1651 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001652 return false;
1653 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001654
Douglas Gregorad964b32009-02-17 01:05:43 +00001655 NamedDecl *Entity = 0;
1656 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1657 return true;
1658
Douglas Gregor8f378a92009-06-11 18:10:32 +00001659 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1660 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001661 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001662 }
1663
Chris Lattner320dff22009-02-20 21:37:53 +00001664 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001665 // -- for a non-type template-parameter of type pointer to
1666 // object, qualification conversions (4.4) and the
1667 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001668 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001669 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001670 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001671
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001672 if (ArgType->isNullPtrType()) {
1673 ArgType = ParamType;
1674 ImpCastExprToType(Arg, ParamType);
1675 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001676 ArgType = Context.getArrayDecayedType(ArgType);
1677 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001678 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001679
Douglas Gregor3f411962009-02-11 01:18:59 +00001680 if (IsQualificationConversion(ArgType, ParamType)) {
1681 ArgType = ParamType;
1682 ImpCastExprToType(Arg, ParamType);
1683 }
1684
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001685 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001686 // We can't perform this conversion.
1687 Diag(Arg->getSourceRange().getBegin(),
1688 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001689 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001690 Diag(Param->getLocation(), diag::note_template_param_here);
1691 return true;
1692 }
1693
Douglas Gregorad964b32009-02-17 01:05:43 +00001694 NamedDecl *Entity = 0;
1695 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1696 return true;
1697
Douglas Gregor8f378a92009-06-11 18:10:32 +00001698 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1699 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001700 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001701 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001702
1703 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1704 // -- For a non-type template-parameter of type reference to
1705 // object, no conversions apply. The type referred to by the
1706 // reference may be more cv-qualified than the (otherwise
1707 // identical) type of the template-argument. The
1708 // template-parameter is bound directly to the
1709 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001710 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001711 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001712
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001713 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001714 Diag(Arg->getSourceRange().getBegin(),
1715 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001716 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001717 << Arg->getSourceRange();
1718 Diag(Param->getLocation(), diag::note_template_param_here);
1719 return true;
1720 }
1721
1722 unsigned ParamQuals
1723 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1724 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1725
1726 if ((ParamQuals | ArgQuals) != ParamQuals) {
1727 Diag(Arg->getSourceRange().getBegin(),
1728 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001729 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001730 << Arg->getSourceRange();
1731 Diag(Param->getLocation(), diag::note_template_param_here);
1732 return true;
1733 }
1734
Douglas Gregorad964b32009-02-17 01:05:43 +00001735 NamedDecl *Entity = 0;
1736 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1737 return true;
1738
Douglas Gregor8f378a92009-06-11 18:10:32 +00001739 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1740 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001741 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001742 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001743
1744 // -- For a non-type template-parameter of type pointer to data
1745 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001746 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001747 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1748
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001749 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001750 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001751 } else if (ArgType->isNullPtrType()) {
1752 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001753 } else if (IsQualificationConversion(ArgType, ParamType)) {
1754 ImpCastExprToType(Arg, ParamType);
1755 } else {
1756 // We can't perform this conversion.
1757 Diag(Arg->getSourceRange().getBegin(),
1758 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001759 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001760 Diag(Param->getLocation(), diag::note_template_param_here);
1761 return true;
1762 }
1763
Douglas Gregorad964b32009-02-17 01:05:43 +00001764 NamedDecl *Member = 0;
1765 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1766 return true;
1767
Douglas Gregor8f378a92009-06-11 18:10:32 +00001768 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1769 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001770 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001771}
1772
1773/// \brief Check a template argument against its corresponding
1774/// template template parameter.
1775///
1776/// This routine implements the semantics of C++ [temp.arg.template].
1777/// It returns true if an error occurred, and false otherwise.
1778bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1779 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001780 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1781 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1782
1783 // C++ [temp.arg.template]p1:
1784 // A template-argument for a template template-parameter shall be
1785 // the name of a class template, expressed as id-expression. Only
1786 // primary class templates are considered when matching the
1787 // template template argument with the corresponding parameter;
1788 // partial specializations are not considered even if their
1789 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001790 //
1791 // Note that we also allow template template parameters here, which
1792 // will happen when we are dealing with, e.g., class template
1793 // partial specializations.
1794 if (!isa<ClassTemplateDecl>(Template) &&
1795 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001796 assert(isa<FunctionTemplateDecl>(Template) &&
1797 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001798 Diag(Arg->getSourceRange().getBegin(),
1799 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001800 << Template;
1801 }
1802
1803 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1804 Param->getTemplateParameters(),
1805 true, true,
1806 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001807}
1808
Douglas Gregord406b032009-02-06 22:42:48 +00001809/// \brief Determine whether the given template parameter lists are
1810/// equivalent.
1811///
1812/// \param New The new template parameter list, typically written in the
1813/// source code as part of a new template declaration.
1814///
1815/// \param Old The old template parameter list, typically found via
1816/// name lookup of the template declared with this template parameter
1817/// list.
1818///
1819/// \param Complain If true, this routine will produce a diagnostic if
1820/// the template parameter lists are not equivalent.
1821///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001822/// \param IsTemplateTemplateParm If true, this routine is being
1823/// called to compare the template parameter lists of a template
1824/// template parameter.
1825///
1826/// \param TemplateArgLoc If this source location is valid, then we
1827/// are actually checking the template parameter list of a template
1828/// argument (New) against the template parameter list of its
1829/// corresponding template template parameter (Old). We produce
1830/// slightly different diagnostics in this scenario.
1831///
Douglas Gregord406b032009-02-06 22:42:48 +00001832/// \returns True if the template parameter lists are equal, false
1833/// otherwise.
1834bool
1835Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1836 TemplateParameterList *Old,
1837 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001838 bool IsTemplateTemplateParm,
1839 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001840 if (Old->size() != New->size()) {
1841 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001842 unsigned NextDiag = diag::err_template_param_list_different_arity;
1843 if (TemplateArgLoc.isValid()) {
1844 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1845 NextDiag = diag::note_template_param_list_different_arity;
1846 }
1847 Diag(New->getTemplateLoc(), NextDiag)
1848 << (New->size() > Old->size())
1849 << IsTemplateTemplateParm
1850 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001851 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1852 << IsTemplateTemplateParm
1853 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1854 }
1855
1856 return false;
1857 }
1858
1859 for (TemplateParameterList::iterator OldParm = Old->begin(),
1860 OldParmEnd = Old->end(), NewParm = New->begin();
1861 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1862 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001863 unsigned NextDiag = diag::err_template_param_different_kind;
1864 if (TemplateArgLoc.isValid()) {
1865 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1866 NextDiag = diag::note_template_param_different_kind;
1867 }
1868 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001869 << IsTemplateTemplateParm;
1870 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1871 << IsTemplateTemplateParm;
1872 return false;
1873 }
1874
1875 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1876 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001877 // know we're at the same index).
1878#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001879 // FIXME: Enable this code in debug mode *after* we properly go through
1880 // and "instantiate" the template parameter lists of template template
1881 // parameters. It's only after this instantiation that (1) any dependent
1882 // types within the template parameter list of the template template
1883 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001884 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001885 QualType OldParmType
1886 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1887 QualType NewParmType
1888 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1889 assert(Context.getCanonicalType(OldParmType) ==
1890 Context.getCanonicalType(NewParmType) &&
1891 "type parameter mismatch?");
1892#endif
1893 } else if (NonTypeTemplateParmDecl *OldNTTP
1894 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1895 // The types of non-type template parameters must agree.
1896 NonTypeTemplateParmDecl *NewNTTP
1897 = cast<NonTypeTemplateParmDecl>(*NewParm);
1898 if (Context.getCanonicalType(OldNTTP->getType()) !=
1899 Context.getCanonicalType(NewNTTP->getType())) {
1900 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001901 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1902 if (TemplateArgLoc.isValid()) {
1903 Diag(TemplateArgLoc,
1904 diag::err_template_arg_template_params_mismatch);
1905 NextDiag = diag::note_template_nontype_parm_different_type;
1906 }
1907 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001908 << NewNTTP->getType()
1909 << IsTemplateTemplateParm;
1910 Diag(OldNTTP->getLocation(),
1911 diag::note_template_nontype_parm_prev_declaration)
1912 << OldNTTP->getType();
1913 }
1914 return false;
1915 }
1916 } else {
1917 // The template parameter lists of template template
1918 // parameters must agree.
1919 // FIXME: Could we perform a faster "type" comparison here?
1920 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1921 "Only template template parameters handled here");
1922 TemplateTemplateParmDecl *OldTTP
1923 = cast<TemplateTemplateParmDecl>(*OldParm);
1924 TemplateTemplateParmDecl *NewTTP
1925 = cast<TemplateTemplateParmDecl>(*NewParm);
1926 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1927 OldTTP->getTemplateParameters(),
1928 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001929 /*IsTemplateTemplateParm=*/true,
1930 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001931 return false;
1932 }
1933 }
1934
1935 return true;
1936}
1937
1938/// \brief Check whether a template can be declared within this scope.
1939///
1940/// If the template declaration is valid in this scope, returns
1941/// false. Otherwise, issues a diagnostic and returns true.
1942bool
1943Sema::CheckTemplateDeclScope(Scope *S,
1944 MultiTemplateParamsArg &TemplateParameterLists) {
1945 assert(TemplateParameterLists.size() > 0 && "Not a template");
1946
1947 // Find the nearest enclosing declaration scope.
1948 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1949 (S->getFlags() & Scope::TemplateParamScope) != 0)
1950 S = S->getParent();
1951
1952 TemplateParameterList *TemplateParams =
1953 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1954 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1955 SourceRange TemplateRange
1956 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1957
1958 // C++ [temp]p2:
1959 // A template-declaration can appear only as a namespace scope or
1960 // class scope declaration.
1961 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1962 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1963 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1964 return Diag(TemplateLoc, diag::err_template_linkage)
1965 << TemplateRange;
1966
1967 Ctx = Ctx->getParent();
1968 }
1969
1970 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1971 return false;
1972
1973 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1974 << TemplateRange;
1975}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001976
Douglas Gregor90177912009-05-13 18:28:20 +00001977/// \brief Check whether a class template specialization or explicit
1978/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001979///
Douglas Gregor90177912009-05-13 18:28:20 +00001980/// This routine determines whether a class template specialization or
1981/// explicit instantiation can be declared in the current context
1982/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1983/// appropriate diagnostics if there was an error. It returns true if
1984// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001985bool
1986Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1987 ClassTemplateSpecializationDecl *PrevDecl,
1988 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001989 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001990 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001991 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001992 // C++ [temp.expl.spec]p2:
1993 // An explicit specialization shall be declared in the namespace
1994 // of which the template is a member, or, for member templates, in
1995 // the namespace of which the enclosing class or enclosing class
1996 // template is a member. An explicit specialization of a member
1997 // function, member class or static data member of a class
1998 // template shall be declared in the namespace of which the class
1999 // template is a member. Such a declaration may also be a
2000 // definition. If the declaration is not a definition, the
2001 // specialization may be defined later in the name- space in which
2002 // the explicit specialization was declared, or in a namespace
2003 // that encloses the one in which the explicit specialization was
2004 // declared.
2005 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002006 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002007 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002008 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002009 return true;
2010 }
2011
2012 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2013 DeclContext *TemplateContext
2014 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002015 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2016 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002017 // There is no prior declaration of this entity, so this
2018 // specialization must be in the same context as the template
2019 // itself.
2020 if (DC != TemplateContext) {
2021 if (isa<TranslationUnitDecl>(TemplateContext))
2022 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002023 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002024 << ClassTemplate << ScopeSpecifierRange;
2025 else if (isa<NamespaceDecl>(TemplateContext))
2026 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002027 << PartialSpecialization << ClassTemplate
2028 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002029
2030 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2031 }
2032
2033 return false;
2034 }
2035
2036 // We have a previous declaration of this entity. Make sure that
2037 // this redeclaration (or definition) occurs in an enclosing namespace.
2038 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002039 // FIXME: In C++98, we would like to turn these errors into warnings,
2040 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002041 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002042 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002043 if (isa<TranslationUnitDecl>(TemplateContext)) {
2044 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2045 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002046 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002047 else
2048 SuppressedDiag = true;
2049 } else if (isa<NamespaceDecl>(TemplateContext)) {
2050 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2051 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002052 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002053 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2054 else
2055 SuppressedDiag = true;
2056 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002057
Douglas Gregor90177912009-05-13 18:28:20 +00002058 if (!SuppressedDiag)
2059 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002060 }
2061
2062 return false;
2063}
2064
Douglas Gregor76e79952009-06-12 21:21:02 +00002065/// \brief Check the non-type template arguments of a class template
2066/// partial specialization according to C++ [temp.class.spec]p9.
2067///
Douglas Gregor42476442009-06-12 22:08:06 +00002068/// \param TemplateParams the template parameters of the primary class
2069/// template.
2070///
2071/// \param TemplateArg the template arguments of the class template
2072/// partial specialization.
2073///
2074/// \param MirrorsPrimaryTemplate will be set true if the class
2075/// template partial specialization arguments are identical to the
2076/// implicit template arguments of the primary template. This is not
2077/// necessarily an error (C++0x), and it is left to the caller to diagnose
2078/// this condition when it is an error.
2079///
Douglas Gregor76e79952009-06-12 21:21:02 +00002080/// \returns true if there was an error, false otherwise.
2081bool Sema::CheckClassTemplatePartialSpecializationArgs(
2082 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002083 const TemplateArgument *TemplateArgs,
2084 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002085 // FIXME: the interface to this function will have to change to
2086 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002087 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002088 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002089 // Determine whether the template argument list of the partial
2090 // specialization is identical to the implicit argument list of
2091 // the primary template. The caller may need to diagnostic this as
2092 // an error per C++ [temp.class.spec]p9b3.
2093 if (MirrorsPrimaryTemplate) {
2094 if (TemplateTypeParmDecl *TTP
2095 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2096 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2097 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2098 MirrorsPrimaryTemplate = false;
2099 } else if (TemplateTemplateParmDecl *TTP
2100 = dyn_cast<TemplateTemplateParmDecl>(
2101 TemplateParams->getParam(I))) {
2102 // FIXME: We should settle on either Declaration storage or
2103 // Expression storage for template template parameters.
2104 TemplateTemplateParmDecl *ArgDecl
2105 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2106 TemplateArgs[I].getAsDecl());
2107 if (!ArgDecl)
2108 if (DeclRefExpr *DRE
2109 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2110 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2111
2112 if (!ArgDecl ||
2113 ArgDecl->getIndex() != TTP->getIndex() ||
2114 ArgDecl->getDepth() != TTP->getDepth())
2115 MirrorsPrimaryTemplate = false;
2116 }
2117 }
2118
Douglas Gregor76e79952009-06-12 21:21:02 +00002119 NonTypeTemplateParmDecl *Param
2120 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002121 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002122 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002123 }
2124
Douglas Gregor76e79952009-06-12 21:21:02 +00002125 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002126 if (!ArgExpr) {
2127 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002128 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002129 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002130
2131 // C++ [temp.class.spec]p8:
2132 // A non-type argument is non-specialized if it is the name of a
2133 // non-type parameter. All other non-type arguments are
2134 // specialized.
2135 //
2136 // Below, we check the two conditions that only apply to
2137 // specialized non-type arguments, so skip any non-specialized
2138 // arguments.
2139 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002140 if (NonTypeTemplateParmDecl *NTTP
2141 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2142 if (MirrorsPrimaryTemplate &&
2143 (Param->getIndex() != NTTP->getIndex() ||
2144 Param->getDepth() != NTTP->getDepth()))
2145 MirrorsPrimaryTemplate = false;
2146
Douglas Gregor76e79952009-06-12 21:21:02 +00002147 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002148 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002149
2150 // C++ [temp.class.spec]p9:
2151 // Within the argument list of a class template partial
2152 // specialization, the following restrictions apply:
2153 // -- A partially specialized non-type argument expression
2154 // shall not involve a template parameter of the partial
2155 // specialization except when the argument expression is a
2156 // simple identifier.
2157 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2158 Diag(ArgExpr->getLocStart(),
2159 diag::err_dependent_non_type_arg_in_partial_spec)
2160 << ArgExpr->getSourceRange();
2161 return true;
2162 }
2163
2164 // -- The type of a template parameter corresponding to a
2165 // specialized non-type argument shall not be dependent on a
2166 // parameter of the specialization.
2167 if (Param->getType()->isDependentType()) {
2168 Diag(ArgExpr->getLocStart(),
2169 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2170 << Param->getType()
2171 << ArgExpr->getSourceRange();
2172 Diag(Param->getLocation(), diag::note_template_param_here);
2173 return true;
2174 }
Douglas Gregor42476442009-06-12 22:08:06 +00002175
2176 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002177 }
2178
2179 return false;
2180}
2181
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002182Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002183Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2184 SourceLocation KWLoc,
2185 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002186 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002187 SourceLocation TemplateNameLoc,
2188 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002189 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002190 SourceLocation *TemplateArgLocs,
2191 SourceLocation RAngleLoc,
2192 AttributeList *Attr,
2193 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002194 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002195 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002196 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002197 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002198
Douglas Gregor58944ac2009-05-31 09:31:02 +00002199 bool isPartialSpecialization = false;
2200
Douglas Gregor0d93f692009-02-25 22:02:03 +00002201 // Check the validity of the template headers that introduce this
2202 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002203 // FIXME: Once we have member templates, we'll need to check
2204 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2205 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002206 if (TemplateParameterLists.size() == 0)
2207 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002208 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002209 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002210 TemplateParameterList *TemplateParams
2211 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002212 if (TemplateParameterLists.size() > 1) {
2213 Diag(TemplateParams->getTemplateLoc(),
2214 diag::err_template_spec_extra_headers);
2215 return true;
2216 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002217
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002218 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002219 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002220
2221 // C++ [temp.class.spec]p10:
2222 // The template parameter list of a specialization shall not
2223 // contain default template argument values.
2224 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2225 Decl *Param = TemplateParams->getParam(I);
2226 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2227 if (TTP->hasDefaultArgument()) {
2228 Diag(TTP->getDefaultArgumentLoc(),
2229 diag::err_default_arg_in_partial_spec);
2230 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2231 }
2232 } else if (NonTypeTemplateParmDecl *NTTP
2233 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2234 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2235 Diag(NTTP->getDefaultArgumentLoc(),
2236 diag::err_default_arg_in_partial_spec)
2237 << DefArg->getSourceRange();
2238 NTTP->setDefaultArgument(0);
2239 DefArg->Destroy(Context);
2240 }
2241 } else {
2242 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2243 if (Expr *DefArg = TTP->getDefaultArgument()) {
2244 Diag(TTP->getDefaultArgumentLoc(),
2245 diag::err_default_arg_in_partial_spec)
2246 << DefArg->getSourceRange();
2247 TTP->setDefaultArgument(0);
2248 DefArg->Destroy(Context);
2249 }
2250 }
2251 }
2252 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002253 }
2254
Douglas Gregora08b6c72009-02-17 23:15:12 +00002255 // Check that the specialization uses the same tag kind as the
2256 // original template.
2257 TagDecl::TagKind Kind;
2258 switch (TagSpec) {
2259 default: assert(0 && "Unknown tag type!");
2260 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2261 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2262 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2263 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002264 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2265 Kind, KWLoc,
2266 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002267 Diag(KWLoc, diag::err_use_with_wrong_tag)
2268 << ClassTemplate
2269 << CodeModificationHint::CreateReplacement(KWLoc,
2270 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002271 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2272 diag::note_previous_use);
2273 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2274 }
2275
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002276 // Translate the parser's template argument list in our AST format.
2277 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2278 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2279
Douglas Gregora08b6c72009-02-17 23:15:12 +00002280 // Check that the template argument list is well-formed for this
2281 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002282 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002283 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002284 &TemplateArgs[0], TemplateArgs.size(),
2285 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002286 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002287
2288 assert((ConvertedTemplateArgs.size() ==
2289 ClassTemplate->getTemplateParameters()->size()) &&
2290 "Converted template argument list is too short!");
2291
Douglas Gregor58944ac2009-05-31 09:31:02 +00002292 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002293 // corresponds to these arguments.
2294 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002295 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002296 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002297 if (CheckClassTemplatePartialSpecializationArgs(
2298 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002299 ConvertedTemplateArgs.getFlatArgumentList(),
2300 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002301 return true;
2302
Douglas Gregor42476442009-06-12 22:08:06 +00002303 if (MirrorsPrimaryTemplate) {
2304 // C++ [temp.class.spec]p9b3:
2305 //
2306 // -- The argument list of the specialization shall not be identical
2307 // to the implicit argument list of the primary template.
2308 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2309 << (TK == TK_Definition)
2310 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2311 RAngleLoc));
2312 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2313 ClassTemplate->getIdentifier(),
2314 TemplateNameLoc,
2315 Attr,
2316 move(TemplateParameterLists),
2317 AS_none);
2318 }
2319
Douglas Gregor58944ac2009-05-31 09:31:02 +00002320 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002321 ClassTemplatePartialSpecializationDecl::Profile(ID,
2322 ConvertedTemplateArgs.getFlatArgumentList(),
2323 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002324 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002325 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002326 ClassTemplateSpecializationDecl::Profile(ID,
2327 ConvertedTemplateArgs.getFlatArgumentList(),
2328 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002329 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002330 ClassTemplateSpecializationDecl *PrevDecl = 0;
2331
2332 if (isPartialSpecialization)
2333 PrevDecl
2334 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2335 InsertPos);
2336 else
2337 PrevDecl
2338 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002339
2340 ClassTemplateSpecializationDecl *Specialization = 0;
2341
Douglas Gregor0d93f692009-02-25 22:02:03 +00002342 // Check whether we can declare a class template specialization in
2343 // the current scope.
2344 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2345 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002346 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002347 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002348 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002349 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002350
Douglas Gregora08b6c72009-02-17 23:15:12 +00002351 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2352 // Since the only prior class template specialization with these
2353 // arguments was referenced but not declared, reuse that
2354 // declaration node as our own, updating its source location to
2355 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002356 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002357 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002358 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002359 } else if (isPartialSpecialization) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002360 // Create a new class template partial specialization declaration node.
2361 TemplateParameterList *TemplateParams
2362 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2363 ClassTemplatePartialSpecializationDecl *PrevPartial
2364 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2365 ClassTemplatePartialSpecializationDecl *Partial
2366 = ClassTemplatePartialSpecializationDecl::Create(Context,
2367 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002368 TemplateNameLoc,
2369 TemplateParams,
2370 ClassTemplate,
2371 ConvertedTemplateArgs,
2372 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002373
2374 if (PrevPartial) {
2375 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2376 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2377 } else {
2378 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2379 }
2380 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002381
2382 // Check that all of the template parameters of the class template
2383 // partial specialization are deducible from the template
2384 // arguments. If not, this class template partial specialization
2385 // will never be used.
2386 llvm::SmallVector<bool, 8> DeducibleParams;
2387 DeducibleParams.resize(TemplateParams->size());
2388 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2389 unsigned NumNonDeducible = 0;
2390 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2391 if (!DeducibleParams[I])
2392 ++NumNonDeducible;
2393
2394 if (NumNonDeducible) {
2395 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2396 << (NumNonDeducible > 1)
2397 << SourceRange(TemplateNameLoc, RAngleLoc);
2398 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2399 if (!DeducibleParams[I]) {
2400 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2401 if (Param->getDeclName())
2402 Diag(Param->getLocation(),
2403 diag::note_partial_spec_unused_parameter)
2404 << Param->getDeclName();
2405 else
2406 Diag(Param->getLocation(),
2407 diag::note_partial_spec_unused_parameter)
2408 << std::string("<anonymous>");
2409 }
2410 }
2411 }
2412
Douglas Gregora08b6c72009-02-17 23:15:12 +00002413 } else {
2414 // Create a new class template specialization declaration node for
2415 // this explicit specialization.
2416 Specialization
2417 = ClassTemplateSpecializationDecl::Create(Context,
2418 ClassTemplate->getDeclContext(),
2419 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002420 ClassTemplate,
2421 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002422 PrevDecl);
2423
2424 if (PrevDecl) {
2425 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2426 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2427 } else {
2428 ClassTemplate->getSpecializations().InsertNode(Specialization,
2429 InsertPos);
2430 }
2431 }
2432
2433 // Note that this is an explicit specialization.
2434 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2435
2436 // Check that this isn't a redefinition of this specialization.
2437 if (TK == TK_Definition) {
2438 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002439 // FIXME: Should also handle explicit specialization after implicit
2440 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002441 SourceRange Range(TemplateNameLoc, RAngleLoc);
2442 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002443 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002444 Diag(Def->getLocation(), diag::note_previous_definition);
2445 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002446 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002447 }
2448 }
2449
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002450 // Build the fully-sugared type for this class template
2451 // specialization as the user wrote in the specialization
2452 // itself. This means that we'll pretty-print the type retrieved
2453 // from the specialization's declaration the way that the user
2454 // actually wrote the specialization, rather than formatting the
2455 // name based on the "canonical" representation used to store the
2456 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002457 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002458 = Context.getTemplateSpecializationType(Name,
2459 &TemplateArgs[0],
2460 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002461 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002462 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002463 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002464
Douglas Gregor50113ca2009-02-25 22:18:32 +00002465 // C++ [temp.expl.spec]p9:
2466 // A template explicit specialization is in the scope of the
2467 // namespace in which the template was defined.
2468 //
2469 // We actually implement this paragraph where we set the semantic
2470 // context (in the creation of the ClassTemplateSpecializationDecl),
2471 // but we also maintain the lexical context where the actual
2472 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002473 Specialization->setLexicalDeclContext(CurContext);
2474
2475 // We may be starting the definition of this specialization.
2476 if (TK == TK_Definition)
2477 Specialization->startDefinition();
2478
2479 // Add the specialization into its lexical context, so that it can
2480 // be seen when iterating through the list of declarations in that
2481 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002482 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002483 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002484}
Douglas Gregord3022602009-03-27 23:10:48 +00002485
Douglas Gregor96b6df92009-05-14 00:28:11 +00002486// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002487Sema::DeclResult
2488Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2489 unsigned TagSpec,
2490 SourceLocation KWLoc,
2491 const CXXScopeSpec &SS,
2492 TemplateTy TemplateD,
2493 SourceLocation TemplateNameLoc,
2494 SourceLocation LAngleLoc,
2495 ASTTemplateArgsPtr TemplateArgsIn,
2496 SourceLocation *TemplateArgLocs,
2497 SourceLocation RAngleLoc,
2498 AttributeList *Attr) {
2499 // Find the class template we're specializing
2500 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2501 ClassTemplateDecl *ClassTemplate
2502 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2503
2504 // Check that the specialization uses the same tag kind as the
2505 // original template.
2506 TagDecl::TagKind Kind;
2507 switch (TagSpec) {
2508 default: assert(0 && "Unknown tag type!");
2509 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2510 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2511 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2512 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002513 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2514 Kind, KWLoc,
2515 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002516 Diag(KWLoc, diag::err_use_with_wrong_tag)
2517 << ClassTemplate
2518 << CodeModificationHint::CreateReplacement(KWLoc,
2519 ClassTemplate->getTemplatedDecl()->getKindName());
2520 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2521 diag::note_previous_use);
2522 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2523 }
2524
Douglas Gregor90177912009-05-13 18:28:20 +00002525 // C++0x [temp.explicit]p2:
2526 // [...] An explicit instantiation shall appear in an enclosing
2527 // namespace of its template. [...]
2528 //
2529 // This is C++ DR 275.
2530 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2531 TemplateNameLoc,
2532 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002533 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002534 /*ExplicitInstantiation=*/true))
2535 return true;
2536
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002537 // Translate the parser's template argument list in our AST format.
2538 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2539 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2540
2541 // Check that the template argument list is well-formed for this
2542 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002543 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002544 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002545 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002546 RAngleLoc, ConvertedTemplateArgs))
2547 return true;
2548
2549 assert((ConvertedTemplateArgs.size() ==
2550 ClassTemplate->getTemplateParameters()->size()) &&
2551 "Converted template argument list is too short!");
2552
2553 // Find the class template specialization declaration that
2554 // corresponds to these arguments.
2555 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002556 ClassTemplateSpecializationDecl::Profile(ID,
2557 ConvertedTemplateArgs.getFlatArgumentList(),
2558 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002559 void *InsertPos = 0;
2560 ClassTemplateSpecializationDecl *PrevDecl
2561 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2562
2563 ClassTemplateSpecializationDecl *Specialization = 0;
2564
Douglas Gregor90177912009-05-13 18:28:20 +00002565 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002566 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002567 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002568 // This particular specialization has already been declared or
2569 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002570 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2571 << Context.getTypeDeclType(PrevDecl);
2572 Diag(PrevDecl->getLocation(),
2573 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002574 return DeclPtrTy::make(PrevDecl);
2575 }
2576
Douglas Gregor90177912009-05-13 18:28:20 +00002577 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002578 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002579 // For a given set of template parameters, if an explicit
2580 // instantiation of a template appears after a declaration of
2581 // an explicit specialization for that template, the explicit
2582 // instantiation has no effect.
2583 if (!getLangOptions().CPlusPlus0x) {
2584 Diag(TemplateNameLoc,
2585 diag::ext_explicit_instantiation_after_specialization)
2586 << Context.getTypeDeclType(PrevDecl);
2587 Diag(PrevDecl->getLocation(),
2588 diag::note_previous_template_specialization);
2589 }
2590
2591 // Create a new class template specialization declaration node
2592 // for this explicit specialization. This node is only used to
2593 // record the existence of this explicit instantiation for
2594 // accurate reproduction of the source code; we don't actually
2595 // use it for anything, since it is semantically irrelevant.
2596 Specialization
2597 = ClassTemplateSpecializationDecl::Create(Context,
2598 ClassTemplate->getDeclContext(),
2599 TemplateNameLoc,
2600 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002601 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002602 Specialization->setLexicalDeclContext(CurContext);
2603 CurContext->addDecl(Context, Specialization);
2604 return DeclPtrTy::make(Specialization);
2605 }
2606
2607 // If we have already (implicitly) instantiated this
2608 // specialization, there is less work to do.
2609 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2610 SpecializationRequiresInstantiation = false;
2611
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002612 // Since the only prior class template specialization with these
2613 // arguments was referenced but not declared, reuse that
2614 // declaration node as our own, updating its source location to
2615 // reflect our new declaration.
2616 Specialization = PrevDecl;
2617 Specialization->setLocation(TemplateNameLoc);
2618 PrevDecl = 0;
2619 } else {
2620 // Create a new class template specialization declaration node for
2621 // this explicit specialization.
2622 Specialization
2623 = ClassTemplateSpecializationDecl::Create(Context,
2624 ClassTemplate->getDeclContext(),
2625 TemplateNameLoc,
2626 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002627 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002628
2629 ClassTemplate->getSpecializations().InsertNode(Specialization,
2630 InsertPos);
2631 }
2632
2633 // Build the fully-sugared type for this explicit instantiation as
2634 // the user wrote in the explicit instantiation itself. This means
2635 // that we'll pretty-print the type retrieved from the
2636 // specialization's declaration the way that the user actually wrote
2637 // the explicit instantiation, rather than formatting the name based
2638 // on the "canonical" representation used to store the template
2639 // arguments in the specialization.
2640 QualType WrittenTy
2641 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002642 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002643 TemplateArgs.size(),
2644 Context.getTypeDeclType(Specialization));
2645 Specialization->setTypeAsWritten(WrittenTy);
2646 TemplateArgsIn.release();
2647
2648 // Add the explicit instantiation into its lexical context. However,
2649 // since explicit instantiations are never found by name lookup, we
2650 // just put it into the declaration context directly.
2651 Specialization->setLexicalDeclContext(CurContext);
2652 CurContext->addDecl(Context, Specialization);
2653
2654 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002655 // A definition of a class template or class member template
2656 // shall be in scope at the point of the explicit instantiation of
2657 // the class template or class member template.
2658 //
2659 // This check comes when we actually try to perform the
2660 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002661 if (SpecializationRequiresInstantiation)
2662 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002663 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002664 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002665
2666 return DeclPtrTy::make(Specialization);
2667}
2668
Douglas Gregor96b6df92009-05-14 00:28:11 +00002669// Explicit instantiation of a member class of a class template.
2670Sema::DeclResult
2671Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2672 unsigned TagSpec,
2673 SourceLocation KWLoc,
2674 const CXXScopeSpec &SS,
2675 IdentifierInfo *Name,
2676 SourceLocation NameLoc,
2677 AttributeList *Attr) {
2678
Douglas Gregor71f06032009-05-28 23:31:59 +00002679 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002680 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002681 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002682 if (!TagD)
2683 return true;
2684
2685 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2686 if (Tag->isEnum()) {
2687 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2688 << Context.getTypeDeclType(Tag);
2689 return true;
2690 }
2691
Douglas Gregord769bfa2009-05-27 17:30:49 +00002692 if (Tag->isInvalidDecl())
2693 return true;
2694
Douglas Gregor96b6df92009-05-14 00:28:11 +00002695 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2696 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2697 if (!Pattern) {
2698 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2699 << Context.getTypeDeclType(Record);
2700 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2701 return true;
2702 }
2703
2704 // C++0x [temp.explicit]p2:
2705 // [...] An explicit instantiation shall appear in an enclosing
2706 // namespace of its template. [...]
2707 //
2708 // This is C++ DR 275.
2709 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002710 // FIXME: In C++98, we would like to turn these errors into warnings,
2711 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002712 DeclContext *PatternContext
2713 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2714 if (!CurContext->Encloses(PatternContext)) {
2715 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2716 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2717 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2718 }
2719 }
2720
Douglas Gregor96b6df92009-05-14 00:28:11 +00002721 if (!Record->getDefinition(Context)) {
2722 // If the class has a definition, instantiate it (and all of its
2723 // members, recursively).
2724 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2725 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002726 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002727 /*ExplicitInstantiation=*/true))
2728 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002729 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002730 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002731 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002732
Mike Stumpe127ae32009-05-16 07:39:55 +00002733 // FIXME: We don't have any representation for explicit instantiations of
2734 // member classes. Such a representation is not needed for compilation, but it
2735 // should be available for clients that want to see all of the declarations in
2736 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002737 return TagD;
2738}
2739
Douglas Gregord3022602009-03-27 23:10:48 +00002740Sema::TypeResult
2741Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2742 const IdentifierInfo &II, SourceLocation IdLoc) {
2743 NestedNameSpecifier *NNS
2744 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2745 if (!NNS)
2746 return true;
2747
2748 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002749 if (T.isNull())
2750 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002751 return T.getAsOpaquePtr();
2752}
2753
Douglas Gregor77da5802009-04-01 00:28:59 +00002754Sema::TypeResult
2755Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2756 SourceLocation TemplateLoc, TypeTy *Ty) {
2757 QualType T = QualType::getFromOpaquePtr(Ty);
2758 NestedNameSpecifier *NNS
2759 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2760 const TemplateSpecializationType *TemplateId
2761 = T->getAsTemplateSpecializationType();
2762 assert(TemplateId && "Expected a template specialization type");
2763
2764 if (NNS->isDependent())
2765 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2766
2767 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2768}
2769
Douglas Gregord3022602009-03-27 23:10:48 +00002770/// \brief Build the type that describes a C++ typename specifier,
2771/// e.g., "typename T::type".
2772QualType
2773Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2774 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002775 CXXRecordDecl *CurrentInstantiation = 0;
2776 if (NNS->isDependent()) {
2777 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002778
Douglas Gregor3eb20702009-05-11 19:58:34 +00002779 // If the nested-name-specifier does not refer to the current
2780 // instantiation, then build a typename type.
2781 if (!CurrentInstantiation)
2782 return Context.getTypenameType(NNS, &II);
2783 }
Douglas Gregord3022602009-03-27 23:10:48 +00002784
Douglas Gregor3eb20702009-05-11 19:58:34 +00002785 DeclContext *Ctx = 0;
2786
2787 if (CurrentInstantiation)
2788 Ctx = CurrentInstantiation;
2789 else {
2790 CXXScopeSpec SS;
2791 SS.setScopeRep(NNS);
2792 SS.setRange(Range);
2793 if (RequireCompleteDeclContext(SS))
2794 return QualType();
2795
2796 Ctx = computeDeclContext(SS);
2797 }
Douglas Gregord3022602009-03-27 23:10:48 +00002798 assert(Ctx && "No declaration context?");
2799
2800 DeclarationName Name(&II);
2801 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2802 false);
2803 unsigned DiagID = 0;
2804 Decl *Referenced = 0;
2805 switch (Result.getKind()) {
2806 case LookupResult::NotFound:
2807 if (Ctx->isTranslationUnit())
2808 DiagID = diag::err_typename_nested_not_found_global;
2809 else
2810 DiagID = diag::err_typename_nested_not_found;
2811 break;
2812
2813 case LookupResult::Found:
2814 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2815 // We found a type. Build a QualifiedNameType, since the
2816 // typename-specifier was just sugar. FIXME: Tell
2817 // QualifiedNameType that it has a "typename" prefix.
2818 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2819 }
2820
2821 DiagID = diag::err_typename_nested_not_type;
2822 Referenced = Result.getAsDecl();
2823 break;
2824
2825 case LookupResult::FoundOverloaded:
2826 DiagID = diag::err_typename_nested_not_type;
2827 Referenced = *Result.begin();
2828 break;
2829
2830 case LookupResult::AmbiguousBaseSubobjectTypes:
2831 case LookupResult::AmbiguousBaseSubobjects:
2832 case LookupResult::AmbiguousReference:
2833 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2834 return QualType();
2835 }
2836
2837 // If we get here, it's because name lookup did not find a
2838 // type. Emit an appropriate diagnostic and return an error.
2839 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2840 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2841 else
2842 Diag(Range.getEnd(), DiagID) << Range << Name;
2843 if (Referenced)
2844 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2845 << Name;
2846 return QualType();
2847}