blob: 119e17f814d017623f753837474361e548e1e805 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregordd861062008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor3f220e82009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregord406b032009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor3f220e82009-08-06 16:20:37 +000020#include "llvm/Support/Compiler.h"
Douglas Gregordd861062008-12-05 18:15:24 +000021
22using namespace clang;
23
Douglas Gregor681d31d2009-09-02 22:59:36 +000024/// \brief Determine whether the declaration found is acceptable as the name
25/// of a template and, if so, return that template declaration. Otherwise,
26/// returns NULL.
27static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
28 if (!D)
29 return 0;
30
31 if (isa<TemplateDecl>(D))
32 return D;
33
34 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
35 // C++ [temp.local]p1:
36 // Like normal (non-template) classes, class templates have an
37 // injected-class-name (Clause 9). The injected-class-name
38 // can be used with or without a template-argument-list. When
39 // it is used without a template-argument-list, it is
40 // equivalent to the injected-class-name followed by the
41 // template-parameters of the class template enclosed in
42 // <>. When it is used with a template-argument-list, it
43 // refers to the specified class template specialization,
44 // which could be the current specialization or another
45 // specialization.
46 if (Record->isInjectedClassName()) {
47 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
48 if (Record->getDescribedClassTemplate())
49 return Record->getDescribedClassTemplate();
50
51 if (ClassTemplateSpecializationDecl *Spec
52 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
53 return Spec->getSpecializedTemplate();
54 }
55
56 return 0;
57 }
58
59 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
60 if (!Ovl)
61 return 0;
62
63 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
64 FEnd = Ovl->function_end();
65 F != FEnd; ++F) {
66 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
67 // We've found a function template. Determine whether there are
68 // any other function templates we need to bundle together in an
69 // OverloadedFunctionDecl
70 for (++F; F != FEnd; ++F) {
71 if (isa<FunctionTemplateDecl>(*F))
72 break;
73 }
74
75 if (F != FEnd) {
76 // Build an overloaded function decl containing only the
77 // function templates in Ovl.
78 OverloadedFunctionDecl *OvlTemplate
79 = OverloadedFunctionDecl::Create(Context,
80 Ovl->getDeclContext(),
81 Ovl->getDeclName());
82 OvlTemplate->addOverload(FuncTmpl);
83 OvlTemplate->addOverload(*F);
84 for (++F; F != FEnd; ++F) {
85 if (isa<FunctionTemplateDecl>(*F))
86 OvlTemplate->addOverload(*F);
87 }
88
89 return OvlTemplate;
90 }
91
92 return FuncTmpl;
93 }
94 }
95
96 return 0;
97}
98
99TemplateNameKind Sema::isTemplateName(Scope *S,
100 const IdentifierInfo &II,
101 SourceLocation IdLoc,
Douglas Gregorc03d3302009-08-25 22:51:20 +0000102 const CXXScopeSpec *SS,
Douglas Gregor681d31d2009-09-02 22:59:36 +0000103 TypeTy *ObjectTypePtr,
Douglas Gregorc03d3302009-08-25 22:51:20 +0000104 bool EnteringContext,
Douglas Gregor681d31d2009-09-02 22:59:36 +0000105 TemplateTy &TemplateResult) {
106 // Determine where to perform name lookup
107 DeclContext *LookupCtx = 0;
108 bool isDependent = false;
109 if (ObjectTypePtr) {
110 // This nested-name-specifier occurs in a member access expression, e.g.,
111 // x->B::f, and we are looking into the type of the object.
112 assert((!SS || !SS->isSet()) &&
113 "ObjectType and scope specifier cannot coexist");
114 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
115 LookupCtx = computeDeclContext(ObjectType);
116 isDependent = ObjectType->isDependentType();
117 } else if (SS && SS->isSet()) {
118 // This nested-name-specifier occurs after another nested-name-specifier,
119 // so long into the context associated with the prior nested-name-specifier.
120
121 LookupCtx = computeDeclContext(*SS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(*SS);
123 }
124
125 LookupResult Found;
126 bool ObjectTypeSearchedInScope = false;
127 if (LookupCtx) {
128 // Perform "qualified" name lookup into the declaration context we
129 // computed, which is either the type of the base of a member access
130 // expression or the declaration context associated with a prior
131 // nested-name-specifier.
132
133 // The declaration context must be complete.
134 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
135 return TNK_Non_template;
136
137 Found = LookupQualifiedName(LookupCtx, &II, LookupOrdinaryName);
138
139 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
140 // C++ [basic.lookup.classref]p1:
141 // In a class member access expression (5.2.5), if the . or -> token is
142 // immediately followed by an identifier followed by a <, the
143 // identifier must be looked up to determine whether the < is the
144 // beginning of a template argument list (14.2) or a less-than operator.
145 // The identifier is first looked up in the class of the object
146 // expression. If the identifier is not found, it is then looked up in
147 // the context of the entire postfix-expression and shall name a class
148 // or function template.
149 //
150 // FIXME: When we're instantiating a template, do we actually have to
151 // look in the scope of the template? Seems fishy...
152 Found = LookupName(S, &II, LookupOrdinaryName);
153 ObjectTypeSearchedInScope = true;
154 }
155 } else if (isDependent) {
156 // We cannot look into a dependent object type or
157 return TNK_Non_template;
158 } else {
159 // Perform unqualified name lookup in the current scope.
160 Found = LookupName(S, &II, LookupOrdinaryName);
161 }
Douglas Gregorc03d3302009-08-25 22:51:20 +0000162
163 // FIXME: Cope with ambiguous name-lookup results.
164 assert(!Found.isAmbiguous() &&
165 "Cannot handle template name-lookup ambiguities");
Douglas Gregordd13e842009-03-30 22:58:21 +0000166
Douglas Gregor681d31d2009-09-02 22:59:36 +0000167 NamedDecl *Template = isAcceptableTemplateName(Context, Found);
168 if (!Template)
169 return TNK_Non_template;
170
171 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
172 // C++ [basic.lookup.classref]p1:
173 // [...] If the lookup in the class of the object expression finds a
174 // template, the name is also looked up in the context of the entire
175 // postfix-expression and [...]
176 //
177 LookupResult FoundOuter = LookupName(S, &II, LookupOrdinaryName);
178 // FIXME: Handle ambiguities in this lookup better
179 NamedDecl *OuterTemplate = isAcceptableTemplateName(Context, FoundOuter);
180
181 if (!OuterTemplate) {
182 // - if the name is not found, the name found in the class of the
183 // object expression is used, otherwise
184 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
185 // - if the name is found in the context of the entire
186 // postfix-expression and does not name a class template, the name
187 // found in the class of the object expression is used, otherwise
188 } else {
189 // - if the name found is a class template, it must refer to the same
190 // entity as the one found in the class of the object expression,
191 // otherwise the program is ill-formed.
192 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
193 Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
194 << &II;
195 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
196 << QualType::getFromOpaquePtr(ObjectTypePtr);
197 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
198
199 // Recover by taking the template that we found in the object
200 // expression's type.
Douglas Gregor55216ac2009-03-26 00:10:35 +0000201 }
Douglas Gregor681d31d2009-09-02 22:59:36 +0000202 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000203 }
Douglas Gregor681d31d2009-09-02 22:59:36 +0000204
205 if (SS && SS->isSet() && !SS->isInvalid()) {
206 NestedNameSpecifier *Qualifier
207 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
208 if (OverloadedFunctionDecl *Ovl
209 = dyn_cast<OverloadedFunctionDecl>(Template))
210 TemplateResult
211 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
212 Ovl));
213 else
214 TemplateResult
215 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
216 cast<TemplateDecl>(Template)));
217 } else if (OverloadedFunctionDecl *Ovl
218 = dyn_cast<OverloadedFunctionDecl>(Template)) {
219 TemplateResult = TemplateTy::make(TemplateName(Ovl));
220 } else {
221 TemplateResult = TemplateTy::make(
222 TemplateName(cast<TemplateDecl>(Template)));
223 }
224
225 if (isa<ClassTemplateDecl>(Template) ||
226 isa<TemplateTemplateParmDecl>(Template))
227 return TNK_Type_template;
228
229 assert((isa<FunctionTemplateDecl>(Template) ||
230 isa<OverloadedFunctionDecl>(Template)) &&
231 "Unhandled template kind in Sema::isTemplateName");
232 return TNK_Function_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000233}
234
Douglas Gregordd861062008-12-05 18:15:24 +0000235/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
236/// that the template parameter 'PrevDecl' is being shadowed by a new
237/// declaration at location Loc. Returns true to indicate that this is
238/// an error, and false otherwise.
239bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000240 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000241
242 // Microsoft Visual C++ permits template parameters to be shadowed.
243 if (getLangOptions().Microsoft)
244 return false;
245
246 // C++ [temp.local]p4:
247 // A template-parameter shall not be redeclared within its
248 // scope (including nested scopes).
249 Diag(Loc, diag::err_template_param_shadow)
250 << cast<NamedDecl>(PrevDecl)->getDeclName();
251 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
252 return true;
253}
254
Douglas Gregored3a3982009-03-03 04:44:36 +0000255/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000256/// the parameter D to reference the templated declaration and return a pointer
257/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000258TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
259 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
260 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000261 return Temp;
262 }
263 return 0;
264}
265
Douglas Gregordd861062008-12-05 18:15:24 +0000266/// ActOnTypeParameter - Called when a C++ template type parameter
267/// (e.g., "typename T") has been parsed. Typename specifies whether
268/// the keyword "typename" was used to declare the type parameter
269/// (otherwise, "class" was used), and KeyLoc is the location of the
270/// "class" or "typename" keyword. ParamName is the name of the
271/// parameter (NULL indicates an unnamed template parameter) and
272/// ParamName is the location of the parameter name (if any).
273/// If the type parameter has a default argument, it will be added
274/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000275Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
276 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000277 SourceLocation KeyLoc,
278 IdentifierInfo *ParamName,
279 SourceLocation ParamNameLoc,
280 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000281 assert(S->isTemplateParamScope() &&
282 "Template type parameter not in template parameter scope!");
283 bool Invalid = false;
284
285 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000286 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000287 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000288 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
289 PrevDecl);
290 }
291
Douglas Gregord406b032009-02-06 22:42:48 +0000292 SourceLocation Loc = ParamNameLoc;
293 if (!ParamName)
294 Loc = KeyLoc;
295
Douglas Gregordd861062008-12-05 18:15:24 +0000296 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000297 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000298 Depth, Position, ParamName, Typename,
299 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000300 if (Invalid)
301 Param->setInvalidDecl();
302
303 if (ParamName) {
304 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000305 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000306 IdResolver.AddDecl(Param);
307 }
308
Chris Lattner5261d0c2009-03-28 19:18:32 +0000309 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000310}
311
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000312/// ActOnTypeParameterDefault - Adds a default argument (the type
313/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000314void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000315 SourceLocation EqualLoc,
316 SourceLocation DefaultLoc,
317 TypeTy *DefaultT) {
318 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000319 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000320 // FIXME: Preserve type source info.
321 QualType Default = GetTypeFromParser(DefaultT);
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000322
Anders Carlssona2333782009-06-12 22:30:13 +0000323 // C++0x [temp.param]p9:
324 // A default template-argument may be specified for any kind of
325 // template-parameter that is not a template parameter pack.
326 if (Parm->isParameterPack()) {
327 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000328 return;
329 }
330
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000331 // C++ [temp.param]p14:
332 // A template-parameter shall not be used in its own default argument.
333 // FIXME: Implement this check! Needs a recursive walk over the types.
334
335 // Check the template argument itself.
336 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
337 Parm->setInvalidDecl();
338 return;
339 }
340
341 Parm->setDefaultArgument(Default, DefaultLoc, false);
342}
343
Douglas Gregored3a3982009-03-03 04:44:36 +0000344/// \brief Check that the type of a non-type template parameter is
345/// well-formed.
346///
347/// \returns the (possibly-promoted) parameter type if valid;
348/// otherwise, produces a diagnostic and returns a NULL type.
349QualType
350Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
351 // C++ [temp.param]p4:
352 //
353 // A non-type template-parameter shall have one of the following
354 // (optionally cv-qualified) types:
355 //
356 // -- integral or enumeration type,
357 if (T->isIntegralType() || T->isEnumeralType() ||
358 // -- pointer to object or pointer to function,
359 (T->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000360 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
361 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregored3a3982009-03-03 04:44:36 +0000362 // -- reference to object or reference to function,
363 T->isReferenceType() ||
364 // -- pointer to member.
365 T->isMemberPointerType() ||
366 // If T is a dependent type, we can't do the check now, so we
367 // assume that it is well-formed.
368 T->isDependentType())
369 return T;
370 // C++ [temp.param]p8:
371 //
372 // A non-type template-parameter of type "array of T" or
373 // "function returning T" is adjusted to be of type "pointer to
374 // T" or "pointer to function returning T", respectively.
375 else if (T->isArrayType())
376 // FIXME: Keep the type prior to promotion?
377 return Context.getArrayDecayedType(T);
378 else if (T->isFunctionType())
379 // FIXME: Keep the type prior to promotion?
380 return Context.getPointerType(T);
381
382 Diag(Loc, diag::err_template_nontype_parm_bad_type)
383 << T;
384
385 return QualType();
386}
387
Douglas Gregordd861062008-12-05 18:15:24 +0000388/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
389/// template parameter (e.g., "int Size" in "template<int Size>
390/// class Array") has been parsed. S is the current scope and D is
391/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000392Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
393 unsigned Depth,
394 unsigned Position) {
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000395 DeclaratorInfo *DInfo = 0;
396 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregordd861062008-12-05 18:15:24 +0000397
Douglas Gregor279272e2009-02-04 19:02:06 +0000398 assert(S->isTemplateParamScope() &&
399 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000400 bool Invalid = false;
401
402 IdentifierInfo *ParamName = D.getIdentifier();
403 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000404 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000405 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000406 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000407 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000408 }
409
Douglas Gregored3a3982009-03-03 04:44:36 +0000410 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000411 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000412 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000413 Invalid = true;
414 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000415
Douglas Gregordd861062008-12-05 18:15:24 +0000416 NonTypeTemplateParmDecl *Param
417 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +0000418 Depth, Position, ParamName, T, DInfo);
Douglas Gregordd861062008-12-05 18:15:24 +0000419 if (Invalid)
420 Param->setInvalidDecl();
421
422 if (D.getIdentifier()) {
423 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000424 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000425 IdResolver.AddDecl(Param);
426 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000427 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000428}
Douglas Gregor52473432008-12-24 02:52:09 +0000429
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000430/// \brief Adds a default argument to the given non-type template
431/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000432void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000433 SourceLocation EqualLoc,
434 ExprArg DefaultE) {
435 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000436 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000437 Expr *Default = static_cast<Expr *>(DefaultE.get());
438
439 // C++ [temp.param]p14:
440 // A template-parameter shall not be used in its own default argument.
441 // FIXME: Implement this check! Needs a recursive walk over the types.
442
443 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000444 TemplateArgument Converted;
445 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
446 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000447 TemplateParm->setInvalidDecl();
448 return;
449 }
450
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000451 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000452}
453
Douglas Gregor279272e2009-02-04 19:02:06 +0000454
455/// ActOnTemplateTemplateParameter - Called when a C++ template template
456/// parameter (e.g. T in template <template <typename> class T> class array)
457/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000458Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
459 SourceLocation TmpLoc,
460 TemplateParamsTy *Params,
461 IdentifierInfo *Name,
462 SourceLocation NameLoc,
463 unsigned Depth,
464 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000465{
466 assert(S->isTemplateParamScope() &&
467 "Template template parameter not in template parameter scope!");
468
469 // Construct the parameter object.
470 TemplateTemplateParmDecl *Param =
471 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
472 Position, Name,
473 (TemplateParameterList*)Params);
474
475 // Make sure the parameter is valid.
476 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
477 // do anything yet. However, if the template parameter list or (eventual)
478 // default value is ever invalidated, that will propagate here.
479 bool Invalid = false;
480 if (Invalid) {
481 Param->setInvalidDecl();
482 }
483
484 // If the tt-param has a name, then link the identifier into the scope
485 // and lookup mechanisms.
486 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000487 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000488 IdResolver.AddDecl(Param);
489 }
490
Chris Lattner5261d0c2009-03-28 19:18:32 +0000491 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000492}
493
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000494/// \brief Adds a default argument to the given template template
495/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000496void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000497 SourceLocation EqualLoc,
498 ExprArg DefaultE) {
499 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000500 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000501
502 // Since a template-template parameter's default argument is an
503 // id-expression, it must be a DeclRefExpr.
504 DeclRefExpr *Default
505 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
506
507 // C++ [temp.param]p14:
508 // A template-parameter shall not be used in its own default argument.
509 // FIXME: Implement this check! Needs a recursive walk over the types.
510
511 // Check the well-formedness of the template argument.
512 if (!isa<TemplateDecl>(Default->getDecl())) {
513 Diag(Default->getSourceRange().getBegin(),
514 diag::err_template_arg_must_be_template)
515 << Default->getSourceRange();
516 TemplateParm->setInvalidDecl();
517 return;
518 }
519 if (CheckTemplateArgument(TemplateParm, Default)) {
520 TemplateParm->setInvalidDecl();
521 return;
522 }
523
524 DefaultE.release();
525 TemplateParm->setDefaultArgument(Default);
526}
527
Douglas Gregor52473432008-12-24 02:52:09 +0000528/// ActOnTemplateParameterList - Builds a TemplateParameterList that
529/// contains the template parameters in Params/NumParams.
530Sema::TemplateParamsTy *
531Sema::ActOnTemplateParameterList(unsigned Depth,
532 SourceLocation ExportLoc,
533 SourceLocation TemplateLoc,
534 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000535 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000536 SourceLocation RAngleLoc) {
537 if (ExportLoc.isValid())
538 Diag(ExportLoc, diag::note_template_export_unsupported);
539
Douglas Gregord406b032009-02-06 22:42:48 +0000540 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
541 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000542}
Douglas Gregor279272e2009-02-04 19:02:06 +0000543
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000544Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +0000545Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregord406b032009-02-06 22:42:48 +0000546 SourceLocation KWLoc, const CXXScopeSpec &SS,
547 IdentifierInfo *Name, SourceLocation NameLoc,
548 AttributeList *Attr,
Douglas Gregore305ae32009-08-25 17:23:04 +0000549 TemplateParameterList *TemplateParams,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000550 AccessSpecifier AS) {
Douglas Gregore305ae32009-08-25 17:23:04 +0000551 assert(TemplateParams && TemplateParams->size() > 0 &&
552 "No template parameters");
John McCall069c23a2009-07-31 02:45:11 +0000553 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000554 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000555
556 // Check that we can declare a template here.
Douglas Gregore305ae32009-08-25 17:23:04 +0000557 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000558 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000559
560 TagDecl::TagKind Kind;
561 switch (TagSpec) {
562 default: assert(0 && "Unknown tag type!");
563 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
564 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
565 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
566 }
567
568 // There is no such thing as an unnamed class template.
569 if (!Name) {
570 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000571 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000572 }
573
574 // Find any previous declaration with this name.
Douglas Gregore305ae32009-08-25 17:23:04 +0000575 DeclContext *SemanticContext;
576 LookupResult Previous;
577 if (SS.isNotEmpty() && !SS.isInvalid()) {
578 SemanticContext = computeDeclContext(SS, true);
579 if (!SemanticContext) {
580 // FIXME: Produce a reasonable diagnostic here
581 return true;
582 }
583
584 Previous = LookupQualifiedName(SemanticContext, Name, LookupOrdinaryName,
585 true);
586 } else {
587 SemanticContext = CurContext;
588 Previous = LookupName(S, Name, LookupOrdinaryName, true);
589 }
590
Douglas Gregord406b032009-02-06 22:42:48 +0000591 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
592 NamedDecl *PrevDecl = 0;
593 if (Previous.begin() != Previous.end())
594 PrevDecl = *Previous.begin();
595
Douglas Gregore305ae32009-08-25 17:23:04 +0000596 if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregor23521802009-06-17 23:37:01 +0000597 PrevDecl = 0;
598
Douglas Gregord406b032009-02-06 22:42:48 +0000599 // If there is a previous declaration with the same name, check
600 // whether this is a valid redeclaration.
601 ClassTemplateDecl *PrevClassTemplate
602 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
603 if (PrevClassTemplate) {
604 // Ensure that the template parameter lists are compatible.
605 if (!TemplateParameterListsAreEqual(TemplateParams,
606 PrevClassTemplate->getTemplateParameters(),
607 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000608 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000609
610 // C++ [temp.class]p4:
611 // In a redeclaration, partial specialization, explicit
612 // specialization or explicit instantiation of a class template,
613 // the class-key shall agree in kind with the original class
614 // template declaration (7.1.5.3).
615 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000616 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000617 Diag(KWLoc, diag::err_use_with_wrong_tag)
618 << Name
619 << CodeModificationHint::CreateReplacement(KWLoc,
620 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000621 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000622 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000623 }
624
Douglas Gregord406b032009-02-06 22:42:48 +0000625 // Check for redefinition of this class template.
John McCall069c23a2009-07-31 02:45:11 +0000626 if (TUK == TUK_Definition) {
Douglas Gregord406b032009-02-06 22:42:48 +0000627 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
628 Diag(NameLoc, diag::err_redefinition) << Name;
629 Diag(Def->getLocation(), diag::note_previous_definition);
630 // FIXME: Would it make sense to try to "forget" the previous
631 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000632 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000633 }
634 }
635 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
636 // Maybe we will complain about the shadowed template parameter.
637 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
638 // Just pretend that we didn't see the previous declaration.
639 PrevDecl = 0;
640 } else if (PrevDecl) {
641 // C++ [temp]p5:
642 // A class template shall not have the same name as any other
643 // template, class, function, object, enumeration, enumerator,
644 // namespace, or type in the same scope (3.3), except as specified
645 // in (14.5.4).
646 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
647 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000648 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000649 }
650
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000651 // Check the template parameter list of this declaration, possibly
652 // merging in the template parameter list from the previous class
653 // template declaration.
654 if (CheckTemplateParameterList(TemplateParams,
655 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
656 Invalid = true;
657
Douglas Gregor9054f982009-05-10 22:57:19 +0000658 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000659 // declaration!
660
Douglas Gregor55216ac2009-03-26 00:10:35 +0000661 CXXRecordDecl *NewClass =
Douglas Gregor9060d0e2009-07-21 14:46:17 +0000662 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregord406b032009-02-06 22:42:48 +0000663 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000664 PrevClassTemplate->getTemplatedDecl() : 0,
665 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000666
667 ClassTemplateDecl *NewTemplate
668 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
669 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000670 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000671 NewClass->setDescribedClassTemplate(NewTemplate);
672
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000673 // Build the type for the class template declaration now.
674 QualType T =
675 Context.getTypeDeclType(NewClass,
676 PrevClassTemplate?
677 PrevClassTemplate->getTemplatedDecl() : 0);
678 assert(T->isDependentType() && "Class template type is not dependent?");
679 (void)T;
680
Anders Carlsson4ca43492009-03-26 01:24:28 +0000681 // Set the access specifier.
682 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
683
Douglas Gregord406b032009-02-06 22:42:48 +0000684 // Set the lexical context of these templates
685 NewClass->setLexicalDeclContext(CurContext);
686 NewTemplate->setLexicalDeclContext(CurContext);
687
John McCall069c23a2009-07-31 02:45:11 +0000688 if (TUK == TUK_Definition)
Douglas Gregord406b032009-02-06 22:42:48 +0000689 NewClass->startDefinition();
690
691 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000692 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000693
694 PushOnScopeChains(NewTemplate, S);
695
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000696 if (Invalid) {
697 NewTemplate->setInvalidDecl();
698 NewClass->setInvalidDecl();
699 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000700 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000701}
702
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000703/// \brief Checks the validity of a template parameter list, possibly
704/// considering the template parameter list from a previous
705/// declaration.
706///
707/// If an "old" template parameter list is provided, it must be
708/// equivalent (per TemplateParameterListsAreEqual) to the "new"
709/// template parameter list.
710///
711/// \param NewParams Template parameter list for a new template
712/// declaration. This template parameter list will be updated with any
713/// default arguments that are carried through from the previous
714/// template parameter list.
715///
716/// \param OldParams If provided, template parameter list from a
717/// previous declaration of the same template. Default template
718/// arguments will be merged from the old template parameter list to
719/// the new template parameter list.
720///
721/// \returns true if an error occurred, false otherwise.
722bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
723 TemplateParameterList *OldParams) {
724 bool Invalid = false;
725
726 // C++ [temp.param]p10:
727 // The set of default template-arguments available for use with a
728 // template declaration or definition is obtained by merging the
729 // default arguments from the definition (if in scope) and all
730 // declarations in scope in the same way default function
731 // arguments are (8.3.6).
732 bool SawDefaultArgument = false;
733 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000734
Anders Carlssonb1929502009-06-12 23:20:15 +0000735 bool SawParameterPack = false;
736 SourceLocation ParameterPackLoc;
737
Mike Stumpe0b7e032009-02-11 23:03:27 +0000738 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000739 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000740 if (OldParams)
741 OldParam = OldParams->begin();
742
743 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
744 NewParamEnd = NewParams->end();
745 NewParam != NewParamEnd; ++NewParam) {
746 // Variables used to diagnose redundant default arguments
747 bool RedundantDefaultArg = false;
748 SourceLocation OldDefaultLoc;
749 SourceLocation NewDefaultLoc;
750
751 // Variables used to diagnose missing default arguments
752 bool MissingDefaultArg = false;
753
Anders Carlssonb1929502009-06-12 23:20:15 +0000754 // C++0x [temp.param]p11:
755 // If a template parameter of a class template is a template parameter pack,
756 // it must be the last template parameter.
757 if (SawParameterPack) {
758 Diag(ParameterPackLoc,
759 diag::err_template_param_pack_must_be_last_template_parameter);
760 Invalid = true;
761 }
762
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000763 // Merge default arguments for template type parameters.
764 if (TemplateTypeParmDecl *NewTypeParm
765 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
766 TemplateTypeParmDecl *OldTypeParm
767 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
768
Anders Carlssonb1929502009-06-12 23:20:15 +0000769 if (NewTypeParm->isParameterPack()) {
770 assert(!NewTypeParm->hasDefaultArgument() &&
771 "Parameter packs can't have a default argument!");
772 SawParameterPack = true;
773 ParameterPackLoc = NewTypeParm->getLocation();
774 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000775 NewTypeParm->hasDefaultArgument()) {
776 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
777 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
778 SawDefaultArgument = true;
779 RedundantDefaultArg = true;
780 PreviousDefaultArgLoc = NewDefaultLoc;
781 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
782 // Merge the default argument from the old declaration to the
783 // new declaration.
784 SawDefaultArgument = true;
785 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
786 OldTypeParm->getDefaultArgumentLoc(),
787 true);
788 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
789 } else if (NewTypeParm->hasDefaultArgument()) {
790 SawDefaultArgument = true;
791 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
792 } else if (SawDefaultArgument)
793 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000794 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000795 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000796 // Merge default arguments for non-type template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000797 NonTypeTemplateParmDecl *OldNonTypeParm
798 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
799 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
800 NewNonTypeParm->hasDefaultArgument()) {
801 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
802 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
803 SawDefaultArgument = true;
804 RedundantDefaultArg = true;
805 PreviousDefaultArgLoc = NewDefaultLoc;
806 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
807 // Merge the default argument from the old declaration to the
808 // new declaration.
809 SawDefaultArgument = true;
810 // FIXME: We need to create a new kind of "default argument"
811 // expression that points to a previous template template
812 // parameter.
813 NewNonTypeParm->setDefaultArgument(
814 OldNonTypeParm->getDefaultArgument());
815 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
816 } else if (NewNonTypeParm->hasDefaultArgument()) {
817 SawDefaultArgument = true;
818 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
819 } else if (SawDefaultArgument)
820 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000821 } else {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000822 // Merge default arguments for template template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000823 TemplateTemplateParmDecl *NewTemplateParm
824 = cast<TemplateTemplateParmDecl>(*NewParam);
825 TemplateTemplateParmDecl *OldTemplateParm
826 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
827 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
828 NewTemplateParm->hasDefaultArgument()) {
829 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
830 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
831 SawDefaultArgument = true;
832 RedundantDefaultArg = true;
833 PreviousDefaultArgLoc = NewDefaultLoc;
834 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
835 // Merge the default argument from the old declaration to the
836 // new declaration.
837 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000838 // FIXME: We need to create a new kind of "default argument" expression
839 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000840 NewTemplateParm->setDefaultArgument(
841 OldTemplateParm->getDefaultArgument());
842 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
843 } else if (NewTemplateParm->hasDefaultArgument()) {
844 SawDefaultArgument = true;
845 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
846 } else if (SawDefaultArgument)
847 MissingDefaultArg = true;
848 }
849
850 if (RedundantDefaultArg) {
851 // C++ [temp.param]p12:
852 // A template-parameter shall not be given default arguments
853 // by two different declarations in the same scope.
854 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
855 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
856 Invalid = true;
857 } else if (MissingDefaultArg) {
858 // C++ [temp.param]p11:
859 // If a template-parameter has a default template-argument,
860 // all subsequent template-parameters shall have a default
861 // template-argument supplied.
862 Diag((*NewParam)->getLocation(),
863 diag::err_template_param_default_arg_missing);
864 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
865 Invalid = true;
866 }
867
868 // If we have an old template parameter list that we're merging
869 // in, move on to the next parameter.
870 if (OldParams)
871 ++OldParam;
872 }
873
874 return Invalid;
875}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000876
Douglas Gregorb462c322009-07-21 23:53:31 +0000877/// \brief Match the given template parameter lists to the given scope
878/// specifier, returning the template parameter list that applies to the
879/// name.
880///
881/// \param DeclStartLoc the start of the declaration that has a scope
882/// specifier or a template parameter list.
883///
884/// \param SS the scope specifier that will be matched to the given template
885/// parameter lists. This scope specifier precedes a qualified name that is
886/// being declared.
887///
888/// \param ParamLists the template parameter lists, from the outermost to the
889/// innermost template parameter lists.
890///
891/// \param NumParamLists the number of template parameter lists in ParamLists.
892///
893/// \returns the template parameter list, if any, that corresponds to the
894/// name that is preceded by the scope specifier @p SS. This template
895/// parameter list may be have template parameters (if we're declaring a
896/// template) or may have no template parameters (if we're declaring a
897/// template specialization), or may be NULL (if we were's declaring isn't
898/// itself a template).
899TemplateParameterList *
900Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
901 const CXXScopeSpec &SS,
902 TemplateParameterList **ParamLists,
903 unsigned NumParamLists) {
Douglas Gregorb462c322009-07-21 23:53:31 +0000904 // Find the template-ids that occur within the nested-name-specifier. These
905 // template-ids will match up with the template parameter lists.
906 llvm::SmallVector<const TemplateSpecializationType *, 4>
907 TemplateIdsInSpecifier;
908 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
909 NNS; NNS = NNS->getPrefix()) {
910 if (const TemplateSpecializationType *SpecType
911 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
912 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
913 if (!Template)
914 continue; // FIXME: should this be an error? probably...
915
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000916 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorb462c322009-07-21 23:53:31 +0000917 ClassTemplateSpecializationDecl *SpecDecl
918 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
919 // If the nested name specifier refers to an explicit specialization,
920 // we don't need a template<> header.
Douglas Gregor1930d202009-07-30 17:40:51 +0000921 // FIXME: revisit this approach once we cope with specialization
922 // properly.
Douglas Gregorb462c322009-07-21 23:53:31 +0000923 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
924 continue;
925 }
926
927 TemplateIdsInSpecifier.push_back(SpecType);
928 }
929 }
930
931 // Reverse the list of template-ids in the scope specifier, so that we can
932 // more easily match up the template-ids and the template parameter lists.
933 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
934
935 SourceLocation FirstTemplateLoc = DeclStartLoc;
936 if (NumParamLists)
937 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
938
939 // Match the template-ids found in the specifier to the template parameter
940 // lists.
941 unsigned Idx = 0;
942 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
943 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor1930d202009-07-30 17:40:51 +0000944 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
945 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorb462c322009-07-21 23:53:31 +0000946 if (Idx >= NumParamLists) {
947 // We have a template-id without a corresponding template parameter
948 // list.
949 if (DependentTemplateId) {
950 // FIXME: the location information here isn't great.
951 Diag(SS.getRange().getBegin(),
952 diag::err_template_spec_needs_template_parameters)
Douglas Gregor1930d202009-07-30 17:40:51 +0000953 << TemplateId
Douglas Gregorb462c322009-07-21 23:53:31 +0000954 << SS.getRange();
955 } else {
956 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
957 << SS.getRange()
958 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
959 "template<> ");
960 }
961 return 0;
962 }
963
964 // Check the template parameter list against its corresponding template-id.
Douglas Gregor1930d202009-07-30 17:40:51 +0000965 if (DependentTemplateId) {
966 TemplateDecl *Template
967 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
968
969 if (ClassTemplateDecl *ClassTemplate
970 = dyn_cast<ClassTemplateDecl>(Template)) {
971 TemplateParameterList *ExpectedTemplateParams = 0;
972 // Is this template-id naming the primary template?
973 if (Context.hasSameType(TemplateId,
974 ClassTemplate->getInjectedClassNameType(Context)))
975 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
976 // ... or a partial specialization?
977 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
978 = ClassTemplate->findPartialSpecialization(TemplateId))
979 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
980
981 if (ExpectedTemplateParams)
982 TemplateParameterListsAreEqual(ParamLists[Idx],
983 ExpectedTemplateParams,
984 true);
985 }
986 } else if (ParamLists[Idx]->size() > 0)
987 Diag(ParamLists[Idx]->getTemplateLoc(),
988 diag::err_template_param_list_matches_nontemplate)
989 << TemplateId
990 << ParamLists[Idx]->getSourceRange();
Douglas Gregorb462c322009-07-21 23:53:31 +0000991 }
992
993 // If there were at least as many template-ids as there were template
994 // parameter lists, then there are no template parameter lists remaining for
995 // the declaration itself.
996 if (Idx >= NumParamLists)
997 return 0;
998
999 // If there were too many template parameter lists, complain about that now.
1000 if (Idx != NumParamLists - 1) {
1001 while (Idx < NumParamLists - 1) {
1002 Diag(ParamLists[Idx]->getTemplateLoc(),
1003 diag::err_template_spec_extra_headers)
1004 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1005 ParamLists[Idx]->getRAngleLoc());
1006 ++Idx;
1007 }
1008 }
1009
1010 // Return the last template parameter list, which corresponds to the
1011 // entity being declared.
1012 return ParamLists[NumParamLists - 1];
1013}
1014
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001015/// \brief Translates template arguments as provided by the parser
1016/// into template arguments used by semantic analysis.
1017static void
1018translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1019 SourceLocation *TemplateArgLocs,
1020 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
1021 TemplateArgs.reserve(TemplateArgsIn.size());
1022
1023 void **Args = TemplateArgsIn.getArgs();
1024 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1025 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
1026 TemplateArgs.push_back(
1027 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001028 //FIXME: Preserve type source info.
1029 Sema::GetTypeFromParser(Args[Arg]))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001030 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
1031 }
1032}
1033
Douglas Gregordd13e842009-03-30 22:58:21 +00001034QualType Sema::CheckTemplateIdType(TemplateName Name,
1035 SourceLocation TemplateLoc,
1036 SourceLocation LAngleLoc,
1037 const TemplateArgument *TemplateArgs,
1038 unsigned NumTemplateArgs,
1039 SourceLocation RAngleLoc) {
1040 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +00001041 if (!Template) {
1042 // The template name does not resolve to a template, so we just
1043 // build a dependent template-id type.
Douglas Gregoraabb8502009-03-31 00:43:58 +00001044 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor4262bc92009-07-28 23:00:59 +00001045 NumTemplateArgs);
Douglas Gregoraabb8502009-03-31 00:43:58 +00001046 }
Douglas Gregordd13e842009-03-30 22:58:21 +00001047
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001048 // Check that the template argument list is well-formed for this
1049 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001050 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1051 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +00001052 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001053 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001054 false, Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001055 return QualType();
1056
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001057 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +00001058 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001059 "Converted template argument list is too short!");
1060
1061 QualType CanonType;
1062
Douglas Gregordd13e842009-03-30 22:58:21 +00001063 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001064 TemplateArgs,
1065 NumTemplateArgs)) {
1066 // This class template specialization is a dependent
1067 // type. Therefore, its canonical type is another class template
1068 // specialization type that contains all of the converted
1069 // arguments in canonical form. This ensures that, e.g., A<T> and
1070 // A<T, T> have identical types when A is declared as:
1071 //
1072 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +00001073 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1074 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001075 Converted.getFlatArguments(),
1076 Converted.flatSize());
Douglas Gregor4262bc92009-07-28 23:00:59 +00001077
1078 // FIXME: CanonType is not actually the canonical type, and unfortunately
1079 // it is a TemplateTypeSpecializationType that we will never use again.
1080 // In the future, we need to teach getTemplateSpecializationType to only
1081 // build the canonical type and return that to us.
1082 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +00001083 } else if (ClassTemplateDecl *ClassTemplate
1084 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001085 // Find the class template specialization declaration that
1086 // corresponds to these arguments.
1087 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00001088 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001089 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00001090 Converted.flatSize(),
1091 Context);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001092 void *InsertPos = 0;
1093 ClassTemplateSpecializationDecl *Decl
1094 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1095 if (!Decl) {
1096 // This is the first time we have referenced this class template
1097 // specialization. Create the canonical declaration and add it to
1098 // the set of specializations.
1099 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +00001100 ClassTemplate->getDeclContext(),
1101 TemplateLoc,
1102 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001103 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001104 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1105 Decl->setLexicalDeclContext(CurContext);
1106 }
1107
1108 CanonType = Context.getTypeDeclType(Decl);
1109 }
1110
1111 // Build the fully-sugared type for this class template
1112 // specialization, which refers back to the class template
1113 // specialization we created or found.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001114 //FIXME: Preserve type source info.
Douglas Gregordd13e842009-03-30 22:58:21 +00001115 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1116 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001117}
1118
Douglas Gregora08b6c72009-02-17 23:15:12 +00001119Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +00001120Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1121 SourceLocation LAngleLoc,
1122 ASTTemplateArgsPtr TemplateArgsIn,
1123 SourceLocation *TemplateArgLocs,
1124 SourceLocation RAngleLoc) {
1125 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001126
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001127 // Translate the parser's template argument list in our AST format.
1128 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1129 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001130
Douglas Gregordd13e842009-03-30 22:58:21 +00001131 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +00001132 TemplateArgs.data(),
1133 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +00001134 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001135 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +00001136
1137 if (Result.isNull())
1138 return true;
1139
Douglas Gregor6f37b582009-02-09 19:34:22 +00001140 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001141}
1142
Douglas Gregor28857752009-06-30 22:34:41 +00001143Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1144 SourceLocation TemplateNameLoc,
1145 SourceLocation LAngleLoc,
1146 const TemplateArgument *TemplateArgs,
1147 unsigned NumTemplateArgs,
1148 SourceLocation RAngleLoc) {
1149 // FIXME: Can we do any checking at this point? I guess we could check the
1150 // template arguments that we have against the template name, if the template
1151 // name refers to a single template. That's not a terribly common case,
1152 // though.
1153 return Owned(TemplateIdRefExpr::Create(Context,
1154 /*FIXME: New type?*/Context.OverloadTy,
1155 /*FIXME: Necessary?*/0,
1156 /*FIXME: Necessary?*/SourceRange(),
1157 Template, TemplateNameLoc, LAngleLoc,
1158 TemplateArgs,
1159 NumTemplateArgs, RAngleLoc));
1160}
1161
1162Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1163 SourceLocation TemplateNameLoc,
1164 SourceLocation LAngleLoc,
1165 ASTTemplateArgsPtr TemplateArgsIn,
1166 SourceLocation *TemplateArgLocs,
1167 SourceLocation RAngleLoc) {
1168 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1169
1170 // Translate the parser's template argument list in our AST format.
1171 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1172 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorf2fedc62009-07-22 20:55:49 +00001173 TemplateArgsIn.release();
Douglas Gregor28857752009-06-30 22:34:41 +00001174
1175 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1176 TemplateArgs.data(), TemplateArgs.size(),
1177 RAngleLoc);
1178}
1179
Douglas Gregord33e3282009-09-01 00:37:14 +00001180Sema::OwningExprResult
1181Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base,
1182 SourceLocation OpLoc,
1183 tok::TokenKind OpKind,
1184 const CXXScopeSpec &SS,
1185 TemplateTy TemplateD,
1186 SourceLocation TemplateNameLoc,
1187 SourceLocation LAngleLoc,
1188 ASTTemplateArgsPtr TemplateArgsIn,
1189 SourceLocation *TemplateArgLocs,
1190 SourceLocation RAngleLoc) {
1191 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1192
1193 // FIXME: We're going to end up looking up the template based on its name,
1194 // twice!
1195 DeclarationName Name;
1196 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
1197 Name = ActualTemplate->getDeclName();
1198 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
1199 Name = Ovl->getDeclName();
1200 else
1201 assert(false && "Cannot support dependent template names yet");
1202
1203 // Translate the parser's template argument list in our AST format.
1204 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1205 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1206 TemplateArgsIn.release();
1207
1208 // Do we have the save the actual template name? We might need it...
1209 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc,
1210 Name, true, LAngleLoc,
1211 TemplateArgs.data(), TemplateArgs.size(),
1212 RAngleLoc, DeclPtrTy(), &SS);
1213}
1214
Douglas Gregoraabb8502009-03-31 00:43:58 +00001215/// \brief Form a dependent template name.
1216///
1217/// This action forms a dependent template name given the template
1218/// name and its (presumably dependent) scope specifier. For
1219/// example, given "MetaFun::template apply", the scope specifier \p
1220/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1221/// of the "template" keyword, and "apply" is the \p Name.
1222Sema::TemplateTy
1223Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1224 const IdentifierInfo &Name,
1225 SourceLocation NameLoc,
Douglas Gregor681d31d2009-09-02 22:59:36 +00001226 const CXXScopeSpec &SS,
1227 TypeTy *ObjectType) {
1228 if ((ObjectType &&
1229 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1230 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregoraabb8502009-03-31 00:43:58 +00001231 // C++0x [temp.names]p5:
1232 // If a name prefixed by the keyword template is not the name of
1233 // a template, the program is ill-formed. [Note: the keyword
1234 // template may not be applied to non-template members of class
1235 // templates. -end note ] [ Note: as is the case with the
1236 // typename prefix, the template prefix is allowed in cases
1237 // where it is not strictly necessary; i.e., when the
1238 // nested-name-specifier or the expression on the left of the ->
1239 // or . is not dependent on a template-parameter, or the use
1240 // does not appear in the scope of a template. -end note]
1241 //
1242 // Note: C++03 was more strict here, because it banned the use of
1243 // the "template" keyword prior to a template-name that was not a
1244 // dependent name. C++ DR468 relaxed this requirement (the
1245 // "template" keyword is now permitted). We follow the C++0x
1246 // rules, even in C++03 mode, retroactively applying the DR.
1247 TemplateTy Template;
Douglas Gregor681d31d2009-09-02 22:59:36 +00001248 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType,
1249 false, Template);
Douglas Gregoraabb8502009-03-31 00:43:58 +00001250 if (TNK == TNK_Non_template) {
1251 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1252 << &Name;
1253 return TemplateTy();
1254 }
1255
1256 return Template;
1257 }
1258
Douglas Gregor681d31d2009-09-02 22:59:36 +00001259 // FIXME: We need to be able to create a dependent template name with just
1260 // an identifier, to handle the x->template f<T> case.
1261 assert(!ObjectType &&
1262 "Cannot handle dependent template names without a nested-name-specifier");
1263
1264 NestedNameSpecifier *Qualifier
1265 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregoraabb8502009-03-31 00:43:58 +00001266 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1267}
1268
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001269bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1270 const TemplateArgument &Arg,
1271 TemplateArgumentListBuilder &Converted) {
1272 // Check template type parameter.
1273 if (Arg.getKind() != TemplateArgument::Type) {
1274 // C++ [temp.arg.type]p1:
1275 // A template-argument for a template-parameter which is a
1276 // type shall be a type-id.
1277
1278 // We have a template type parameter but the template argument
1279 // is not a type.
1280 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1281 Diag(Param->getLocation(), diag::note_template_param_here);
1282
1283 return true;
1284 }
1285
1286 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1287 return true;
1288
1289 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001290 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001291 TemplateArgument(Arg.getLocation(),
1292 Context.getCanonicalType(Arg.getAsType())));
1293 return false;
1294}
1295
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001296/// \brief Check that the given template argument list is well-formed
1297/// for specializing the given template.
1298bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1299 SourceLocation TemplateLoc,
1300 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001301 const TemplateArgument *TemplateArgs,
1302 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001303 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001304 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001305 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001306 TemplateParameterList *Params = Template->getTemplateParameters();
1307 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001308 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001309 bool Invalid = false;
1310
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001311 bool HasParameterPack =
1312 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1313
1314 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001315 (NumArgs < Params->getMinRequiredArguments() &&
1316 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001317 // FIXME: point at either the first arg beyond what we can handle,
1318 // or the '>', depending on whether we have too many or too few
1319 // arguments.
1320 SourceRange Range;
1321 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001322 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001323 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1324 << (NumArgs > NumParams)
1325 << (isa<ClassTemplateDecl>(Template)? 0 :
1326 isa<FunctionTemplateDecl>(Template)? 1 :
1327 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1328 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001329 Diag(Template->getLocation(), diag::note_template_decl_here)
1330 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001331 Invalid = true;
1332 }
1333
1334 // C++ [temp.arg]p1:
1335 // [...] The type and form of each template-argument specified in
1336 // a template-id shall match the type and form specified for the
1337 // corresponding parameter declared by the template in its
1338 // template-parameter-list.
1339 unsigned ArgIdx = 0;
1340 for (TemplateParameterList::iterator Param = Params->begin(),
1341 ParamEnd = Params->end();
1342 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001343 if (ArgIdx > NumArgs && PartialTemplateArgs)
1344 break;
1345
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001346 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001347 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001348 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001349 // Retrieve the default template argument from the template
1350 // parameter.
1351 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001352 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001353 // We have an empty argument pack.
1354 Converted.BeginPack();
1355 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001356 break;
1357 }
1358
Douglas Gregorad964b32009-02-17 01:05:43 +00001359 if (!TTP->hasDefaultArgument())
1360 break;
1361
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001362 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001363
1364 // If the argument type is dependent, instantiate it now based
1365 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001366 if (ArgType->isDependentType()) {
1367 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001368 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001369 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001370 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001371
Anders Carlsson0233eb62009-06-05 04:47:51 +00001372 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001373 /*TakeArgs=*/false);
Douglas Gregor8dbd0382009-08-28 20:31:08 +00001374 ArgType = SubstType(ArgType,
1375 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall0ba26ee2009-08-25 22:02:44 +00001376 TTP->getDefaultArgumentLoc(),
1377 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001378 }
Douglas Gregor74296542009-02-27 19:31:52 +00001379
1380 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001381 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001382
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001383 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001384 } else if (NonTypeTemplateParmDecl *NTTP
1385 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1386 if (!NTTP->hasDefaultArgument())
1387 break;
1388
Anders Carlsson0297caf2009-06-11 16:06:49 +00001389 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001390 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001391 Converted.flatSize(),
1392 SourceRange(TemplateLoc, RAngleLoc));
1393
1394 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001395 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001396
Douglas Gregor8dbd0382009-08-28 20:31:08 +00001397 Sema::OwningExprResult E
1398 = SubstExpr(NTTP->getDefaultArgument(),
1399 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson0297caf2009-06-11 16:06:49 +00001400 if (E.isInvalid())
1401 return true;
1402
1403 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001404 } else {
1405 TemplateTemplateParmDecl *TempParm
1406 = cast<TemplateTemplateParmDecl>(*Param);
1407
1408 if (!TempParm->hasDefaultArgument())
1409 break;
1410
John McCall0ba26ee2009-08-25 22:02:44 +00001411 // FIXME: Subst default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001412 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001413 }
1414 } else {
1415 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001416 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001417 }
1418
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001419
1420 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001421 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001422 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001423 // Check all the remaining arguments (if any).
1424 for (; ArgIdx < NumArgs; ++ArgIdx) {
1425 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1426 Invalid = true;
1427 }
1428
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001429 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001430 } else {
1431 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1432 Invalid = true;
1433 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001434 } else if (NonTypeTemplateParmDecl *NTTP
1435 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1436 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001437
John McCall0ba26ee2009-08-25 22:02:44 +00001438 // Do substitution on the type of the non-type template parameter
1439 // with the template arguments we've seen thus far.
Douglas Gregored3a3982009-03-03 04:44:36 +00001440 QualType NTTPType = NTTP->getType();
1441 if (NTTPType->isDependentType()) {
John McCall0ba26ee2009-08-25 22:02:44 +00001442 // Do substitution on the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001443 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001444 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001445 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001446 SourceRange(TemplateLoc, RAngleLoc));
1447
Anders Carlsson0233eb62009-06-05 04:47:51 +00001448 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001449 /*TakeArgs=*/false);
Douglas Gregor01b7a1c2009-08-28 20:50:45 +00001450 NTTPType = SubstType(NTTPType,
1451 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall0ba26ee2009-08-25 22:02:44 +00001452 NTTP->getLocation(),
1453 NTTP->getDeclName());
Douglas Gregored3a3982009-03-03 04:44:36 +00001454 // If that worked, check the non-type template parameter type
1455 // for validity.
1456 if (!NTTPType.isNull())
1457 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1458 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001459 if (NTTPType.isNull()) {
1460 Invalid = true;
1461 break;
1462 }
1463 }
1464
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001465 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001466 case TemplateArgument::Null:
1467 assert(false && "Should never see a NULL template argument here");
1468 break;
1469
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001470 case TemplateArgument::Expression: {
1471 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001472 TemplateArgument Result;
1473 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001474 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001475 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001476 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001477 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001478 }
1479
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001480 case TemplateArgument::Declaration:
1481 case TemplateArgument::Integral:
1482 // We've already checked this template argument, so just copy
1483 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001484 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001485 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001486
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001487 case TemplateArgument::Type:
1488 // We have a non-type template parameter but the template
1489 // argument is a type.
1490
1491 // C++ [temp.arg]p2:
1492 // In a template-argument, an ambiguity between a type-id and
1493 // an expression is resolved to a type-id, regardless of the
1494 // form of the corresponding template-parameter.
1495 //
1496 // We warn specifically about this case, since it can be rather
1497 // confusing for users.
1498 if (Arg.getAsType()->isFunctionType())
1499 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1500 << Arg.getAsType();
1501 else
1502 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1503 Diag((*Param)->getLocation(), diag::note_template_param_here);
1504 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001505 break;
1506
1507 case TemplateArgument::Pack:
1508 assert(0 && "FIXME: Implement!");
1509 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001510 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001511 } else {
1512 // Check template template parameters.
1513 TemplateTemplateParmDecl *TempParm
1514 = cast<TemplateTemplateParmDecl>(*Param);
1515
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001516 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001517 case TemplateArgument::Null:
1518 assert(false && "Should never see a NULL template argument here");
1519 break;
1520
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001521 case TemplateArgument::Expression: {
1522 Expr *ArgExpr = Arg.getAsExpr();
1523 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1524 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1525 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1526 Invalid = true;
1527
1528 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001529 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001530 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001531 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001532 continue;
1533 }
1534 }
1535 // fall through
1536
1537 case TemplateArgument::Type: {
1538 // We have a template template parameter but the template
1539 // argument does not refer to a template.
1540 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1541 Invalid = true;
1542 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001543 }
1544
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001545 case TemplateArgument::Declaration:
1546 // We've already checked this template argument, so just copy
1547 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001548 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001549 break;
1550
1551 case TemplateArgument::Integral:
1552 assert(false && "Integral argument with template template parameter");
1553 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001554
1555 case TemplateArgument::Pack:
1556 assert(0 && "FIXME: Implement!");
1557 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001558 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001559 }
1560 }
1561
1562 return Invalid;
1563}
1564
1565/// \brief Check a template argument against its corresponding
1566/// template type parameter.
1567///
1568/// This routine implements the semantics of C++ [temp.arg.type]. It
1569/// returns true if an error occurred, and false otherwise.
1570bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1571 QualType Arg, SourceLocation ArgLoc) {
1572 // C++ [temp.arg.type]p2:
1573 // A local type, a type with no linkage, an unnamed type or a type
1574 // compounded from any of these types shall not be used as a
1575 // template-argument for a template type-parameter.
1576 //
1577 // FIXME: Perform the recursive and no-linkage type checks.
1578 const TagType *Tag = 0;
1579 if (const EnumType *EnumT = Arg->getAsEnumType())
1580 Tag = EnumT;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001581 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001582 Tag = RecordT;
1583 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1584 return Diag(ArgLoc, diag::err_template_arg_local_type)
1585 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001586 else if (Tag && !Tag->getDecl()->getDeclName() &&
1587 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001588 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1589 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1590 return true;
1591 }
1592
1593 return false;
1594}
1595
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001596/// \brief Checks whether the given template argument is the address
1597/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001598bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1599 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001600 bool Invalid = false;
1601
1602 // See through any implicit casts we added to fix the type.
1603 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1604 Arg = Cast->getSubExpr();
1605
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001606 // C++0x allows nullptr, and there's no further checking to be done for that.
1607 if (Arg->getType()->isNullPtrType())
1608 return false;
1609
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001610 // C++ [temp.arg.nontype]p1:
1611 //
1612 // A template-argument for a non-type, non-template
1613 // template-parameter shall be one of: [...]
1614 //
1615 // -- the address of an object or function with external
1616 // linkage, including function templates and function
1617 // template-ids but excluding non-static class members,
1618 // expressed as & id-expression where the & is optional if
1619 // the name refers to a function or array, or if the
1620 // corresponding template-parameter is a reference; or
1621 DeclRefExpr *DRE = 0;
1622
1623 // Ignore (and complain about) any excess parentheses.
1624 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1625 if (!Invalid) {
1626 Diag(Arg->getSourceRange().getBegin(),
1627 diag::err_template_arg_extra_parens)
1628 << Arg->getSourceRange();
1629 Invalid = true;
1630 }
1631
1632 Arg = Parens->getSubExpr();
1633 }
1634
1635 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1636 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1637 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1638 } else
1639 DRE = dyn_cast<DeclRefExpr>(Arg);
1640
1641 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1642 return Diag(Arg->getSourceRange().getBegin(),
1643 diag::err_template_arg_not_object_or_func_form)
1644 << Arg->getSourceRange();
1645
1646 // Cannot refer to non-static data members
1647 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1648 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1649 << Field << Arg->getSourceRange();
1650
1651 // Cannot refer to non-static member functions
1652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1653 if (!Method->isStatic())
1654 return Diag(Arg->getSourceRange().getBegin(),
1655 diag::err_template_arg_method)
1656 << Method << Arg->getSourceRange();
1657
1658 // Functions must have external linkage.
1659 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1660 if (Func->getStorageClass() == FunctionDecl::Static) {
1661 Diag(Arg->getSourceRange().getBegin(),
1662 diag::err_template_arg_function_not_extern)
1663 << Func << Arg->getSourceRange();
1664 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1665 << true;
1666 return true;
1667 }
1668
1669 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001670 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001671 return Invalid;
1672 }
1673
1674 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1675 if (!Var->hasGlobalStorage()) {
1676 Diag(Arg->getSourceRange().getBegin(),
1677 diag::err_template_arg_object_not_extern)
1678 << Var << Arg->getSourceRange();
1679 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1680 << true;
1681 return true;
1682 }
1683
1684 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001685 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001686 return Invalid;
1687 }
1688
1689 // We found something else, but we don't know specifically what it is.
1690 Diag(Arg->getSourceRange().getBegin(),
1691 diag::err_template_arg_not_object_or_func)
1692 << Arg->getSourceRange();
1693 Diag(DRE->getDecl()->getLocation(),
1694 diag::note_template_arg_refers_here);
1695 return true;
1696}
1697
1698/// \brief Checks whether the given template argument is a pointer to
1699/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001700bool
1701Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001702 bool Invalid = false;
1703
1704 // See through any implicit casts we added to fix the type.
1705 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1706 Arg = Cast->getSubExpr();
1707
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001708 // C++0x allows nullptr, and there's no further checking to be done for that.
1709 if (Arg->getType()->isNullPtrType())
1710 return false;
1711
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001712 // C++ [temp.arg.nontype]p1:
1713 //
1714 // A template-argument for a non-type, non-template
1715 // template-parameter shall be one of: [...]
1716 //
1717 // -- a pointer to member expressed as described in 5.3.1.
1718 QualifiedDeclRefExpr *DRE = 0;
1719
1720 // Ignore (and complain about) any excess parentheses.
1721 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1722 if (!Invalid) {
1723 Diag(Arg->getSourceRange().getBegin(),
1724 diag::err_template_arg_extra_parens)
1725 << Arg->getSourceRange();
1726 Invalid = true;
1727 }
1728
1729 Arg = Parens->getSubExpr();
1730 }
1731
1732 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1733 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1734 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1735
1736 if (!DRE)
1737 return Diag(Arg->getSourceRange().getBegin(),
1738 diag::err_template_arg_not_pointer_to_member_form)
1739 << Arg->getSourceRange();
1740
1741 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1742 assert((isa<FieldDecl>(DRE->getDecl()) ||
1743 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1744 "Only non-static member pointers can make it here");
1745
1746 // Okay: this is the address of a non-static member, and therefore
1747 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001748 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001749 return Invalid;
1750 }
1751
1752 // We found something else, but we don't know specifically what it is.
1753 Diag(Arg->getSourceRange().getBegin(),
1754 diag::err_template_arg_not_pointer_to_member_form)
1755 << Arg->getSourceRange();
1756 Diag(DRE->getDecl()->getLocation(),
1757 diag::note_template_arg_refers_here);
1758 return true;
1759}
1760
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001761/// \brief Check a template argument against its corresponding
1762/// non-type template parameter.
1763///
Douglas Gregored3a3982009-03-03 04:44:36 +00001764/// This routine implements the semantics of C++ [temp.arg.nontype].
1765/// It returns true if an error occurred, and false otherwise. \p
1766/// InstantiatedParamType is the type of the non-type template
1767/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001768///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001769/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001770bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001771 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001772 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001773 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1774
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001775 // If either the parameter has a dependent type or the argument is
1776 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001777 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001778 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1779 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001780 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001781 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001782 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001783
1784 // C++ [temp.arg.nontype]p5:
1785 // The following conversions are performed on each expression used
1786 // as a non-type template-argument. If a non-type
1787 // template-argument cannot be converted to the type of the
1788 // corresponding template-parameter then the program is
1789 // ill-formed.
1790 //
1791 // -- for a non-type template-parameter of integral or
1792 // enumeration type, integral promotions (4.5) and integral
1793 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001794 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001795 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001796 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001797 // C++ [temp.arg.nontype]p1:
1798 // A template-argument for a non-type, non-template
1799 // template-parameter shall be one of:
1800 //
1801 // -- an integral constant-expression of integral or enumeration
1802 // type; or
1803 // -- the name of a non-type template-parameter; or
1804 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001805 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001806 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1807 Diag(Arg->getSourceRange().getBegin(),
1808 diag::err_template_arg_not_integral_or_enumeral)
1809 << ArgType << Arg->getSourceRange();
1810 Diag(Param->getLocation(), diag::note_template_param_here);
1811 return true;
1812 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001813 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001814 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1815 << ArgType << Arg->getSourceRange();
1816 return true;
1817 }
1818
1819 // FIXME: We need some way to more easily get the unqualified form
1820 // of the types without going all the way to the
1821 // canonical type.
1822 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1823 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1824 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1825 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1826
1827 // Try to convert the argument to the parameter's type.
1828 if (ParamType == ArgType) {
1829 // Okay: no conversion necessary
1830 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1831 !ParamType->isEnumeralType()) {
1832 // This is an integral promotion or conversion.
1833 ImpCastExprToType(Arg, ParamType);
1834 } else {
1835 // We can't perform this conversion.
1836 Diag(Arg->getSourceRange().getBegin(),
1837 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001838 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001839 Diag(Param->getLocation(), diag::note_template_param_here);
1840 return true;
1841 }
1842
Douglas Gregorafc86942009-03-14 00:20:21 +00001843 QualType IntegerType = Context.getCanonicalType(ParamType);
1844 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001845 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001846
1847 if (!Arg->isValueDependent()) {
1848 // Check that an unsigned parameter does not receive a negative
1849 // value.
1850 if (IntegerType->isUnsignedIntegerType()
1851 && (Value.isSigned() && Value.isNegative())) {
1852 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1853 << Value.toString(10) << Param->getType()
1854 << Arg->getSourceRange();
1855 Diag(Param->getLocation(), diag::note_template_param_here);
1856 return true;
1857 }
1858
1859 // Check that we don't overflow the template parameter type.
1860 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1861 if (Value.getActiveBits() > AllowedBits) {
1862 Diag(Arg->getSourceRange().getBegin(),
1863 diag::err_template_arg_too_large)
1864 << Value.toString(10) << Param->getType()
1865 << Arg->getSourceRange();
1866 Diag(Param->getLocation(), diag::note_template_param_here);
1867 return true;
1868 }
1869
1870 if (Value.getBitWidth() != AllowedBits)
1871 Value.extOrTrunc(AllowedBits);
1872 Value.setIsSigned(IntegerType->isSignedIntegerType());
1873 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001874
Douglas Gregor8f378a92009-06-11 18:10:32 +00001875 // Add the value of this argument to the list of converted
1876 // arguments. We use the bitwidth and signedness of the template
1877 // parameter.
1878 if (Arg->isValueDependent()) {
1879 // The argument is value-dependent. Create a new
1880 // TemplateArgument with the converted expression.
1881 Converted = TemplateArgument(Arg);
1882 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001883 }
1884
Douglas Gregor8f378a92009-06-11 18:10:32 +00001885 Converted = TemplateArgument(StartLoc, Value,
1886 ParamType->isEnumeralType() ? ParamType
1887 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001888 return false;
1889 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001890
Douglas Gregor3f411962009-02-11 01:18:59 +00001891 // Handle pointer-to-function, reference-to-function, and
1892 // pointer-to-member-function all in (roughly) the same way.
1893 if (// -- For a non-type template-parameter of type pointer to
1894 // function, only the function-to-pointer conversion (4.3) is
1895 // applied. If the template-argument represents a set of
1896 // overloaded functions (or a pointer to such), the matching
1897 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001898 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001899 (ParamType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001900 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001901 // -- For a non-type template-parameter of type reference to
1902 // function, no conversions apply. If the template-argument
1903 // represents a set of overloaded functions, the matching
1904 // function is selected from the set (13.4).
1905 (ParamType->isReferenceType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001906 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001907 // -- For a non-type template-parameter of type pointer to
1908 // member function, no conversions apply. If the
1909 // template-argument represents a set of overloaded member
1910 // functions, the matching member function is selected from
1911 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001912 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001913 (ParamType->isMemberPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001914 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001915 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001916 if (Context.hasSameUnqualifiedType(ArgType,
1917 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001918 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001919 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1920 ParamType->isMemberPointerType())) {
1921 ArgType = ParamType;
1922 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001923 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001924 ArgType = Context.getPointerType(ArgType);
1925 ImpCastExprToType(Arg, ArgType);
1926 } else if (FunctionDecl *Fn
1927 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001928 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1929 return true;
1930
Douglas Gregor2eedd992009-02-11 00:19:33 +00001931 FixOverloadedFunctionReference(Arg, Fn);
1932 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001933 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001934 ArgType = Context.getPointerType(Arg->getType());
1935 ImpCastExprToType(Arg, ArgType);
1936 }
1937 }
1938
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001939 if (!Context.hasSameUnqualifiedType(ArgType,
1940 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001941 // We can't perform this conversion.
1942 Diag(Arg->getSourceRange().getBegin(),
1943 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001944 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001945 Diag(Param->getLocation(), diag::note_template_param_here);
1946 return true;
1947 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001948
Douglas Gregorad964b32009-02-17 01:05:43 +00001949 if (ParamType->isMemberPointerType()) {
1950 NamedDecl *Member = 0;
1951 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1952 return true;
1953
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001954 if (Member)
1955 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001956 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001957 return false;
1958 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001959
Douglas Gregorad964b32009-02-17 01:05:43 +00001960 NamedDecl *Entity = 0;
1961 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1962 return true;
1963
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001964 if (Entity)
1965 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001966 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001967 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001968 }
1969
Chris Lattner320dff22009-02-20 21:37:53 +00001970 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001971 // -- for a non-type template-parameter of type pointer to
1972 // object, qualification conversions (4.4) and the
1973 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001974 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001975 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001976 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001977
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001978 if (ArgType->isNullPtrType()) {
1979 ArgType = ParamType;
1980 ImpCastExprToType(Arg, ParamType);
1981 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001982 ArgType = Context.getArrayDecayedType(ArgType);
1983 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001984 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001985
Douglas Gregor3f411962009-02-11 01:18:59 +00001986 if (IsQualificationConversion(ArgType, ParamType)) {
1987 ArgType = ParamType;
1988 ImpCastExprToType(Arg, ParamType);
1989 }
1990
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001991 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001992 // We can't perform this conversion.
1993 Diag(Arg->getSourceRange().getBegin(),
1994 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001995 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001996 Diag(Param->getLocation(), diag::note_template_param_here);
1997 return true;
1998 }
1999
Douglas Gregorad964b32009-02-17 01:05:43 +00002000 NamedDecl *Entity = 0;
2001 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2002 return true;
2003
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00002004 if (Entity)
2005 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00002006 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00002007 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00002008 }
Douglas Gregor3f411962009-02-11 01:18:59 +00002009
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002010 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00002011 // -- For a non-type template-parameter of type reference to
2012 // object, no conversions apply. The type referred to by the
2013 // reference may be more cv-qualified than the (otherwise
2014 // identical) type of the template-argument. The
2015 // template-parameter is bound directly to the
2016 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00002017 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00002018 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00002019
Douglas Gregor0ea4e302009-02-11 18:22:40 +00002020 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00002021 Diag(Arg->getSourceRange().getBegin(),
2022 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00002023 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00002024 << Arg->getSourceRange();
2025 Diag(Param->getLocation(), diag::note_template_param_here);
2026 return true;
2027 }
2028
2029 unsigned ParamQuals
2030 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2031 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
2032
2033 if ((ParamQuals | ArgQuals) != ParamQuals) {
2034 Diag(Arg->getSourceRange().getBegin(),
2035 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00002036 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00002037 << Arg->getSourceRange();
2038 Diag(Param->getLocation(), diag::note_template_param_here);
2039 return true;
2040 }
2041
Douglas Gregorad964b32009-02-17 01:05:43 +00002042 NamedDecl *Entity = 0;
2043 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2044 return true;
2045
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00002046 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00002047 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00002048 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00002049 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00002050
2051 // -- For a non-type template-parameter of type pointer to data
2052 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00002053 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00002054 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2055
Douglas Gregor0ea4e302009-02-11 18:22:40 +00002056 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00002057 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00002058 } else if (ArgType->isNullPtrType()) {
2059 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00002060 } else if (IsQualificationConversion(ArgType, ParamType)) {
2061 ImpCastExprToType(Arg, ParamType);
2062 } else {
2063 // We can't perform this conversion.
2064 Diag(Arg->getSourceRange().getBegin(),
2065 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00002066 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00002067 Diag(Param->getLocation(), diag::note_template_param_here);
2068 return true;
2069 }
2070
Douglas Gregorad964b32009-02-17 01:05:43 +00002071 NamedDecl *Member = 0;
2072 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2073 return true;
2074
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00002075 if (Member)
2076 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00002077 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00002078 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00002079}
2080
2081/// \brief Check a template argument against its corresponding
2082/// template template parameter.
2083///
2084/// This routine implements the semantics of C++ [temp.arg.template].
2085/// It returns true if an error occurred, and false otherwise.
2086bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2087 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002088 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2089 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2090
2091 // C++ [temp.arg.template]p1:
2092 // A template-argument for a template template-parameter shall be
2093 // the name of a class template, expressed as id-expression. Only
2094 // primary class templates are considered when matching the
2095 // template template argument with the corresponding parameter;
2096 // partial specializations are not considered even if their
2097 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002098 //
2099 // Note that we also allow template template parameters here, which
2100 // will happen when we are dealing with, e.g., class template
2101 // partial specializations.
2102 if (!isa<ClassTemplateDecl>(Template) &&
2103 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002104 assert(isa<FunctionTemplateDecl>(Template) &&
2105 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002106 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2107 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00002108 << Template;
2109 }
2110
2111 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2112 Param->getTemplateParameters(),
2113 true, true,
2114 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00002115}
2116
Douglas Gregord406b032009-02-06 22:42:48 +00002117/// \brief Determine whether the given template parameter lists are
2118/// equivalent.
2119///
2120/// \param New The new template parameter list, typically written in the
2121/// source code as part of a new template declaration.
2122///
2123/// \param Old The old template parameter list, typically found via
2124/// name lookup of the template declared with this template parameter
2125/// list.
2126///
2127/// \param Complain If true, this routine will produce a diagnostic if
2128/// the template parameter lists are not equivalent.
2129///
Douglas Gregore8e367f2009-02-10 00:24:35 +00002130/// \param IsTemplateTemplateParm If true, this routine is being
2131/// called to compare the template parameter lists of a template
2132/// template parameter.
2133///
2134/// \param TemplateArgLoc If this source location is valid, then we
2135/// are actually checking the template parameter list of a template
2136/// argument (New) against the template parameter list of its
2137/// corresponding template template parameter (Old). We produce
2138/// slightly different diagnostics in this scenario.
2139///
Douglas Gregord406b032009-02-06 22:42:48 +00002140/// \returns True if the template parameter lists are equal, false
2141/// otherwise.
2142bool
2143Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2144 TemplateParameterList *Old,
2145 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002146 bool IsTemplateTemplateParm,
2147 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00002148 if (Old->size() != New->size()) {
2149 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002150 unsigned NextDiag = diag::err_template_param_list_different_arity;
2151 if (TemplateArgLoc.isValid()) {
2152 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2153 NextDiag = diag::note_template_param_list_different_arity;
2154 }
2155 Diag(New->getTemplateLoc(), NextDiag)
2156 << (New->size() > Old->size())
2157 << IsTemplateTemplateParm
2158 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00002159 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2160 << IsTemplateTemplateParm
2161 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2162 }
2163
2164 return false;
2165 }
2166
2167 for (TemplateParameterList::iterator OldParm = Old->begin(),
2168 OldParmEnd = Old->end(), NewParm = New->begin();
2169 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2170 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00002171 if (Complain) {
2172 unsigned NextDiag = diag::err_template_param_different_kind;
2173 if (TemplateArgLoc.isValid()) {
2174 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2175 NextDiag = diag::note_template_param_different_kind;
2176 }
2177 Diag((*NewParm)->getLocation(), NextDiag)
2178 << IsTemplateTemplateParm;
2179 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2180 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00002181 }
Douglas Gregord406b032009-02-06 22:42:48 +00002182 return false;
2183 }
2184
2185 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2186 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00002187 // know we're at the same index).
2188#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00002189 // FIXME: Enable this code in debug mode *after* we properly go through
2190 // and "instantiate" the template parameter lists of template template
2191 // parameters. It's only after this instantiation that (1) any dependent
2192 // types within the template parameter list of the template template
2193 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00002194 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00002195 QualType OldParmType
2196 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2197 QualType NewParmType
2198 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2199 assert(Context.getCanonicalType(OldParmType) ==
2200 Context.getCanonicalType(NewParmType) &&
2201 "type parameter mismatch?");
2202#endif
2203 } else if (NonTypeTemplateParmDecl *OldNTTP
2204 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2205 // The types of non-type template parameters must agree.
2206 NonTypeTemplateParmDecl *NewNTTP
2207 = cast<NonTypeTemplateParmDecl>(*NewParm);
2208 if (Context.getCanonicalType(OldNTTP->getType()) !=
2209 Context.getCanonicalType(NewNTTP->getType())) {
2210 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002211 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2212 if (TemplateArgLoc.isValid()) {
2213 Diag(TemplateArgLoc,
2214 diag::err_template_arg_template_params_mismatch);
2215 NextDiag = diag::note_template_nontype_parm_different_type;
2216 }
2217 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002218 << NewNTTP->getType()
2219 << IsTemplateTemplateParm;
2220 Diag(OldNTTP->getLocation(),
2221 diag::note_template_nontype_parm_prev_declaration)
2222 << OldNTTP->getType();
2223 }
2224 return false;
2225 }
2226 } else {
2227 // The template parameter lists of template template
2228 // parameters must agree.
2229 // FIXME: Could we perform a faster "type" comparison here?
2230 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2231 "Only template template parameters handled here");
2232 TemplateTemplateParmDecl *OldTTP
2233 = cast<TemplateTemplateParmDecl>(*OldParm);
2234 TemplateTemplateParmDecl *NewTTP
2235 = cast<TemplateTemplateParmDecl>(*NewParm);
2236 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2237 OldTTP->getTemplateParameters(),
2238 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002239 /*IsTemplateTemplateParm=*/true,
2240 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002241 return false;
2242 }
2243 }
2244
2245 return true;
2246}
2247
2248/// \brief Check whether a template can be declared within this scope.
2249///
2250/// If the template declaration is valid in this scope, returns
2251/// false. Otherwise, issues a diagnostic and returns true.
2252bool
Douglas Gregore305ae32009-08-25 17:23:04 +00002253Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregord406b032009-02-06 22:42:48 +00002254 // Find the nearest enclosing declaration scope.
2255 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2256 (S->getFlags() & Scope::TemplateParamScope) != 0)
2257 S = S->getParent();
2258
Douglas Gregord406b032009-02-06 22:42:48 +00002259 // C++ [temp]p2:
2260 // A template-declaration can appear only as a namespace scope or
2261 // class scope declaration.
2262 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandda81522009-07-31 01:43:05 +00002263 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2264 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Douglas Gregore305ae32009-08-25 17:23:04 +00002265 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
2266 << TemplateParams->getSourceRange();
Eli Friedmandda81522009-07-31 01:43:05 +00002267
2268 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregord406b032009-02-06 22:42:48 +00002269 Ctx = Ctx->getParent();
Douglas Gregord406b032009-02-06 22:42:48 +00002270
2271 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2272 return false;
2273
Douglas Gregore305ae32009-08-25 17:23:04 +00002274 return Diag(TemplateParams->getTemplateLoc(),
2275 diag::err_template_outside_namespace_or_class_scope)
2276 << TemplateParams->getSourceRange();
Douglas Gregord406b032009-02-06 22:42:48 +00002277}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002278
Douglas Gregor90177912009-05-13 18:28:20 +00002279/// \brief Check whether a class template specialization or explicit
2280/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002281///
Douglas Gregor90177912009-05-13 18:28:20 +00002282/// This routine determines whether a class template specialization or
2283/// explicit instantiation can be declared in the current context
2284/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2285/// appropriate diagnostics if there was an error. It returns true if
2286// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002287bool
2288Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2289 ClassTemplateSpecializationDecl *PrevDecl,
2290 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002291 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002292 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002293 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002294 // C++ [temp.expl.spec]p2:
2295 // An explicit specialization shall be declared in the namespace
2296 // of which the template is a member, or, for member templates, in
2297 // the namespace of which the enclosing class or enclosing class
2298 // template is a member. An explicit specialization of a member
2299 // function, member class or static data member of a class
2300 // template shall be declared in the namespace of which the class
2301 // template is a member. Such a declaration may also be a
2302 // definition. If the declaration is not a definition, the
2303 // specialization may be defined later in the name- space in which
2304 // the explicit specialization was declared, or in a namespace
2305 // that encloses the one in which the explicit specialization was
2306 // declared.
2307 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002308 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002309 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002310 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002311 return true;
2312 }
2313
2314 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2315 DeclContext *TemplateContext
2316 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002317 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2318 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002319 // There is no prior declaration of this entity, so this
2320 // specialization must be in the same context as the template
2321 // itself.
2322 if (DC != TemplateContext) {
2323 if (isa<TranslationUnitDecl>(TemplateContext))
2324 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002325 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002326 << ClassTemplate << ScopeSpecifierRange;
2327 else if (isa<NamespaceDecl>(TemplateContext))
2328 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002329 << PartialSpecialization << ClassTemplate
2330 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002331
2332 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2333 }
2334
2335 return false;
2336 }
2337
2338 // We have a previous declaration of this entity. Make sure that
2339 // this redeclaration (or definition) occurs in an enclosing namespace.
2340 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002341 // FIXME: In C++98, we would like to turn these errors into warnings,
2342 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002343 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002344 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002345 if (isa<TranslationUnitDecl>(TemplateContext)) {
2346 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2347 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002348 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002349 else
2350 SuppressedDiag = true;
2351 } else if (isa<NamespaceDecl>(TemplateContext)) {
2352 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2353 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002354 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002355 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2356 else
2357 SuppressedDiag = true;
2358 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002359
Douglas Gregor90177912009-05-13 18:28:20 +00002360 if (!SuppressedDiag)
2361 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002362 }
2363
2364 return false;
2365}
2366
Douglas Gregor76e79952009-06-12 21:21:02 +00002367/// \brief Check the non-type template arguments of a class template
2368/// partial specialization according to C++ [temp.class.spec]p9.
2369///
Douglas Gregor42476442009-06-12 22:08:06 +00002370/// \param TemplateParams the template parameters of the primary class
2371/// template.
2372///
2373/// \param TemplateArg the template arguments of the class template
2374/// partial specialization.
2375///
2376/// \param MirrorsPrimaryTemplate will be set true if the class
2377/// template partial specialization arguments are identical to the
2378/// implicit template arguments of the primary template. This is not
2379/// necessarily an error (C++0x), and it is left to the caller to diagnose
2380/// this condition when it is an error.
2381///
Douglas Gregor76e79952009-06-12 21:21:02 +00002382/// \returns true if there was an error, false otherwise.
2383bool Sema::CheckClassTemplatePartialSpecializationArgs(
2384 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002385 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002386 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002387 // FIXME: the interface to this function will have to change to
2388 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002389 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002390
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002391 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002392
Douglas Gregor76e79952009-06-12 21:21:02 +00002393 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002394 // Determine whether the template argument list of the partial
2395 // specialization is identical to the implicit argument list of
2396 // the primary template. The caller may need to diagnostic this as
2397 // an error per C++ [temp.class.spec]p9b3.
2398 if (MirrorsPrimaryTemplate) {
2399 if (TemplateTypeParmDecl *TTP
2400 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2401 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002402 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002403 MirrorsPrimaryTemplate = false;
2404 } else if (TemplateTemplateParmDecl *TTP
2405 = dyn_cast<TemplateTemplateParmDecl>(
2406 TemplateParams->getParam(I))) {
2407 // FIXME: We should settle on either Declaration storage or
2408 // Expression storage for template template parameters.
2409 TemplateTemplateParmDecl *ArgDecl
2410 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002411 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002412 if (!ArgDecl)
2413 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002414 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002415 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2416
2417 if (!ArgDecl ||
2418 ArgDecl->getIndex() != TTP->getIndex() ||
2419 ArgDecl->getDepth() != TTP->getDepth())
2420 MirrorsPrimaryTemplate = false;
2421 }
2422 }
2423
Douglas Gregor76e79952009-06-12 21:21:02 +00002424 NonTypeTemplateParmDecl *Param
2425 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002426 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002427 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002428 }
2429
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002430 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002431 if (!ArgExpr) {
2432 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002433 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002434 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002435
2436 // C++ [temp.class.spec]p8:
2437 // A non-type argument is non-specialized if it is the name of a
2438 // non-type parameter. All other non-type arguments are
2439 // specialized.
2440 //
2441 // Below, we check the two conditions that only apply to
2442 // specialized non-type arguments, so skip any non-specialized
2443 // arguments.
2444 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002445 if (NonTypeTemplateParmDecl *NTTP
2446 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2447 if (MirrorsPrimaryTemplate &&
2448 (Param->getIndex() != NTTP->getIndex() ||
2449 Param->getDepth() != NTTP->getDepth()))
2450 MirrorsPrimaryTemplate = false;
2451
Douglas Gregor76e79952009-06-12 21:21:02 +00002452 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002453 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002454
2455 // C++ [temp.class.spec]p9:
2456 // Within the argument list of a class template partial
2457 // specialization, the following restrictions apply:
2458 // -- A partially specialized non-type argument expression
2459 // shall not involve a template parameter of the partial
2460 // specialization except when the argument expression is a
2461 // simple identifier.
2462 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2463 Diag(ArgExpr->getLocStart(),
2464 diag::err_dependent_non_type_arg_in_partial_spec)
2465 << ArgExpr->getSourceRange();
2466 return true;
2467 }
2468
2469 // -- The type of a template parameter corresponding to a
2470 // specialized non-type argument shall not be dependent on a
2471 // parameter of the specialization.
2472 if (Param->getType()->isDependentType()) {
2473 Diag(ArgExpr->getLocStart(),
2474 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2475 << Param->getType()
2476 << ArgExpr->getSourceRange();
2477 Diag(Param->getLocation(), diag::note_template_param_here);
2478 return true;
2479 }
Douglas Gregor42476442009-06-12 22:08:06 +00002480
2481 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002482 }
2483
2484 return false;
2485}
2486
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002487Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +00002488Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2489 TagUseKind TUK,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002490 SourceLocation KWLoc,
2491 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002492 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002493 SourceLocation TemplateNameLoc,
2494 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002495 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002496 SourceLocation *TemplateArgLocs,
2497 SourceLocation RAngleLoc,
2498 AttributeList *Attr,
2499 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002500 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002501 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002502 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002503 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002504
Douglas Gregor58944ac2009-05-31 09:31:02 +00002505 bool isPartialSpecialization = false;
2506
Douglas Gregor0d93f692009-02-25 22:02:03 +00002507 // Check the validity of the template headers that introduce this
2508 // template.
Douglas Gregore305ae32009-08-25 17:23:04 +00002509 TemplateParameterList *TemplateParams
2510 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2511 (TemplateParameterList**)TemplateParameterLists.get(),
2512 TemplateParameterLists.size());
2513 if (TemplateParams && TemplateParams->size() > 0) {
2514 isPartialSpecialization = true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002515
Douglas Gregore305ae32009-08-25 17:23:04 +00002516 // C++ [temp.class.spec]p10:
2517 // The template parameter list of a specialization shall not
2518 // contain default template argument values.
2519 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2520 Decl *Param = TemplateParams->getParam(I);
2521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2522 if (TTP->hasDefaultArgument()) {
2523 Diag(TTP->getDefaultArgumentLoc(),
2524 diag::err_default_arg_in_partial_spec);
2525 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2526 }
2527 } else if (NonTypeTemplateParmDecl *NTTP
2528 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2529 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2530 Diag(NTTP->getDefaultArgumentLoc(),
2531 diag::err_default_arg_in_partial_spec)
2532 << DefArg->getSourceRange();
2533 NTTP->setDefaultArgument(0);
2534 DefArg->Destroy(Context);
2535 }
2536 } else {
2537 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2538 if (Expr *DefArg = TTP->getDefaultArgument()) {
2539 Diag(TTP->getDefaultArgumentLoc(),
2540 diag::err_default_arg_in_partial_spec)
2541 << DefArg->getSourceRange();
2542 TTP->setDefaultArgument(0);
2543 DefArg->Destroy(Context);
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002544 }
2545 }
2546 }
Douglas Gregore305ae32009-08-25 17:23:04 +00002547 } else if (!TemplateParams)
2548 Diag(KWLoc, diag::err_template_spec_needs_header)
2549 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor0d93f692009-02-25 22:02:03 +00002550
Douglas Gregora08b6c72009-02-17 23:15:12 +00002551 // Check that the specialization uses the same tag kind as the
2552 // original template.
2553 TagDecl::TagKind Kind;
2554 switch (TagSpec) {
2555 default: assert(0 && "Unknown tag type!");
2556 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2557 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2558 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2559 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002560 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2561 Kind, KWLoc,
2562 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002563 Diag(KWLoc, diag::err_use_with_wrong_tag)
2564 << ClassTemplate
2565 << CodeModificationHint::CreateReplacement(KWLoc,
2566 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002567 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2568 diag::note_previous_use);
2569 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2570 }
2571
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002572 // Translate the parser's template argument list in our AST format.
2573 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2574 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2575
Douglas Gregora08b6c72009-02-17 23:15:12 +00002576 // Check that the template argument list is well-formed for this
2577 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002578 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2579 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002580 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002581 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002582 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002583 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002584
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002585 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002586 ClassTemplate->getTemplateParameters()->size()) &&
2587 "Converted template argument list is too short!");
2588
Douglas Gregor58944ac2009-05-31 09:31:02 +00002589 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002590 // corresponds to these arguments.
2591 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002592 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002593 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002594 if (CheckClassTemplatePartialSpecializationArgs(
2595 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002596 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002597 return true;
2598
Douglas Gregor42476442009-06-12 22:08:06 +00002599 if (MirrorsPrimaryTemplate) {
2600 // C++ [temp.class.spec]p9b3:
2601 //
2602 // -- The argument list of the specialization shall not be identical
2603 // to the implicit argument list of the primary template.
2604 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall069c23a2009-07-31 02:45:11 +00002605 << (TUK == TUK_Definition)
Douglas Gregor42476442009-06-12 22:08:06 +00002606 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2607 RAngleLoc));
John McCall069c23a2009-07-31 02:45:11 +00002608 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor42476442009-06-12 22:08:06 +00002609 ClassTemplate->getIdentifier(),
2610 TemplateNameLoc,
2611 Attr,
Douglas Gregore305ae32009-08-25 17:23:04 +00002612 TemplateParams,
Douglas Gregor42476442009-06-12 22:08:06 +00002613 AS_none);
2614 }
2615
Douglas Gregor58944ac2009-05-31 09:31:02 +00002616 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002617 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002618 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002619 Converted.flatSize(),
2620 Context);
Mike Stump90fc78e2009-08-04 21:02:39 +00002621 } else
Anders Carlssona35faf92009-06-05 03:43:12 +00002622 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002623 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002624 Converted.flatSize(),
2625 Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002626 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002627 ClassTemplateSpecializationDecl *PrevDecl = 0;
2628
2629 if (isPartialSpecialization)
2630 PrevDecl
2631 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2632 InsertPos);
2633 else
2634 PrevDecl
2635 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002636
2637 ClassTemplateSpecializationDecl *Specialization = 0;
2638
Douglas Gregor0d93f692009-02-25 22:02:03 +00002639 // Check whether we can declare a class template specialization in
2640 // the current scope.
2641 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2642 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002643 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002644 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002645 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002646 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002647
Douglas Gregor1930d202009-07-30 17:40:51 +00002648 // The canonical type
2649 QualType CanonType;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002650 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2651 // Since the only prior class template specialization with these
2652 // arguments was referenced but not declared, reuse that
2653 // declaration node as our own, updating its source location to
2654 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002655 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002656 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002657 PrevDecl = 0;
Douglas Gregor1930d202009-07-30 17:40:51 +00002658 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002659 } else if (isPartialSpecialization) {
Douglas Gregor1930d202009-07-30 17:40:51 +00002660 // Build the canonical type that describes the converted template
2661 // arguments of the class template partial specialization.
2662 CanonType = Context.getTemplateSpecializationType(
2663 TemplateName(ClassTemplate),
2664 Converted.getFlatArguments(),
2665 Converted.flatSize());
2666
Douglas Gregor58944ac2009-05-31 09:31:02 +00002667 // Create a new class template partial specialization declaration node.
2668 TemplateParameterList *TemplateParams
2669 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2670 ClassTemplatePartialSpecializationDecl *PrevPartial
2671 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2672 ClassTemplatePartialSpecializationDecl *Partial
2673 = ClassTemplatePartialSpecializationDecl::Create(Context,
2674 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002675 TemplateNameLoc,
2676 TemplateParams,
2677 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002678 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002679 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002680
2681 if (PrevPartial) {
2682 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2683 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2684 } else {
2685 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2686 }
2687 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002688
2689 // Check that all of the template parameters of the class template
2690 // partial specialization are deducible from the template
2691 // arguments. If not, this class template partial specialization
2692 // will never be used.
2693 llvm::SmallVector<bool, 8> DeducibleParams;
2694 DeducibleParams.resize(TemplateParams->size());
2695 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2696 unsigned NumNonDeducible = 0;
2697 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2698 if (!DeducibleParams[I])
2699 ++NumNonDeducible;
2700
2701 if (NumNonDeducible) {
2702 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2703 << (NumNonDeducible > 1)
2704 << SourceRange(TemplateNameLoc, RAngleLoc);
2705 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2706 if (!DeducibleParams[I]) {
2707 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2708 if (Param->getDeclName())
2709 Diag(Param->getLocation(),
2710 diag::note_partial_spec_unused_parameter)
2711 << Param->getDeclName();
2712 else
2713 Diag(Param->getLocation(),
2714 diag::note_partial_spec_unused_parameter)
2715 << std::string("<anonymous>");
2716 }
2717 }
2718 }
Douglas Gregora08b6c72009-02-17 23:15:12 +00002719 } else {
2720 // Create a new class template specialization declaration node for
2721 // this explicit specialization.
2722 Specialization
2723 = ClassTemplateSpecializationDecl::Create(Context,
2724 ClassTemplate->getDeclContext(),
2725 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002726 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002727 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002728 PrevDecl);
2729
2730 if (PrevDecl) {
2731 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2732 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2733 } else {
2734 ClassTemplate->getSpecializations().InsertNode(Specialization,
2735 InsertPos);
2736 }
Douglas Gregor1930d202009-07-30 17:40:51 +00002737
2738 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002739 }
2740
2741 // Note that this is an explicit specialization.
2742 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2743
2744 // Check that this isn't a redefinition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002745 if (TUK == TUK_Definition) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002746 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002747 // FIXME: Should also handle explicit specialization after implicit
2748 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002749 SourceRange Range(TemplateNameLoc, RAngleLoc);
2750 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002751 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002752 Diag(Def->getLocation(), diag::note_previous_definition);
2753 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002754 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002755 }
2756 }
2757
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002758 // Build the fully-sugared type for this class template
2759 // specialization as the user wrote in the specialization
2760 // itself. This means that we'll pretty-print the type retrieved
2761 // from the specialization's declaration the way that the user
2762 // actually wrote the specialization, rather than formatting the
2763 // name based on the "canonical" representation used to store the
2764 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002765 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002766 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002767 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002768 TemplateArgs.size(),
Douglas Gregor1930d202009-07-30 17:40:51 +00002769 CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +00002770 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002771 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002772
Douglas Gregor50113ca2009-02-25 22:18:32 +00002773 // C++ [temp.expl.spec]p9:
2774 // A template explicit specialization is in the scope of the
2775 // namespace in which the template was defined.
2776 //
2777 // We actually implement this paragraph where we set the semantic
2778 // context (in the creation of the ClassTemplateSpecializationDecl),
2779 // but we also maintain the lexical context where the actual
2780 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002781 Specialization->setLexicalDeclContext(CurContext);
2782
2783 // We may be starting the definition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002784 if (TUK == TUK_Definition)
Douglas Gregora08b6c72009-02-17 23:15:12 +00002785 Specialization->startDefinition();
2786
2787 // Add the specialization into its lexical context, so that it can
2788 // be seen when iterating through the list of declarations in that
2789 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002790 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002791 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002792}
Douglas Gregord3022602009-03-27 23:10:48 +00002793
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002794Sema::DeclPtrTy
2795Sema::ActOnTemplateDeclarator(Scope *S,
2796 MultiTemplateParamsArg TemplateParameterLists,
2797 Declarator &D) {
2798 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2799}
2800
Douglas Gregor19d10652009-06-24 00:54:41 +00002801Sema::DeclPtrTy
2802Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2803 MultiTemplateParamsArg TemplateParameterLists,
2804 Declarator &D) {
2805 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2806 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2807 "Not a function declarator!");
2808 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2809
2810 if (FTI.hasPrototype) {
2811 // FIXME: Diagnose arguments without names in C.
2812 }
2813
2814 Scope *ParentScope = FnBodyScope->getParent();
2815
2816 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2817 move(TemplateParameterLists),
2818 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002819 if (FunctionTemplateDecl *FunctionTemplate
2820 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002821 return ActOnStartOfFunctionDef(FnBodyScope,
2822 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002823 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2824 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002825 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002826}
2827
Douglas Gregor96b6df92009-05-14 00:28:11 +00002828// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002829Sema::DeclResult
2830Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2831 unsigned TagSpec,
2832 SourceLocation KWLoc,
2833 const CXXScopeSpec &SS,
2834 TemplateTy TemplateD,
2835 SourceLocation TemplateNameLoc,
2836 SourceLocation LAngleLoc,
2837 ASTTemplateArgsPtr TemplateArgsIn,
2838 SourceLocation *TemplateArgLocs,
2839 SourceLocation RAngleLoc,
2840 AttributeList *Attr) {
2841 // Find the class template we're specializing
2842 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2843 ClassTemplateDecl *ClassTemplate
2844 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2845
2846 // Check that the specialization uses the same tag kind as the
2847 // original template.
2848 TagDecl::TagKind Kind;
2849 switch (TagSpec) {
2850 default: assert(0 && "Unknown tag type!");
2851 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2852 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2853 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2854 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002855 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2856 Kind, KWLoc,
2857 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002858 Diag(KWLoc, diag::err_use_with_wrong_tag)
2859 << ClassTemplate
2860 << CodeModificationHint::CreateReplacement(KWLoc,
2861 ClassTemplate->getTemplatedDecl()->getKindName());
2862 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2863 diag::note_previous_use);
2864 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2865 }
2866
Douglas Gregor90177912009-05-13 18:28:20 +00002867 // C++0x [temp.explicit]p2:
2868 // [...] An explicit instantiation shall appear in an enclosing
2869 // namespace of its template. [...]
2870 //
2871 // This is C++ DR 275.
2872 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2873 TemplateNameLoc,
2874 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002875 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002876 /*ExplicitInstantiation=*/true))
2877 return true;
2878
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002879 // Translate the parser's template argument list in our AST format.
2880 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2881 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2882
2883 // Check that the template argument list is well-formed for this
2884 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002885 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2886 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002887 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002888 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002889 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002890 return true;
2891
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002892 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002893 ClassTemplate->getTemplateParameters()->size()) &&
2894 "Converted template argument list is too short!");
2895
2896 // Find the class template specialization declaration that
2897 // corresponds to these arguments.
2898 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002899 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002900 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002901 Converted.flatSize(),
2902 Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002903 void *InsertPos = 0;
2904 ClassTemplateSpecializationDecl *PrevDecl
2905 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2906
2907 ClassTemplateSpecializationDecl *Specialization = 0;
2908
Douglas Gregor90177912009-05-13 18:28:20 +00002909 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002910 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002911 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002912 // This particular specialization has already been declared or
2913 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002914 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2915 << Context.getTypeDeclType(PrevDecl);
2916 Diag(PrevDecl->getLocation(),
2917 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002918 return DeclPtrTy::make(PrevDecl);
2919 }
2920
Douglas Gregor90177912009-05-13 18:28:20 +00002921 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002922 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002923 // For a given set of template parameters, if an explicit
2924 // instantiation of a template appears after a declaration of
2925 // an explicit specialization for that template, the explicit
2926 // instantiation has no effect.
2927 if (!getLangOptions().CPlusPlus0x) {
2928 Diag(TemplateNameLoc,
2929 diag::ext_explicit_instantiation_after_specialization)
2930 << Context.getTypeDeclType(PrevDecl);
2931 Diag(PrevDecl->getLocation(),
2932 diag::note_previous_template_specialization);
2933 }
2934
2935 // Create a new class template specialization declaration node
2936 // for this explicit specialization. This node is only used to
2937 // record the existence of this explicit instantiation for
2938 // accurate reproduction of the source code; we don't actually
2939 // use it for anything, since it is semantically irrelevant.
2940 Specialization
2941 = ClassTemplateSpecializationDecl::Create(Context,
2942 ClassTemplate->getDeclContext(),
2943 TemplateNameLoc,
2944 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002945 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002946 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002947 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002948 return DeclPtrTy::make(Specialization);
2949 }
2950
2951 // If we have already (implicitly) instantiated this
2952 // specialization, there is less work to do.
2953 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2954 SpecializationRequiresInstantiation = false;
2955
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002956 // Since the only prior class template specialization with these
2957 // arguments was referenced but not declared, reuse that
2958 // declaration node as our own, updating its source location to
2959 // reflect our new declaration.
2960 Specialization = PrevDecl;
2961 Specialization->setLocation(TemplateNameLoc);
2962 PrevDecl = 0;
2963 } else {
2964 // Create a new class template specialization declaration node for
2965 // this explicit specialization.
2966 Specialization
2967 = ClassTemplateSpecializationDecl::Create(Context,
2968 ClassTemplate->getDeclContext(),
2969 TemplateNameLoc,
2970 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002971 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002972
2973 ClassTemplate->getSpecializations().InsertNode(Specialization,
2974 InsertPos);
2975 }
2976
2977 // Build the fully-sugared type for this explicit instantiation as
2978 // the user wrote in the explicit instantiation itself. This means
2979 // that we'll pretty-print the type retrieved from the
2980 // specialization's declaration the way that the user actually wrote
2981 // the explicit instantiation, rather than formatting the name based
2982 // on the "canonical" representation used to store the template
2983 // arguments in the specialization.
2984 QualType WrittenTy
2985 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002986 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002987 TemplateArgs.size(),
2988 Context.getTypeDeclType(Specialization));
2989 Specialization->setTypeAsWritten(WrittenTy);
2990 TemplateArgsIn.release();
2991
2992 // Add the explicit instantiation into its lexical context. However,
2993 // since explicit instantiations are never found by name lookup, we
2994 // just put it into the declaration context directly.
2995 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002996 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002997
2998 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002999 // A definition of a class template or class member template
3000 // shall be in scope at the point of the explicit instantiation of
3001 // the class template or class member template.
3002 //
3003 // This check comes when we actually try to perform the
3004 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00003005 if (SpecializationRequiresInstantiation)
3006 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00003007 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00003008 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00003009
3010 return DeclPtrTy::make(Specialization);
3011}
3012
Douglas Gregor96b6df92009-05-14 00:28:11 +00003013// Explicit instantiation of a member class of a class template.
3014Sema::DeclResult
3015Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
3016 unsigned TagSpec,
3017 SourceLocation KWLoc,
3018 const CXXScopeSpec &SS,
3019 IdentifierInfo *Name,
3020 SourceLocation NameLoc,
3021 AttributeList *Attr) {
3022
Douglas Gregor71f06032009-05-28 23:31:59 +00003023 bool Owned = false;
John McCall069c23a2009-07-31 02:45:11 +00003024 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor84a20812009-07-22 23:48:44 +00003025 KWLoc, SS, Name, NameLoc, Attr, AS_none,
3026 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00003027 if (!TagD)
3028 return true;
3029
3030 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3031 if (Tag->isEnum()) {
3032 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3033 << Context.getTypeDeclType(Tag);
3034 return true;
3035 }
3036
Douglas Gregord769bfa2009-05-27 17:30:49 +00003037 if (Tag->isInvalidDecl())
3038 return true;
3039
Douglas Gregor96b6df92009-05-14 00:28:11 +00003040 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3041 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3042 if (!Pattern) {
3043 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3044 << Context.getTypeDeclType(Record);
3045 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3046 return true;
3047 }
3048
3049 // C++0x [temp.explicit]p2:
3050 // [...] An explicit instantiation shall appear in an enclosing
3051 // namespace of its template. [...]
3052 //
3053 // This is C++ DR 275.
3054 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00003055 // FIXME: In C++98, we would like to turn these errors into warnings,
3056 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00003057 DeclContext *PatternContext
3058 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
3059 if (!CurContext->Encloses(PatternContext)) {
3060 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
3061 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
3062 Diag(Pattern->getLocation(), diag::note_previous_declaration);
3063 }
3064 }
3065
Douglas Gregor96b6df92009-05-14 00:28:11 +00003066 if (!Record->getDefinition(Context)) {
3067 // If the class has a definition, instantiate it (and all of its
3068 // members, recursively).
3069 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3070 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00003071 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00003072 /*ExplicitInstantiation=*/true))
3073 return true;
John McCall0ba26ee2009-08-25 22:02:44 +00003074 } else // Instantiate all of the members of the class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00003075 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00003076 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00003077
Mike Stumpe127ae32009-05-16 07:39:55 +00003078 // FIXME: We don't have any representation for explicit instantiations of
3079 // member classes. Such a representation is not needed for compilation, but it
3080 // should be available for clients that want to see all of the declarations in
3081 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00003082 return TagD;
3083}
3084
Douglas Gregord3022602009-03-27 23:10:48 +00003085Sema::TypeResult
3086Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3087 const IdentifierInfo &II, SourceLocation IdLoc) {
3088 NestedNameSpecifier *NNS
3089 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3090 if (!NNS)
3091 return true;
3092
3093 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00003094 if (T.isNull())
3095 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00003096 return T.getAsOpaquePtr();
3097}
3098
Douglas Gregor77da5802009-04-01 00:28:59 +00003099Sema::TypeResult
3100Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
3101 SourceLocation TemplateLoc, TypeTy *Ty) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003102 QualType T = GetTypeFromParser(Ty);
Douglas Gregor77da5802009-04-01 00:28:59 +00003103 NestedNameSpecifier *NNS
3104 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3105 const TemplateSpecializationType *TemplateId
3106 = T->getAsTemplateSpecializationType();
3107 assert(TemplateId && "Expected a template specialization type");
3108
Douglas Gregorfaa28fb2009-09-02 13:05:45 +00003109 if (computeDeclContext(SS, false)) {
3110 // If we can compute a declaration context, then the "typename"
3111 // keyword was superfluous. Just build a QualifiedNameType to keep
3112 // track of the nested-name-specifier.
3113
3114 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
3115 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
3116 }
3117
3118 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor77da5802009-04-01 00:28:59 +00003119}
3120
Douglas Gregord3022602009-03-27 23:10:48 +00003121/// \brief Build the type that describes a C++ typename specifier,
3122/// e.g., "typename T::type".
3123QualType
3124Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
3125 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00003126 CXXRecordDecl *CurrentInstantiation = 0;
3127 if (NNS->isDependent()) {
3128 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00003129
Douglas Gregor3eb20702009-05-11 19:58:34 +00003130 // If the nested-name-specifier does not refer to the current
3131 // instantiation, then build a typename type.
3132 if (!CurrentInstantiation)
3133 return Context.getTypenameType(NNS, &II);
Douglas Gregorab241c32009-09-02 13:12:51 +00003134
3135 // The nested-name-specifier refers to the current instantiation, so the
3136 // "typename" keyword itself is superfluous. In C++03, the program is
3137 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
3138 // extraneous "typename" keywords, and we retroactively apply this DR to
3139 // C++03 code.
Douglas Gregor3eb20702009-05-11 19:58:34 +00003140 }
Douglas Gregord3022602009-03-27 23:10:48 +00003141
Douglas Gregor3eb20702009-05-11 19:58:34 +00003142 DeclContext *Ctx = 0;
3143
3144 if (CurrentInstantiation)
3145 Ctx = CurrentInstantiation;
3146 else {
3147 CXXScopeSpec SS;
3148 SS.setScopeRep(NNS);
3149 SS.setRange(Range);
3150 if (RequireCompleteDeclContext(SS))
3151 return QualType();
3152
3153 Ctx = computeDeclContext(SS);
3154 }
Douglas Gregord3022602009-03-27 23:10:48 +00003155 assert(Ctx && "No declaration context?");
3156
3157 DeclarationName Name(&II);
3158 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3159 false);
3160 unsigned DiagID = 0;
3161 Decl *Referenced = 0;
3162 switch (Result.getKind()) {
3163 case LookupResult::NotFound:
3164 if (Ctx->isTranslationUnit())
3165 DiagID = diag::err_typename_nested_not_found_global;
3166 else
3167 DiagID = diag::err_typename_nested_not_found;
3168 break;
3169
3170 case LookupResult::Found:
3171 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3172 // We found a type. Build a QualifiedNameType, since the
3173 // typename-specifier was just sugar. FIXME: Tell
3174 // QualifiedNameType that it has a "typename" prefix.
3175 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3176 }
3177
3178 DiagID = diag::err_typename_nested_not_type;
3179 Referenced = Result.getAsDecl();
3180 break;
3181
3182 case LookupResult::FoundOverloaded:
3183 DiagID = diag::err_typename_nested_not_type;
3184 Referenced = *Result.begin();
3185 break;
3186
3187 case LookupResult::AmbiguousBaseSubobjectTypes:
3188 case LookupResult::AmbiguousBaseSubobjects:
3189 case LookupResult::AmbiguousReference:
3190 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3191 return QualType();
3192 }
3193
3194 // If we get here, it's because name lookup did not find a
3195 // type. Emit an appropriate diagnostic and return an error.
3196 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3197 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3198 else
3199 Diag(Range.getEnd(), DiagID) << Range << Name;
3200 if (Referenced)
3201 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3202 << Name;
3203 return QualType();
3204}
Douglas Gregor3f220e82009-08-06 16:20:37 +00003205
3206namespace {
3207 // See Sema::RebuildTypeInCurrentInstantiation
3208 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
3209 : public TreeTransform<CurrentInstantiationRebuilder>
3210 {
3211 SourceLocation Loc;
3212 DeclarationName Entity;
3213
3214 public:
3215 CurrentInstantiationRebuilder(Sema &SemaRef,
3216 SourceLocation Loc,
3217 DeclarationName Entity)
3218 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
3219 Loc(Loc), Entity(Entity) { }
3220
3221 /// \brief Determine whether the given type \p T has already been
3222 /// transformed.
3223 ///
3224 /// For the purposes of type reconstruction, a type has already been
3225 /// transformed if it is NULL or if it is not dependent.
3226 bool AlreadyTransformed(QualType T) {
3227 return T.isNull() || !T->isDependentType();
3228 }
3229
3230 /// \brief Returns the location of the entity whose type is being
3231 /// rebuilt.
3232 SourceLocation getBaseLocation() { return Loc; }
3233
3234 /// \brief Returns the name of the entity whose type is being rebuilt.
3235 DeclarationName getBaseEntity() { return Entity; }
3236
3237 /// \brief Transforms an expression by returning the expression itself
3238 /// (an identity function).
3239 ///
3240 /// FIXME: This is completely unsafe; we will need to actually clone the
3241 /// expressions.
3242 Sema::OwningExprResult TransformExpr(Expr *E) {
3243 return getSema().Owned(E);
3244 }
3245
3246 /// \brief Transforms a typename type by determining whether the type now
3247 /// refers to a member of the current instantiation, and then
3248 /// type-checking and building a QualifiedNameType (when possible).
3249 QualType TransformTypenameType(const TypenameType *T);
3250 };
3251}
3252
3253QualType
3254CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) {
3255 NestedNameSpecifier *NNS
3256 = TransformNestedNameSpecifier(T->getQualifier(),
3257 /*FIXME:*/SourceRange(getBaseLocation()));
3258 if (!NNS)
3259 return QualType();
3260
3261 // If the nested-name-specifier did not change, and we cannot compute the
3262 // context corresponding to the nested-name-specifier, then this
3263 // typename type will not change; exit early.
3264 CXXScopeSpec SS;
3265 SS.setRange(SourceRange(getBaseLocation()));
3266 SS.setScopeRep(NNS);
3267 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
3268 return QualType(T, 0);
3269
3270 // Rebuild the typename type, which will probably turn into a
3271 // QualifiedNameType.
3272 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
3273 QualType NewTemplateId
3274 = TransformType(QualType(TemplateId, 0));
3275 if (NewTemplateId.isNull())
3276 return QualType();
3277
3278 if (NNS == T->getQualifier() &&
3279 NewTemplateId == QualType(TemplateId, 0))
3280 return QualType(T, 0);
3281
3282 return getDerived().RebuildTypenameType(NNS, NewTemplateId);
3283 }
3284
3285 return getDerived().RebuildTypenameType(NNS, T->getIdentifier());
3286}
3287
3288/// \brief Rebuilds a type within the context of the current instantiation.
3289///
3290/// The type \p T is part of the type of an out-of-line member definition of
3291/// a class template (or class template partial specialization) that was parsed
3292/// and constructed before we entered the scope of the class template (or
3293/// partial specialization thereof). This routine will rebuild that type now
3294/// that we have entered the declarator's scope, which may produce different
3295/// canonical types, e.g.,
3296///
3297/// \code
3298/// template<typename T>
3299/// struct X {
3300/// typedef T* pointer;
3301/// pointer data();
3302/// };
3303///
3304/// template<typename T>
3305/// typename X<T>::pointer X<T>::data() { ... }
3306/// \endcode
3307///
3308/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
3309/// since we do not know that we can look into X<T> when we parsed the type.
3310/// This function will rebuild the type, performing the lookup of "pointer"
3311/// in X<T> and returning a QualifiedNameType whose canonical type is the same
3312/// as the canonical type of T*, allowing the return types of the out-of-line
3313/// definition and the declaration to match.
3314QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
3315 DeclarationName Name) {
3316 if (T.isNull() || !T->isDependentType())
3317 return T;
3318
3319 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
3320 return Rebuilder.TransformType(T);
Benjamin Kramer3e2ac772009-08-11 22:33:06 +00003321}