blob: 0300093fa4a8a42b3bcc870a4a40693db1a1ee1c [file] [log] [blame]
Douglas Gregor72c3f312008-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 Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-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 Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-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()) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +000059 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregorf511e472009-07-29 16:56:42 +000068 } else if (OverloadedFunctionDecl *Ovl
69 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000070 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
71 FEnd = Ovl->function_end();
72 F != FEnd; ++F) {
Douglas Gregorf511e472009-07-29 16:56:42 +000073 if (FunctionTemplateDecl *FuncTmpl
74 = dyn_cast<FunctionTemplateDecl>(*F)) {
75 // We've found a function template. Determine whether there are
76 // any other function templates we need to bundle together in an
77 // OverloadedFunctionDecl
78 for (++F; F != FEnd; ++F) {
79 if (isa<FunctionTemplateDecl>(*F))
80 break;
81 }
82
83 if (F != FEnd) {
84 // Build an overloaded function decl containing only the
85 // function templates in Ovl.
86 OverloadedFunctionDecl *OvlTemplate
87 = OverloadedFunctionDecl::Create(Context,
88 Ovl->getDeclContext(),
89 Ovl->getDeclName());
90 OvlTemplate->addOverload(FuncTmpl);
91 OvlTemplate->addOverload(*F);
92 for (++F; F != FEnd; ++F) {
93 if (isa<FunctionTemplateDecl>(*F))
94 OvlTemplate->addOverload(*F);
95 }
96
97 // FIXME: HACK! We need TemplateName to be able to refer to
98 // sets of overloaded function templates.
99 TemplateResult = TemplateTy::make(OvlTemplate);
100 return TNK_Function_template;
101 }
102
103 TNK = TNK_Function_template;
104 Template = FuncTmpl;
105 break;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000106 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000107 }
108 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000109
110 if (TNK != TNK_Non_template) {
111 if (SS && SS->isSet() && !SS->isInvalid()) {
112 NestedNameSpecifier *Qualifier
113 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
114 TemplateResult
115 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
116 false,
117 Template));
118 } else
119 TemplateResult = TemplateTy::make(TemplateName(Template));
120 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000121 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000122 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000123}
124
Douglas Gregor72c3f312008-12-05 18:15:24 +0000125/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
126/// that the template parameter 'PrevDecl' is being shadowed by a new
127/// declaration at location Loc. Returns true to indicate that this is
128/// an error, and false otherwise.
129bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000130 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000131
132 // Microsoft Visual C++ permits template parameters to be shadowed.
133 if (getLangOptions().Microsoft)
134 return false;
135
136 // C++ [temp.local]p4:
137 // A template-parameter shall not be redeclared within its
138 // scope (including nested scopes).
139 Diag(Loc, diag::err_template_param_shadow)
140 << cast<NamedDecl>(PrevDecl)->getDeclName();
141 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
142 return true;
143}
144
Douglas Gregor2943aed2009-03-03 04:44:36 +0000145/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000146/// the parameter D to reference the templated declaration and return a pointer
147/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000148TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
149 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
150 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000151 return Temp;
152 }
153 return 0;
154}
155
Douglas Gregor72c3f312008-12-05 18:15:24 +0000156/// ActOnTypeParameter - Called when a C++ template type parameter
157/// (e.g., "typename T") has been parsed. Typename specifies whether
158/// the keyword "typename" was used to declare the type parameter
159/// (otherwise, "class" was used), and KeyLoc is the location of the
160/// "class" or "typename" keyword. ParamName is the name of the
161/// parameter (NULL indicates an unnamed template parameter) and
162/// ParamName is the location of the parameter name (if any).
163/// If the type parameter has a default argument, it will be added
164/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000165Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
166 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000167 SourceLocation KeyLoc,
168 IdentifierInfo *ParamName,
169 SourceLocation ParamNameLoc,
170 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000171 assert(S->isTemplateParamScope() &&
172 "Template type parameter not in template parameter scope!");
173 bool Invalid = false;
174
175 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000176 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000177 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000178 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
179 PrevDecl);
180 }
181
Douglas Gregorddc29e12009-02-06 22:42:48 +0000182 SourceLocation Loc = ParamNameLoc;
183 if (!ParamName)
184 Loc = KeyLoc;
185
Douglas Gregor72c3f312008-12-05 18:15:24 +0000186 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000187 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000188 Depth, Position, ParamName, Typename,
189 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000190 if (Invalid)
191 Param->setInvalidDecl();
192
193 if (ParamName) {
194 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000195 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000196 IdResolver.AddDecl(Param);
197 }
198
Chris Lattnerb28317a2009-03-28 19:18:32 +0000199 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000200}
201
Douglas Gregord684b002009-02-10 19:49:53 +0000202/// ActOnTypeParameterDefault - Adds a default argument (the type
203/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000204void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000205 SourceLocation EqualLoc,
206 SourceLocation DefaultLoc,
207 TypeTy *DefaultT) {
208 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000209 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000210 QualType Default = QualType::getFromOpaquePtr(DefaultT);
211
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000212 // C++0x [temp.param]p9:
213 // A default template-argument may be specified for any kind of
214 // template-parameter that is not a template parameter pack.
215 if (Parm->isParameterPack()) {
216 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000217 return;
218 }
219
Douglas Gregord684b002009-02-10 19:49:53 +0000220 // C++ [temp.param]p14:
221 // A template-parameter shall not be used in its own default argument.
222 // FIXME: Implement this check! Needs a recursive walk over the types.
223
224 // Check the template argument itself.
225 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
226 Parm->setInvalidDecl();
227 return;
228 }
229
230 Parm->setDefaultArgument(Default, DefaultLoc, false);
231}
232
Douglas Gregor2943aed2009-03-03 04:44:36 +0000233/// \brief Check that the type of a non-type template parameter is
234/// well-formed.
235///
236/// \returns the (possibly-promoted) parameter type if valid;
237/// otherwise, produces a diagnostic and returns a NULL type.
238QualType
239Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
240 // C++ [temp.param]p4:
241 //
242 // A non-type template-parameter shall have one of the following
243 // (optionally cv-qualified) types:
244 //
245 // -- integral or enumeration type,
246 if (T->isIntegralType() || T->isEnumeralType() ||
247 // -- pointer to object or pointer to function,
248 (T->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +0000249 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
250 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregor2943aed2009-03-03 04:44:36 +0000251 // -- reference to object or reference to function,
252 T->isReferenceType() ||
253 // -- pointer to member.
254 T->isMemberPointerType() ||
255 // If T is a dependent type, we can't do the check now, so we
256 // assume that it is well-formed.
257 T->isDependentType())
258 return T;
259 // C++ [temp.param]p8:
260 //
261 // A non-type template-parameter of type "array of T" or
262 // "function returning T" is adjusted to be of type "pointer to
263 // T" or "pointer to function returning T", respectively.
264 else if (T->isArrayType())
265 // FIXME: Keep the type prior to promotion?
266 return Context.getArrayDecayedType(T);
267 else if (T->isFunctionType())
268 // FIXME: Keep the type prior to promotion?
269 return Context.getPointerType(T);
270
271 Diag(Loc, diag::err_template_nontype_parm_bad_type)
272 << T;
273
274 return QualType();
275}
276
Douglas Gregor72c3f312008-12-05 18:15:24 +0000277/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
278/// template parameter (e.g., "int Size" in "template<int Size>
279/// class Array") has been parsed. S is the current scope and D is
280/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000281Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
282 unsigned Depth,
283 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000284 QualType T = GetTypeForDeclarator(D, S);
285
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000286 assert(S->isTemplateParamScope() &&
287 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000288 bool Invalid = false;
289
290 IdentifierInfo *ParamName = D.getIdentifier();
291 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000292 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000293 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000294 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000295 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000296 }
297
Douglas Gregor2943aed2009-03-03 04:44:36 +0000298 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000299 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000300 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000301 Invalid = true;
302 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000303
Douglas Gregor72c3f312008-12-05 18:15:24 +0000304 NonTypeTemplateParmDecl *Param
305 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000306 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000307 if (Invalid)
308 Param->setInvalidDecl();
309
310 if (D.getIdentifier()) {
311 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000312 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000313 IdResolver.AddDecl(Param);
314 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000315 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000316}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000317
Douglas Gregord684b002009-02-10 19:49:53 +0000318/// \brief Adds a default argument to the given non-type template
319/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000320void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000321 SourceLocation EqualLoc,
322 ExprArg DefaultE) {
323 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000324 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000325 Expr *Default = static_cast<Expr *>(DefaultE.get());
326
327 // C++ [temp.param]p14:
328 // A template-parameter shall not be used in its own default argument.
329 // FIXME: Implement this check! Needs a recursive walk over the types.
330
331 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000332 TemplateArgument Converted;
333 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
334 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000335 TemplateParm->setInvalidDecl();
336 return;
337 }
338
Anders Carlssone9146f22009-05-01 19:49:17 +0000339 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000340}
341
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000342
343/// ActOnTemplateTemplateParameter - Called when a C++ template template
344/// parameter (e.g. T in template <template <typename> class T> class array)
345/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000346Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
347 SourceLocation TmpLoc,
348 TemplateParamsTy *Params,
349 IdentifierInfo *Name,
350 SourceLocation NameLoc,
351 unsigned Depth,
352 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000353{
354 assert(S->isTemplateParamScope() &&
355 "Template template parameter not in template parameter scope!");
356
357 // Construct the parameter object.
358 TemplateTemplateParmDecl *Param =
359 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
360 Position, Name,
361 (TemplateParameterList*)Params);
362
363 // Make sure the parameter is valid.
364 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
365 // do anything yet. However, if the template parameter list or (eventual)
366 // default value is ever invalidated, that will propagate here.
367 bool Invalid = false;
368 if (Invalid) {
369 Param->setInvalidDecl();
370 }
371
372 // If the tt-param has a name, then link the identifier into the scope
373 // and lookup mechanisms.
374 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000375 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000376 IdResolver.AddDecl(Param);
377 }
378
Chris Lattnerb28317a2009-03-28 19:18:32 +0000379 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000380}
381
Douglas Gregord684b002009-02-10 19:49:53 +0000382/// \brief Adds a default argument to the given template template
383/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000384void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000385 SourceLocation EqualLoc,
386 ExprArg DefaultE) {
387 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000388 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000389
390 // Since a template-template parameter's default argument is an
391 // id-expression, it must be a DeclRefExpr.
392 DeclRefExpr *Default
393 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
394
395 // C++ [temp.param]p14:
396 // A template-parameter shall not be used in its own default argument.
397 // FIXME: Implement this check! Needs a recursive walk over the types.
398
399 // Check the well-formedness of the template argument.
400 if (!isa<TemplateDecl>(Default->getDecl())) {
401 Diag(Default->getSourceRange().getBegin(),
402 diag::err_template_arg_must_be_template)
403 << Default->getSourceRange();
404 TemplateParm->setInvalidDecl();
405 return;
406 }
407 if (CheckTemplateArgument(TemplateParm, Default)) {
408 TemplateParm->setInvalidDecl();
409 return;
410 }
411
412 DefaultE.release();
413 TemplateParm->setDefaultArgument(Default);
414}
415
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000416/// ActOnTemplateParameterList - Builds a TemplateParameterList that
417/// contains the template parameters in Params/NumParams.
418Sema::TemplateParamsTy *
419Sema::ActOnTemplateParameterList(unsigned Depth,
420 SourceLocation ExportLoc,
421 SourceLocation TemplateLoc,
422 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000423 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000424 SourceLocation RAngleLoc) {
425 if (ExportLoc.isValid())
426 Diag(ExportLoc, diag::note_template_export_unsupported);
427
Douglas Gregorddc29e12009-02-06 22:42:48 +0000428 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
429 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000430}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000431
Douglas Gregor212e81c2009-03-25 00:13:59 +0000432Sema::DeclResult
Douglas Gregorbd1099e2009-07-23 16:36:45 +0000433Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000434 SourceLocation KWLoc, const CXXScopeSpec &SS,
435 IdentifierInfo *Name, SourceLocation NameLoc,
436 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000437 MultiTemplateParamsArg TemplateParameterLists,
438 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000439 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
440 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000441 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000442
443 // Check that we can declare a template here.
444 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000445 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000446
447 TagDecl::TagKind Kind;
448 switch (TagSpec) {
449 default: assert(0 && "Unknown tag type!");
450 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
451 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
452 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
453 }
454
455 // There is no such thing as an unnamed class template.
456 if (!Name) {
457 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000458 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000459 }
460
461 // Find any previous declaration with this name.
462 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
463 true);
464 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
465 NamedDecl *PrevDecl = 0;
466 if (Previous.begin() != Previous.end())
467 PrevDecl = *Previous.begin();
468
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000469 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
470 PrevDecl = 0;
471
Douglas Gregorddc29e12009-02-06 22:42:48 +0000472 DeclContext *SemanticContext = CurContext;
473 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000474 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000475
Mike Stump390b4cc2009-05-16 07:39:55 +0000476 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000477 }
478
479 // FIXME: member templates!
480 TemplateParameterList *TemplateParams
481 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
482
483 // If there is a previous declaration with the same name, check
484 // whether this is a valid redeclaration.
485 ClassTemplateDecl *PrevClassTemplate
486 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
487 if (PrevClassTemplate) {
488 // Ensure that the template parameter lists are compatible.
489 if (!TemplateParameterListsAreEqual(TemplateParams,
490 PrevClassTemplate->getTemplateParameters(),
491 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000492 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000493
494 // C++ [temp.class]p4:
495 // In a redeclaration, partial specialization, explicit
496 // specialization or explicit instantiation of a class template,
497 // the class-key shall agree in kind with the original class
498 // template declaration (7.1.5.3).
499 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000500 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000501 Diag(KWLoc, diag::err_use_with_wrong_tag)
502 << Name
503 << CodeModificationHint::CreateReplacement(KWLoc,
504 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000505 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000506 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000507 }
508
Douglas Gregorddc29e12009-02-06 22:42:48 +0000509 // Check for redefinition of this class template.
510 if (TK == TK_Definition) {
511 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
512 Diag(NameLoc, diag::err_redefinition) << Name;
513 Diag(Def->getLocation(), diag::note_previous_definition);
514 // FIXME: Would it make sense to try to "forget" the previous
515 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000516 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000517 }
518 }
519 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
520 // Maybe we will complain about the shadowed template parameter.
521 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
522 // Just pretend that we didn't see the previous declaration.
523 PrevDecl = 0;
524 } else if (PrevDecl) {
525 // C++ [temp]p5:
526 // A class template shall not have the same name as any other
527 // template, class, function, object, enumeration, enumerator,
528 // namespace, or type in the same scope (3.3), except as specified
529 // in (14.5.4).
530 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
531 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000532 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000533 }
534
Douglas Gregord684b002009-02-10 19:49:53 +0000535 // Check the template parameter list of this declaration, possibly
536 // merging in the template parameter list from the previous class
537 // template declaration.
538 if (CheckTemplateParameterList(TemplateParams,
539 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
540 Invalid = true;
541
Douglas Gregor7da97d02009-05-10 22:57:19 +0000542 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000543 // declaration!
544
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000545 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000546 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000547 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000548 PrevClassTemplate->getTemplatedDecl() : 0,
549 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000550
551 ClassTemplateDecl *NewTemplate
552 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
553 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000554 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000555 NewClass->setDescribedClassTemplate(NewTemplate);
556
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000557 // Build the type for the class template declaration now.
558 QualType T =
559 Context.getTypeDeclType(NewClass,
560 PrevClassTemplate?
561 PrevClassTemplate->getTemplatedDecl() : 0);
562 assert(T->isDependentType() && "Class template type is not dependent?");
563 (void)T;
564
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000565 // Set the access specifier.
566 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
567
Douglas Gregorddc29e12009-02-06 22:42:48 +0000568 // Set the lexical context of these templates
569 NewClass->setLexicalDeclContext(CurContext);
570 NewTemplate->setLexicalDeclContext(CurContext);
571
572 if (TK == TK_Definition)
573 NewClass->startDefinition();
574
575 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000576 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000577
578 PushOnScopeChains(NewTemplate, S);
579
Douglas Gregord684b002009-02-10 19:49:53 +0000580 if (Invalid) {
581 NewTemplate->setInvalidDecl();
582 NewClass->setInvalidDecl();
583 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000584 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000585}
586
Douglas Gregord684b002009-02-10 19:49:53 +0000587/// \brief Checks the validity of a template parameter list, possibly
588/// considering the template parameter list from a previous
589/// declaration.
590///
591/// If an "old" template parameter list is provided, it must be
592/// equivalent (per TemplateParameterListsAreEqual) to the "new"
593/// template parameter list.
594///
595/// \param NewParams Template parameter list for a new template
596/// declaration. This template parameter list will be updated with any
597/// default arguments that are carried through from the previous
598/// template parameter list.
599///
600/// \param OldParams If provided, template parameter list from a
601/// previous declaration of the same template. Default template
602/// arguments will be merged from the old template parameter list to
603/// the new template parameter list.
604///
605/// \returns true if an error occurred, false otherwise.
606bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
607 TemplateParameterList *OldParams) {
608 bool Invalid = false;
609
610 // C++ [temp.param]p10:
611 // The set of default template-arguments available for use with a
612 // template declaration or definition is obtained by merging the
613 // default arguments from the definition (if in scope) and all
614 // declarations in scope in the same way default function
615 // arguments are (8.3.6).
616 bool SawDefaultArgument = false;
617 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000618
Anders Carlsson49d25572009-06-12 23:20:15 +0000619 bool SawParameterPack = false;
620 SourceLocation ParameterPackLoc;
621
Mike Stump1a35fde2009-02-11 23:03:27 +0000622 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000623 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000624 if (OldParams)
625 OldParam = OldParams->begin();
626
627 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
628 NewParamEnd = NewParams->end();
629 NewParam != NewParamEnd; ++NewParam) {
630 // Variables used to diagnose redundant default arguments
631 bool RedundantDefaultArg = false;
632 SourceLocation OldDefaultLoc;
633 SourceLocation NewDefaultLoc;
634
635 // Variables used to diagnose missing default arguments
636 bool MissingDefaultArg = false;
637
Anders Carlsson49d25572009-06-12 23:20:15 +0000638 // C++0x [temp.param]p11:
639 // If a template parameter of a class template is a template parameter pack,
640 // it must be the last template parameter.
641 if (SawParameterPack) {
642 Diag(ParameterPackLoc,
643 diag::err_template_param_pack_must_be_last_template_parameter);
644 Invalid = true;
645 }
646
Douglas Gregord684b002009-02-10 19:49:53 +0000647 // Merge default arguments for template type parameters.
648 if (TemplateTypeParmDecl *NewTypeParm
649 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
650 TemplateTypeParmDecl *OldTypeParm
651 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
652
Anders Carlsson49d25572009-06-12 23:20:15 +0000653 if (NewTypeParm->isParameterPack()) {
654 assert(!NewTypeParm->hasDefaultArgument() &&
655 "Parameter packs can't have a default argument!");
656 SawParameterPack = true;
657 ParameterPackLoc = NewTypeParm->getLocation();
658 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000659 NewTypeParm->hasDefaultArgument()) {
660 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
661 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
662 SawDefaultArgument = true;
663 RedundantDefaultArg = true;
664 PreviousDefaultArgLoc = NewDefaultLoc;
665 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
666 // Merge the default argument from the old declaration to the
667 // new declaration.
668 SawDefaultArgument = true;
669 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
670 OldTypeParm->getDefaultArgumentLoc(),
671 true);
672 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
673 } else if (NewTypeParm->hasDefaultArgument()) {
674 SawDefaultArgument = true;
675 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
676 } else if (SawDefaultArgument)
677 MissingDefaultArg = true;
678 }
679 // Merge default arguments for non-type template parameters
680 else if (NonTypeTemplateParmDecl *NewNonTypeParm
681 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
682 NonTypeTemplateParmDecl *OldNonTypeParm
683 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
684 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
685 NewNonTypeParm->hasDefaultArgument()) {
686 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
687 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
688 SawDefaultArgument = true;
689 RedundantDefaultArg = true;
690 PreviousDefaultArgLoc = NewDefaultLoc;
691 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
692 // Merge the default argument from the old declaration to the
693 // new declaration.
694 SawDefaultArgument = true;
695 // FIXME: We need to create a new kind of "default argument"
696 // expression that points to a previous template template
697 // parameter.
698 NewNonTypeParm->setDefaultArgument(
699 OldNonTypeParm->getDefaultArgument());
700 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
701 } else if (NewNonTypeParm->hasDefaultArgument()) {
702 SawDefaultArgument = true;
703 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
704 } else if (SawDefaultArgument)
705 MissingDefaultArg = true;
706 }
707 // Merge default arguments for template template parameters
708 else {
709 TemplateTemplateParmDecl *NewTemplateParm
710 = cast<TemplateTemplateParmDecl>(*NewParam);
711 TemplateTemplateParmDecl *OldTemplateParm
712 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
713 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
714 NewTemplateParm->hasDefaultArgument()) {
715 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
716 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
717 SawDefaultArgument = true;
718 RedundantDefaultArg = true;
719 PreviousDefaultArgLoc = NewDefaultLoc;
720 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
721 // Merge the default argument from the old declaration to the
722 // new declaration.
723 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000724 // FIXME: We need to create a new kind of "default argument" expression
725 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000726 NewTemplateParm->setDefaultArgument(
727 OldTemplateParm->getDefaultArgument());
728 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
729 } else if (NewTemplateParm->hasDefaultArgument()) {
730 SawDefaultArgument = true;
731 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
732 } else if (SawDefaultArgument)
733 MissingDefaultArg = true;
734 }
735
736 if (RedundantDefaultArg) {
737 // C++ [temp.param]p12:
738 // A template-parameter shall not be given default arguments
739 // by two different declarations in the same scope.
740 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
741 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
742 Invalid = true;
743 } else if (MissingDefaultArg) {
744 // C++ [temp.param]p11:
745 // If a template-parameter has a default template-argument,
746 // all subsequent template-parameters shall have a default
747 // template-argument supplied.
748 Diag((*NewParam)->getLocation(),
749 diag::err_template_param_default_arg_missing);
750 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
751 Invalid = true;
752 }
753
754 // If we have an old template parameter list that we're merging
755 // in, move on to the next parameter.
756 if (OldParams)
757 ++OldParam;
758 }
759
760 return Invalid;
761}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000762
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000763/// \brief Match the given template parameter lists to the given scope
764/// specifier, returning the template parameter list that applies to the
765/// name.
766///
767/// \param DeclStartLoc the start of the declaration that has a scope
768/// specifier or a template parameter list.
769///
770/// \param SS the scope specifier that will be matched to the given template
771/// parameter lists. This scope specifier precedes a qualified name that is
772/// being declared.
773///
774/// \param ParamLists the template parameter lists, from the outermost to the
775/// innermost template parameter lists.
776///
777/// \param NumParamLists the number of template parameter lists in ParamLists.
778///
779/// \returns the template parameter list, if any, that corresponds to the
780/// name that is preceded by the scope specifier @p SS. This template
781/// parameter list may be have template parameters (if we're declaring a
782/// template) or may have no template parameters (if we're declaring a
783/// template specialization), or may be NULL (if we were's declaring isn't
784/// itself a template).
785TemplateParameterList *
786Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
787 const CXXScopeSpec &SS,
788 TemplateParameterList **ParamLists,
789 unsigned NumParamLists) {
790 // FIXME: This routine will need a lot more testing once we have support for
791 // member templates.
792
793 // Find the template-ids that occur within the nested-name-specifier. These
794 // template-ids will match up with the template parameter lists.
795 llvm::SmallVector<const TemplateSpecializationType *, 4>
796 TemplateIdsInSpecifier;
797 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
798 NNS; NNS = NNS->getPrefix()) {
799 if (const TemplateSpecializationType *SpecType
800 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
801 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
802 if (!Template)
803 continue; // FIXME: should this be an error? probably...
804
805 if (const RecordType *Record = SpecType->getAsRecordType()) {
806 ClassTemplateSpecializationDecl *SpecDecl
807 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
808 // If the nested name specifier refers to an explicit specialization,
809 // we don't need a template<> header.
810 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
811 continue;
812 }
813
814 TemplateIdsInSpecifier.push_back(SpecType);
815 }
816 }
817
818 // Reverse the list of template-ids in the scope specifier, so that we can
819 // more easily match up the template-ids and the template parameter lists.
820 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
821
822 SourceLocation FirstTemplateLoc = DeclStartLoc;
823 if (NumParamLists)
824 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
825
826 // Match the template-ids found in the specifier to the template parameter
827 // lists.
828 unsigned Idx = 0;
829 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
830 Idx != NumTemplateIds; ++Idx) {
831 bool DependentTemplateId = TemplateIdsInSpecifier[Idx]->isDependentType();
832 if (Idx >= NumParamLists) {
833 // We have a template-id without a corresponding template parameter
834 // list.
835 if (DependentTemplateId) {
836 // FIXME: the location information here isn't great.
837 Diag(SS.getRange().getBegin(),
838 diag::err_template_spec_needs_template_parameters)
839 << QualType(TemplateIdsInSpecifier[Idx], 0)
840 << SS.getRange();
841 } else {
842 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
843 << SS.getRange()
844 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
845 "template<> ");
846 }
847 return 0;
848 }
849
850 // Check the template parameter list against its corresponding template-id.
851 TemplateDecl *Template
852 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
853 TemplateParameterListsAreEqual(ParamLists[Idx],
854 Template->getTemplateParameters(),
855 true);
856 }
857
858 // If there were at least as many template-ids as there were template
859 // parameter lists, then there are no template parameter lists remaining for
860 // the declaration itself.
861 if (Idx >= NumParamLists)
862 return 0;
863
864 // If there were too many template parameter lists, complain about that now.
865 if (Idx != NumParamLists - 1) {
866 while (Idx < NumParamLists - 1) {
867 Diag(ParamLists[Idx]->getTemplateLoc(),
868 diag::err_template_spec_extra_headers)
869 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
870 ParamLists[Idx]->getRAngleLoc());
871 ++Idx;
872 }
873 }
874
875 // Return the last template parameter list, which corresponds to the
876 // entity being declared.
877 return ParamLists[NumParamLists - 1];
878}
879
Douglas Gregor40808ce2009-03-09 23:48:35 +0000880/// \brief Translates template arguments as provided by the parser
881/// into template arguments used by semantic analysis.
882static void
883translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
884 SourceLocation *TemplateArgLocs,
885 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
886 TemplateArgs.reserve(TemplateArgsIn.size());
887
888 void **Args = TemplateArgsIn.getArgs();
889 bool *ArgIsType = TemplateArgsIn.getArgIsType();
890 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
891 TemplateArgs.push_back(
892 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
893 QualType::getFromOpaquePtr(Args[Arg]))
894 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
895 }
896}
897
Douglas Gregor7532dc62009-03-30 22:58:21 +0000898QualType Sema::CheckTemplateIdType(TemplateName Name,
899 SourceLocation TemplateLoc,
900 SourceLocation LAngleLoc,
901 const TemplateArgument *TemplateArgs,
902 unsigned NumTemplateArgs,
903 SourceLocation RAngleLoc) {
904 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000905 if (!Template) {
906 // The template name does not resolve to a template, so we just
907 // build a dependent template-id type.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000908 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor1275ae02009-07-28 23:00:59 +0000909 NumTemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000910 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000911
Douglas Gregor40808ce2009-03-09 23:48:35 +0000912 // Check that the template argument list is well-formed for this
913 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000914 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
915 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000916 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000917 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +0000918 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000919 return QualType();
920
Anders Carlssonfb250522009-06-23 01:26:57 +0000921 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000922 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000923 "Converted template argument list is too short!");
924
925 QualType CanonType;
926
Douglas Gregor7532dc62009-03-30 22:58:21 +0000927 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000928 TemplateArgs,
929 NumTemplateArgs)) {
930 // This class template specialization is a dependent
931 // type. Therefore, its canonical type is another class template
932 // specialization type that contains all of the converted
933 // arguments in canonical form. This ensures that, e.g., A<T> and
934 // A<T, T> have identical types when A is declared as:
935 //
936 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000937 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
938 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000939 Converted.getFlatArguments(),
940 Converted.flatSize());
Douglas Gregor1275ae02009-07-28 23:00:59 +0000941
942 // FIXME: CanonType is not actually the canonical type, and unfortunately
943 // it is a TemplateTypeSpecializationType that we will never use again.
944 // In the future, we need to teach getTemplateSpecializationType to only
945 // build the canonical type and return that to us.
946 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000947 } else if (ClassTemplateDecl *ClassTemplate
948 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000949 // Find the class template specialization declaration that
950 // corresponds to these arguments.
951 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000952 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000953 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000954 Converted.flatSize(),
955 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000956 void *InsertPos = 0;
957 ClassTemplateSpecializationDecl *Decl
958 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
959 if (!Decl) {
960 // This is the first time we have referenced this class template
961 // specialization. Create the canonical declaration and add it to
962 // the set of specializations.
963 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000964 ClassTemplate->getDeclContext(),
965 TemplateLoc,
966 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000967 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000968 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
969 Decl->setLexicalDeclContext(CurContext);
970 }
971
972 CanonType = Context.getTypeDeclType(Decl);
973 }
974
975 // Build the fully-sugared type for this class template
976 // specialization, which refers back to the class template
977 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000978 return Context.getTemplateSpecializationType(Name, TemplateArgs,
979 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000980}
981
Douglas Gregorcc636682009-02-17 23:15:12 +0000982Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000983Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
984 SourceLocation LAngleLoc,
985 ASTTemplateArgsPtr TemplateArgsIn,
986 SourceLocation *TemplateArgLocs,
987 SourceLocation RAngleLoc) {
988 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000989
Douglas Gregor40808ce2009-03-09 23:48:35 +0000990 // Translate the parser's template argument list in our AST format.
991 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
992 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000993
Douglas Gregor7532dc62009-03-30 22:58:21 +0000994 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000995 TemplateArgs.data(),
996 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000997 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000998 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000999
1000 if (Result.isNull())
1001 return true;
1002
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001003 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001004}
1005
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001006Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1007 SourceLocation TemplateNameLoc,
1008 SourceLocation LAngleLoc,
1009 const TemplateArgument *TemplateArgs,
1010 unsigned NumTemplateArgs,
1011 SourceLocation RAngleLoc) {
1012 // FIXME: Can we do any checking at this point? I guess we could check the
1013 // template arguments that we have against the template name, if the template
1014 // name refers to a single template. That's not a terribly common case,
1015 // though.
1016 return Owned(TemplateIdRefExpr::Create(Context,
1017 /*FIXME: New type?*/Context.OverloadTy,
1018 /*FIXME: Necessary?*/0,
1019 /*FIXME: Necessary?*/SourceRange(),
1020 Template, TemplateNameLoc, LAngleLoc,
1021 TemplateArgs,
1022 NumTemplateArgs, RAngleLoc));
1023}
1024
1025Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1026 SourceLocation TemplateNameLoc,
1027 SourceLocation LAngleLoc,
1028 ASTTemplateArgsPtr TemplateArgsIn,
1029 SourceLocation *TemplateArgLocs,
1030 SourceLocation RAngleLoc) {
1031 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1032
1033 // Translate the parser's template argument list in our AST format.
1034 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1035 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001036 TemplateArgsIn.release();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001037
1038 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1039 TemplateArgs.data(), TemplateArgs.size(),
1040 RAngleLoc);
1041}
1042
Douglas Gregorc45c2322009-03-31 00:43:58 +00001043/// \brief Form a dependent template name.
1044///
1045/// This action forms a dependent template name given the template
1046/// name and its (presumably dependent) scope specifier. For
1047/// example, given "MetaFun::template apply", the scope specifier \p
1048/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1049/// of the "template" keyword, and "apply" is the \p Name.
1050Sema::TemplateTy
1051Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1052 const IdentifierInfo &Name,
1053 SourceLocation NameLoc,
1054 const CXXScopeSpec &SS) {
1055 if (!SS.isSet() || SS.isInvalid())
1056 return TemplateTy();
1057
1058 NestedNameSpecifier *Qualifier
1059 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1060
1061 // FIXME: member of the current instantiation
1062
1063 if (!Qualifier->isDependent()) {
1064 // C++0x [temp.names]p5:
1065 // If a name prefixed by the keyword template is not the name of
1066 // a template, the program is ill-formed. [Note: the keyword
1067 // template may not be applied to non-template members of class
1068 // templates. -end note ] [ Note: as is the case with the
1069 // typename prefix, the template prefix is allowed in cases
1070 // where it is not strictly necessary; i.e., when the
1071 // nested-name-specifier or the expression on the left of the ->
1072 // or . is not dependent on a template-parameter, or the use
1073 // does not appear in the scope of a template. -end note]
1074 //
1075 // Note: C++03 was more strict here, because it banned the use of
1076 // the "template" keyword prior to a template-name that was not a
1077 // dependent name. C++ DR468 relaxed this requirement (the
1078 // "template" keyword is now permitted). We follow the C++0x
1079 // rules, even in C++03 mode, retroactively applying the DR.
1080 TemplateTy Template;
1081 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1082 if (TNK == TNK_Non_template) {
1083 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1084 << &Name;
1085 return TemplateTy();
1086 }
1087
1088 return Template;
1089 }
1090
1091 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1092}
1093
Anders Carlsson436b1562009-06-13 00:33:33 +00001094bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1095 const TemplateArgument &Arg,
1096 TemplateArgumentListBuilder &Converted) {
1097 // Check template type parameter.
1098 if (Arg.getKind() != TemplateArgument::Type) {
1099 // C++ [temp.arg.type]p1:
1100 // A template-argument for a template-parameter which is a
1101 // type shall be a type-id.
1102
1103 // We have a template type parameter but the template argument
1104 // is not a type.
1105 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1106 Diag(Param->getLocation(), diag::note_template_param_here);
1107
1108 return true;
1109 }
1110
1111 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1112 return true;
1113
1114 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001115 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001116 TemplateArgument(Arg.getLocation(),
1117 Context.getCanonicalType(Arg.getAsType())));
1118 return false;
1119}
1120
Douglas Gregorc15cb382009-02-09 23:23:08 +00001121/// \brief Check that the given template argument list is well-formed
1122/// for specializing the given template.
1123bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1124 SourceLocation TemplateLoc,
1125 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001126 const TemplateArgument *TemplateArgs,
1127 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001128 SourceLocation RAngleLoc,
Douglas Gregor16134c62009-07-01 00:28:38 +00001129 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001130 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001131 TemplateParameterList *Params = Template->getTemplateParameters();
1132 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001133 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001134 bool Invalid = false;
1135
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001136 bool HasParameterPack =
1137 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1138
1139 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00001140 (NumArgs < Params->getMinRequiredArguments() &&
1141 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001142 // FIXME: point at either the first arg beyond what we can handle,
1143 // or the '>', depending on whether we have too many or too few
1144 // arguments.
1145 SourceRange Range;
1146 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001147 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001148 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1149 << (NumArgs > NumParams)
1150 << (isa<ClassTemplateDecl>(Template)? 0 :
1151 isa<FunctionTemplateDecl>(Template)? 1 :
1152 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1153 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001154 Diag(Template->getLocation(), diag::note_template_decl_here)
1155 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001156 Invalid = true;
1157 }
1158
1159 // C++ [temp.arg]p1:
1160 // [...] The type and form of each template-argument specified in
1161 // a template-id shall match the type and form specified for the
1162 // corresponding parameter declared by the template in its
1163 // template-parameter-list.
1164 unsigned ArgIdx = 0;
1165 for (TemplateParameterList::iterator Param = Params->begin(),
1166 ParamEnd = Params->end();
1167 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00001168 if (ArgIdx > NumArgs && PartialTemplateArgs)
1169 break;
1170
Douglas Gregorc15cb382009-02-09 23:23:08 +00001171 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001172 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001173 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001174 // Retrieve the default template argument from the template
1175 // parameter.
1176 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001177 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001178 // We have an empty argument pack.
1179 Converted.BeginPack();
1180 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001181 break;
1182 }
1183
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001184 if (!TTP->hasDefaultArgument())
1185 break;
1186
Douglas Gregor40808ce2009-03-09 23:48:35 +00001187 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001188
1189 // If the argument type is dependent, instantiate it now based
1190 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001191 if (ArgType->isDependentType()) {
1192 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001193 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001194 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001195 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001196
Anders Carlssone9c904b2009-06-05 04:47:51 +00001197 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001198 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001199 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001200 TTP->getDefaultArgumentLoc(),
1201 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001202 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001203
1204 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001205 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001206
Douglas Gregor40808ce2009-03-09 23:48:35 +00001207 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001208 } else if (NonTypeTemplateParmDecl *NTTP
1209 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1210 if (!NTTP->hasDefaultArgument())
1211 break;
1212
Anders Carlsson3b56c002009-06-11 16:06:49 +00001213 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001214 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001215 Converted.flatSize(),
1216 SourceRange(TemplateLoc, RAngleLoc));
1217
1218 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001219 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001220
1221 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1222 TemplateArgs);
1223 if (E.isInvalid())
1224 return true;
1225
1226 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001227 } else {
1228 TemplateTemplateParmDecl *TempParm
1229 = cast<TemplateTemplateParmDecl>(*Param);
1230
1231 if (!TempParm->hasDefaultArgument())
1232 break;
1233
Douglas Gregor2943aed2009-03-03 04:44:36 +00001234 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001235 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001236 }
1237 } else {
1238 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001239 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001240 }
1241
Douglas Gregorc15cb382009-02-09 23:23:08 +00001242
1243 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001244 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001245 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001246 // Check all the remaining arguments (if any).
1247 for (; ArgIdx < NumArgs; ++ArgIdx) {
1248 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1249 Invalid = true;
1250 }
1251
Anders Carlssonfb250522009-06-23 01:26:57 +00001252 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001253 } else {
1254 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1255 Invalid = true;
1256 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001257 } else if (NonTypeTemplateParmDecl *NTTP
1258 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1259 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260
1261 // Instantiate the type of the non-type template parameter with
1262 // the template arguments we've seen thus far.
1263 QualType NTTPType = NTTP->getType();
1264 if (NTTPType->isDependentType()) {
1265 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001266 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001267 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001268 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001269 SourceRange(TemplateLoc, RAngleLoc));
1270
Anders Carlssone9c904b2009-06-05 04:47:51 +00001271 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001272 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001273 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001274 NTTP->getLocation(),
1275 NTTP->getDeclName());
1276 // If that worked, check the non-type template parameter type
1277 // for validity.
1278 if (!NTTPType.isNull())
1279 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1280 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001281 if (NTTPType.isNull()) {
1282 Invalid = true;
1283 break;
1284 }
1285 }
1286
Douglas Gregor40808ce2009-03-09 23:48:35 +00001287 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001288 case TemplateArgument::Null:
1289 assert(false && "Should never see a NULL template argument here");
1290 break;
1291
Douglas Gregor40808ce2009-03-09 23:48:35 +00001292 case TemplateArgument::Expression: {
1293 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001294 TemplateArgument Result;
1295 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001296 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001297 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001298 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001299 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001300 }
1301
Douglas Gregor40808ce2009-03-09 23:48:35 +00001302 case TemplateArgument::Declaration:
1303 case TemplateArgument::Integral:
1304 // We've already checked this template argument, so just copy
1305 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001306 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001307 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001308
Douglas Gregor40808ce2009-03-09 23:48:35 +00001309 case TemplateArgument::Type:
1310 // We have a non-type template parameter but the template
1311 // argument is a type.
1312
1313 // C++ [temp.arg]p2:
1314 // In a template-argument, an ambiguity between a type-id and
1315 // an expression is resolved to a type-id, regardless of the
1316 // form of the corresponding template-parameter.
1317 //
1318 // We warn specifically about this case, since it can be rather
1319 // confusing for users.
1320 if (Arg.getAsType()->isFunctionType())
1321 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1322 << Arg.getAsType();
1323 else
1324 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1325 Diag((*Param)->getLocation(), diag::note_template_param_here);
1326 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001327 break;
1328
1329 case TemplateArgument::Pack:
1330 assert(0 && "FIXME: Implement!");
1331 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001332 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001333 } else {
1334 // Check template template parameters.
1335 TemplateTemplateParmDecl *TempParm
1336 = cast<TemplateTemplateParmDecl>(*Param);
1337
Douglas Gregor40808ce2009-03-09 23:48:35 +00001338 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001339 case TemplateArgument::Null:
1340 assert(false && "Should never see a NULL template argument here");
1341 break;
1342
Douglas Gregor40808ce2009-03-09 23:48:35 +00001343 case TemplateArgument::Expression: {
1344 Expr *ArgExpr = Arg.getAsExpr();
1345 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1346 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1347 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1348 Invalid = true;
1349
1350 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001351 Decl *D
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001352 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonfb250522009-06-23 01:26:57 +00001353 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001354 continue;
1355 }
1356 }
1357 // fall through
1358
1359 case TemplateArgument::Type: {
1360 // We have a template template parameter but the template
1361 // argument does not refer to a template.
1362 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1363 Invalid = true;
1364 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001365 }
1366
Douglas Gregor40808ce2009-03-09 23:48:35 +00001367 case TemplateArgument::Declaration:
1368 // We've already checked this template argument, so just copy
1369 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001370 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001371 break;
1372
1373 case TemplateArgument::Integral:
1374 assert(false && "Integral argument with template template parameter");
1375 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001376
1377 case TemplateArgument::Pack:
1378 assert(0 && "FIXME: Implement!");
1379 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001380 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001381 }
1382 }
1383
1384 return Invalid;
1385}
1386
1387/// \brief Check a template argument against its corresponding
1388/// template type parameter.
1389///
1390/// This routine implements the semantics of C++ [temp.arg.type]. It
1391/// returns true if an error occurred, and false otherwise.
1392bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1393 QualType Arg, SourceLocation ArgLoc) {
1394 // C++ [temp.arg.type]p2:
1395 // A local type, a type with no linkage, an unnamed type or a type
1396 // compounded from any of these types shall not be used as a
1397 // template-argument for a template type-parameter.
1398 //
1399 // FIXME: Perform the recursive and no-linkage type checks.
1400 const TagType *Tag = 0;
1401 if (const EnumType *EnumT = Arg->getAsEnumType())
1402 Tag = EnumT;
Ted Kremenek35366a62009-07-17 17:50:17 +00001403 else if (const RecordType *RecordT = Arg->getAsRecordType())
Douglas Gregorc15cb382009-02-09 23:23:08 +00001404 Tag = RecordT;
1405 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1406 return Diag(ArgLoc, diag::err_template_arg_local_type)
1407 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001408 else if (Tag && !Tag->getDecl()->getDeclName() &&
1409 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001410 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1411 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1412 return true;
1413 }
1414
1415 return false;
1416}
1417
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001418/// \brief Checks whether the given template argument is the address
1419/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001420bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1421 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001422 bool Invalid = false;
1423
1424 // See through any implicit casts we added to fix the type.
1425 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1426 Arg = Cast->getSubExpr();
1427
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001428 // C++0x allows nullptr, and there's no further checking to be done for that.
1429 if (Arg->getType()->isNullPtrType())
1430 return false;
1431
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001432 // C++ [temp.arg.nontype]p1:
1433 //
1434 // A template-argument for a non-type, non-template
1435 // template-parameter shall be one of: [...]
1436 //
1437 // -- the address of an object or function with external
1438 // linkage, including function templates and function
1439 // template-ids but excluding non-static class members,
1440 // expressed as & id-expression where the & is optional if
1441 // the name refers to a function or array, or if the
1442 // corresponding template-parameter is a reference; or
1443 DeclRefExpr *DRE = 0;
1444
1445 // Ignore (and complain about) any excess parentheses.
1446 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1447 if (!Invalid) {
1448 Diag(Arg->getSourceRange().getBegin(),
1449 diag::err_template_arg_extra_parens)
1450 << Arg->getSourceRange();
1451 Invalid = true;
1452 }
1453
1454 Arg = Parens->getSubExpr();
1455 }
1456
1457 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1458 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1459 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1460 } else
1461 DRE = dyn_cast<DeclRefExpr>(Arg);
1462
1463 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1464 return Diag(Arg->getSourceRange().getBegin(),
1465 diag::err_template_arg_not_object_or_func_form)
1466 << Arg->getSourceRange();
1467
1468 // Cannot refer to non-static data members
1469 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1470 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1471 << Field << Arg->getSourceRange();
1472
1473 // Cannot refer to non-static member functions
1474 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1475 if (!Method->isStatic())
1476 return Diag(Arg->getSourceRange().getBegin(),
1477 diag::err_template_arg_method)
1478 << Method << Arg->getSourceRange();
1479
1480 // Functions must have external linkage.
1481 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1482 if (Func->getStorageClass() == FunctionDecl::Static) {
1483 Diag(Arg->getSourceRange().getBegin(),
1484 diag::err_template_arg_function_not_extern)
1485 << Func << Arg->getSourceRange();
1486 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1487 << true;
1488 return true;
1489 }
1490
1491 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001492 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001493 return Invalid;
1494 }
1495
1496 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1497 if (!Var->hasGlobalStorage()) {
1498 Diag(Arg->getSourceRange().getBegin(),
1499 diag::err_template_arg_object_not_extern)
1500 << Var << Arg->getSourceRange();
1501 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1502 << true;
1503 return true;
1504 }
1505
1506 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001507 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001508 return Invalid;
1509 }
1510
1511 // We found something else, but we don't know specifically what it is.
1512 Diag(Arg->getSourceRange().getBegin(),
1513 diag::err_template_arg_not_object_or_func)
1514 << Arg->getSourceRange();
1515 Diag(DRE->getDecl()->getLocation(),
1516 diag::note_template_arg_refers_here);
1517 return true;
1518}
1519
1520/// \brief Checks whether the given template argument is a pointer to
1521/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001522bool
1523Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001524 bool Invalid = false;
1525
1526 // See through any implicit casts we added to fix the type.
1527 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1528 Arg = Cast->getSubExpr();
1529
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001530 // C++0x allows nullptr, and there's no further checking to be done for that.
1531 if (Arg->getType()->isNullPtrType())
1532 return false;
1533
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001534 // C++ [temp.arg.nontype]p1:
1535 //
1536 // A template-argument for a non-type, non-template
1537 // template-parameter shall be one of: [...]
1538 //
1539 // -- a pointer to member expressed as described in 5.3.1.
1540 QualifiedDeclRefExpr *DRE = 0;
1541
1542 // Ignore (and complain about) any excess parentheses.
1543 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1544 if (!Invalid) {
1545 Diag(Arg->getSourceRange().getBegin(),
1546 diag::err_template_arg_extra_parens)
1547 << Arg->getSourceRange();
1548 Invalid = true;
1549 }
1550
1551 Arg = Parens->getSubExpr();
1552 }
1553
1554 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1555 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1556 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1557
1558 if (!DRE)
1559 return Diag(Arg->getSourceRange().getBegin(),
1560 diag::err_template_arg_not_pointer_to_member_form)
1561 << Arg->getSourceRange();
1562
1563 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1564 assert((isa<FieldDecl>(DRE->getDecl()) ||
1565 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1566 "Only non-static member pointers can make it here");
1567
1568 // Okay: this is the address of a non-static member, and therefore
1569 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001570 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001571 return Invalid;
1572 }
1573
1574 // We found something else, but we don't know specifically what it is.
1575 Diag(Arg->getSourceRange().getBegin(),
1576 diag::err_template_arg_not_pointer_to_member_form)
1577 << Arg->getSourceRange();
1578 Diag(DRE->getDecl()->getLocation(),
1579 diag::note_template_arg_refers_here);
1580 return true;
1581}
1582
Douglas Gregorc15cb382009-02-09 23:23:08 +00001583/// \brief Check a template argument against its corresponding
1584/// non-type template parameter.
1585///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001586/// This routine implements the semantics of C++ [temp.arg.nontype].
1587/// It returns true if an error occurred, and false otherwise. \p
1588/// InstantiatedParamType is the type of the non-type template
1589/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001590///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001591/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001592bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001593 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001594 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001595 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1596
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001597 // If either the parameter has a dependent type or the argument is
1598 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001599 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001600 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1601 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001602 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001603 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001604 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001605
1606 // C++ [temp.arg.nontype]p5:
1607 // The following conversions are performed on each expression used
1608 // as a non-type template-argument. If a non-type
1609 // template-argument cannot be converted to the type of the
1610 // corresponding template-parameter then the program is
1611 // ill-formed.
1612 //
1613 // -- for a non-type template-parameter of integral or
1614 // enumeration type, integral promotions (4.5) and integral
1615 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001616 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001617 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001618 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001619 // C++ [temp.arg.nontype]p1:
1620 // A template-argument for a non-type, non-template
1621 // template-parameter shall be one of:
1622 //
1623 // -- an integral constant-expression of integral or enumeration
1624 // type; or
1625 // -- the name of a non-type template-parameter; or
1626 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001627 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001628 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1629 Diag(Arg->getSourceRange().getBegin(),
1630 diag::err_template_arg_not_integral_or_enumeral)
1631 << ArgType << Arg->getSourceRange();
1632 Diag(Param->getLocation(), diag::note_template_param_here);
1633 return true;
1634 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001635 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001636 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1637 << ArgType << Arg->getSourceRange();
1638 return true;
1639 }
1640
1641 // FIXME: We need some way to more easily get the unqualified form
1642 // of the types without going all the way to the
1643 // canonical type.
1644 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1645 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1646 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1647 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1648
1649 // Try to convert the argument to the parameter's type.
1650 if (ParamType == ArgType) {
1651 // Okay: no conversion necessary
1652 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1653 !ParamType->isEnumeralType()) {
1654 // This is an integral promotion or conversion.
1655 ImpCastExprToType(Arg, ParamType);
1656 } else {
1657 // We can't perform this conversion.
1658 Diag(Arg->getSourceRange().getBegin(),
1659 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001660 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001661 Diag(Param->getLocation(), diag::note_template_param_here);
1662 return true;
1663 }
1664
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001665 QualType IntegerType = Context.getCanonicalType(ParamType);
1666 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001667 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001668
1669 if (!Arg->isValueDependent()) {
1670 // Check that an unsigned parameter does not receive a negative
1671 // value.
1672 if (IntegerType->isUnsignedIntegerType()
1673 && (Value.isSigned() && Value.isNegative())) {
1674 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1675 << Value.toString(10) << Param->getType()
1676 << Arg->getSourceRange();
1677 Diag(Param->getLocation(), diag::note_template_param_here);
1678 return true;
1679 }
1680
1681 // Check that we don't overflow the template parameter type.
1682 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1683 if (Value.getActiveBits() > AllowedBits) {
1684 Diag(Arg->getSourceRange().getBegin(),
1685 diag::err_template_arg_too_large)
1686 << Value.toString(10) << Param->getType()
1687 << Arg->getSourceRange();
1688 Diag(Param->getLocation(), diag::note_template_param_here);
1689 return true;
1690 }
1691
1692 if (Value.getBitWidth() != AllowedBits)
1693 Value.extOrTrunc(AllowedBits);
1694 Value.setIsSigned(IntegerType->isSignedIntegerType());
1695 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001696
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001697 // Add the value of this argument to the list of converted
1698 // arguments. We use the bitwidth and signedness of the template
1699 // parameter.
1700 if (Arg->isValueDependent()) {
1701 // The argument is value-dependent. Create a new
1702 // TemplateArgument with the converted expression.
1703 Converted = TemplateArgument(Arg);
1704 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001705 }
1706
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001707 Converted = TemplateArgument(StartLoc, Value,
1708 ParamType->isEnumeralType() ? ParamType
1709 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001710 return false;
1711 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001712
Douglas Gregorb86b0572009-02-11 01:18:59 +00001713 // Handle pointer-to-function, reference-to-function, and
1714 // pointer-to-member-function all in (roughly) the same way.
1715 if (// -- For a non-type template-parameter of type pointer to
1716 // function, only the function-to-pointer conversion (4.3) is
1717 // applied. If the template-argument represents a set of
1718 // overloaded functions (or a pointer to such), the matching
1719 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001720 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001721 (ParamType->isPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001722 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001723 // -- For a non-type template-parameter of type reference to
1724 // function, no conversions apply. If the template-argument
1725 // represents a set of overloaded functions, the matching
1726 // function is selected from the set (13.4).
1727 (ParamType->isReferenceType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001728 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00001729 // -- For a non-type template-parameter of type pointer to
1730 // member function, no conversions apply. If the
1731 // template-argument represents a set of overloaded member
1732 // functions, the matching member function is selected from
1733 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001734 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001735 (ParamType->isMemberPointerType() &&
Ted Kremenek35366a62009-07-17 17:50:17 +00001736 ParamType->getAsMemberPointerType()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001737 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001738 if (Context.hasSameUnqualifiedType(ArgType,
1739 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001740 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001741 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1742 ParamType->isMemberPointerType())) {
1743 ArgType = ParamType;
1744 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001745 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001746 ArgType = Context.getPointerType(ArgType);
1747 ImpCastExprToType(Arg, ArgType);
1748 } else if (FunctionDecl *Fn
1749 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001750 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1751 return true;
1752
Douglas Gregora35284b2009-02-11 00:19:33 +00001753 FixOverloadedFunctionReference(Arg, Fn);
1754 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001755 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001756 ArgType = Context.getPointerType(Arg->getType());
1757 ImpCastExprToType(Arg, ArgType);
1758 }
1759 }
1760
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001761 if (!Context.hasSameUnqualifiedType(ArgType,
1762 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001763 // We can't perform this conversion.
1764 Diag(Arg->getSourceRange().getBegin(),
1765 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001766 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001767 Diag(Param->getLocation(), diag::note_template_param_here);
1768 return true;
1769 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001770
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001771 if (ParamType->isMemberPointerType()) {
1772 NamedDecl *Member = 0;
1773 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1774 return true;
1775
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001776 if (Member)
1777 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001778 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001779 return false;
1780 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001781
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001782 NamedDecl *Entity = 0;
1783 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1784 return true;
1785
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001786 if (Entity)
1787 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001788 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001789 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001790 }
1791
Chris Lattnerfe90de72009-02-20 21:37:53 +00001792 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001793 // -- for a non-type template-parameter of type pointer to
1794 // object, qualification conversions (4.4) and the
1795 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001796 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek35366a62009-07-17 17:50:17 +00001797 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001798 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001799
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001800 if (ArgType->isNullPtrType()) {
1801 ArgType = ParamType;
1802 ImpCastExprToType(Arg, ParamType);
1803 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001804 ArgType = Context.getArrayDecayedType(ArgType);
1805 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001806 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001807
Douglas Gregorb86b0572009-02-11 01:18:59 +00001808 if (IsQualificationConversion(ArgType, ParamType)) {
1809 ArgType = ParamType;
1810 ImpCastExprToType(Arg, ParamType);
1811 }
1812
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001813 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001814 // We can't perform this conversion.
1815 Diag(Arg->getSourceRange().getBegin(),
1816 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001817 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001818 Diag(Param->getLocation(), diag::note_template_param_here);
1819 return true;
1820 }
1821
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001822 NamedDecl *Entity = 0;
1823 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1824 return true;
1825
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001826 if (Entity)
1827 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001828 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001829 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001830 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001831
Ted Kremenek35366a62009-07-17 17:50:17 +00001832 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001833 // -- For a non-type template-parameter of type reference to
1834 // object, no conversions apply. The type referred to by the
1835 // reference may be more cv-qualified than the (otherwise
1836 // identical) type of the template-argument. The
1837 // template-parameter is bound directly to the
1838 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001839 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001840 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001841
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001842 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001843 Diag(Arg->getSourceRange().getBegin(),
1844 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001845 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001846 << Arg->getSourceRange();
1847 Diag(Param->getLocation(), diag::note_template_param_here);
1848 return true;
1849 }
1850
1851 unsigned ParamQuals
1852 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1853 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1854
1855 if ((ParamQuals | ArgQuals) != ParamQuals) {
1856 Diag(Arg->getSourceRange().getBegin(),
1857 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001858 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001859 << Arg->getSourceRange();
1860 Diag(Param->getLocation(), diag::note_template_param_here);
1861 return true;
1862 }
1863
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001864 NamedDecl *Entity = 0;
1865 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1866 return true;
1867
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001868 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001869 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001870 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001871 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001872
1873 // -- For a non-type template-parameter of type pointer to data
1874 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001875 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001876 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1877
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001878 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001879 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001880 } else if (ArgType->isNullPtrType()) {
1881 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001882 } else if (IsQualificationConversion(ArgType, ParamType)) {
1883 ImpCastExprToType(Arg, ParamType);
1884 } else {
1885 // We can't perform this conversion.
1886 Diag(Arg->getSourceRange().getBegin(),
1887 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001888 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001889 Diag(Param->getLocation(), diag::note_template_param_here);
1890 return true;
1891 }
1892
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001893 NamedDecl *Member = 0;
1894 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1895 return true;
1896
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001897 if (Member)
1898 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001899 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001900 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001901}
1902
1903/// \brief Check a template argument against its corresponding
1904/// template template parameter.
1905///
1906/// This routine implements the semantics of C++ [temp.arg.template].
1907/// It returns true if an error occurred, and false otherwise.
1908bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1909 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001910 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1911 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1912
1913 // C++ [temp.arg.template]p1:
1914 // A template-argument for a template template-parameter shall be
1915 // the name of a class template, expressed as id-expression. Only
1916 // primary class templates are considered when matching the
1917 // template template argument with the corresponding parameter;
1918 // partial specializations are not considered even if their
1919 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001920 //
1921 // Note that we also allow template template parameters here, which
1922 // will happen when we are dealing with, e.g., class template
1923 // partial specializations.
1924 if (!isa<ClassTemplateDecl>(Template) &&
1925 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001926 assert(isa<FunctionTemplateDecl>(Template) &&
1927 "Only function templates are possible here");
Douglas Gregore53060f2009-06-25 22:08:12 +00001928 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1929 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001930 << Template;
1931 }
1932
1933 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1934 Param->getTemplateParameters(),
1935 true, true,
1936 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001937}
1938
Douglas Gregorddc29e12009-02-06 22:42:48 +00001939/// \brief Determine whether the given template parameter lists are
1940/// equivalent.
1941///
1942/// \param New The new template parameter list, typically written in the
1943/// source code as part of a new template declaration.
1944///
1945/// \param Old The old template parameter list, typically found via
1946/// name lookup of the template declared with this template parameter
1947/// list.
1948///
1949/// \param Complain If true, this routine will produce a diagnostic if
1950/// the template parameter lists are not equivalent.
1951///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001952/// \param IsTemplateTemplateParm If true, this routine is being
1953/// called to compare the template parameter lists of a template
1954/// template parameter.
1955///
1956/// \param TemplateArgLoc If this source location is valid, then we
1957/// are actually checking the template parameter list of a template
1958/// argument (New) against the template parameter list of its
1959/// corresponding template template parameter (Old). We produce
1960/// slightly different diagnostics in this scenario.
1961///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001962/// \returns True if the template parameter lists are equal, false
1963/// otherwise.
1964bool
1965Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1966 TemplateParameterList *Old,
1967 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001968 bool IsTemplateTemplateParm,
1969 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001970 if (Old->size() != New->size()) {
1971 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001972 unsigned NextDiag = diag::err_template_param_list_different_arity;
1973 if (TemplateArgLoc.isValid()) {
1974 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1975 NextDiag = diag::note_template_param_list_different_arity;
1976 }
1977 Diag(New->getTemplateLoc(), NextDiag)
1978 << (New->size() > Old->size())
1979 << IsTemplateTemplateParm
1980 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001981 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1982 << IsTemplateTemplateParm
1983 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1984 }
1985
1986 return false;
1987 }
1988
1989 for (TemplateParameterList::iterator OldParm = Old->begin(),
1990 OldParmEnd = Old->end(), NewParm = New->begin();
1991 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1992 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00001993 if (Complain) {
1994 unsigned NextDiag = diag::err_template_param_different_kind;
1995 if (TemplateArgLoc.isValid()) {
1996 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1997 NextDiag = diag::note_template_param_different_kind;
1998 }
1999 Diag((*NewParm)->getLocation(), NextDiag)
2000 << IsTemplateTemplateParm;
2001 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2002 << IsTemplateTemplateParm;
Douglas Gregordd0574e2009-02-10 00:24:35 +00002003 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002004 return false;
2005 }
2006
2007 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2008 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002009 // know we're at the same index).
2010#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00002011 // FIXME: Enable this code in debug mode *after* we properly go through
2012 // and "instantiate" the template parameter lists of template template
2013 // parameters. It's only after this instantiation that (1) any dependent
2014 // types within the template parameter list of the template template
2015 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00002016 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00002017 QualType OldParmType
2018 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2019 QualType NewParmType
2020 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2021 assert(Context.getCanonicalType(OldParmType) ==
2022 Context.getCanonicalType(NewParmType) &&
2023 "type parameter mismatch?");
2024#endif
2025 } else if (NonTypeTemplateParmDecl *OldNTTP
2026 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2027 // The types of non-type template parameters must agree.
2028 NonTypeTemplateParmDecl *NewNTTP
2029 = cast<NonTypeTemplateParmDecl>(*NewParm);
2030 if (Context.getCanonicalType(OldNTTP->getType()) !=
2031 Context.getCanonicalType(NewNTTP->getType())) {
2032 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002033 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2034 if (TemplateArgLoc.isValid()) {
2035 Diag(TemplateArgLoc,
2036 diag::err_template_arg_template_params_mismatch);
2037 NextDiag = diag::note_template_nontype_parm_different_type;
2038 }
2039 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002040 << NewNTTP->getType()
2041 << IsTemplateTemplateParm;
2042 Diag(OldNTTP->getLocation(),
2043 diag::note_template_nontype_parm_prev_declaration)
2044 << OldNTTP->getType();
2045 }
2046 return false;
2047 }
2048 } else {
2049 // The template parameter lists of template template
2050 // parameters must agree.
2051 // FIXME: Could we perform a faster "type" comparison here?
2052 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2053 "Only template template parameters handled here");
2054 TemplateTemplateParmDecl *OldTTP
2055 = cast<TemplateTemplateParmDecl>(*OldParm);
2056 TemplateTemplateParmDecl *NewTTP
2057 = cast<TemplateTemplateParmDecl>(*NewParm);
2058 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2059 OldTTP->getTemplateParameters(),
2060 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002061 /*IsTemplateTemplateParm=*/true,
2062 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002063 return false;
2064 }
2065 }
2066
2067 return true;
2068}
2069
2070/// \brief Check whether a template can be declared within this scope.
2071///
2072/// If the template declaration is valid in this scope, returns
2073/// false. Otherwise, issues a diagnostic and returns true.
2074bool
2075Sema::CheckTemplateDeclScope(Scope *S,
2076 MultiTemplateParamsArg &TemplateParameterLists) {
2077 assert(TemplateParameterLists.size() > 0 && "Not a template");
2078
2079 // Find the nearest enclosing declaration scope.
2080 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2081 (S->getFlags() & Scope::TemplateParamScope) != 0)
2082 S = S->getParent();
2083
2084 TemplateParameterList *TemplateParams =
2085 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2086 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2087 SourceRange TemplateRange
2088 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2089
2090 // C++ [temp]p2:
2091 // A template-declaration can appear only as a namespace scope or
2092 // class scope declaration.
2093 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
2094 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
2095 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2096 return Diag(TemplateLoc, diag::err_template_linkage)
2097 << TemplateRange;
2098
2099 Ctx = Ctx->getParent();
2100 }
2101
2102 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2103 return false;
2104
2105 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2106 << TemplateRange;
2107}
Douglas Gregorcc636682009-02-17 23:15:12 +00002108
Douglas Gregorff668032009-05-13 18:28:20 +00002109/// \brief Check whether a class template specialization or explicit
2110/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00002111///
Douglas Gregorff668032009-05-13 18:28:20 +00002112/// This routine determines whether a class template specialization or
2113/// explicit instantiation can be declared in the current context
2114/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2115/// appropriate diagnostics if there was an error. It returns true if
2116// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00002117bool
2118Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2119 ClassTemplateSpecializationDecl *PrevDecl,
2120 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002121 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002122 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002123 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002124 // C++ [temp.expl.spec]p2:
2125 // An explicit specialization shall be declared in the namespace
2126 // of which the template is a member, or, for member templates, in
2127 // the namespace of which the enclosing class or enclosing class
2128 // template is a member. An explicit specialization of a member
2129 // function, member class or static data member of a class
2130 // template shall be declared in the namespace of which the class
2131 // template is a member. Such a declaration may also be a
2132 // definition. If the declaration is not a definition, the
2133 // specialization may be defined later in the name- space in which
2134 // the explicit specialization was declared, or in a namespace
2135 // that encloses the one in which the explicit specialization was
2136 // declared.
2137 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002138 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002139 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002140 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002141 return true;
2142 }
2143
2144 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2145 DeclContext *TemplateContext
2146 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002147 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2148 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002149 // There is no prior declaration of this entity, so this
2150 // specialization must be in the same context as the template
2151 // itself.
2152 if (DC != TemplateContext) {
2153 if (isa<TranslationUnitDecl>(TemplateContext))
2154 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002155 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002156 << ClassTemplate << ScopeSpecifierRange;
2157 else if (isa<NamespaceDecl>(TemplateContext))
2158 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002159 << PartialSpecialization << ClassTemplate
2160 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002161
2162 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2163 }
2164
2165 return false;
2166 }
2167
2168 // We have a previous declaration of this entity. Make sure that
2169 // this redeclaration (or definition) occurs in an enclosing namespace.
2170 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002171 // FIXME: In C++98, we would like to turn these errors into warnings,
2172 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002173 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002174 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002175 if (isa<TranslationUnitDecl>(TemplateContext)) {
2176 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2177 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002178 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002179 else
2180 SuppressedDiag = true;
2181 } else if (isa<NamespaceDecl>(TemplateContext)) {
2182 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2183 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002184 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002185 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2186 else
2187 SuppressedDiag = true;
2188 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002189
Douglas Gregorff668032009-05-13 18:28:20 +00002190 if (!SuppressedDiag)
2191 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002192 }
2193
2194 return false;
2195}
2196
Douglas Gregore94866f2009-06-12 21:21:02 +00002197/// \brief Check the non-type template arguments of a class template
2198/// partial specialization according to C++ [temp.class.spec]p9.
2199///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002200/// \param TemplateParams the template parameters of the primary class
2201/// template.
2202///
2203/// \param TemplateArg the template arguments of the class template
2204/// partial specialization.
2205///
2206/// \param MirrorsPrimaryTemplate will be set true if the class
2207/// template partial specialization arguments are identical to the
2208/// implicit template arguments of the primary template. This is not
2209/// necessarily an error (C++0x), and it is left to the caller to diagnose
2210/// this condition when it is an error.
2211///
Douglas Gregore94866f2009-06-12 21:21:02 +00002212/// \returns true if there was an error, false otherwise.
2213bool Sema::CheckClassTemplatePartialSpecializationArgs(
2214 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002215 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002216 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002217 // FIXME: the interface to this function will have to change to
2218 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002219 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002220
Anders Carlssonfb250522009-06-23 01:26:57 +00002221 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002222
Douglas Gregore94866f2009-06-12 21:21:02 +00002223 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002224 // Determine whether the template argument list of the partial
2225 // specialization is identical to the implicit argument list of
2226 // the primary template. The caller may need to diagnostic this as
2227 // an error per C++ [temp.class.spec]p9b3.
2228 if (MirrorsPrimaryTemplate) {
2229 if (TemplateTypeParmDecl *TTP
2230 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2231 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002232 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002233 MirrorsPrimaryTemplate = false;
2234 } else if (TemplateTemplateParmDecl *TTP
2235 = dyn_cast<TemplateTemplateParmDecl>(
2236 TemplateParams->getParam(I))) {
2237 // FIXME: We should settle on either Declaration storage or
2238 // Expression storage for template template parameters.
2239 TemplateTemplateParmDecl *ArgDecl
2240 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002241 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002242 if (!ArgDecl)
2243 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002244 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002245 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2246
2247 if (!ArgDecl ||
2248 ArgDecl->getIndex() != TTP->getIndex() ||
2249 ArgDecl->getDepth() != TTP->getDepth())
2250 MirrorsPrimaryTemplate = false;
2251 }
2252 }
2253
Douglas Gregore94866f2009-06-12 21:21:02 +00002254 NonTypeTemplateParmDecl *Param
2255 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002256 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002257 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002258 }
2259
Anders Carlsson6360be72009-06-13 18:20:51 +00002260 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002261 if (!ArgExpr) {
2262 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002263 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002264 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002265
2266 // C++ [temp.class.spec]p8:
2267 // A non-type argument is non-specialized if it is the name of a
2268 // non-type parameter. All other non-type arguments are
2269 // specialized.
2270 //
2271 // Below, we check the two conditions that only apply to
2272 // specialized non-type arguments, so skip any non-specialized
2273 // arguments.
2274 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002275 if (NonTypeTemplateParmDecl *NTTP
2276 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2277 if (MirrorsPrimaryTemplate &&
2278 (Param->getIndex() != NTTP->getIndex() ||
2279 Param->getDepth() != NTTP->getDepth()))
2280 MirrorsPrimaryTemplate = false;
2281
Douglas Gregore94866f2009-06-12 21:21:02 +00002282 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002283 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002284
2285 // C++ [temp.class.spec]p9:
2286 // Within the argument list of a class template partial
2287 // specialization, the following restrictions apply:
2288 // -- A partially specialized non-type argument expression
2289 // shall not involve a template parameter of the partial
2290 // specialization except when the argument expression is a
2291 // simple identifier.
2292 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2293 Diag(ArgExpr->getLocStart(),
2294 diag::err_dependent_non_type_arg_in_partial_spec)
2295 << ArgExpr->getSourceRange();
2296 return true;
2297 }
2298
2299 // -- The type of a template parameter corresponding to a
2300 // specialized non-type argument shall not be dependent on a
2301 // parameter of the specialization.
2302 if (Param->getType()->isDependentType()) {
2303 Diag(ArgExpr->getLocStart(),
2304 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2305 << Param->getType()
2306 << ArgExpr->getSourceRange();
2307 Diag(Param->getLocation(), diag::note_template_param_here);
2308 return true;
2309 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002310
2311 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002312 }
2313
2314 return false;
2315}
2316
Douglas Gregor212e81c2009-03-25 00:13:59 +00002317Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002318Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2319 SourceLocation KWLoc,
2320 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002321 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002322 SourceLocation TemplateNameLoc,
2323 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002324 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002325 SourceLocation *TemplateArgLocs,
2326 SourceLocation RAngleLoc,
2327 AttributeList *Attr,
2328 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002329 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002330 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002331 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002332 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002333
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002334 bool isPartialSpecialization = false;
2335
Douglas Gregor88b70942009-02-25 22:02:03 +00002336 // Check the validity of the template headers that introduce this
2337 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002338 // FIXME: Once we have member templates, we'll need to check
2339 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2340 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002341 if (TemplateParameterLists.size() == 0)
2342 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002343 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002344 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002345 TemplateParameterList *TemplateParams
2346 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002347 if (TemplateParameterLists.size() > 1) {
2348 Diag(TemplateParams->getTemplateLoc(),
2349 diag::err_template_spec_extra_headers);
2350 return true;
2351 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002352
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002353 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002354 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002355
2356 // C++ [temp.class.spec]p10:
2357 // The template parameter list of a specialization shall not
2358 // contain default template argument values.
2359 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2360 Decl *Param = TemplateParams->getParam(I);
2361 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2362 if (TTP->hasDefaultArgument()) {
2363 Diag(TTP->getDefaultArgumentLoc(),
2364 diag::err_default_arg_in_partial_spec);
2365 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2366 }
2367 } else if (NonTypeTemplateParmDecl *NTTP
2368 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2369 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2370 Diag(NTTP->getDefaultArgumentLoc(),
2371 diag::err_default_arg_in_partial_spec)
2372 << DefArg->getSourceRange();
2373 NTTP->setDefaultArgument(0);
2374 DefArg->Destroy(Context);
2375 }
2376 } else {
2377 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2378 if (Expr *DefArg = TTP->getDefaultArgument()) {
2379 Diag(TTP->getDefaultArgumentLoc(),
2380 diag::err_default_arg_in_partial_spec)
2381 << DefArg->getSourceRange();
2382 TTP->setDefaultArgument(0);
2383 DefArg->Destroy(Context);
2384 }
2385 }
2386 }
2387 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002388 }
2389
Douglas Gregorcc636682009-02-17 23:15:12 +00002390 // Check that the specialization uses the same tag kind as the
2391 // original template.
2392 TagDecl::TagKind Kind;
2393 switch (TagSpec) {
2394 default: assert(0 && "Unknown tag type!");
2395 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2396 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2397 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2398 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002399 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2400 Kind, KWLoc,
2401 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002402 Diag(KWLoc, diag::err_use_with_wrong_tag)
2403 << ClassTemplate
2404 << CodeModificationHint::CreateReplacement(KWLoc,
2405 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002406 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2407 diag::note_previous_use);
2408 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2409 }
2410
Douglas Gregor40808ce2009-03-09 23:48:35 +00002411 // Translate the parser's template argument list in our AST format.
2412 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2413 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2414
Douglas Gregorcc636682009-02-17 23:15:12 +00002415 // Check that the template argument list is well-formed for this
2416 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002417 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2418 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002419 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002420 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002421 RAngleLoc, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002422 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002423
Anders Carlssonfb250522009-06-23 01:26:57 +00002424 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002425 ClassTemplate->getTemplateParameters()->size()) &&
2426 "Converted template argument list is too short!");
2427
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002428 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002429 // corresponds to these arguments.
2430 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002431 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002432 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002433 if (CheckClassTemplatePartialSpecializationArgs(
2434 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002435 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002436 return true;
2437
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002438 if (MirrorsPrimaryTemplate) {
2439 // C++ [temp.class.spec]p9b3:
2440 //
2441 // -- The argument list of the specialization shall not be identical
2442 // to the implicit argument list of the primary template.
2443 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2444 << (TK == TK_Definition)
2445 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2446 RAngleLoc));
Douglas Gregorbd1099e2009-07-23 16:36:45 +00002447 return CheckClassTemplate(S, TagSpec, TK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002448 ClassTemplate->getIdentifier(),
2449 TemplateNameLoc,
2450 Attr,
2451 move(TemplateParameterLists),
2452 AS_none);
2453 }
2454
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002455 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002456 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002457 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002458 Converted.flatSize(),
2459 Context);
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002460 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002461 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002462 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002463 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002464 Converted.flatSize(),
2465 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00002466 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002467 ClassTemplateSpecializationDecl *PrevDecl = 0;
2468
2469 if (isPartialSpecialization)
2470 PrevDecl
2471 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2472 InsertPos);
2473 else
2474 PrevDecl
2475 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002476
2477 ClassTemplateSpecializationDecl *Specialization = 0;
2478
Douglas Gregor88b70942009-02-25 22:02:03 +00002479 // Check whether we can declare a class template specialization in
2480 // the current scope.
2481 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2482 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002483 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002484 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002485 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002486 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002487
Douglas Gregorcc636682009-02-17 23:15:12 +00002488 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2489 // Since the only prior class template specialization with these
2490 // arguments was referenced but not declared, reuse that
2491 // declaration node as our own, updating its source location to
2492 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002493 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002494 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002495 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002496 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002497 // Create a new class template partial specialization declaration node.
2498 TemplateParameterList *TemplateParams
2499 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2500 ClassTemplatePartialSpecializationDecl *PrevPartial
2501 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2502 ClassTemplatePartialSpecializationDecl *Partial
2503 = ClassTemplatePartialSpecializationDecl::Create(Context,
2504 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002505 TemplateNameLoc,
2506 TemplateParams,
2507 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002508 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002509 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002510
2511 if (PrevPartial) {
2512 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2513 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2514 } else {
2515 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2516 }
2517 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002518
2519 // Check that all of the template parameters of the class template
2520 // partial specialization are deducible from the template
2521 // arguments. If not, this class template partial specialization
2522 // will never be used.
2523 llvm::SmallVector<bool, 8> DeducibleParams;
2524 DeducibleParams.resize(TemplateParams->size());
2525 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2526 unsigned NumNonDeducible = 0;
2527 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2528 if (!DeducibleParams[I])
2529 ++NumNonDeducible;
2530
2531 if (NumNonDeducible) {
2532 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2533 << (NumNonDeducible > 1)
2534 << SourceRange(TemplateNameLoc, RAngleLoc);
2535 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2536 if (!DeducibleParams[I]) {
2537 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2538 if (Param->getDeclName())
2539 Diag(Param->getLocation(),
2540 diag::note_partial_spec_unused_parameter)
2541 << Param->getDeclName();
2542 else
2543 Diag(Param->getLocation(),
2544 diag::note_partial_spec_unused_parameter)
2545 << std::string("<anonymous>");
2546 }
2547 }
2548 }
2549
Douglas Gregorcc636682009-02-17 23:15:12 +00002550 } else {
2551 // Create a new class template specialization declaration node for
2552 // this explicit specialization.
2553 Specialization
2554 = ClassTemplateSpecializationDecl::Create(Context,
2555 ClassTemplate->getDeclContext(),
2556 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002557 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002558 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002559 PrevDecl);
2560
2561 if (PrevDecl) {
2562 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2563 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2564 } else {
2565 ClassTemplate->getSpecializations().InsertNode(Specialization,
2566 InsertPos);
2567 }
2568 }
2569
2570 // Note that this is an explicit specialization.
2571 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2572
2573 // Check that this isn't a redefinition of this specialization.
2574 if (TK == TK_Definition) {
2575 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002576 // FIXME: Should also handle explicit specialization after implicit
2577 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002578 SourceRange Range(TemplateNameLoc, RAngleLoc);
2579 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002580 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002581 Diag(Def->getLocation(), diag::note_previous_definition);
2582 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002583 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002584 }
2585 }
2586
Douglas Gregorfc705b82009-02-26 22:19:44 +00002587 // Build the fully-sugared type for this class template
2588 // specialization as the user wrote in the specialization
2589 // itself. This means that we'll pretty-print the type retrieved
2590 // from the specialization's declaration the way that the user
2591 // actually wrote the specialization, rather than formatting the
2592 // name based on the "canonical" representation used to store the
2593 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002594 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002595 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002596 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002597 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002598 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002599 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002600 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002601
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002602 // C++ [temp.expl.spec]p9:
2603 // A template explicit specialization is in the scope of the
2604 // namespace in which the template was defined.
2605 //
2606 // We actually implement this paragraph where we set the semantic
2607 // context (in the creation of the ClassTemplateSpecializationDecl),
2608 // but we also maintain the lexical context where the actual
2609 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002610 Specialization->setLexicalDeclContext(CurContext);
2611
2612 // We may be starting the definition of this specialization.
2613 if (TK == TK_Definition)
2614 Specialization->startDefinition();
2615
2616 // Add the specialization into its lexical context, so that it can
2617 // be seen when iterating through the list of declarations in that
2618 // context. However, specializations are not found by name lookup.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002619 CurContext->addDecl(Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002620 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002621}
Douglas Gregord57959a2009-03-27 23:10:48 +00002622
Douglas Gregore542c862009-06-23 23:11:28 +00002623Sema::DeclPtrTy
2624Sema::ActOnTemplateDeclarator(Scope *S,
2625 MultiTemplateParamsArg TemplateParameterLists,
2626 Declarator &D) {
2627 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2628}
2629
Douglas Gregor52591bf2009-06-24 00:54:41 +00002630Sema::DeclPtrTy
2631Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2632 MultiTemplateParamsArg TemplateParameterLists,
2633 Declarator &D) {
2634 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2635 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2636 "Not a function declarator!");
2637 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2638
2639 if (FTI.hasPrototype) {
2640 // FIXME: Diagnose arguments without names in C.
2641 }
2642
2643 Scope *ParentScope = FnBodyScope->getParent();
2644
2645 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2646 move(TemplateParameterLists),
2647 /*IsFunctionDefinition=*/true);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002648 if (FunctionTemplateDecl *FunctionTemplate
2649 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregore53060f2009-06-25 22:08:12 +00002650 return ActOnStartOfFunctionDef(FnBodyScope,
2651 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00002652 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2653 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00002654 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00002655}
2656
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002657// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002658Sema::DeclResult
2659Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2660 unsigned TagSpec,
2661 SourceLocation KWLoc,
2662 const CXXScopeSpec &SS,
2663 TemplateTy TemplateD,
2664 SourceLocation TemplateNameLoc,
2665 SourceLocation LAngleLoc,
2666 ASTTemplateArgsPtr TemplateArgsIn,
2667 SourceLocation *TemplateArgLocs,
2668 SourceLocation RAngleLoc,
2669 AttributeList *Attr) {
2670 // Find the class template we're specializing
2671 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2672 ClassTemplateDecl *ClassTemplate
2673 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2674
2675 // Check that the specialization uses the same tag kind as the
2676 // original template.
2677 TagDecl::TagKind Kind;
2678 switch (TagSpec) {
2679 default: assert(0 && "Unknown tag type!");
2680 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2681 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2682 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2683 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002684 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2685 Kind, KWLoc,
2686 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002687 Diag(KWLoc, diag::err_use_with_wrong_tag)
2688 << ClassTemplate
2689 << CodeModificationHint::CreateReplacement(KWLoc,
2690 ClassTemplate->getTemplatedDecl()->getKindName());
2691 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2692 diag::note_previous_use);
2693 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2694 }
2695
Douglas Gregorff668032009-05-13 18:28:20 +00002696 // C++0x [temp.explicit]p2:
2697 // [...] An explicit instantiation shall appear in an enclosing
2698 // namespace of its template. [...]
2699 //
2700 // This is C++ DR 275.
2701 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2702 TemplateNameLoc,
2703 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002704 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002705 /*ExplicitInstantiation=*/true))
2706 return true;
2707
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002708 // Translate the parser's template argument list in our AST format.
2709 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2710 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2711
2712 // Check that the template argument list is well-formed for this
2713 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002714 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2715 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002716 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002717 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor16134c62009-07-01 00:28:38 +00002718 RAngleLoc, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002719 return true;
2720
Anders Carlssonfb250522009-06-23 01:26:57 +00002721 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002722 ClassTemplate->getTemplateParameters()->size()) &&
2723 "Converted template argument list is too short!");
2724
2725 // Find the class template specialization declaration that
2726 // corresponds to these arguments.
2727 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002728 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002729 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00002730 Converted.flatSize(),
2731 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002732 void *InsertPos = 0;
2733 ClassTemplateSpecializationDecl *PrevDecl
2734 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2735
2736 ClassTemplateSpecializationDecl *Specialization = 0;
2737
Douglas Gregorff668032009-05-13 18:28:20 +00002738 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002739 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002740 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002741 // This particular specialization has already been declared or
2742 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002743 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2744 << Context.getTypeDeclType(PrevDecl);
2745 Diag(PrevDecl->getLocation(),
2746 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002747 return DeclPtrTy::make(PrevDecl);
2748 }
2749
Douglas Gregorff668032009-05-13 18:28:20 +00002750 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002751 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002752 // For a given set of template parameters, if an explicit
2753 // instantiation of a template appears after a declaration of
2754 // an explicit specialization for that template, the explicit
2755 // instantiation has no effect.
2756 if (!getLangOptions().CPlusPlus0x) {
2757 Diag(TemplateNameLoc,
2758 diag::ext_explicit_instantiation_after_specialization)
2759 << Context.getTypeDeclType(PrevDecl);
2760 Diag(PrevDecl->getLocation(),
2761 diag::note_previous_template_specialization);
2762 }
2763
2764 // Create a new class template specialization declaration node
2765 // for this explicit specialization. This node is only used to
2766 // record the existence of this explicit instantiation for
2767 // accurate reproduction of the source code; we don't actually
2768 // use it for anything, since it is semantically irrelevant.
2769 Specialization
2770 = ClassTemplateSpecializationDecl::Create(Context,
2771 ClassTemplate->getDeclContext(),
2772 TemplateNameLoc,
2773 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002774 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002775 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002776 CurContext->addDecl(Specialization);
Douglas Gregorff668032009-05-13 18:28:20 +00002777 return DeclPtrTy::make(Specialization);
2778 }
2779
2780 // If we have already (implicitly) instantiated this
2781 // specialization, there is less work to do.
2782 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2783 SpecializationRequiresInstantiation = false;
2784
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002785 // Since the only prior class template specialization with these
2786 // arguments was referenced but not declared, reuse that
2787 // declaration node as our own, updating its source location to
2788 // reflect our new declaration.
2789 Specialization = PrevDecl;
2790 Specialization->setLocation(TemplateNameLoc);
2791 PrevDecl = 0;
2792 } else {
2793 // Create a new class template specialization declaration node for
2794 // this explicit specialization.
2795 Specialization
2796 = ClassTemplateSpecializationDecl::Create(Context,
2797 ClassTemplate->getDeclContext(),
2798 TemplateNameLoc,
2799 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002800 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002801
2802 ClassTemplate->getSpecializations().InsertNode(Specialization,
2803 InsertPos);
2804 }
2805
2806 // Build the fully-sugared type for this explicit instantiation as
2807 // the user wrote in the explicit instantiation itself. This means
2808 // that we'll pretty-print the type retrieved from the
2809 // specialization's declaration the way that the user actually wrote
2810 // the explicit instantiation, rather than formatting the name based
2811 // on the "canonical" representation used to store the template
2812 // arguments in the specialization.
2813 QualType WrittenTy
2814 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002815 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002816 TemplateArgs.size(),
2817 Context.getTypeDeclType(Specialization));
2818 Specialization->setTypeAsWritten(WrittenTy);
2819 TemplateArgsIn.release();
2820
2821 // Add the explicit instantiation into its lexical context. However,
2822 // since explicit instantiations are never found by name lookup, we
2823 // just put it into the declaration context directly.
2824 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002825 CurContext->addDecl(Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002826
2827 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002828 // A definition of a class template or class member template
2829 // shall be in scope at the point of the explicit instantiation of
2830 // the class template or class member template.
2831 //
2832 // This check comes when we actually try to perform the
2833 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002834 if (SpecializationRequiresInstantiation)
2835 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002836 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002837 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002838
2839 return DeclPtrTy::make(Specialization);
2840}
2841
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002842// Explicit instantiation of a member class of a class template.
2843Sema::DeclResult
2844Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2845 unsigned TagSpec,
2846 SourceLocation KWLoc,
2847 const CXXScopeSpec &SS,
2848 IdentifierInfo *Name,
2849 SourceLocation NameLoc,
2850 AttributeList *Attr) {
2851
Douglas Gregor402abb52009-05-28 23:31:59 +00002852 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002853 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002854 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2855 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002856 if (!TagD)
2857 return true;
2858
2859 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2860 if (Tag->isEnum()) {
2861 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2862 << Context.getTypeDeclType(Tag);
2863 return true;
2864 }
2865
Douglas Gregord0c87372009-05-27 17:30:49 +00002866 if (Tag->isInvalidDecl())
2867 return true;
2868
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002869 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2870 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2871 if (!Pattern) {
2872 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2873 << Context.getTypeDeclType(Record);
2874 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2875 return true;
2876 }
2877
2878 // C++0x [temp.explicit]p2:
2879 // [...] An explicit instantiation shall appear in an enclosing
2880 // namespace of its template. [...]
2881 //
2882 // This is C++ DR 275.
2883 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002884 // FIXME: In C++98, we would like to turn these errors into warnings,
2885 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002886 DeclContext *PatternContext
2887 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2888 if (!CurContext->Encloses(PatternContext)) {
2889 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2890 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2891 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2892 }
2893 }
2894
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002895 if (!Record->getDefinition(Context)) {
2896 // If the class has a definition, instantiate it (and all of its
2897 // members, recursively).
2898 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2899 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002900 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002901 /*ExplicitInstantiation=*/true))
2902 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002903 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002904 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002905 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002906
Mike Stump390b4cc2009-05-16 07:39:55 +00002907 // FIXME: We don't have any representation for explicit instantiations of
2908 // member classes. Such a representation is not needed for compilation, but it
2909 // should be available for clients that want to see all of the declarations in
2910 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002911 return TagD;
2912}
2913
Douglas Gregord57959a2009-03-27 23:10:48 +00002914Sema::TypeResult
2915Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2916 const IdentifierInfo &II, SourceLocation IdLoc) {
2917 NestedNameSpecifier *NNS
2918 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2919 if (!NNS)
2920 return true;
2921
2922 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002923 if (T.isNull())
2924 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002925 return T.getAsOpaquePtr();
2926}
2927
Douglas Gregor17343172009-04-01 00:28:59 +00002928Sema::TypeResult
2929Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2930 SourceLocation TemplateLoc, TypeTy *Ty) {
2931 QualType T = QualType::getFromOpaquePtr(Ty);
2932 NestedNameSpecifier *NNS
2933 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2934 const TemplateSpecializationType *TemplateId
2935 = T->getAsTemplateSpecializationType();
2936 assert(TemplateId && "Expected a template specialization type");
2937
2938 if (NNS->isDependent())
2939 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2940
2941 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2942}
2943
Douglas Gregord57959a2009-03-27 23:10:48 +00002944/// \brief Build the type that describes a C++ typename specifier,
2945/// e.g., "typename T::type".
2946QualType
2947Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2948 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002949 CXXRecordDecl *CurrentInstantiation = 0;
2950 if (NNS->isDependent()) {
2951 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002952
Douglas Gregor42af25f2009-05-11 19:58:34 +00002953 // If the nested-name-specifier does not refer to the current
2954 // instantiation, then build a typename type.
2955 if (!CurrentInstantiation)
2956 return Context.getTypenameType(NNS, &II);
2957 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002958
Douglas Gregor42af25f2009-05-11 19:58:34 +00002959 DeclContext *Ctx = 0;
2960
2961 if (CurrentInstantiation)
2962 Ctx = CurrentInstantiation;
2963 else {
2964 CXXScopeSpec SS;
2965 SS.setScopeRep(NNS);
2966 SS.setRange(Range);
2967 if (RequireCompleteDeclContext(SS))
2968 return QualType();
2969
2970 Ctx = computeDeclContext(SS);
2971 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002972 assert(Ctx && "No declaration context?");
2973
2974 DeclarationName Name(&II);
2975 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2976 false);
2977 unsigned DiagID = 0;
2978 Decl *Referenced = 0;
2979 switch (Result.getKind()) {
2980 case LookupResult::NotFound:
2981 if (Ctx->isTranslationUnit())
2982 DiagID = diag::err_typename_nested_not_found_global;
2983 else
2984 DiagID = diag::err_typename_nested_not_found;
2985 break;
2986
2987 case LookupResult::Found:
2988 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2989 // We found a type. Build a QualifiedNameType, since the
2990 // typename-specifier was just sugar. FIXME: Tell
2991 // QualifiedNameType that it has a "typename" prefix.
2992 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2993 }
2994
2995 DiagID = diag::err_typename_nested_not_type;
2996 Referenced = Result.getAsDecl();
2997 break;
2998
2999 case LookupResult::FoundOverloaded:
3000 DiagID = diag::err_typename_nested_not_type;
3001 Referenced = *Result.begin();
3002 break;
3003
3004 case LookupResult::AmbiguousBaseSubobjectTypes:
3005 case LookupResult::AmbiguousBaseSubobjects:
3006 case LookupResult::AmbiguousReference:
3007 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3008 return QualType();
3009 }
3010
3011 // If we get here, it's because name lookup did not find a
3012 // type. Emit an appropriate diagnostic and return an error.
3013 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3014 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3015 else
3016 Diag(Range.getEnd(), DiagID) << Range << Name;
3017 if (Referenced)
3018 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3019 << Name;
3020 return QualType();
3021}