blob: e1b2084469b74491c4d488976b489e2437d24b6e [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
Mike Stumpe0b7e032009-02-11 23:03:27 +0000594 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000595 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000596 if (OldParams)
597 OldParam = OldParams->begin();
598
599 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
600 NewParamEnd = NewParams->end();
601 NewParam != NewParamEnd; ++NewParam) {
602 // Variables used to diagnose redundant default arguments
603 bool RedundantDefaultArg = false;
604 SourceLocation OldDefaultLoc;
605 SourceLocation NewDefaultLoc;
606
607 // Variables used to diagnose missing default arguments
608 bool MissingDefaultArg = false;
609
610 // Merge default arguments for template type parameters.
611 if (TemplateTypeParmDecl *NewTypeParm
612 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
613 TemplateTypeParmDecl *OldTypeParm
614 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
615
616 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
617 NewTypeParm->hasDefaultArgument()) {
618 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
619 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
620 SawDefaultArgument = true;
621 RedundantDefaultArg = true;
622 PreviousDefaultArgLoc = NewDefaultLoc;
623 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
624 // Merge the default argument from the old declaration to the
625 // new declaration.
626 SawDefaultArgument = true;
627 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
628 OldTypeParm->getDefaultArgumentLoc(),
629 true);
630 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
631 } else if (NewTypeParm->hasDefaultArgument()) {
632 SawDefaultArgument = true;
633 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
634 } else if (SawDefaultArgument)
635 MissingDefaultArg = true;
636 }
637 // Merge default arguments for non-type template parameters
638 else if (NonTypeTemplateParmDecl *NewNonTypeParm
639 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
640 NonTypeTemplateParmDecl *OldNonTypeParm
641 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
642 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
643 NewNonTypeParm->hasDefaultArgument()) {
644 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
645 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
646 SawDefaultArgument = true;
647 RedundantDefaultArg = true;
648 PreviousDefaultArgLoc = NewDefaultLoc;
649 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
650 // Merge the default argument from the old declaration to the
651 // new declaration.
652 SawDefaultArgument = true;
653 // FIXME: We need to create a new kind of "default argument"
654 // expression that points to a previous template template
655 // parameter.
656 NewNonTypeParm->setDefaultArgument(
657 OldNonTypeParm->getDefaultArgument());
658 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
659 } else if (NewNonTypeParm->hasDefaultArgument()) {
660 SawDefaultArgument = true;
661 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
662 } else if (SawDefaultArgument)
663 MissingDefaultArg = true;
664 }
665 // Merge default arguments for template template parameters
666 else {
667 TemplateTemplateParmDecl *NewTemplateParm
668 = cast<TemplateTemplateParmDecl>(*NewParam);
669 TemplateTemplateParmDecl *OldTemplateParm
670 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
671 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
672 NewTemplateParm->hasDefaultArgument()) {
673 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
674 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
675 SawDefaultArgument = true;
676 RedundantDefaultArg = true;
677 PreviousDefaultArgLoc = NewDefaultLoc;
678 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
679 // Merge the default argument from the old declaration to the
680 // new declaration.
681 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000682 // FIXME: We need to create a new kind of "default argument" expression
683 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000684 NewTemplateParm->setDefaultArgument(
685 OldTemplateParm->getDefaultArgument());
686 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
687 } else if (NewTemplateParm->hasDefaultArgument()) {
688 SawDefaultArgument = true;
689 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
690 } else if (SawDefaultArgument)
691 MissingDefaultArg = true;
692 }
693
694 if (RedundantDefaultArg) {
695 // C++ [temp.param]p12:
696 // A template-parameter shall not be given default arguments
697 // by two different declarations in the same scope.
698 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
699 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
700 Invalid = true;
701 } else if (MissingDefaultArg) {
702 // C++ [temp.param]p11:
703 // If a template-parameter has a default template-argument,
704 // all subsequent template-parameters shall have a default
705 // template-argument supplied.
706 Diag((*NewParam)->getLocation(),
707 diag::err_template_param_default_arg_missing);
708 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
709 Invalid = true;
710 }
711
712 // If we have an old template parameter list that we're merging
713 // in, move on to the next parameter.
714 if (OldParams)
715 ++OldParam;
716 }
717
718 return Invalid;
719}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000720
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000721/// \brief Translates template arguments as provided by the parser
722/// into template arguments used by semantic analysis.
723static void
724translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
725 SourceLocation *TemplateArgLocs,
726 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
727 TemplateArgs.reserve(TemplateArgsIn.size());
728
729 void **Args = TemplateArgsIn.getArgs();
730 bool *ArgIsType = TemplateArgsIn.getArgIsType();
731 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
732 TemplateArgs.push_back(
733 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
734 QualType::getFromOpaquePtr(Args[Arg]))
735 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
736 }
737}
738
Douglas Gregoraabb8502009-03-31 00:43:58 +0000739/// \brief Build a canonical version of a template argument list.
740///
741/// This function builds a canonical version of the given template
742/// argument list, where each of the template arguments has been
743/// converted into its canonical form. This routine is typically used
744/// to canonicalize a template argument list when the template name
745/// itself is dependent. When the template name refers to an actual
746/// template declaration, Sema::CheckTemplateArgumentList should be
747/// used to check and canonicalize the template arguments.
748///
749/// \param TemplateArgs The incoming template arguments.
750///
751/// \param NumTemplateArgs The number of template arguments in \p
752/// TemplateArgs.
753///
754/// \param Canonical A vector to be filled with the canonical versions
755/// of the template arguments.
756///
757/// \param Context The ASTContext in which the template arguments live.
758static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
759 unsigned NumTemplateArgs,
760 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
761 ASTContext &Context) {
762 Canonical.reserve(NumTemplateArgs);
763 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
764 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000765 case TemplateArgument::Null:
766 assert(false && "Should never see a NULL template argument here");
767 break;
768
Douglas Gregoraabb8502009-03-31 00:43:58 +0000769 case TemplateArgument::Expression:
770 // FIXME: Build canonical expression (!)
771 Canonical.push_back(TemplateArgs[Idx]);
772 break;
773
774 case TemplateArgument::Declaration:
Douglas Gregor9054f982009-05-10 22:57:19 +0000775 Canonical.push_back(
776 TemplateArgument(SourceLocation(),
777 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregoraabb8502009-03-31 00:43:58 +0000778 break;
779
780 case TemplateArgument::Integral:
781 Canonical.push_back(TemplateArgument(SourceLocation(),
782 *TemplateArgs[Idx].getAsIntegral(),
783 TemplateArgs[Idx].getIntegralType()));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000784 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000785
786 case TemplateArgument::Type: {
787 QualType CanonType
788 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
789 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregorbf23a8a2009-06-04 00:03:07 +0000790 break;
Douglas Gregoraabb8502009-03-31 00:43:58 +0000791 }
792 }
793 }
794}
795
Douglas Gregordd13e842009-03-30 22:58:21 +0000796QualType Sema::CheckTemplateIdType(TemplateName Name,
797 SourceLocation TemplateLoc,
798 SourceLocation LAngleLoc,
799 const TemplateArgument *TemplateArgs,
800 unsigned NumTemplateArgs,
801 SourceLocation RAngleLoc) {
802 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000803 if (!Template) {
804 // The template name does not resolve to a template, so we just
805 // build a dependent template-id type.
806
807 // Canonicalize the template arguments to build the canonical
808 // template-id type.
809 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
810 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
811 CanonicalTemplateArgs, Context);
812
Douglas Gregor905406b2009-05-07 06:49:52 +0000813 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000814 QualType CanonType
Douglas Gregor905406b2009-05-07 06:49:52 +0000815 = Context.getTemplateSpecializationType(CanonName,
816 &CanonicalTemplateArgs[0],
Douglas Gregoraabb8502009-03-31 00:43:58 +0000817 CanonicalTemplateArgs.size());
818
819 // Build the dependent template-id type.
820 return Context.getTemplateSpecializationType(Name, TemplateArgs,
821 NumTemplateArgs, CanonType);
822 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000823
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000824 // Check that the template argument list is well-formed for this
825 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +0000826 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregordd13e842009-03-30 22:58:21 +0000827 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000828 TemplateArgs, NumTemplateArgs, RAngleLoc,
829 ConvertedTemplateArgs))
830 return QualType();
831
832 assert((ConvertedTemplateArgs.size() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000833 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000834 "Converted template argument list is too short!");
835
836 QualType CanonType;
837
Douglas Gregordd13e842009-03-30 22:58:21 +0000838 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000839 TemplateArgs,
840 NumTemplateArgs)) {
841 // This class template specialization is a dependent
842 // type. Therefore, its canonical type is another class template
843 // specialization type that contains all of the converted
844 // arguments in canonical form. This ensures that, e.g., A<T> and
845 // A<T, T> have identical types when A is declared as:
846 //
847 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000848 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
849 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssona35faf92009-06-05 03:43:12 +0000850 ConvertedTemplateArgs.getFlatArgumentList(),
851 ConvertedTemplateArgs.flatSize());
Douglas Gregordd13e842009-03-30 22:58:21 +0000852 } else if (ClassTemplateDecl *ClassTemplate
853 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000854 // Find the class template specialization declaration that
855 // corresponds to these arguments.
856 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000857 ClassTemplateSpecializationDecl::Profile(ID,
858 ConvertedTemplateArgs.getFlatArgumentList(),
859 ConvertedTemplateArgs.flatSize());
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000860 void *InsertPos = 0;
861 ClassTemplateSpecializationDecl *Decl
862 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
863 if (!Decl) {
864 // This is the first time we have referenced this class template
865 // specialization. Create the canonical declaration and add it to
866 // the set of specializations.
867 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000868 ClassTemplate->getDeclContext(),
869 TemplateLoc,
870 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +0000871 ConvertedTemplateArgs, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000872 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
873 Decl->setLexicalDeclContext(CurContext);
874 }
875
876 CanonType = Context.getTypeDeclType(Decl);
877 }
878
879 // Build the fully-sugared type for this class template
880 // specialization, which refers back to the class template
881 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +0000882 return Context.getTemplateSpecializationType(Name, TemplateArgs,
883 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000884}
885
Douglas Gregora08b6c72009-02-17 23:15:12 +0000886Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +0000887Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
888 SourceLocation LAngleLoc,
889 ASTTemplateArgsPtr TemplateArgsIn,
890 SourceLocation *TemplateArgLocs,
891 SourceLocation RAngleLoc) {
892 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000893
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000894 // Translate the parser's template argument list in our AST format.
895 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
896 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000897
Douglas Gregordd13e842009-03-30 22:58:21 +0000898 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000899 TemplateArgs.data(),
900 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +0000901 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000902 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +0000903
904 if (Result.isNull())
905 return true;
906
Douglas Gregor6f37b582009-02-09 19:34:22 +0000907 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000908}
909
Douglas Gregoraabb8502009-03-31 00:43:58 +0000910/// \brief Form a dependent template name.
911///
912/// This action forms a dependent template name given the template
913/// name and its (presumably dependent) scope specifier. For
914/// example, given "MetaFun::template apply", the scope specifier \p
915/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
916/// of the "template" keyword, and "apply" is the \p Name.
917Sema::TemplateTy
918Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
919 const IdentifierInfo &Name,
920 SourceLocation NameLoc,
921 const CXXScopeSpec &SS) {
922 if (!SS.isSet() || SS.isInvalid())
923 return TemplateTy();
924
925 NestedNameSpecifier *Qualifier
926 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
927
928 // FIXME: member of the current instantiation
929
930 if (!Qualifier->isDependent()) {
931 // C++0x [temp.names]p5:
932 // If a name prefixed by the keyword template is not the name of
933 // a template, the program is ill-formed. [Note: the keyword
934 // template may not be applied to non-template members of class
935 // templates. -end note ] [ Note: as is the case with the
936 // typename prefix, the template prefix is allowed in cases
937 // where it is not strictly necessary; i.e., when the
938 // nested-name-specifier or the expression on the left of the ->
939 // or . is not dependent on a template-parameter, or the use
940 // does not appear in the scope of a template. -end note]
941 //
942 // Note: C++03 was more strict here, because it banned the use of
943 // the "template" keyword prior to a template-name that was not a
944 // dependent name. C++ DR468 relaxed this requirement (the
945 // "template" keyword is now permitted). We follow the C++0x
946 // rules, even in C++03 mode, retroactively applying the DR.
947 TemplateTy Template;
948 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
949 if (TNK == TNK_Non_template) {
950 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
951 << &Name;
952 return TemplateTy();
953 }
954
955 return Template;
956 }
957
958 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
959}
960
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000961/// \brief Check that the given template argument list is well-formed
962/// for specializing the given template.
963bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
964 SourceLocation TemplateLoc,
965 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000966 const TemplateArgument *TemplateArgs,
967 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000968 SourceLocation RAngleLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +0000969 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000970 TemplateParameterList *Params = Template->getTemplateParameters();
971 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000972 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000973 bool Invalid = false;
974
975 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000976 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000977 // FIXME: point at either the first arg beyond what we can handle,
978 // or the '>', depending on whether we have too many or too few
979 // arguments.
980 SourceRange Range;
981 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000982 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000983 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
984 << (NumArgs > NumParams)
985 << (isa<ClassTemplateDecl>(Template)? 0 :
986 isa<FunctionTemplateDecl>(Template)? 1 :
987 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
988 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000989 Diag(Template->getLocation(), diag::note_template_decl_here)
990 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000991 Invalid = true;
992 }
993
994 // C++ [temp.arg]p1:
995 // [...] The type and form of each template-argument specified in
996 // a template-id shall match the type and form specified for the
997 // corresponding parameter declared by the template in its
998 // template-parameter-list.
999 unsigned ArgIdx = 0;
1000 for (TemplateParameterList::iterator Param = Params->begin(),
1001 ParamEnd = Params->end();
1002 Param != ParamEnd; ++Param, ++ArgIdx) {
1003 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001004 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001005 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001006 // Retrieve the default template argument from the template
1007 // parameter.
1008 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1009 if (!TTP->hasDefaultArgument())
1010 break;
1011
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001012 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001013
1014 // If the argument type is dependent, instantiate it now based
1015 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001016 if (ArgType->isDependentType()) {
1017 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001018 Template, Converted.getFlatArgumentList(),
1019 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001020 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001021
Anders Carlsson0233eb62009-06-05 04:47:51 +00001022 TemplateArgumentList TemplateArgs(Context, Converted,
1023 /*CopyArgs=*/false,
1024 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001025 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001026 TTP->getDefaultArgumentLoc(),
1027 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001028 }
Douglas Gregor74296542009-02-27 19:31:52 +00001029
1030 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001031 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001032
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001033 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001034 } else if (NonTypeTemplateParmDecl *NTTP
1035 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1036 if (!NTTP->hasDefaultArgument())
1037 break;
1038
Anders Carlsson0297caf2009-06-11 16:06:49 +00001039 InstantiatingTemplate Inst(*this, TemplateLoc,
1040 Template, Converted.getFlatArgumentList(),
1041 Converted.flatSize(),
1042 SourceRange(TemplateLoc, RAngleLoc));
1043
1044 TemplateArgumentList TemplateArgs(Context, Converted,
1045 /*CopyArgs=*/false,
1046 /*FlattenArgs=*/false);
1047
1048 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1049 TemplateArgs);
1050 if (E.isInvalid())
1051 return true;
1052
1053 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001054 } else {
1055 TemplateTemplateParmDecl *TempParm
1056 = cast<TemplateTemplateParmDecl>(*Param);
1057
1058 if (!TempParm->hasDefaultArgument())
1059 break;
1060
Douglas Gregored3a3982009-03-03 04:44:36 +00001061 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001062 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001063 }
1064 } else {
1065 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001066 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001067 }
1068
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001069
1070 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
1071 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001072 if (Arg.getKind() == TemplateArgument::Type) {
1073 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001074 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +00001075
1076 // Add the converted template type argument.
1077 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001078 TemplateArgument(Arg.getLocation(),
1079 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001080 continue;
1081 }
1082
1083 // C++ [temp.arg.type]p1:
1084 // A template-argument for a template-parameter which is a
1085 // type shall be a type-id.
1086
1087 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001088 // is not a type.
1089 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +00001090 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001091 Invalid = true;
1092 } else if (NonTypeTemplateParmDecl *NTTP
1093 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1094 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001095
1096 // Instantiate the type of the non-type template parameter with
1097 // the template arguments we've seen thus far.
1098 QualType NTTPType = NTTP->getType();
1099 if (NTTPType->isDependentType()) {
1100 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001101 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssona35faf92009-06-05 03:43:12 +00001102 Template, Converted.getFlatArgumentList(),
1103 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001104 SourceRange(TemplateLoc, RAngleLoc));
1105
Anders Carlsson0233eb62009-06-05 04:47:51 +00001106 TemplateArgumentList TemplateArgs(Context, Converted,
1107 /*CopyArgs=*/false,
1108 /*FlattenArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001109 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001110 NTTP->getLocation(),
1111 NTTP->getDeclName());
1112 // If that worked, check the non-type template parameter type
1113 // for validity.
1114 if (!NTTPType.isNull())
1115 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1116 NTTP->getLocation());
1117
1118 if (NTTPType.isNull()) {
1119 Invalid = true;
1120 break;
1121 }
1122 }
1123
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001124 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001125 case TemplateArgument::Null:
1126 assert(false && "Should never see a NULL template argument here");
1127 break;
1128
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001129 case TemplateArgument::Expression: {
1130 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001131 TemplateArgument Result;
1132 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001133 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001134 else
1135 Converted.push_back(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001136 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001137 }
1138
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001139 case TemplateArgument::Declaration:
1140 case TemplateArgument::Integral:
1141 // We've already checked this template argument, so just copy
1142 // it to the list of converted arguments.
1143 Converted.push_back(Arg);
1144 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001145
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001146 case TemplateArgument::Type:
1147 // We have a non-type template parameter but the template
1148 // argument is a type.
1149
1150 // C++ [temp.arg]p2:
1151 // In a template-argument, an ambiguity between a type-id and
1152 // an expression is resolved to a type-id, regardless of the
1153 // form of the corresponding template-parameter.
1154 //
1155 // We warn specifically about this case, since it can be rather
1156 // confusing for users.
1157 if (Arg.getAsType()->isFunctionType())
1158 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1159 << Arg.getAsType();
1160 else
1161 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1162 Diag((*Param)->getLocation(), diag::note_template_param_here);
1163 Invalid = true;
1164 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001165 } else {
1166 // Check template template parameters.
1167 TemplateTemplateParmDecl *TempParm
1168 = cast<TemplateTemplateParmDecl>(*Param);
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 *ArgExpr = Arg.getAsExpr();
1177 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1178 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1179 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1180 Invalid = true;
1181
1182 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001183 Decl *D
1184 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
1185 Converted.push_back(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001186 continue;
1187 }
1188 }
1189 // fall through
1190
1191 case TemplateArgument::Type: {
1192 // We have a template template parameter but the template
1193 // argument does not refer to a template.
1194 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1195 Invalid = true;
1196 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001197 }
1198
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001199 case TemplateArgument::Declaration:
1200 // We've already checked this template argument, so just copy
1201 // it to the list of converted arguments.
1202 Converted.push_back(Arg);
1203 break;
1204
1205 case TemplateArgument::Integral:
1206 assert(false && "Integral argument with template template parameter");
1207 break;
1208 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001209 }
1210 }
1211
1212 return Invalid;
1213}
1214
1215/// \brief Check a template argument against its corresponding
1216/// template type parameter.
1217///
1218/// This routine implements the semantics of C++ [temp.arg.type]. It
1219/// returns true if an error occurred, and false otherwise.
1220bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1221 QualType Arg, SourceLocation ArgLoc) {
1222 // C++ [temp.arg.type]p2:
1223 // A local type, a type with no linkage, an unnamed type or a type
1224 // compounded from any of these types shall not be used as a
1225 // template-argument for a template type-parameter.
1226 //
1227 // FIXME: Perform the recursive and no-linkage type checks.
1228 const TagType *Tag = 0;
1229 if (const EnumType *EnumT = Arg->getAsEnumType())
1230 Tag = EnumT;
1231 else if (const RecordType *RecordT = Arg->getAsRecordType())
1232 Tag = RecordT;
1233 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1234 return Diag(ArgLoc, diag::err_template_arg_local_type)
1235 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001236 else if (Tag && !Tag->getDecl()->getDeclName() &&
1237 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001238 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1239 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1240 return true;
1241 }
1242
1243 return false;
1244}
1245
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001246/// \brief Checks whether the given template argument is the address
1247/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001248bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1249 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001250 bool Invalid = false;
1251
1252 // See through any implicit casts we added to fix the type.
1253 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1254 Arg = Cast->getSubExpr();
1255
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001256 // C++0x allows nullptr, and there's no further checking to be done for that.
1257 if (Arg->getType()->isNullPtrType())
1258 return false;
1259
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001260 // C++ [temp.arg.nontype]p1:
1261 //
1262 // A template-argument for a non-type, non-template
1263 // template-parameter shall be one of: [...]
1264 //
1265 // -- the address of an object or function with external
1266 // linkage, including function templates and function
1267 // template-ids but excluding non-static class members,
1268 // expressed as & id-expression where the & is optional if
1269 // the name refers to a function or array, or if the
1270 // corresponding template-parameter is a reference; or
1271 DeclRefExpr *DRE = 0;
1272
1273 // Ignore (and complain about) any excess parentheses.
1274 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1275 if (!Invalid) {
1276 Diag(Arg->getSourceRange().getBegin(),
1277 diag::err_template_arg_extra_parens)
1278 << Arg->getSourceRange();
1279 Invalid = true;
1280 }
1281
1282 Arg = Parens->getSubExpr();
1283 }
1284
1285 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1286 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1287 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1288 } else
1289 DRE = dyn_cast<DeclRefExpr>(Arg);
1290
1291 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1292 return Diag(Arg->getSourceRange().getBegin(),
1293 diag::err_template_arg_not_object_or_func_form)
1294 << Arg->getSourceRange();
1295
1296 // Cannot refer to non-static data members
1297 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1298 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1299 << Field << Arg->getSourceRange();
1300
1301 // Cannot refer to non-static member functions
1302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1303 if (!Method->isStatic())
1304 return Diag(Arg->getSourceRange().getBegin(),
1305 diag::err_template_arg_method)
1306 << Method << Arg->getSourceRange();
1307
1308 // Functions must have external linkage.
1309 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1310 if (Func->getStorageClass() == FunctionDecl::Static) {
1311 Diag(Arg->getSourceRange().getBegin(),
1312 diag::err_template_arg_function_not_extern)
1313 << Func << Arg->getSourceRange();
1314 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1315 << true;
1316 return true;
1317 }
1318
1319 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001320 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001321 return Invalid;
1322 }
1323
1324 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1325 if (!Var->hasGlobalStorage()) {
1326 Diag(Arg->getSourceRange().getBegin(),
1327 diag::err_template_arg_object_not_extern)
1328 << Var << Arg->getSourceRange();
1329 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1330 << true;
1331 return true;
1332 }
1333
1334 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001335 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001336 return Invalid;
1337 }
1338
1339 // We found something else, but we don't know specifically what it is.
1340 Diag(Arg->getSourceRange().getBegin(),
1341 diag::err_template_arg_not_object_or_func)
1342 << Arg->getSourceRange();
1343 Diag(DRE->getDecl()->getLocation(),
1344 diag::note_template_arg_refers_here);
1345 return true;
1346}
1347
1348/// \brief Checks whether the given template argument is a pointer to
1349/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001350bool
1351Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001352 bool Invalid = false;
1353
1354 // See through any implicit casts we added to fix the type.
1355 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1356 Arg = Cast->getSubExpr();
1357
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001358 // C++0x allows nullptr, and there's no further checking to be done for that.
1359 if (Arg->getType()->isNullPtrType())
1360 return false;
1361
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001362 // C++ [temp.arg.nontype]p1:
1363 //
1364 // A template-argument for a non-type, non-template
1365 // template-parameter shall be one of: [...]
1366 //
1367 // -- a pointer to member expressed as described in 5.3.1.
1368 QualifiedDeclRefExpr *DRE = 0;
1369
1370 // Ignore (and complain about) any excess parentheses.
1371 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1372 if (!Invalid) {
1373 Diag(Arg->getSourceRange().getBegin(),
1374 diag::err_template_arg_extra_parens)
1375 << Arg->getSourceRange();
1376 Invalid = true;
1377 }
1378
1379 Arg = Parens->getSubExpr();
1380 }
1381
1382 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1383 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1384 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1385
1386 if (!DRE)
1387 return Diag(Arg->getSourceRange().getBegin(),
1388 diag::err_template_arg_not_pointer_to_member_form)
1389 << Arg->getSourceRange();
1390
1391 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1392 assert((isa<FieldDecl>(DRE->getDecl()) ||
1393 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1394 "Only non-static member pointers can make it here");
1395
1396 // Okay: this is the address of a non-static member, and therefore
1397 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001398 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001399 return Invalid;
1400 }
1401
1402 // We found something else, but we don't know specifically what it is.
1403 Diag(Arg->getSourceRange().getBegin(),
1404 diag::err_template_arg_not_pointer_to_member_form)
1405 << Arg->getSourceRange();
1406 Diag(DRE->getDecl()->getLocation(),
1407 diag::note_template_arg_refers_here);
1408 return true;
1409}
1410
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001411/// \brief Check a template argument against its corresponding
1412/// non-type template parameter.
1413///
Douglas Gregored3a3982009-03-03 04:44:36 +00001414/// This routine implements the semantics of C++ [temp.arg.nontype].
1415/// It returns true if an error occurred, and false otherwise. \p
1416/// InstantiatedParamType is the type of the non-type template
1417/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001418///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001419/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001420bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001421 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001422 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001423 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1424
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001425 // If either the parameter has a dependent type or the argument is
1426 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001427 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001428 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1429 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001430 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001431 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001432 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001433
1434 // C++ [temp.arg.nontype]p5:
1435 // The following conversions are performed on each expression used
1436 // as a non-type template-argument. If a non-type
1437 // template-argument cannot be converted to the type of the
1438 // corresponding template-parameter then the program is
1439 // ill-formed.
1440 //
1441 // -- for a non-type template-parameter of integral or
1442 // enumeration type, integral promotions (4.5) and integral
1443 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001444 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001445 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001446 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001447 // C++ [temp.arg.nontype]p1:
1448 // A template-argument for a non-type, non-template
1449 // template-parameter shall be one of:
1450 //
1451 // -- an integral constant-expression of integral or enumeration
1452 // type; or
1453 // -- the name of a non-type template-parameter; or
1454 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001455 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001456 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1457 Diag(Arg->getSourceRange().getBegin(),
1458 diag::err_template_arg_not_integral_or_enumeral)
1459 << ArgType << Arg->getSourceRange();
1460 Diag(Param->getLocation(), diag::note_template_param_here);
1461 return true;
1462 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001463 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001464 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1465 << ArgType << Arg->getSourceRange();
1466 return true;
1467 }
1468
1469 // FIXME: We need some way to more easily get the unqualified form
1470 // of the types without going all the way to the
1471 // canonical type.
1472 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1473 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1474 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1475 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1476
1477 // Try to convert the argument to the parameter's type.
1478 if (ParamType == ArgType) {
1479 // Okay: no conversion necessary
1480 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1481 !ParamType->isEnumeralType()) {
1482 // This is an integral promotion or conversion.
1483 ImpCastExprToType(Arg, ParamType);
1484 } else {
1485 // We can't perform this conversion.
1486 Diag(Arg->getSourceRange().getBegin(),
1487 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001488 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001489 Diag(Param->getLocation(), diag::note_template_param_here);
1490 return true;
1491 }
1492
Douglas Gregorafc86942009-03-14 00:20:21 +00001493 QualType IntegerType = Context.getCanonicalType(ParamType);
1494 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001495 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001496
1497 if (!Arg->isValueDependent()) {
1498 // Check that an unsigned parameter does not receive a negative
1499 // value.
1500 if (IntegerType->isUnsignedIntegerType()
1501 && (Value.isSigned() && Value.isNegative())) {
1502 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1503 << Value.toString(10) << Param->getType()
1504 << Arg->getSourceRange();
1505 Diag(Param->getLocation(), diag::note_template_param_here);
1506 return true;
1507 }
1508
1509 // Check that we don't overflow the template parameter type.
1510 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1511 if (Value.getActiveBits() > AllowedBits) {
1512 Diag(Arg->getSourceRange().getBegin(),
1513 diag::err_template_arg_too_large)
1514 << Value.toString(10) << Param->getType()
1515 << Arg->getSourceRange();
1516 Diag(Param->getLocation(), diag::note_template_param_here);
1517 return true;
1518 }
1519
1520 if (Value.getBitWidth() != AllowedBits)
1521 Value.extOrTrunc(AllowedBits);
1522 Value.setIsSigned(IntegerType->isSignedIntegerType());
1523 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001524
Douglas Gregor8f378a92009-06-11 18:10:32 +00001525 // Add the value of this argument to the list of converted
1526 // arguments. We use the bitwidth and signedness of the template
1527 // parameter.
1528 if (Arg->isValueDependent()) {
1529 // The argument is value-dependent. Create a new
1530 // TemplateArgument with the converted expression.
1531 Converted = TemplateArgument(Arg);
1532 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001533 }
1534
Douglas Gregor8f378a92009-06-11 18:10:32 +00001535 Converted = TemplateArgument(StartLoc, Value,
1536 ParamType->isEnumeralType() ? ParamType
1537 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001538 return false;
1539 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001540
Douglas Gregor3f411962009-02-11 01:18:59 +00001541 // Handle pointer-to-function, reference-to-function, and
1542 // pointer-to-member-function all in (roughly) the same way.
1543 if (// -- For a non-type template-parameter of type pointer to
1544 // function, only the function-to-pointer conversion (4.3) is
1545 // applied. If the template-argument represents a set of
1546 // overloaded functions (or a pointer to such), the matching
1547 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001548 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001549 (ParamType->isPointerType() &&
1550 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1551 // -- For a non-type template-parameter of type reference to
1552 // function, no conversions apply. If the template-argument
1553 // represents a set of overloaded functions, the matching
1554 // function is selected from the set (13.4).
1555 (ParamType->isReferenceType() &&
1556 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1557 // -- For a non-type template-parameter of type pointer to
1558 // member function, no conversions apply. If the
1559 // template-argument represents a set of overloaded member
1560 // functions, the matching member function is selected from
1561 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001562 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001563 (ParamType->isMemberPointerType() &&
1564 ParamType->getAsMemberPointerType()->getPointeeType()
1565 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001566 if (Context.hasSameUnqualifiedType(ArgType,
1567 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001568 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001569 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1570 ParamType->isMemberPointerType())) {
1571 ArgType = ParamType;
1572 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001573 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001574 ArgType = Context.getPointerType(ArgType);
1575 ImpCastExprToType(Arg, ArgType);
1576 } else if (FunctionDecl *Fn
1577 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001578 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1579 return true;
1580
Douglas Gregor2eedd992009-02-11 00:19:33 +00001581 FixOverloadedFunctionReference(Arg, Fn);
1582 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001583 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001584 ArgType = Context.getPointerType(Arg->getType());
1585 ImpCastExprToType(Arg, ArgType);
1586 }
1587 }
1588
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001589 if (!Context.hasSameUnqualifiedType(ArgType,
1590 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001591 // We can't perform this conversion.
1592 Diag(Arg->getSourceRange().getBegin(),
1593 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001594 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001595 Diag(Param->getLocation(), diag::note_template_param_here);
1596 return true;
1597 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001598
Douglas Gregorad964b32009-02-17 01:05:43 +00001599 if (ParamType->isMemberPointerType()) {
1600 NamedDecl *Member = 0;
1601 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1602 return true;
1603
Douglas Gregor8f378a92009-06-11 18:10:32 +00001604 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1605 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001606 return false;
1607 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001608
Douglas Gregorad964b32009-02-17 01:05:43 +00001609 NamedDecl *Entity = 0;
1610 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1611 return true;
1612
Douglas Gregor8f378a92009-06-11 18:10:32 +00001613 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1614 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001615 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001616 }
1617
Chris Lattner320dff22009-02-20 21:37:53 +00001618 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001619 // -- for a non-type template-parameter of type pointer to
1620 // object, qualification conversions (4.4) and the
1621 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001622 // C++0x also allows a value of std::nullptr_t.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001623 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001624 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001625
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001626 if (ArgType->isNullPtrType()) {
1627 ArgType = ParamType;
1628 ImpCastExprToType(Arg, ParamType);
1629 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001630 ArgType = Context.getArrayDecayedType(ArgType);
1631 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001632 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001633
Douglas Gregor3f411962009-02-11 01:18:59 +00001634 if (IsQualificationConversion(ArgType, ParamType)) {
1635 ArgType = ParamType;
1636 ImpCastExprToType(Arg, ParamType);
1637 }
1638
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001639 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001640 // We can't perform this conversion.
1641 Diag(Arg->getSourceRange().getBegin(),
1642 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001643 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001644 Diag(Param->getLocation(), diag::note_template_param_here);
1645 return true;
1646 }
1647
Douglas Gregorad964b32009-02-17 01:05:43 +00001648 NamedDecl *Entity = 0;
1649 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1650 return true;
1651
Douglas Gregor8f378a92009-06-11 18:10:32 +00001652 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1653 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001654 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001655 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001656
1657 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1658 // -- For a non-type template-parameter of type reference to
1659 // object, no conversions apply. The type referred to by the
1660 // reference may be more cv-qualified than the (otherwise
1661 // identical) type of the template-argument. The
1662 // template-parameter is bound directly to the
1663 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001664 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001665 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001666
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001667 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001668 Diag(Arg->getSourceRange().getBegin(),
1669 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001670 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001671 << Arg->getSourceRange();
1672 Diag(Param->getLocation(), diag::note_template_param_here);
1673 return true;
1674 }
1675
1676 unsigned ParamQuals
1677 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1678 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1679
1680 if ((ParamQuals | ArgQuals) != ParamQuals) {
1681 Diag(Arg->getSourceRange().getBegin(),
1682 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001683 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001684 << Arg->getSourceRange();
1685 Diag(Param->getLocation(), diag::note_template_param_here);
1686 return true;
1687 }
1688
Douglas Gregorad964b32009-02-17 01:05:43 +00001689 NamedDecl *Entity = 0;
1690 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1691 return true;
1692
Douglas Gregor8f378a92009-06-11 18:10:32 +00001693 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1694 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001695 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001696 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001697
1698 // -- For a non-type template-parameter of type pointer to data
1699 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001700 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001701 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1702
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001703 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001704 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001705 } else if (ArgType->isNullPtrType()) {
1706 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001707 } else if (IsQualificationConversion(ArgType, ParamType)) {
1708 ImpCastExprToType(Arg, ParamType);
1709 } else {
1710 // We can't perform this conversion.
1711 Diag(Arg->getSourceRange().getBegin(),
1712 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001713 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001714 Diag(Param->getLocation(), diag::note_template_param_here);
1715 return true;
1716 }
1717
Douglas Gregorad964b32009-02-17 01:05:43 +00001718 NamedDecl *Member = 0;
1719 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1720 return true;
1721
Douglas Gregor8f378a92009-06-11 18:10:32 +00001722 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1723 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001724 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001725}
1726
1727/// \brief Check a template argument against its corresponding
1728/// template template parameter.
1729///
1730/// This routine implements the semantics of C++ [temp.arg.template].
1731/// It returns true if an error occurred, and false otherwise.
1732bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1733 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001734 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1735 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1736
1737 // C++ [temp.arg.template]p1:
1738 // A template-argument for a template template-parameter shall be
1739 // the name of a class template, expressed as id-expression. Only
1740 // primary class templates are considered when matching the
1741 // template template argument with the corresponding parameter;
1742 // partial specializations are not considered even if their
1743 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001744 //
1745 // Note that we also allow template template parameters here, which
1746 // will happen when we are dealing with, e.g., class template
1747 // partial specializations.
1748 if (!isa<ClassTemplateDecl>(Template) &&
1749 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001750 assert(isa<FunctionTemplateDecl>(Template) &&
1751 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001752 Diag(Arg->getSourceRange().getBegin(),
1753 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001754 << Template;
1755 }
1756
1757 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1758 Param->getTemplateParameters(),
1759 true, true,
1760 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001761}
1762
Douglas Gregord406b032009-02-06 22:42:48 +00001763/// \brief Determine whether the given template parameter lists are
1764/// equivalent.
1765///
1766/// \param New The new template parameter list, typically written in the
1767/// source code as part of a new template declaration.
1768///
1769/// \param Old The old template parameter list, typically found via
1770/// name lookup of the template declared with this template parameter
1771/// list.
1772///
1773/// \param Complain If true, this routine will produce a diagnostic if
1774/// the template parameter lists are not equivalent.
1775///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001776/// \param IsTemplateTemplateParm If true, this routine is being
1777/// called to compare the template parameter lists of a template
1778/// template parameter.
1779///
1780/// \param TemplateArgLoc If this source location is valid, then we
1781/// are actually checking the template parameter list of a template
1782/// argument (New) against the template parameter list of its
1783/// corresponding template template parameter (Old). We produce
1784/// slightly different diagnostics in this scenario.
1785///
Douglas Gregord406b032009-02-06 22:42:48 +00001786/// \returns True if the template parameter lists are equal, false
1787/// otherwise.
1788bool
1789Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1790 TemplateParameterList *Old,
1791 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001792 bool IsTemplateTemplateParm,
1793 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001794 if (Old->size() != New->size()) {
1795 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001796 unsigned NextDiag = diag::err_template_param_list_different_arity;
1797 if (TemplateArgLoc.isValid()) {
1798 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1799 NextDiag = diag::note_template_param_list_different_arity;
1800 }
1801 Diag(New->getTemplateLoc(), NextDiag)
1802 << (New->size() > Old->size())
1803 << IsTemplateTemplateParm
1804 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001805 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1806 << IsTemplateTemplateParm
1807 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1808 }
1809
1810 return false;
1811 }
1812
1813 for (TemplateParameterList::iterator OldParm = Old->begin(),
1814 OldParmEnd = Old->end(), NewParm = New->begin();
1815 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1816 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001817 unsigned NextDiag = diag::err_template_param_different_kind;
1818 if (TemplateArgLoc.isValid()) {
1819 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1820 NextDiag = diag::note_template_param_different_kind;
1821 }
1822 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001823 << IsTemplateTemplateParm;
1824 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1825 << IsTemplateTemplateParm;
1826 return false;
1827 }
1828
1829 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1830 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001831 // know we're at the same index).
1832#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00001833 // FIXME: Enable this code in debug mode *after* we properly go through
1834 // and "instantiate" the template parameter lists of template template
1835 // parameters. It's only after this instantiation that (1) any dependent
1836 // types within the template parameter list of the template template
1837 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00001838 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001839 QualType OldParmType
1840 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1841 QualType NewParmType
1842 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1843 assert(Context.getCanonicalType(OldParmType) ==
1844 Context.getCanonicalType(NewParmType) &&
1845 "type parameter mismatch?");
1846#endif
1847 } else if (NonTypeTemplateParmDecl *OldNTTP
1848 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1849 // The types of non-type template parameters must agree.
1850 NonTypeTemplateParmDecl *NewNTTP
1851 = cast<NonTypeTemplateParmDecl>(*NewParm);
1852 if (Context.getCanonicalType(OldNTTP->getType()) !=
1853 Context.getCanonicalType(NewNTTP->getType())) {
1854 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001855 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1856 if (TemplateArgLoc.isValid()) {
1857 Diag(TemplateArgLoc,
1858 diag::err_template_arg_template_params_mismatch);
1859 NextDiag = diag::note_template_nontype_parm_different_type;
1860 }
1861 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001862 << NewNTTP->getType()
1863 << IsTemplateTemplateParm;
1864 Diag(OldNTTP->getLocation(),
1865 diag::note_template_nontype_parm_prev_declaration)
1866 << OldNTTP->getType();
1867 }
1868 return false;
1869 }
1870 } else {
1871 // The template parameter lists of template template
1872 // parameters must agree.
1873 // FIXME: Could we perform a faster "type" comparison here?
1874 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1875 "Only template template parameters handled here");
1876 TemplateTemplateParmDecl *OldTTP
1877 = cast<TemplateTemplateParmDecl>(*OldParm);
1878 TemplateTemplateParmDecl *NewTTP
1879 = cast<TemplateTemplateParmDecl>(*NewParm);
1880 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1881 OldTTP->getTemplateParameters(),
1882 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001883 /*IsTemplateTemplateParm=*/true,
1884 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001885 return false;
1886 }
1887 }
1888
1889 return true;
1890}
1891
1892/// \brief Check whether a template can be declared within this scope.
1893///
1894/// If the template declaration is valid in this scope, returns
1895/// false. Otherwise, issues a diagnostic and returns true.
1896bool
1897Sema::CheckTemplateDeclScope(Scope *S,
1898 MultiTemplateParamsArg &TemplateParameterLists) {
1899 assert(TemplateParameterLists.size() > 0 && "Not a template");
1900
1901 // Find the nearest enclosing declaration scope.
1902 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1903 (S->getFlags() & Scope::TemplateParamScope) != 0)
1904 S = S->getParent();
1905
1906 TemplateParameterList *TemplateParams =
1907 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1908 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1909 SourceRange TemplateRange
1910 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1911
1912 // C++ [temp]p2:
1913 // A template-declaration can appear only as a namespace scope or
1914 // class scope declaration.
1915 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1916 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1917 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1918 return Diag(TemplateLoc, diag::err_template_linkage)
1919 << TemplateRange;
1920
1921 Ctx = Ctx->getParent();
1922 }
1923
1924 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1925 return false;
1926
1927 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1928 << TemplateRange;
1929}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001930
Douglas Gregor90177912009-05-13 18:28:20 +00001931/// \brief Check whether a class template specialization or explicit
1932/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001933///
Douglas Gregor90177912009-05-13 18:28:20 +00001934/// This routine determines whether a class template specialization or
1935/// explicit instantiation can be declared in the current context
1936/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1937/// appropriate diagnostics if there was an error. It returns true if
1938// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00001939bool
1940Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1941 ClassTemplateSpecializationDecl *PrevDecl,
1942 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00001943 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00001944 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00001945 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001946 // C++ [temp.expl.spec]p2:
1947 // An explicit specialization shall be declared in the namespace
1948 // of which the template is a member, or, for member templates, in
1949 // the namespace of which the enclosing class or enclosing class
1950 // template is a member. An explicit specialization of a member
1951 // function, member class or static data member of a class
1952 // template shall be declared in the namespace of which the class
1953 // template is a member. Such a declaration may also be a
1954 // definition. If the declaration is not a definition, the
1955 // specialization may be defined later in the name- space in which
1956 // the explicit specialization was declared, or in a namespace
1957 // that encloses the one in which the explicit specialization was
1958 // declared.
1959 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00001960 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001961 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001962 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001963 return true;
1964 }
1965
1966 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1967 DeclContext *TemplateContext
1968 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00001969 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
1970 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001971 // There is no prior declaration of this entity, so this
1972 // specialization must be in the same context as the template
1973 // itself.
1974 if (DC != TemplateContext) {
1975 if (isa<TranslationUnitDecl>(TemplateContext))
1976 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001977 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00001978 << ClassTemplate << ScopeSpecifierRange;
1979 else if (isa<NamespaceDecl>(TemplateContext))
1980 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00001981 << PartialSpecialization << ClassTemplate
1982 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001983
1984 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1985 }
1986
1987 return false;
1988 }
1989
1990 // We have a previous declaration of this entity. Make sure that
1991 // this redeclaration (or definition) occurs in an enclosing namespace.
1992 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001993 // FIXME: In C++98, we would like to turn these errors into warnings,
1994 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00001995 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00001996 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00001997 if (isa<TranslationUnitDecl>(TemplateContext)) {
1998 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
1999 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002000 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002001 else
2002 SuppressedDiag = true;
2003 } else if (isa<NamespaceDecl>(TemplateContext)) {
2004 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2005 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002006 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002007 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2008 else
2009 SuppressedDiag = true;
2010 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002011
Douglas Gregor90177912009-05-13 18:28:20 +00002012 if (!SuppressedDiag)
2013 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002014 }
2015
2016 return false;
2017}
2018
Douglas Gregor76e79952009-06-12 21:21:02 +00002019/// \brief Check the non-type template arguments of a class template
2020/// partial specialization according to C++ [temp.class.spec]p9.
2021///
Douglas Gregor42476442009-06-12 22:08:06 +00002022/// \param TemplateParams the template parameters of the primary class
2023/// template.
2024///
2025/// \param TemplateArg the template arguments of the class template
2026/// partial specialization.
2027///
2028/// \param MirrorsPrimaryTemplate will be set true if the class
2029/// template partial specialization arguments are identical to the
2030/// implicit template arguments of the primary template. This is not
2031/// necessarily an error (C++0x), and it is left to the caller to diagnose
2032/// this condition when it is an error.
2033///
Douglas Gregor76e79952009-06-12 21:21:02 +00002034/// \returns true if there was an error, false otherwise.
2035bool Sema::CheckClassTemplatePartialSpecializationArgs(
2036 TemplateParameterList *TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002037 const TemplateArgument *TemplateArgs,
2038 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002039 // FIXME: the interface to this function will have to change to
2040 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002041 MirrorsPrimaryTemplate = true;
Douglas Gregor76e79952009-06-12 21:21:02 +00002042 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002043 // Determine whether the template argument list of the partial
2044 // specialization is identical to the implicit argument list of
2045 // the primary template. The caller may need to diagnostic this as
2046 // an error per C++ [temp.class.spec]p9b3.
2047 if (MirrorsPrimaryTemplate) {
2048 if (TemplateTypeParmDecl *TTP
2049 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2050 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
2051 Context.getCanonicalType(TemplateArgs[I].getAsType()))
2052 MirrorsPrimaryTemplate = false;
2053 } else if (TemplateTemplateParmDecl *TTP
2054 = dyn_cast<TemplateTemplateParmDecl>(
2055 TemplateParams->getParam(I))) {
2056 // FIXME: We should settle on either Declaration storage or
2057 // Expression storage for template template parameters.
2058 TemplateTemplateParmDecl *ArgDecl
2059 = dyn_cast_or_null<TemplateTemplateParmDecl>(
2060 TemplateArgs[I].getAsDecl());
2061 if (!ArgDecl)
2062 if (DeclRefExpr *DRE
2063 = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
2064 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2065
2066 if (!ArgDecl ||
2067 ArgDecl->getIndex() != TTP->getIndex() ||
2068 ArgDecl->getDepth() != TTP->getDepth())
2069 MirrorsPrimaryTemplate = false;
2070 }
2071 }
2072
Douglas Gregor76e79952009-06-12 21:21:02 +00002073 NonTypeTemplateParmDecl *Param
2074 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002075 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002076 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002077 }
2078
Douglas Gregor76e79952009-06-12 21:21:02 +00002079 Expr *ArgExpr = TemplateArgs[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002080 if (!ArgExpr) {
2081 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002082 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002083 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002084
2085 // C++ [temp.class.spec]p8:
2086 // A non-type argument is non-specialized if it is the name of a
2087 // non-type parameter. All other non-type arguments are
2088 // specialized.
2089 //
2090 // Below, we check the two conditions that only apply to
2091 // specialized non-type arguments, so skip any non-specialized
2092 // arguments.
2093 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002094 if (NonTypeTemplateParmDecl *NTTP
2095 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2096 if (MirrorsPrimaryTemplate &&
2097 (Param->getIndex() != NTTP->getIndex() ||
2098 Param->getDepth() != NTTP->getDepth()))
2099 MirrorsPrimaryTemplate = false;
2100
Douglas Gregor76e79952009-06-12 21:21:02 +00002101 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002102 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002103
2104 // C++ [temp.class.spec]p9:
2105 // Within the argument list of a class template partial
2106 // specialization, the following restrictions apply:
2107 // -- A partially specialized non-type argument expression
2108 // shall not involve a template parameter of the partial
2109 // specialization except when the argument expression is a
2110 // simple identifier.
2111 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2112 Diag(ArgExpr->getLocStart(),
2113 diag::err_dependent_non_type_arg_in_partial_spec)
2114 << ArgExpr->getSourceRange();
2115 return true;
2116 }
2117
2118 // -- The type of a template parameter corresponding to a
2119 // specialized non-type argument shall not be dependent on a
2120 // parameter of the specialization.
2121 if (Param->getType()->isDependentType()) {
2122 Diag(ArgExpr->getLocStart(),
2123 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2124 << Param->getType()
2125 << ArgExpr->getSourceRange();
2126 Diag(Param->getLocation(), diag::note_template_param_here);
2127 return true;
2128 }
Douglas Gregor42476442009-06-12 22:08:06 +00002129
2130 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002131 }
2132
2133 return false;
2134}
2135
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002136Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00002137Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2138 SourceLocation KWLoc,
2139 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002140 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002141 SourceLocation TemplateNameLoc,
2142 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002143 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002144 SourceLocation *TemplateArgLocs,
2145 SourceLocation RAngleLoc,
2146 AttributeList *Attr,
2147 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002148 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002149 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002150 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002151 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002152
Douglas Gregor58944ac2009-05-31 09:31:02 +00002153 bool isPartialSpecialization = false;
2154
Douglas Gregor0d93f692009-02-25 22:02:03 +00002155 // Check the validity of the template headers that introduce this
2156 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002157 // FIXME: Once we have member templates, we'll need to check
2158 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2159 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002160 if (TemplateParameterLists.size() == 0)
2161 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002162 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002163 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002164 TemplateParameterList *TemplateParams
2165 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002166 if (TemplateParameterLists.size() > 1) {
2167 Diag(TemplateParams->getTemplateLoc(),
2168 diag::err_template_spec_extra_headers);
2169 return true;
2170 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002171
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002172 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002173 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002174
2175 // C++ [temp.class.spec]p10:
2176 // The template parameter list of a specialization shall not
2177 // contain default template argument values.
2178 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2179 Decl *Param = TemplateParams->getParam(I);
2180 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2181 if (TTP->hasDefaultArgument()) {
2182 Diag(TTP->getDefaultArgumentLoc(),
2183 diag::err_default_arg_in_partial_spec);
2184 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2185 }
2186 } else if (NonTypeTemplateParmDecl *NTTP
2187 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2188 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2189 Diag(NTTP->getDefaultArgumentLoc(),
2190 diag::err_default_arg_in_partial_spec)
2191 << DefArg->getSourceRange();
2192 NTTP->setDefaultArgument(0);
2193 DefArg->Destroy(Context);
2194 }
2195 } else {
2196 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2197 if (Expr *DefArg = TTP->getDefaultArgument()) {
2198 Diag(TTP->getDefaultArgumentLoc(),
2199 diag::err_default_arg_in_partial_spec)
2200 << DefArg->getSourceRange();
2201 TTP->setDefaultArgument(0);
2202 DefArg->Destroy(Context);
2203 }
2204 }
2205 }
2206 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002207 }
2208
Douglas Gregora08b6c72009-02-17 23:15:12 +00002209 // Check that the specialization uses the same tag kind as the
2210 // original template.
2211 TagDecl::TagKind Kind;
2212 switch (TagSpec) {
2213 default: assert(0 && "Unknown tag type!");
2214 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2215 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2216 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2217 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002218 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2219 Kind, KWLoc,
2220 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002221 Diag(KWLoc, diag::err_use_with_wrong_tag)
2222 << ClassTemplate
2223 << CodeModificationHint::CreateReplacement(KWLoc,
2224 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002225 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2226 diag::note_previous_use);
2227 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2228 }
2229
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002230 // Translate the parser's template argument list in our AST format.
2231 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2232 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2233
Douglas Gregora08b6c72009-02-17 23:15:12 +00002234 // Check that the template argument list is well-formed for this
2235 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002236 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002237 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002238 &TemplateArgs[0], TemplateArgs.size(),
2239 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002240 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002241
2242 assert((ConvertedTemplateArgs.size() ==
2243 ClassTemplate->getTemplateParameters()->size()) &&
2244 "Converted template argument list is too short!");
2245
Douglas Gregor58944ac2009-05-31 09:31:02 +00002246 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002247 // corresponds to these arguments.
2248 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002249 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002250 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002251 if (CheckClassTemplatePartialSpecializationArgs(
2252 ClassTemplate->getTemplateParameters(),
Douglas Gregor42476442009-06-12 22:08:06 +00002253 ConvertedTemplateArgs.getFlatArgumentList(),
2254 MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002255 return true;
2256
Douglas Gregor42476442009-06-12 22:08:06 +00002257 if (MirrorsPrimaryTemplate) {
2258 // C++ [temp.class.spec]p9b3:
2259 //
2260 // -- The argument list of the specialization shall not be identical
2261 // to the implicit argument list of the primary template.
2262 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2263 << (TK == TK_Definition)
2264 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2265 RAngleLoc));
2266 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2267 ClassTemplate->getIdentifier(),
2268 TemplateNameLoc,
2269 Attr,
2270 move(TemplateParameterLists),
2271 AS_none);
2272 }
2273
Douglas Gregor58944ac2009-05-31 09:31:02 +00002274 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002275 ClassTemplatePartialSpecializationDecl::Profile(ID,
2276 ConvertedTemplateArgs.getFlatArgumentList(),
2277 ConvertedTemplateArgs.flatSize());
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002278 }
Douglas Gregor58944ac2009-05-31 09:31:02 +00002279 else
Anders Carlssona35faf92009-06-05 03:43:12 +00002280 ClassTemplateSpecializationDecl::Profile(ID,
2281 ConvertedTemplateArgs.getFlatArgumentList(),
2282 ConvertedTemplateArgs.flatSize());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002283 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002284 ClassTemplateSpecializationDecl *PrevDecl = 0;
2285
2286 if (isPartialSpecialization)
2287 PrevDecl
2288 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2289 InsertPos);
2290 else
2291 PrevDecl
2292 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002293
2294 ClassTemplateSpecializationDecl *Specialization = 0;
2295
Douglas Gregor0d93f692009-02-25 22:02:03 +00002296 // Check whether we can declare a class template specialization in
2297 // the current scope.
2298 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2299 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002300 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002301 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002302 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002303 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002304
Douglas Gregora08b6c72009-02-17 23:15:12 +00002305 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2306 // Since the only prior class template specialization with these
2307 // arguments was referenced but not declared, reuse that
2308 // declaration node as our own, updating its source location to
2309 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002310 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002311 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002312 PrevDecl = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002313 } else if (isPartialSpecialization) {
2314 // FIXME: extra checking for partial specializations
2315
2316 // Create a new class template partial specialization declaration node.
2317 TemplateParameterList *TemplateParams
2318 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2319 ClassTemplatePartialSpecializationDecl *PrevPartial
2320 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2321 ClassTemplatePartialSpecializationDecl *Partial
2322 = ClassTemplatePartialSpecializationDecl::Create(Context,
2323 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002324 TemplateNameLoc,
2325 TemplateParams,
2326 ClassTemplate,
2327 ConvertedTemplateArgs,
2328 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002329
2330 if (PrevPartial) {
2331 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2332 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2333 } else {
2334 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2335 }
2336 Specialization = Partial;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002337 } else {
2338 // Create a new class template specialization declaration node for
2339 // this explicit specialization.
2340 Specialization
2341 = ClassTemplateSpecializationDecl::Create(Context,
2342 ClassTemplate->getDeclContext(),
2343 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002344 ClassTemplate,
2345 ConvertedTemplateArgs,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002346 PrevDecl);
2347
2348 if (PrevDecl) {
2349 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2350 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2351 } else {
2352 ClassTemplate->getSpecializations().InsertNode(Specialization,
2353 InsertPos);
2354 }
2355 }
2356
2357 // Note that this is an explicit specialization.
2358 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2359
2360 // Check that this isn't a redefinition of this specialization.
2361 if (TK == TK_Definition) {
2362 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002363 // FIXME: Should also handle explicit specialization after implicit
2364 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002365 SourceRange Range(TemplateNameLoc, RAngleLoc);
2366 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002367 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002368 Diag(Def->getLocation(), diag::note_previous_definition);
2369 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002370 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002371 }
2372 }
2373
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002374 // Build the fully-sugared type for this class template
2375 // specialization as the user wrote in the specialization
2376 // itself. This means that we'll pretty-print the type retrieved
2377 // from the specialization's declaration the way that the user
2378 // actually wrote the specialization, rather than formatting the
2379 // name based on the "canonical" representation used to store the
2380 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002381 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002382 = Context.getTemplateSpecializationType(Name,
2383 &TemplateArgs[0],
2384 TemplateArgs.size(),
Douglas Gregor8c795a12009-03-19 00:39:20 +00002385 Context.getTypeDeclType(Specialization));
Douglas Gregordd13e842009-03-30 22:58:21 +00002386 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002387 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002388
Douglas Gregor50113ca2009-02-25 22:18:32 +00002389 // C++ [temp.expl.spec]p9:
2390 // A template explicit specialization is in the scope of the
2391 // namespace in which the template was defined.
2392 //
2393 // We actually implement this paragraph where we set the semantic
2394 // context (in the creation of the ClassTemplateSpecializationDecl),
2395 // but we also maintain the lexical context where the actual
2396 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002397 Specialization->setLexicalDeclContext(CurContext);
2398
2399 // We may be starting the definition of this specialization.
2400 if (TK == TK_Definition)
2401 Specialization->startDefinition();
2402
2403 // Add the specialization into its lexical context, so that it can
2404 // be seen when iterating through the list of declarations in that
2405 // context. However, specializations are not found by name lookup.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002406 CurContext->addDecl(Context, Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002407 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002408}
Douglas Gregord3022602009-03-27 23:10:48 +00002409
Douglas Gregor96b6df92009-05-14 00:28:11 +00002410// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002411Sema::DeclResult
2412Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2413 unsigned TagSpec,
2414 SourceLocation KWLoc,
2415 const CXXScopeSpec &SS,
2416 TemplateTy TemplateD,
2417 SourceLocation TemplateNameLoc,
2418 SourceLocation LAngleLoc,
2419 ASTTemplateArgsPtr TemplateArgsIn,
2420 SourceLocation *TemplateArgLocs,
2421 SourceLocation RAngleLoc,
2422 AttributeList *Attr) {
2423 // Find the class template we're specializing
2424 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2425 ClassTemplateDecl *ClassTemplate
2426 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2427
2428 // Check that the specialization uses the same tag kind as the
2429 // original template.
2430 TagDecl::TagKind Kind;
2431 switch (TagSpec) {
2432 default: assert(0 && "Unknown tag type!");
2433 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2434 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2435 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2436 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002437 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2438 Kind, KWLoc,
2439 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002440 Diag(KWLoc, diag::err_use_with_wrong_tag)
2441 << ClassTemplate
2442 << CodeModificationHint::CreateReplacement(KWLoc,
2443 ClassTemplate->getTemplatedDecl()->getKindName());
2444 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2445 diag::note_previous_use);
2446 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2447 }
2448
Douglas Gregor90177912009-05-13 18:28:20 +00002449 // C++0x [temp.explicit]p2:
2450 // [...] An explicit instantiation shall appear in an enclosing
2451 // namespace of its template. [...]
2452 //
2453 // This is C++ DR 275.
2454 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2455 TemplateNameLoc,
2456 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002457 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002458 /*ExplicitInstantiation=*/true))
2459 return true;
2460
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002461 // Translate the parser's template argument list in our AST format.
2462 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2463 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2464
2465 // Check that the template argument list is well-formed for this
2466 // template.
Anders Carlsson558a3a32009-06-05 05:31:27 +00002467 TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002468 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002469 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002470 RAngleLoc, ConvertedTemplateArgs))
2471 return true;
2472
2473 assert((ConvertedTemplateArgs.size() ==
2474 ClassTemplate->getTemplateParameters()->size()) &&
2475 "Converted template argument list is too short!");
2476
2477 // Find the class template specialization declaration that
2478 // corresponds to these arguments.
2479 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002480 ClassTemplateSpecializationDecl::Profile(ID,
2481 ConvertedTemplateArgs.getFlatArgumentList(),
2482 ConvertedTemplateArgs.flatSize());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002483 void *InsertPos = 0;
2484 ClassTemplateSpecializationDecl *PrevDecl
2485 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2486
2487 ClassTemplateSpecializationDecl *Specialization = 0;
2488
Douglas Gregor90177912009-05-13 18:28:20 +00002489 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002490 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002491 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002492 // This particular specialization has already been declared or
2493 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002494 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2495 << Context.getTypeDeclType(PrevDecl);
2496 Diag(PrevDecl->getLocation(),
2497 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002498 return DeclPtrTy::make(PrevDecl);
2499 }
2500
Douglas Gregor90177912009-05-13 18:28:20 +00002501 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002502 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002503 // For a given set of template parameters, if an explicit
2504 // instantiation of a template appears after a declaration of
2505 // an explicit specialization for that template, the explicit
2506 // instantiation has no effect.
2507 if (!getLangOptions().CPlusPlus0x) {
2508 Diag(TemplateNameLoc,
2509 diag::ext_explicit_instantiation_after_specialization)
2510 << Context.getTypeDeclType(PrevDecl);
2511 Diag(PrevDecl->getLocation(),
2512 diag::note_previous_template_specialization);
2513 }
2514
2515 // Create a new class template specialization declaration node
2516 // for this explicit specialization. This node is only used to
2517 // record the existence of this explicit instantiation for
2518 // accurate reproduction of the source code; we don't actually
2519 // use it for anything, since it is semantically irrelevant.
2520 Specialization
2521 = ClassTemplateSpecializationDecl::Create(Context,
2522 ClassTemplate->getDeclContext(),
2523 TemplateNameLoc,
2524 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002525 ConvertedTemplateArgs, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002526 Specialization->setLexicalDeclContext(CurContext);
2527 CurContext->addDecl(Context, Specialization);
2528 return DeclPtrTy::make(Specialization);
2529 }
2530
2531 // If we have already (implicitly) instantiated this
2532 // specialization, there is less work to do.
2533 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2534 SpecializationRequiresInstantiation = false;
2535
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002536 // Since the only prior class template specialization with these
2537 // arguments was referenced but not declared, reuse that
2538 // declaration node as our own, updating its source location to
2539 // reflect our new declaration.
2540 Specialization = PrevDecl;
2541 Specialization->setLocation(TemplateNameLoc);
2542 PrevDecl = 0;
2543 } else {
2544 // Create a new class template specialization declaration node for
2545 // this explicit specialization.
2546 Specialization
2547 = ClassTemplateSpecializationDecl::Create(Context,
2548 ClassTemplate->getDeclContext(),
2549 TemplateNameLoc,
2550 ClassTemplate,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002551 ConvertedTemplateArgs, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002552
2553 ClassTemplate->getSpecializations().InsertNode(Specialization,
2554 InsertPos);
2555 }
2556
2557 // Build the fully-sugared type for this explicit instantiation as
2558 // the user wrote in the explicit instantiation itself. This means
2559 // that we'll pretty-print the type retrieved from the
2560 // specialization's declaration the way that the user actually wrote
2561 // the explicit instantiation, rather than formatting the name based
2562 // on the "canonical" representation used to store the template
2563 // arguments in the specialization.
2564 QualType WrittenTy
2565 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002566 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002567 TemplateArgs.size(),
2568 Context.getTypeDeclType(Specialization));
2569 Specialization->setTypeAsWritten(WrittenTy);
2570 TemplateArgsIn.release();
2571
2572 // Add the explicit instantiation into its lexical context. However,
2573 // since explicit instantiations are never found by name lookup, we
2574 // just put it into the declaration context directly.
2575 Specialization->setLexicalDeclContext(CurContext);
2576 CurContext->addDecl(Context, Specialization);
2577
2578 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002579 // A definition of a class template or class member template
2580 // shall be in scope at the point of the explicit instantiation of
2581 // the class template or class member template.
2582 //
2583 // This check comes when we actually try to perform the
2584 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002585 if (SpecializationRequiresInstantiation)
2586 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002587 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002588 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002589
2590 return DeclPtrTy::make(Specialization);
2591}
2592
Douglas Gregor96b6df92009-05-14 00:28:11 +00002593// Explicit instantiation of a member class of a class template.
2594Sema::DeclResult
2595Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2596 unsigned TagSpec,
2597 SourceLocation KWLoc,
2598 const CXXScopeSpec &SS,
2599 IdentifierInfo *Name,
2600 SourceLocation NameLoc,
2601 AttributeList *Attr) {
2602
Douglas Gregor71f06032009-05-28 23:31:59 +00002603 bool Owned = false;
Douglas Gregor96b6df92009-05-14 00:28:11 +00002604 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor71f06032009-05-28 23:31:59 +00002605 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002606 if (!TagD)
2607 return true;
2608
2609 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2610 if (Tag->isEnum()) {
2611 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2612 << Context.getTypeDeclType(Tag);
2613 return true;
2614 }
2615
Douglas Gregord769bfa2009-05-27 17:30:49 +00002616 if (Tag->isInvalidDecl())
2617 return true;
2618
Douglas Gregor96b6df92009-05-14 00:28:11 +00002619 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2620 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2621 if (!Pattern) {
2622 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2623 << Context.getTypeDeclType(Record);
2624 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2625 return true;
2626 }
2627
2628 // C++0x [temp.explicit]p2:
2629 // [...] An explicit instantiation shall appear in an enclosing
2630 // namespace of its template. [...]
2631 //
2632 // This is C++ DR 275.
2633 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002634 // FIXME: In C++98, we would like to turn these errors into warnings,
2635 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002636 DeclContext *PatternContext
2637 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2638 if (!CurContext->Encloses(PatternContext)) {
2639 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2640 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2641 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2642 }
2643 }
2644
Douglas Gregor96b6df92009-05-14 00:28:11 +00002645 if (!Record->getDefinition(Context)) {
2646 // If the class has a definition, instantiate it (and all of its
2647 // members, recursively).
2648 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2649 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002650 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002651 /*ExplicitInstantiation=*/true))
2652 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002653 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002654 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002655 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002656
Mike Stumpe127ae32009-05-16 07:39:55 +00002657 // FIXME: We don't have any representation for explicit instantiations of
2658 // member classes. Such a representation is not needed for compilation, but it
2659 // should be available for clients that want to see all of the declarations in
2660 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002661 return TagD;
2662}
2663
Douglas Gregord3022602009-03-27 23:10:48 +00002664Sema::TypeResult
2665Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2666 const IdentifierInfo &II, SourceLocation IdLoc) {
2667 NestedNameSpecifier *NNS
2668 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2669 if (!NNS)
2670 return true;
2671
2672 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002673 if (T.isNull())
2674 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002675 return T.getAsOpaquePtr();
2676}
2677
Douglas Gregor77da5802009-04-01 00:28:59 +00002678Sema::TypeResult
2679Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2680 SourceLocation TemplateLoc, TypeTy *Ty) {
2681 QualType T = QualType::getFromOpaquePtr(Ty);
2682 NestedNameSpecifier *NNS
2683 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2684 const TemplateSpecializationType *TemplateId
2685 = T->getAsTemplateSpecializationType();
2686 assert(TemplateId && "Expected a template specialization type");
2687
2688 if (NNS->isDependent())
2689 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2690
2691 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2692}
2693
Douglas Gregord3022602009-03-27 23:10:48 +00002694/// \brief Build the type that describes a C++ typename specifier,
2695/// e.g., "typename T::type".
2696QualType
2697Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2698 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002699 CXXRecordDecl *CurrentInstantiation = 0;
2700 if (NNS->isDependent()) {
2701 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002702
Douglas Gregor3eb20702009-05-11 19:58:34 +00002703 // If the nested-name-specifier does not refer to the current
2704 // instantiation, then build a typename type.
2705 if (!CurrentInstantiation)
2706 return Context.getTypenameType(NNS, &II);
2707 }
Douglas Gregord3022602009-03-27 23:10:48 +00002708
Douglas Gregor3eb20702009-05-11 19:58:34 +00002709 DeclContext *Ctx = 0;
2710
2711 if (CurrentInstantiation)
2712 Ctx = CurrentInstantiation;
2713 else {
2714 CXXScopeSpec SS;
2715 SS.setScopeRep(NNS);
2716 SS.setRange(Range);
2717 if (RequireCompleteDeclContext(SS))
2718 return QualType();
2719
2720 Ctx = computeDeclContext(SS);
2721 }
Douglas Gregord3022602009-03-27 23:10:48 +00002722 assert(Ctx && "No declaration context?");
2723
2724 DeclarationName Name(&II);
2725 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2726 false);
2727 unsigned DiagID = 0;
2728 Decl *Referenced = 0;
2729 switch (Result.getKind()) {
2730 case LookupResult::NotFound:
2731 if (Ctx->isTranslationUnit())
2732 DiagID = diag::err_typename_nested_not_found_global;
2733 else
2734 DiagID = diag::err_typename_nested_not_found;
2735 break;
2736
2737 case LookupResult::Found:
2738 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2739 // We found a type. Build a QualifiedNameType, since the
2740 // typename-specifier was just sugar. FIXME: Tell
2741 // QualifiedNameType that it has a "typename" prefix.
2742 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2743 }
2744
2745 DiagID = diag::err_typename_nested_not_type;
2746 Referenced = Result.getAsDecl();
2747 break;
2748
2749 case LookupResult::FoundOverloaded:
2750 DiagID = diag::err_typename_nested_not_type;
2751 Referenced = *Result.begin();
2752 break;
2753
2754 case LookupResult::AmbiguousBaseSubobjectTypes:
2755 case LookupResult::AmbiguousBaseSubobjects:
2756 case LookupResult::AmbiguousReference:
2757 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2758 return QualType();
2759 }
2760
2761 // If we get here, it's because name lookup did not find a
2762 // type. Emit an appropriate diagnostic and return an error.
2763 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2764 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2765 else
2766 Diag(Range.getEnd(), DiagID) << Range << Name;
2767 if (Referenced)
2768 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2769 << Name;
2770 return QualType();
2771}