blob: 8dfb7d3881479c2397f4daf6c49308dfc65414e2 [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 Gregord406b032009-02-06 22:42:48 +000013#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000014#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000015#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000016#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000017#include "clang/Parse/DeclSpec.h"
18#include "clang/Basic/LangOptions.h"
19
20using namespace clang;
21
Douglas Gregor2fa10442008-12-18 19:37:40 +000022/// isTemplateName - Determines whether the identifier II is a
23/// template name in the current scope, and returns the template
24/// declaration if II names a template. An optional CXXScope can be
25/// passed to indicate the C++ scope in which the identifier will be
26/// found.
Douglas Gregoraabb8502009-03-31 00:43:58 +000027TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregordd13e842009-03-30 22:58:21 +000028 TemplateTy &TemplateResult,
Douglas Gregor0c281a82009-02-25 19:37:18 +000029 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000030 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000031
Douglas Gregordd13e842009-03-30 22:58:21 +000032 TemplateNameKind TNK = TNK_Non_template;
33 TemplateDecl *Template = 0;
34
Douglas Gregor2fa10442008-12-18 19:37:40 +000035 if (IIDecl) {
Douglas Gregordd13e842009-03-30 22:58:21 +000036 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000037 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregordd13e842009-03-30 22:58:21 +000038 TNK = TNK_Function_template;
Douglas Gregoraabb8502009-03-31 00:43:58 +000039 else if (isa<ClassTemplateDecl>(IIDecl) ||
40 isa<TemplateTemplateParmDecl>(IIDecl))
41 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000042 else
43 assert(false && "Unknown template declaration kind");
Douglas Gregor55216ac2009-03-26 00:10:35 +000044 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
45 // C++ [temp.local]p1:
46 // Like normal (non-template) classes, class templates have an
47 // injected-class-name (Clause 9). The injected-class-name
48 // can be used with or without a template-argument-list. When
49 // it is used without a template-argument-list, it is
50 // equivalent to the injected-class-name followed by the
51 // template-parameters of the class template enclosed in
52 // <>. When it is used with a template-argument-list, it
53 // refers to the specified class template specialization,
54 // which could be the current specialization or another
55 // specialization.
56 if (Record->isInjectedClassName()) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +000057 Record = cast<CXXRecordDecl>(Record->getCanonicalDecl());
Douglas Gregordd13e842009-03-30 22:58:21 +000058 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregoraabb8502009-03-31 00:43:58 +000059 TNK = TNK_Type_template;
Douglas Gregordd13e842009-03-30 22:58:21 +000060 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor55216ac2009-03-26 00:10:35 +000061 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregordd13e842009-03-30 22:58:21 +000062 Template = Spec->getSpecializedTemplate();
Douglas Gregoraabb8502009-03-31 00:43:58 +000063 TNK = TNK_Type_template;
Douglas Gregor55216ac2009-03-26 00:10:35 +000064 }
65 }
Douglas Gregord6ea07d2009-07-29 16:56:42 +000066 } else if (OverloadedFunctionDecl *Ovl
67 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
Douglas Gregor2fa10442008-12-18 19:37:40 +000068 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
69 FEnd = Ovl->function_end();
70 F != FEnd; ++F) {
Douglas Gregord6ea07d2009-07-29 16:56:42 +000071 if (FunctionTemplateDecl *FuncTmpl
72 = dyn_cast<FunctionTemplateDecl>(*F)) {
73 // We've found a function template. Determine whether there are
74 // any other function templates we need to bundle together in an
75 // OverloadedFunctionDecl
76 for (++F; F != FEnd; ++F) {
77 if (isa<FunctionTemplateDecl>(*F))
78 break;
79 }
80
81 if (F != FEnd) {
82 // Build an overloaded function decl containing only the
83 // function templates in Ovl.
84 OverloadedFunctionDecl *OvlTemplate
85 = OverloadedFunctionDecl::Create(Context,
86 Ovl->getDeclContext(),
87 Ovl->getDeclName());
88 OvlTemplate->addOverload(FuncTmpl);
89 OvlTemplate->addOverload(*F);
90 for (++F; F != FEnd; ++F) {
91 if (isa<FunctionTemplateDecl>(*F))
92 OvlTemplate->addOverload(*F);
93 }
Douglas Gregor6631cb42009-07-29 18:26:50 +000094
95 // Form the resulting TemplateName
96 if (SS && SS->isSet() && !SS->isInvalid()) {
97 NestedNameSpecifier *Qualifier
98 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
99 TemplateResult
100 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
101 false,
102 OvlTemplate));
103 } else {
104 TemplateResult = TemplateTy::make(TemplateName(OvlTemplate));
105 }
Douglas Gregord6ea07d2009-07-29 16:56:42 +0000106 return TNK_Function_template;
107 }
108
109 TNK = TNK_Function_template;
110 Template = FuncTmpl;
111 break;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000112 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000113 }
114 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000115
116 if (TNK != TNK_Non_template) {
117 if (SS && SS->isSet() && !SS->isInvalid()) {
118 NestedNameSpecifier *Qualifier
119 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
120 TemplateResult
121 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
122 false,
123 Template));
124 } else
125 TemplateResult = TemplateTy::make(TemplateName(Template));
126 }
Douglas Gregor2fa10442008-12-18 19:37:40 +0000127 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000128 return TNK;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000129}
130
Douglas Gregordd861062008-12-05 18:15:24 +0000131/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
132/// that the template parameter 'PrevDecl' is being shadowed by a new
133/// declaration at location Loc. Returns true to indicate that this is
134/// an error, and false otherwise.
135bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000136 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +0000137
138 // Microsoft Visual C++ permits template parameters to be shadowed.
139 if (getLangOptions().Microsoft)
140 return false;
141
142 // C++ [temp.local]p4:
143 // A template-parameter shall not be redeclared within its
144 // scope (including nested scopes).
145 Diag(Loc, diag::err_template_param_shadow)
146 << cast<NamedDecl>(PrevDecl)->getDeclName();
147 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
148 return true;
149}
150
Douglas Gregored3a3982009-03-03 04:44:36 +0000151/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000152/// the parameter D to reference the templated declaration and return a pointer
153/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000154TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
155 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
156 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregor279272e2009-02-04 19:02:06 +0000157 return Temp;
158 }
159 return 0;
160}
161
Douglas Gregordd861062008-12-05 18:15:24 +0000162/// ActOnTypeParameter - Called when a C++ template type parameter
163/// (e.g., "typename T") has been parsed. Typename specifies whether
164/// the keyword "typename" was used to declare the type parameter
165/// (otherwise, "class" was used), and KeyLoc is the location of the
166/// "class" or "typename" keyword. ParamName is the name of the
167/// parameter (NULL indicates an unnamed template parameter) and
168/// ParamName is the location of the parameter name (if any).
169/// If the type parameter has a default argument, it will be added
170/// later via ActOnTypeParameterDefault.
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000171Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
172 SourceLocation EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000173 SourceLocation KeyLoc,
174 IdentifierInfo *ParamName,
175 SourceLocation ParamNameLoc,
176 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000177 assert(S->isTemplateParamScope() &&
178 "Template type parameter not in template parameter scope!");
179 bool Invalid = false;
180
181 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000182 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000183 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000184 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
185 PrevDecl);
186 }
187
Douglas Gregord406b032009-02-06 22:42:48 +0000188 SourceLocation Loc = ParamNameLoc;
189 if (!ParamName)
190 Loc = KeyLoc;
191
Douglas Gregordd861062008-12-05 18:15:24 +0000192 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000193 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlssoneebbf9a2009-06-12 22:23:22 +0000194 Depth, Position, ParamName, Typename,
195 Ellipsis);
Douglas Gregordd861062008-12-05 18:15:24 +0000196 if (Invalid)
197 Param->setInvalidDecl();
198
199 if (ParamName) {
200 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000201 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000202 IdResolver.AddDecl(Param);
203 }
204
Chris Lattner5261d0c2009-03-28 19:18:32 +0000205 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000206}
207
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000208/// ActOnTypeParameterDefault - Adds a default argument (the type
209/// Default) to the given template type parameter (TypeParam).
Chris Lattner5261d0c2009-03-28 19:18:32 +0000210void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000211 SourceLocation EqualLoc,
212 SourceLocation DefaultLoc,
213 TypeTy *DefaultT) {
214 TemplateTypeParmDecl *Parm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000215 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000216 QualType Default = QualType::getFromOpaquePtr(DefaultT);
217
Anders Carlssona2333782009-06-12 22:30:13 +0000218 // C++0x [temp.param]p9:
219 // A default template-argument may be specified for any kind of
220 // template-parameter that is not a template parameter pack.
221 if (Parm->isParameterPack()) {
222 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssona2333782009-06-12 22:30:13 +0000223 return;
224 }
225
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000226 // C++ [temp.param]p14:
227 // A template-parameter shall not be used in its own default argument.
228 // FIXME: Implement this check! Needs a recursive walk over the types.
229
230 // Check the template argument itself.
231 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
232 Parm->setInvalidDecl();
233 return;
234 }
235
236 Parm->setDefaultArgument(Default, DefaultLoc, false);
237}
238
Douglas Gregored3a3982009-03-03 04:44:36 +0000239/// \brief Check that the type of a non-type template parameter is
240/// well-formed.
241///
242/// \returns the (possibly-promoted) parameter type if valid;
243/// otherwise, produces a diagnostic and returns a NULL type.
244QualType
245Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
246 // C++ [temp.param]p4:
247 //
248 // A non-type template-parameter shall have one of the following
249 // (optionally cv-qualified) types:
250 //
251 // -- integral or enumeration type,
252 if (T->isIntegralType() || T->isEnumeralType() ||
253 // -- pointer to object or pointer to function,
254 (T->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000255 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
256 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Douglas Gregored3a3982009-03-03 04:44:36 +0000257 // -- reference to object or reference to function,
258 T->isReferenceType() ||
259 // -- pointer to member.
260 T->isMemberPointerType() ||
261 // If T is a dependent type, we can't do the check now, so we
262 // assume that it is well-formed.
263 T->isDependentType())
264 return T;
265 // C++ [temp.param]p8:
266 //
267 // A non-type template-parameter of type "array of T" or
268 // "function returning T" is adjusted to be of type "pointer to
269 // T" or "pointer to function returning T", respectively.
270 else if (T->isArrayType())
271 // FIXME: Keep the type prior to promotion?
272 return Context.getArrayDecayedType(T);
273 else if (T->isFunctionType())
274 // FIXME: Keep the type prior to promotion?
275 return Context.getPointerType(T);
276
277 Diag(Loc, diag::err_template_nontype_parm_bad_type)
278 << T;
279
280 return QualType();
281}
282
Douglas Gregordd861062008-12-05 18:15:24 +0000283/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
284/// template parameter (e.g., "int Size" in "template<int Size>
285/// class Array") has been parsed. S is the current scope and D is
286/// the parsed declarator.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000287Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
288 unsigned Depth,
289 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000290 QualType T = GetTypeForDeclarator(D, S);
291
Douglas Gregor279272e2009-02-04 19:02:06 +0000292 assert(S->isTemplateParamScope() &&
293 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000294 bool Invalid = false;
295
296 IdentifierInfo *ParamName = D.getIdentifier();
297 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000298 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000299 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000300 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000301 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000302 }
303
Douglas Gregored3a3982009-03-03 04:44:36 +0000304 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000305 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000306 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000307 Invalid = true;
308 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000309
Douglas Gregordd861062008-12-05 18:15:24 +0000310 NonTypeTemplateParmDecl *Param
311 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000312 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000313 if (Invalid)
314 Param->setInvalidDecl();
315
316 if (D.getIdentifier()) {
317 // Add the template parameter into the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000318 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregordd861062008-12-05 18:15:24 +0000319 IdResolver.AddDecl(Param);
320 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000321 return DeclPtrTy::make(Param);
Douglas Gregordd861062008-12-05 18:15:24 +0000322}
Douglas Gregor52473432008-12-24 02:52:09 +0000323
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000324/// \brief Adds a default argument to the given non-type template
325/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000326void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000327 SourceLocation EqualLoc,
328 ExprArg DefaultE) {
329 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000330 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000331 Expr *Default = static_cast<Expr *>(DefaultE.get());
332
333 // C++ [temp.param]p14:
334 // A template-parameter shall not be used in its own default argument.
335 // FIXME: Implement this check! Needs a recursive walk over the types.
336
337 // Check the well-formedness of the default template argument.
Douglas Gregor8f378a92009-06-11 18:10:32 +0000338 TemplateArgument Converted;
339 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
340 Converted)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000341 TemplateParm->setInvalidDecl();
342 return;
343 }
344
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000345 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000346}
347
Douglas Gregor279272e2009-02-04 19:02:06 +0000348
349/// ActOnTemplateTemplateParameter - Called when a C++ template template
350/// parameter (e.g. T in template <template <typename> class T> class array)
351/// has been parsed. S is the current scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000352Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
353 SourceLocation TmpLoc,
354 TemplateParamsTy *Params,
355 IdentifierInfo *Name,
356 SourceLocation NameLoc,
357 unsigned Depth,
358 unsigned Position)
Douglas Gregor279272e2009-02-04 19:02:06 +0000359{
360 assert(S->isTemplateParamScope() &&
361 "Template template parameter not in template parameter scope!");
362
363 // Construct the parameter object.
364 TemplateTemplateParmDecl *Param =
365 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
366 Position, Name,
367 (TemplateParameterList*)Params);
368
369 // Make sure the parameter is valid.
370 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
371 // do anything yet. However, if the template parameter list or (eventual)
372 // default value is ever invalidated, that will propagate here.
373 bool Invalid = false;
374 if (Invalid) {
375 Param->setInvalidDecl();
376 }
377
378 // If the tt-param has a name, then link the identifier into the scope
379 // and lookup mechanisms.
380 if (Name) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000381 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor279272e2009-02-04 19:02:06 +0000382 IdResolver.AddDecl(Param);
383 }
384
Chris Lattner5261d0c2009-03-28 19:18:32 +0000385 return DeclPtrTy::make(Param);
Douglas Gregor279272e2009-02-04 19:02:06 +0000386}
387
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000388/// \brief Adds a default argument to the given template template
389/// parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000390void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000391 SourceLocation EqualLoc,
392 ExprArg DefaultE) {
393 TemplateTemplateParmDecl *TemplateParm
Chris Lattner5261d0c2009-03-28 19:18:32 +0000394 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000395
396 // Since a template-template parameter's default argument is an
397 // id-expression, it must be a DeclRefExpr.
398 DeclRefExpr *Default
399 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
400
401 // C++ [temp.param]p14:
402 // A template-parameter shall not be used in its own default argument.
403 // FIXME: Implement this check! Needs a recursive walk over the types.
404
405 // Check the well-formedness of the template argument.
406 if (!isa<TemplateDecl>(Default->getDecl())) {
407 Diag(Default->getSourceRange().getBegin(),
408 diag::err_template_arg_must_be_template)
409 << Default->getSourceRange();
410 TemplateParm->setInvalidDecl();
411 return;
412 }
413 if (CheckTemplateArgument(TemplateParm, Default)) {
414 TemplateParm->setInvalidDecl();
415 return;
416 }
417
418 DefaultE.release();
419 TemplateParm->setDefaultArgument(Default);
420}
421
Douglas Gregor52473432008-12-24 02:52:09 +0000422/// ActOnTemplateParameterList - Builds a TemplateParameterList that
423/// contains the template parameters in Params/NumParams.
424Sema::TemplateParamsTy *
425Sema::ActOnTemplateParameterList(unsigned Depth,
426 SourceLocation ExportLoc,
427 SourceLocation TemplateLoc,
428 SourceLocation LAngleLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000429 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregor52473432008-12-24 02:52:09 +0000430 SourceLocation RAngleLoc) {
431 if (ExportLoc.isValid())
432 Diag(ExportLoc, diag::note_template_export_unsupported);
433
Douglas Gregord406b032009-02-06 22:42:48 +0000434 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
435 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000436}
Douglas Gregor279272e2009-02-04 19:02:06 +0000437
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000438Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +0000439Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregord406b032009-02-06 22:42:48 +0000440 SourceLocation KWLoc, const CXXScopeSpec &SS,
441 IdentifierInfo *Name, SourceLocation NameLoc,
442 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000443 MultiTemplateParamsArg TemplateParameterLists,
444 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000445 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
John McCall069c23a2009-07-31 02:45:11 +0000446 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000447 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000448
449 // Check that we can declare a template here.
450 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000451 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000452
453 TagDecl::TagKind Kind;
454 switch (TagSpec) {
455 default: assert(0 && "Unknown tag type!");
456 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
457 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
458 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
459 }
460
461 // There is no such thing as an unnamed class template.
462 if (!Name) {
463 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000464 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000465 }
466
467 // Find any previous declaration with this name.
468 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
469 true);
470 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
471 NamedDecl *PrevDecl = 0;
472 if (Previous.begin() != Previous.end())
473 PrevDecl = *Previous.begin();
474
Douglas Gregor23521802009-06-17 23:37:01 +0000475 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
476 PrevDecl = 0;
477
Douglas Gregord406b032009-02-06 22:42:48 +0000478 DeclContext *SemanticContext = CurContext;
479 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000480 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000481
Mike Stumpe127ae32009-05-16 07:39:55 +0000482 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregord406b032009-02-06 22:42:48 +0000483 }
484
485 // FIXME: member templates!
486 TemplateParameterList *TemplateParams
487 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
488
489 // If there is a previous declaration with the same name, check
490 // whether this is a valid redeclaration.
491 ClassTemplateDecl *PrevClassTemplate
492 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
493 if (PrevClassTemplate) {
494 // Ensure that the template parameter lists are compatible.
495 if (!TemplateParameterListsAreEqual(TemplateParams,
496 PrevClassTemplate->getTemplateParameters(),
497 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000498 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000499
500 // C++ [temp.class]p4:
501 // In a redeclaration, partial specialization, explicit
502 // specialization or explicit instantiation of a class template,
503 // the class-key shall agree in kind with the original class
504 // template declaration (7.1.5.3).
505 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor625185c2009-05-14 16:41:31 +0000506 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregor3faaa812009-04-01 23:51:29 +0000507 Diag(KWLoc, diag::err_use_with_wrong_tag)
508 << Name
509 << CodeModificationHint::CreateReplacement(KWLoc,
510 PrevRecordDecl->getKindName());
Douglas Gregord406b032009-02-06 22:42:48 +0000511 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor3faaa812009-04-01 23:51:29 +0000512 Kind = PrevRecordDecl->getTagKind();
Douglas Gregord406b032009-02-06 22:42:48 +0000513 }
514
Douglas Gregord406b032009-02-06 22:42:48 +0000515 // Check for redefinition of this class template.
John McCall069c23a2009-07-31 02:45:11 +0000516 if (TUK == TUK_Definition) {
Douglas Gregord406b032009-02-06 22:42:48 +0000517 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
518 Diag(NameLoc, diag::err_redefinition) << Name;
519 Diag(Def->getLocation(), diag::note_previous_definition);
520 // FIXME: Would it make sense to try to "forget" the previous
521 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000522 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000523 }
524 }
525 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
526 // Maybe we will complain about the shadowed template parameter.
527 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
528 // Just pretend that we didn't see the previous declaration.
529 PrevDecl = 0;
530 } else if (PrevDecl) {
531 // C++ [temp]p5:
532 // A class template shall not have the same name as any other
533 // template, class, function, object, enumeration, enumerator,
534 // namespace, or type in the same scope (3.3), except as specified
535 // in (14.5.4).
536 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
537 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000538 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000539 }
540
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000541 // Check the template parameter list of this declaration, possibly
542 // merging in the template parameter list from the previous class
543 // template declaration.
544 if (CheckTemplateParameterList(TemplateParams,
545 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
546 Invalid = true;
547
Douglas Gregor9054f982009-05-10 22:57:19 +0000548 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregord406b032009-02-06 22:42:48 +0000549 // declaration!
550
Douglas Gregor55216ac2009-03-26 00:10:35 +0000551 CXXRecordDecl *NewClass =
Douglas Gregor9060d0e2009-07-21 14:46:17 +0000552 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Douglas Gregord406b032009-02-06 22:42:48 +0000553 PrevClassTemplate?
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000554 PrevClassTemplate->getTemplatedDecl() : 0,
555 /*DelayTypeCreation=*/true);
Douglas Gregord406b032009-02-06 22:42:48 +0000556
557 ClassTemplateDecl *NewTemplate
558 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
559 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000560 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000561 NewClass->setDescribedClassTemplate(NewTemplate);
562
Douglas Gregor12aed0b2009-05-15 19:11:46 +0000563 // Build the type for the class template declaration now.
564 QualType T =
565 Context.getTypeDeclType(NewClass,
566 PrevClassTemplate?
567 PrevClassTemplate->getTemplatedDecl() : 0);
568 assert(T->isDependentType() && "Class template type is not dependent?");
569 (void)T;
570
Anders Carlsson4ca43492009-03-26 01:24:28 +0000571 // Set the access specifier.
572 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
573
Douglas Gregord406b032009-02-06 22:42:48 +0000574 // Set the lexical context of these templates
575 NewClass->setLexicalDeclContext(CurContext);
576 NewTemplate->setLexicalDeclContext(CurContext);
577
John McCall069c23a2009-07-31 02:45:11 +0000578 if (TUK == TUK_Definition)
Douglas Gregord406b032009-02-06 22:42:48 +0000579 NewClass->startDefinition();
580
581 if (Attr)
Douglas Gregor2a2e0402009-06-17 21:51:59 +0000582 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregord406b032009-02-06 22:42:48 +0000583
584 PushOnScopeChains(NewTemplate, S);
585
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000586 if (Invalid) {
587 NewTemplate->setInvalidDecl();
588 NewClass->setInvalidDecl();
589 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000590 return DeclPtrTy::make(NewTemplate);
Douglas Gregord406b032009-02-06 22:42:48 +0000591}
592
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000593/// \brief Checks the validity of a template parameter list, possibly
594/// considering the template parameter list from a previous
595/// declaration.
596///
597/// If an "old" template parameter list is provided, it must be
598/// equivalent (per TemplateParameterListsAreEqual) to the "new"
599/// template parameter list.
600///
601/// \param NewParams Template parameter list for a new template
602/// declaration. This template parameter list will be updated with any
603/// default arguments that are carried through from the previous
604/// template parameter list.
605///
606/// \param OldParams If provided, template parameter list from a
607/// previous declaration of the same template. Default template
608/// arguments will be merged from the old template parameter list to
609/// the new template parameter list.
610///
611/// \returns true if an error occurred, false otherwise.
612bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
613 TemplateParameterList *OldParams) {
614 bool Invalid = false;
615
616 // C++ [temp.param]p10:
617 // The set of default template-arguments available for use with a
618 // template declaration or definition is obtained by merging the
619 // default arguments from the definition (if in scope) and all
620 // declarations in scope in the same way default function
621 // arguments are (8.3.6).
622 bool SawDefaultArgument = false;
623 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000624
Anders Carlssonb1929502009-06-12 23:20:15 +0000625 bool SawParameterPack = false;
626 SourceLocation ParameterPackLoc;
627
Mike Stumpe0b7e032009-02-11 23:03:27 +0000628 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000629 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000630 if (OldParams)
631 OldParam = OldParams->begin();
632
633 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
634 NewParamEnd = NewParams->end();
635 NewParam != NewParamEnd; ++NewParam) {
636 // Variables used to diagnose redundant default arguments
637 bool RedundantDefaultArg = false;
638 SourceLocation OldDefaultLoc;
639 SourceLocation NewDefaultLoc;
640
641 // Variables used to diagnose missing default arguments
642 bool MissingDefaultArg = false;
643
Anders Carlssonb1929502009-06-12 23:20:15 +0000644 // C++0x [temp.param]p11:
645 // If a template parameter of a class template is a template parameter pack,
646 // it must be the last template parameter.
647 if (SawParameterPack) {
648 Diag(ParameterPackLoc,
649 diag::err_template_param_pack_must_be_last_template_parameter);
650 Invalid = true;
651 }
652
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000653 // Merge default arguments for template type parameters.
654 if (TemplateTypeParmDecl *NewTypeParm
655 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
656 TemplateTypeParmDecl *OldTypeParm
657 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
658
Anders Carlssonb1929502009-06-12 23:20:15 +0000659 if (NewTypeParm->isParameterPack()) {
660 assert(!NewTypeParm->hasDefaultArgument() &&
661 "Parameter packs can't have a default argument!");
662 SawParameterPack = true;
663 ParameterPackLoc = NewTypeParm->getLocation();
664 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000665 NewTypeParm->hasDefaultArgument()) {
666 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
667 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
668 SawDefaultArgument = true;
669 RedundantDefaultArg = true;
670 PreviousDefaultArgLoc = NewDefaultLoc;
671 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
672 // Merge the default argument from the old declaration to the
673 // new declaration.
674 SawDefaultArgument = true;
675 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
676 OldTypeParm->getDefaultArgumentLoc(),
677 true);
678 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
679 } else if (NewTypeParm->hasDefaultArgument()) {
680 SawDefaultArgument = true;
681 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
682 } else if (SawDefaultArgument)
683 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000684 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000685 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000686 // Merge default arguments for non-type template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000687 NonTypeTemplateParmDecl *OldNonTypeParm
688 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
689 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
690 NewNonTypeParm->hasDefaultArgument()) {
691 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
692 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
693 SawDefaultArgument = true;
694 RedundantDefaultArg = true;
695 PreviousDefaultArgLoc = NewDefaultLoc;
696 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
697 // Merge the default argument from the old declaration to the
698 // new declaration.
699 SawDefaultArgument = true;
700 // FIXME: We need to create a new kind of "default argument"
701 // expression that points to a previous template template
702 // parameter.
703 NewNonTypeParm->setDefaultArgument(
704 OldNonTypeParm->getDefaultArgument());
705 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
706 } else if (NewNonTypeParm->hasDefaultArgument()) {
707 SawDefaultArgument = true;
708 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
709 } else if (SawDefaultArgument)
710 MissingDefaultArg = true;
Mike Stump90fc78e2009-08-04 21:02:39 +0000711 } else {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000712 // Merge default arguments for template template parameters
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000713 TemplateTemplateParmDecl *NewTemplateParm
714 = cast<TemplateTemplateParmDecl>(*NewParam);
715 TemplateTemplateParmDecl *OldTemplateParm
716 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
717 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
718 NewTemplateParm->hasDefaultArgument()) {
719 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
720 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
721 SawDefaultArgument = true;
722 RedundantDefaultArg = true;
723 PreviousDefaultArgLoc = NewDefaultLoc;
724 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
725 // Merge the default argument from the old declaration to the
726 // new declaration.
727 SawDefaultArgument = true;
Mike Stumpe127ae32009-05-16 07:39:55 +0000728 // FIXME: We need to create a new kind of "default argument" expression
729 // that points to a previous template template parameter.
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000730 NewTemplateParm->setDefaultArgument(
731 OldTemplateParm->getDefaultArgument());
732 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
733 } else if (NewTemplateParm->hasDefaultArgument()) {
734 SawDefaultArgument = true;
735 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
736 } else if (SawDefaultArgument)
737 MissingDefaultArg = true;
738 }
739
740 if (RedundantDefaultArg) {
741 // C++ [temp.param]p12:
742 // A template-parameter shall not be given default arguments
743 // by two different declarations in the same scope.
744 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
745 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
746 Invalid = true;
747 } else if (MissingDefaultArg) {
748 // C++ [temp.param]p11:
749 // If a template-parameter has a default template-argument,
750 // all subsequent template-parameters shall have a default
751 // template-argument supplied.
752 Diag((*NewParam)->getLocation(),
753 diag::err_template_param_default_arg_missing);
754 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
755 Invalid = true;
756 }
757
758 // If we have an old template parameter list that we're merging
759 // in, move on to the next parameter.
760 if (OldParams)
761 ++OldParam;
762 }
763
764 return Invalid;
765}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000766
Douglas Gregorb462c322009-07-21 23:53:31 +0000767/// \brief Match the given template parameter lists to the given scope
768/// specifier, returning the template parameter list that applies to the
769/// name.
770///
771/// \param DeclStartLoc the start of the declaration that has a scope
772/// specifier or a template parameter list.
773///
774/// \param SS the scope specifier that will be matched to the given template
775/// parameter lists. This scope specifier precedes a qualified name that is
776/// being declared.
777///
778/// \param ParamLists the template parameter lists, from the outermost to the
779/// innermost template parameter lists.
780///
781/// \param NumParamLists the number of template parameter lists in ParamLists.
782///
783/// \returns the template parameter list, if any, that corresponds to the
784/// name that is preceded by the scope specifier @p SS. This template
785/// parameter list may be have template parameters (if we're declaring a
786/// template) or may have no template parameters (if we're declaring a
787/// template specialization), or may be NULL (if we were's declaring isn't
788/// itself a template).
789TemplateParameterList *
790Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
791 const CXXScopeSpec &SS,
792 TemplateParameterList **ParamLists,
793 unsigned NumParamLists) {
794 // FIXME: This routine will need a lot more testing once we have support for
795 // member templates.
796
797 // Find the template-ids that occur within the nested-name-specifier. These
798 // template-ids will match up with the template parameter lists.
799 llvm::SmallVector<const TemplateSpecializationType *, 4>
800 TemplateIdsInSpecifier;
801 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
802 NNS; NNS = NNS->getPrefix()) {
803 if (const TemplateSpecializationType *SpecType
804 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
805 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
806 if (!Template)
807 continue; // FIXME: should this be an error? probably...
808
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000809 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorb462c322009-07-21 23:53:31 +0000810 ClassTemplateSpecializationDecl *SpecDecl
811 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
812 // If the nested name specifier refers to an explicit specialization,
813 // we don't need a template<> header.
Douglas Gregor1930d202009-07-30 17:40:51 +0000814 // FIXME: revisit this approach once we cope with specialization
815 // properly.
Douglas Gregorb462c322009-07-21 23:53:31 +0000816 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
817 continue;
818 }
819
820 TemplateIdsInSpecifier.push_back(SpecType);
821 }
822 }
823
824 // Reverse the list of template-ids in the scope specifier, so that we can
825 // more easily match up the template-ids and the template parameter lists.
826 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
827
828 SourceLocation FirstTemplateLoc = DeclStartLoc;
829 if (NumParamLists)
830 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
831
832 // Match the template-ids found in the specifier to the template parameter
833 // lists.
834 unsigned Idx = 0;
835 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
836 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor1930d202009-07-30 17:40:51 +0000837 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
838 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorb462c322009-07-21 23:53:31 +0000839 if (Idx >= NumParamLists) {
840 // We have a template-id without a corresponding template parameter
841 // list.
842 if (DependentTemplateId) {
843 // FIXME: the location information here isn't great.
844 Diag(SS.getRange().getBegin(),
845 diag::err_template_spec_needs_template_parameters)
Douglas Gregor1930d202009-07-30 17:40:51 +0000846 << TemplateId
Douglas Gregorb462c322009-07-21 23:53:31 +0000847 << SS.getRange();
848 } else {
849 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
850 << SS.getRange()
851 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
852 "template<> ");
853 }
854 return 0;
855 }
856
857 // Check the template parameter list against its corresponding template-id.
Douglas Gregor1930d202009-07-30 17:40:51 +0000858 if (DependentTemplateId) {
859 TemplateDecl *Template
860 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
861
862 if (ClassTemplateDecl *ClassTemplate
863 = dyn_cast<ClassTemplateDecl>(Template)) {
864 TemplateParameterList *ExpectedTemplateParams = 0;
865 // Is this template-id naming the primary template?
866 if (Context.hasSameType(TemplateId,
867 ClassTemplate->getInjectedClassNameType(Context)))
868 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
869 // ... or a partial specialization?
870 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
871 = ClassTemplate->findPartialSpecialization(TemplateId))
872 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
873
874 if (ExpectedTemplateParams)
875 TemplateParameterListsAreEqual(ParamLists[Idx],
876 ExpectedTemplateParams,
877 true);
878 }
879 } else if (ParamLists[Idx]->size() > 0)
880 Diag(ParamLists[Idx]->getTemplateLoc(),
881 diag::err_template_param_list_matches_nontemplate)
882 << TemplateId
883 << ParamLists[Idx]->getSourceRange();
Douglas Gregorb462c322009-07-21 23:53:31 +0000884 }
885
886 // If there were at least as many template-ids as there were template
887 // parameter lists, then there are no template parameter lists remaining for
888 // the declaration itself.
889 if (Idx >= NumParamLists)
890 return 0;
891
892 // If there were too many template parameter lists, complain about that now.
893 if (Idx != NumParamLists - 1) {
894 while (Idx < NumParamLists - 1) {
895 Diag(ParamLists[Idx]->getTemplateLoc(),
896 diag::err_template_spec_extra_headers)
897 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
898 ParamLists[Idx]->getRAngleLoc());
899 ++Idx;
900 }
901 }
902
903 // Return the last template parameter list, which corresponds to the
904 // entity being declared.
905 return ParamLists[NumParamLists - 1];
906}
907
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000908/// \brief Translates template arguments as provided by the parser
909/// into template arguments used by semantic analysis.
910static void
911translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
912 SourceLocation *TemplateArgLocs,
913 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
914 TemplateArgs.reserve(TemplateArgsIn.size());
915
916 void **Args = TemplateArgsIn.getArgs();
917 bool *ArgIsType = TemplateArgsIn.getArgIsType();
918 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
919 TemplateArgs.push_back(
920 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
921 QualType::getFromOpaquePtr(Args[Arg]))
922 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
923 }
924}
925
Douglas Gregordd13e842009-03-30 22:58:21 +0000926QualType Sema::CheckTemplateIdType(TemplateName Name,
927 SourceLocation TemplateLoc,
928 SourceLocation LAngleLoc,
929 const TemplateArgument *TemplateArgs,
930 unsigned NumTemplateArgs,
931 SourceLocation RAngleLoc) {
932 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregoraabb8502009-03-31 00:43:58 +0000933 if (!Template) {
934 // The template name does not resolve to a template, so we just
935 // build a dependent template-id type.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000936 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor4262bc92009-07-28 23:00:59 +0000937 NumTemplateArgs);
Douglas Gregoraabb8502009-03-31 00:43:58 +0000938 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000939
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000940 // Check that the template argument list is well-formed for this
941 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000942 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
943 NumTemplateArgs);
Douglas Gregordd13e842009-03-30 22:58:21 +0000944 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000945 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +0000946 false, Converted))
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000947 return QualType();
948
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000949 assert((Converted.structuredSize() ==
Douglas Gregordd13e842009-03-30 22:58:21 +0000950 Template->getTemplateParameters()->size()) &&
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000951 "Converted template argument list is too short!");
952
953 QualType CanonType;
954
Douglas Gregordd13e842009-03-30 22:58:21 +0000955 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000956 TemplateArgs,
957 NumTemplateArgs)) {
958 // This class template specialization is a dependent
959 // type. Therefore, its canonical type is another class template
960 // specialization type that contains all of the converted
961 // arguments in canonical form. This ensures that, e.g., A<T> and
962 // A<T, T> have identical types when A is declared as:
963 //
964 // template<typename T, typename U = T> struct A;
Douglas Gregorb88ba412009-05-07 06:41:52 +0000965 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
966 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000967 Converted.getFlatArguments(),
968 Converted.flatSize());
Douglas Gregor4262bc92009-07-28 23:00:59 +0000969
970 // FIXME: CanonType is not actually the canonical type, and unfortunately
971 // it is a TemplateTypeSpecializationType that we will never use again.
972 // In the future, we need to teach getTemplateSpecializationType to only
973 // build the canonical type and return that to us.
974 CanonType = Context.getCanonicalType(CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +0000975 } else if (ClassTemplateDecl *ClassTemplate
976 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000977 // Find the class template specialization declaration that
978 // corresponds to these arguments.
979 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +0000980 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000981 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +0000982 Converted.flatSize(),
983 Context);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000984 void *InsertPos = 0;
985 ClassTemplateSpecializationDecl *Decl
986 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
987 if (!Decl) {
988 // This is the first time we have referenced this class template
989 // specialization. Create the canonical declaration and add it to
990 // the set of specializations.
991 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlssona35faf92009-06-05 03:43:12 +0000992 ClassTemplate->getDeclContext(),
993 TemplateLoc,
994 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +0000995 Converted, 0);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000996 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
997 Decl->setLexicalDeclContext(CurContext);
998 }
999
1000 CanonType = Context.getTypeDeclType(Decl);
1001 }
1002
1003 // Build the fully-sugared type for this class template
1004 // specialization, which refers back to the class template
1005 // specialization we created or found.
Douglas Gregordd13e842009-03-30 22:58:21 +00001006 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1007 NumTemplateArgs, CanonType);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001008}
1009
Douglas Gregora08b6c72009-02-17 23:15:12 +00001010Action::TypeResult
Douglas Gregordd13e842009-03-30 22:58:21 +00001011Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1012 SourceLocation LAngleLoc,
1013 ASTTemplateArgsPtr TemplateArgsIn,
1014 SourceLocation *TemplateArgLocs,
1015 SourceLocation RAngleLoc) {
1016 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001017
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001018 // Translate the parser's template argument list in our AST format.
1019 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1020 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001021
Douglas Gregordd13e842009-03-30 22:58:21 +00001022 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +00001023 TemplateArgs.data(),
1024 TemplateArgs.size(),
Douglas Gregordd13e842009-03-30 22:58:21 +00001025 RAngleLoc);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001026 TemplateArgsIn.release();
Douglas Gregord7cb0372009-04-01 21:51:26 +00001027
1028 if (Result.isNull())
1029 return true;
1030
Douglas Gregor6f37b582009-02-09 19:34:22 +00001031 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +00001032}
1033
Douglas Gregor28857752009-06-30 22:34:41 +00001034Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template,
1035 SourceLocation TemplateNameLoc,
1036 SourceLocation LAngleLoc,
1037 const TemplateArgument *TemplateArgs,
1038 unsigned NumTemplateArgs,
1039 SourceLocation RAngleLoc) {
1040 // FIXME: Can we do any checking at this point? I guess we could check the
1041 // template arguments that we have against the template name, if the template
1042 // name refers to a single template. That's not a terribly common case,
1043 // though.
1044 return Owned(TemplateIdRefExpr::Create(Context,
1045 /*FIXME: New type?*/Context.OverloadTy,
1046 /*FIXME: Necessary?*/0,
1047 /*FIXME: Necessary?*/SourceRange(),
1048 Template, TemplateNameLoc, LAngleLoc,
1049 TemplateArgs,
1050 NumTemplateArgs, RAngleLoc));
1051}
1052
1053Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD,
1054 SourceLocation TemplateNameLoc,
1055 SourceLocation LAngleLoc,
1056 ASTTemplateArgsPtr TemplateArgsIn,
1057 SourceLocation *TemplateArgLocs,
1058 SourceLocation RAngleLoc) {
1059 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1060
1061 // Translate the parser's template argument list in our AST format.
1062 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1063 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorf2fedc62009-07-22 20:55:49 +00001064 TemplateArgsIn.release();
Douglas Gregor28857752009-06-30 22:34:41 +00001065
1066 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc,
1067 TemplateArgs.data(), TemplateArgs.size(),
1068 RAngleLoc);
1069}
1070
Douglas Gregoraabb8502009-03-31 00:43:58 +00001071/// \brief Form a dependent template name.
1072///
1073/// This action forms a dependent template name given the template
1074/// name and its (presumably dependent) scope specifier. For
1075/// example, given "MetaFun::template apply", the scope specifier \p
1076/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1077/// of the "template" keyword, and "apply" is the \p Name.
1078Sema::TemplateTy
1079Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1080 const IdentifierInfo &Name,
1081 SourceLocation NameLoc,
1082 const CXXScopeSpec &SS) {
1083 if (!SS.isSet() || SS.isInvalid())
1084 return TemplateTy();
1085
1086 NestedNameSpecifier *Qualifier
1087 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1088
1089 // FIXME: member of the current instantiation
1090
1091 if (!Qualifier->isDependent()) {
1092 // C++0x [temp.names]p5:
1093 // If a name prefixed by the keyword template is not the name of
1094 // a template, the program is ill-formed. [Note: the keyword
1095 // template may not be applied to non-template members of class
1096 // templates. -end note ] [ Note: as is the case with the
1097 // typename prefix, the template prefix is allowed in cases
1098 // where it is not strictly necessary; i.e., when the
1099 // nested-name-specifier or the expression on the left of the ->
1100 // or . is not dependent on a template-parameter, or the use
1101 // does not appear in the scope of a template. -end note]
1102 //
1103 // Note: C++03 was more strict here, because it banned the use of
1104 // the "template" keyword prior to a template-name that was not a
1105 // dependent name. C++ DR468 relaxed this requirement (the
1106 // "template" keyword is now permitted). We follow the C++0x
1107 // rules, even in C++03 mode, retroactively applying the DR.
1108 TemplateTy Template;
1109 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
1110 if (TNK == TNK_Non_template) {
1111 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1112 << &Name;
1113 return TemplateTy();
1114 }
1115
1116 return Template;
1117 }
1118
1119 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
1120}
1121
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001122bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1123 const TemplateArgument &Arg,
1124 TemplateArgumentListBuilder &Converted) {
1125 // Check template type parameter.
1126 if (Arg.getKind() != TemplateArgument::Type) {
1127 // C++ [temp.arg.type]p1:
1128 // A template-argument for a template-parameter which is a
1129 // type shall be a type-id.
1130
1131 // We have a template type parameter but the template argument
1132 // is not a type.
1133 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
1134 Diag(Param->getLocation(), diag::note_template_param_here);
1135
1136 return true;
1137 }
1138
1139 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1140 return true;
1141
1142 // Add the converted template type argument.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001143 Converted.Append(
Anders Carlssonfdd33cc2009-06-13 00:33:33 +00001144 TemplateArgument(Arg.getLocation(),
1145 Context.getCanonicalType(Arg.getAsType())));
1146 return false;
1147}
1148
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001149/// \brief Check that the given template argument list is well-formed
1150/// for specializing the given template.
1151bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1152 SourceLocation TemplateLoc,
1153 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001154 const TemplateArgument *TemplateArgs,
1155 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +00001156 SourceLocation RAngleLoc,
Douglas Gregorecd63b82009-07-01 00:28:38 +00001157 bool PartialTemplateArgs,
Anders Carlssona35faf92009-06-05 03:43:12 +00001158 TemplateArgumentListBuilder &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001159 TemplateParameterList *Params = Template->getTemplateParameters();
1160 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001161 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001162 bool Invalid = false;
1163
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001164 bool HasParameterPack =
1165 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1166
1167 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregorecd63b82009-07-01 00:28:38 +00001168 (NumArgs < Params->getMinRequiredArguments() &&
1169 !PartialTemplateArgs)) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001170 // FIXME: point at either the first arg beyond what we can handle,
1171 // or the '>', depending on whether we have too many or too few
1172 // arguments.
1173 SourceRange Range;
1174 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001175 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001176 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1177 << (NumArgs > NumParams)
1178 << (isa<ClassTemplateDecl>(Template)? 0 :
1179 isa<FunctionTemplateDecl>(Template)? 1 :
1180 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1181 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +00001182 Diag(Template->getLocation(), diag::note_template_decl_here)
1183 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001184 Invalid = true;
1185 }
1186
1187 // C++ [temp.arg]p1:
1188 // [...] The type and form of each template-argument specified in
1189 // a template-id shall match the type and form specified for the
1190 // corresponding parameter declared by the template in its
1191 // template-parameter-list.
1192 unsigned ArgIdx = 0;
1193 for (TemplateParameterList::iterator Param = Params->begin(),
1194 ParamEnd = Params->end();
1195 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregorecd63b82009-07-01 00:28:38 +00001196 if (ArgIdx > NumArgs && PartialTemplateArgs)
1197 break;
1198
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001199 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001200 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001201 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +00001202 // Retrieve the default template argument from the template
1203 // parameter.
1204 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001205 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001206 // We have an empty argument pack.
1207 Converted.BeginPack();
1208 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001209 break;
1210 }
1211
Douglas Gregorad964b32009-02-17 01:05:43 +00001212 if (!TTP->hasDefaultArgument())
1213 break;
1214
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001215 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +00001216
1217 // If the argument type is dependent, instantiate it now based
1218 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001219 if (ArgType->isDependentType()) {
1220 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001221 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001222 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001223 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001224
Anders Carlsson0233eb62009-06-05 04:47:51 +00001225 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001226 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001227 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor74296542009-02-27 19:31:52 +00001228 TTP->getDefaultArgumentLoc(),
1229 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +00001230 }
Douglas Gregor74296542009-02-27 19:31:52 +00001231
1232 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +00001233 return true;
Douglas Gregor74296542009-02-27 19:31:52 +00001234
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001235 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +00001236 } else if (NonTypeTemplateParmDecl *NTTP
1237 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1238 if (!NTTP->hasDefaultArgument())
1239 break;
1240
Anders Carlsson0297caf2009-06-11 16:06:49 +00001241 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001242 Template, Converted.getFlatArguments(),
Anders Carlsson0297caf2009-06-11 16:06:49 +00001243 Converted.flatSize(),
1244 SourceRange(TemplateLoc, RAngleLoc));
1245
1246 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001247 /*TakeArgs=*/false);
Anders Carlsson0297caf2009-06-11 16:06:49 +00001248
1249 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1250 TemplateArgs);
1251 if (E.isInvalid())
1252 return true;
1253
1254 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregorad964b32009-02-17 01:05:43 +00001255 } else {
1256 TemplateTemplateParmDecl *TempParm
1257 = cast<TemplateTemplateParmDecl>(*Param);
1258
1259 if (!TempParm->hasDefaultArgument())
1260 break;
1261
Douglas Gregored3a3982009-03-03 04:44:36 +00001262 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001263 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +00001264 }
1265 } else {
1266 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001267 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +00001268 }
1269
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001270
1271 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001272 if (TTP->isParameterPack()) {
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001273 Converted.BeginPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001274 // Check all the remaining arguments (if any).
1275 for (; ArgIdx < NumArgs; ++ArgIdx) {
1276 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1277 Invalid = true;
1278 }
1279
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001280 Converted.EndPack();
Anders Carlsson4ffb5812009-06-13 02:08:00 +00001281 } else {
1282 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1283 Invalid = true;
1284 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001285 } else if (NonTypeTemplateParmDecl *NTTP
1286 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1287 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +00001288
1289 // Instantiate the type of the non-type template parameter with
1290 // the template arguments we've seen thus far.
1291 QualType NTTPType = NTTP->getType();
1292 if (NTTPType->isDependentType()) {
1293 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +00001294 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001295 Template, Converted.getFlatArguments(),
Anders Carlssona35faf92009-06-05 03:43:12 +00001296 Converted.flatSize(),
Douglas Gregor56d25a72009-03-10 20:44:00 +00001297 SourceRange(TemplateLoc, RAngleLoc));
1298
Anders Carlsson0233eb62009-06-05 04:47:51 +00001299 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001300 /*TakeArgs=*/false);
Douglas Gregorf9e7d3d2009-05-11 23:53:27 +00001301 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregored3a3982009-03-03 04:44:36 +00001302 NTTP->getLocation(),
1303 NTTP->getDeclName());
1304 // If that worked, check the non-type template parameter type
1305 // for validity.
1306 if (!NTTPType.isNull())
1307 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1308 NTTP->getLocation());
Douglas Gregored3a3982009-03-03 04:44:36 +00001309 if (NTTPType.isNull()) {
1310 Invalid = true;
1311 break;
1312 }
1313 }
1314
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001315 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001316 case TemplateArgument::Null:
1317 assert(false && "Should never see a NULL template argument here");
1318 break;
1319
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001320 case TemplateArgument::Expression: {
1321 Expr *E = Arg.getAsExpr();
Douglas Gregor8f378a92009-06-11 18:10:32 +00001322 TemplateArgument Result;
1323 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001324 Invalid = true;
Douglas Gregor8f378a92009-06-11 18:10:32 +00001325 else
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001326 Converted.Append(Result);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001327 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001328 }
1329
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001330 case TemplateArgument::Declaration:
1331 case TemplateArgument::Integral:
1332 // We've already checked this template argument, so just copy
1333 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001334 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001335 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001336
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001337 case TemplateArgument::Type:
1338 // We have a non-type template parameter but the template
1339 // argument is a type.
1340
1341 // C++ [temp.arg]p2:
1342 // In a template-argument, an ambiguity between a type-id and
1343 // an expression is resolved to a type-id, regardless of the
1344 // form of the corresponding template-parameter.
1345 //
1346 // We warn specifically about this case, since it can be rather
1347 // confusing for users.
1348 if (Arg.getAsType()->isFunctionType())
1349 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1350 << Arg.getAsType();
1351 else
1352 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1353 Diag((*Param)->getLocation(), diag::note_template_param_here);
1354 Invalid = true;
Anders Carlsson584b5062009-06-15 17:04:53 +00001355 break;
1356
1357 case TemplateArgument::Pack:
1358 assert(0 && "FIXME: Implement!");
1359 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001360 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001361 } else {
1362 // Check template template parameters.
1363 TemplateTemplateParmDecl *TempParm
1364 = cast<TemplateTemplateParmDecl>(*Param);
1365
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001366 switch (Arg.getKind()) {
Douglas Gregorbf23a8a2009-06-04 00:03:07 +00001367 case TemplateArgument::Null:
1368 assert(false && "Should never see a NULL template argument here");
1369 break;
1370
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001371 case TemplateArgument::Expression: {
1372 Expr *ArgExpr = Arg.getAsExpr();
1373 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1374 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1375 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1376 Invalid = true;
1377
1378 // Add the converted template argument.
Douglas Gregor9054f982009-05-10 22:57:19 +00001379 Decl *D
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001380 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001381 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001382 continue;
1383 }
1384 }
1385 // fall through
1386
1387 case TemplateArgument::Type: {
1388 // We have a template template parameter but the template
1389 // argument does not refer to a template.
1390 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1391 Invalid = true;
1392 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001393 }
1394
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001395 case TemplateArgument::Declaration:
1396 // We've already checked this template argument, so just copy
1397 // it to the list of converted arguments.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00001398 Converted.Append(Arg);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001399 break;
1400
1401 case TemplateArgument::Integral:
1402 assert(false && "Integral argument with template template parameter");
1403 break;
Anders Carlsson584b5062009-06-15 17:04:53 +00001404
1405 case TemplateArgument::Pack:
1406 assert(0 && "FIXME: Implement!");
1407 break;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001408 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001409 }
1410 }
1411
1412 return Invalid;
1413}
1414
1415/// \brief Check a template argument against its corresponding
1416/// template type parameter.
1417///
1418/// This routine implements the semantics of C++ [temp.arg.type]. It
1419/// returns true if an error occurred, and false otherwise.
1420bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1421 QualType Arg, SourceLocation ArgLoc) {
1422 // C++ [temp.arg.type]p2:
1423 // A local type, a type with no linkage, an unnamed type or a type
1424 // compounded from any of these types shall not be used as a
1425 // template-argument for a template type-parameter.
1426 //
1427 // FIXME: Perform the recursive and no-linkage type checks.
1428 const TagType *Tag = 0;
1429 if (const EnumType *EnumT = Arg->getAsEnumType())
1430 Tag = EnumT;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001431 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001432 Tag = RecordT;
1433 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1434 return Diag(ArgLoc, diag::err_template_arg_local_type)
1435 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001436 else if (Tag && !Tag->getDecl()->getDeclName() &&
1437 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001438 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1439 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1440 return true;
1441 }
1442
1443 return false;
1444}
1445
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001446/// \brief Checks whether the given template argument is the address
1447/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001448bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1449 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001450 bool Invalid = false;
1451
1452 // See through any implicit casts we added to fix the type.
1453 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1454 Arg = Cast->getSubExpr();
1455
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001456 // C++0x allows nullptr, and there's no further checking to be done for that.
1457 if (Arg->getType()->isNullPtrType())
1458 return false;
1459
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001460 // C++ [temp.arg.nontype]p1:
1461 //
1462 // A template-argument for a non-type, non-template
1463 // template-parameter shall be one of: [...]
1464 //
1465 // -- the address of an object or function with external
1466 // linkage, including function templates and function
1467 // template-ids but excluding non-static class members,
1468 // expressed as & id-expression where the & is optional if
1469 // the name refers to a function or array, or if the
1470 // corresponding template-parameter is a reference; or
1471 DeclRefExpr *DRE = 0;
1472
1473 // Ignore (and complain about) any excess parentheses.
1474 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1475 if (!Invalid) {
1476 Diag(Arg->getSourceRange().getBegin(),
1477 diag::err_template_arg_extra_parens)
1478 << Arg->getSourceRange();
1479 Invalid = true;
1480 }
1481
1482 Arg = Parens->getSubExpr();
1483 }
1484
1485 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1486 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1487 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1488 } else
1489 DRE = dyn_cast<DeclRefExpr>(Arg);
1490
1491 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1492 return Diag(Arg->getSourceRange().getBegin(),
1493 diag::err_template_arg_not_object_or_func_form)
1494 << Arg->getSourceRange();
1495
1496 // Cannot refer to non-static data members
1497 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1498 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1499 << Field << Arg->getSourceRange();
1500
1501 // Cannot refer to non-static member functions
1502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1503 if (!Method->isStatic())
1504 return Diag(Arg->getSourceRange().getBegin(),
1505 diag::err_template_arg_method)
1506 << Method << Arg->getSourceRange();
1507
1508 // Functions must have external linkage.
1509 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1510 if (Func->getStorageClass() == FunctionDecl::Static) {
1511 Diag(Arg->getSourceRange().getBegin(),
1512 diag::err_template_arg_function_not_extern)
1513 << Func << Arg->getSourceRange();
1514 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1515 << true;
1516 return true;
1517 }
1518
1519 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001520 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001521 return Invalid;
1522 }
1523
1524 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1525 if (!Var->hasGlobalStorage()) {
1526 Diag(Arg->getSourceRange().getBegin(),
1527 diag::err_template_arg_object_not_extern)
1528 << Var << Arg->getSourceRange();
1529 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1530 << true;
1531 return true;
1532 }
1533
1534 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001535 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001536 return Invalid;
1537 }
1538
1539 // We found something else, but we don't know specifically what it is.
1540 Diag(Arg->getSourceRange().getBegin(),
1541 diag::err_template_arg_not_object_or_func)
1542 << Arg->getSourceRange();
1543 Diag(DRE->getDecl()->getLocation(),
1544 diag::note_template_arg_refers_here);
1545 return true;
1546}
1547
1548/// \brief Checks whether the given template argument is a pointer to
1549/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001550bool
1551Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001552 bool Invalid = false;
1553
1554 // See through any implicit casts we added to fix the type.
1555 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1556 Arg = Cast->getSubExpr();
1557
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001558 // C++0x allows nullptr, and there's no further checking to be done for that.
1559 if (Arg->getType()->isNullPtrType())
1560 return false;
1561
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001562 // C++ [temp.arg.nontype]p1:
1563 //
1564 // A template-argument for a non-type, non-template
1565 // template-parameter shall be one of: [...]
1566 //
1567 // -- a pointer to member expressed as described in 5.3.1.
1568 QualifiedDeclRefExpr *DRE = 0;
1569
1570 // Ignore (and complain about) any excess parentheses.
1571 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1572 if (!Invalid) {
1573 Diag(Arg->getSourceRange().getBegin(),
1574 diag::err_template_arg_extra_parens)
1575 << Arg->getSourceRange();
1576 Invalid = true;
1577 }
1578
1579 Arg = Parens->getSubExpr();
1580 }
1581
1582 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1583 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1584 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1585
1586 if (!DRE)
1587 return Diag(Arg->getSourceRange().getBegin(),
1588 diag::err_template_arg_not_pointer_to_member_form)
1589 << Arg->getSourceRange();
1590
1591 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1592 assert((isa<FieldDecl>(DRE->getDecl()) ||
1593 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1594 "Only non-static member pointers can make it here");
1595
1596 // Okay: this is the address of a non-static member, and therefore
1597 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001598 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001599 return Invalid;
1600 }
1601
1602 // We found something else, but we don't know specifically what it is.
1603 Diag(Arg->getSourceRange().getBegin(),
1604 diag::err_template_arg_not_pointer_to_member_form)
1605 << Arg->getSourceRange();
1606 Diag(DRE->getDecl()->getLocation(),
1607 diag::note_template_arg_refers_here);
1608 return true;
1609}
1610
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001611/// \brief Check a template argument against its corresponding
1612/// non-type template parameter.
1613///
Douglas Gregored3a3982009-03-03 04:44:36 +00001614/// This routine implements the semantics of C++ [temp.arg.nontype].
1615/// It returns true if an error occurred, and false otherwise. \p
1616/// InstantiatedParamType is the type of the non-type template
1617/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001618///
Douglas Gregor8f378a92009-06-11 18:10:32 +00001619/// If no error was detected, Converted receives the converted template argument.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001620bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001621 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor8f378a92009-06-11 18:10:32 +00001622 TemplateArgument &Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001623 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1624
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001625 // If either the parameter has a dependent type or the argument is
1626 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001627 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001628 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1629 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor8f378a92009-06-11 18:10:32 +00001630 Converted = TemplateArgument(Arg);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001631 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001632 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001633
1634 // C++ [temp.arg.nontype]p5:
1635 // The following conversions are performed on each expression used
1636 // as a non-type template-argument. If a non-type
1637 // template-argument cannot be converted to the type of the
1638 // corresponding template-parameter then the program is
1639 // ill-formed.
1640 //
1641 // -- for a non-type template-parameter of integral or
1642 // enumeration type, integral promotions (4.5) and integral
1643 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001644 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001645 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001646 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001647 // C++ [temp.arg.nontype]p1:
1648 // A template-argument for a non-type, non-template
1649 // template-parameter shall be one of:
1650 //
1651 // -- an integral constant-expression of integral or enumeration
1652 // type; or
1653 // -- the name of a non-type template-parameter; or
1654 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001655 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001656 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1657 Diag(Arg->getSourceRange().getBegin(),
1658 diag::err_template_arg_not_integral_or_enumeral)
1659 << ArgType << Arg->getSourceRange();
1660 Diag(Param->getLocation(), diag::note_template_param_here);
1661 return true;
1662 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001663 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001664 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1665 << ArgType << Arg->getSourceRange();
1666 return true;
1667 }
1668
1669 // FIXME: We need some way to more easily get the unqualified form
1670 // of the types without going all the way to the
1671 // canonical type.
1672 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1673 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1674 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1675 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1676
1677 // Try to convert the argument to the parameter's type.
1678 if (ParamType == ArgType) {
1679 // Okay: no conversion necessary
1680 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1681 !ParamType->isEnumeralType()) {
1682 // This is an integral promotion or conversion.
1683 ImpCastExprToType(Arg, ParamType);
1684 } else {
1685 // We can't perform this conversion.
1686 Diag(Arg->getSourceRange().getBegin(),
1687 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001688 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001689 Diag(Param->getLocation(), diag::note_template_param_here);
1690 return true;
1691 }
1692
Douglas Gregorafc86942009-03-14 00:20:21 +00001693 QualType IntegerType = Context.getCanonicalType(ParamType);
1694 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor8f378a92009-06-11 18:10:32 +00001695 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorafc86942009-03-14 00:20:21 +00001696
1697 if (!Arg->isValueDependent()) {
1698 // Check that an unsigned parameter does not receive a negative
1699 // value.
1700 if (IntegerType->isUnsignedIntegerType()
1701 && (Value.isSigned() && Value.isNegative())) {
1702 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1703 << Value.toString(10) << Param->getType()
1704 << Arg->getSourceRange();
1705 Diag(Param->getLocation(), diag::note_template_param_here);
1706 return true;
1707 }
1708
1709 // Check that we don't overflow the template parameter type.
1710 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1711 if (Value.getActiveBits() > AllowedBits) {
1712 Diag(Arg->getSourceRange().getBegin(),
1713 diag::err_template_arg_too_large)
1714 << Value.toString(10) << Param->getType()
1715 << Arg->getSourceRange();
1716 Diag(Param->getLocation(), diag::note_template_param_here);
1717 return true;
1718 }
1719
1720 if (Value.getBitWidth() != AllowedBits)
1721 Value.extOrTrunc(AllowedBits);
1722 Value.setIsSigned(IntegerType->isSignedIntegerType());
1723 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001724
Douglas Gregor8f378a92009-06-11 18:10:32 +00001725 // Add the value of this argument to the list of converted
1726 // arguments. We use the bitwidth and signedness of the template
1727 // parameter.
1728 if (Arg->isValueDependent()) {
1729 // The argument is value-dependent. Create a new
1730 // TemplateArgument with the converted expression.
1731 Converted = TemplateArgument(Arg);
1732 return false;
Douglas Gregorad964b32009-02-17 01:05:43 +00001733 }
1734
Douglas Gregor8f378a92009-06-11 18:10:32 +00001735 Converted = TemplateArgument(StartLoc, Value,
1736 ParamType->isEnumeralType() ? ParamType
1737 : IntegerType);
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001738 return false;
1739 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001740
Douglas Gregor3f411962009-02-11 01:18:59 +00001741 // Handle pointer-to-function, reference-to-function, and
1742 // pointer-to-member-function all in (roughly) the same way.
1743 if (// -- For a non-type template-parameter of type pointer to
1744 // function, only the function-to-pointer conversion (4.3) is
1745 // applied. If the template-argument represents a set of
1746 // overloaded functions (or a pointer to such), the matching
1747 // function is selected from the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001748 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor3f411962009-02-11 01:18:59 +00001749 (ParamType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001750 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001751 // -- For a non-type template-parameter of type reference to
1752 // function, no conversions apply. If the template-argument
1753 // represents a set of overloaded functions, the matching
1754 // function is selected from the set (13.4).
1755 (ParamType->isReferenceType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001756 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor3f411962009-02-11 01:18:59 +00001757 // -- For a non-type template-parameter of type pointer to
1758 // member function, no conversions apply. If the
1759 // template-argument represents a set of overloaded member
1760 // functions, the matching member function is selected from
1761 // the set (13.4).
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001762 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor3f411962009-02-11 01:18:59 +00001763 (ParamType->isMemberPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001764 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001765 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001766 if (Context.hasSameUnqualifiedType(ArgType,
1767 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001768 // We don't have to do anything: the types already match.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001769 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1770 ParamType->isMemberPointerType())) {
1771 ArgType = ParamType;
1772 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3f411962009-02-11 01:18:59 +00001773 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001774 ArgType = Context.getPointerType(ArgType);
1775 ImpCastExprToType(Arg, ArgType);
1776 } else if (FunctionDecl *Fn
1777 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001778 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1779 return true;
1780
Douglas Gregor2eedd992009-02-11 00:19:33 +00001781 FixOverloadedFunctionReference(Arg, Fn);
1782 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001783 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001784 ArgType = Context.getPointerType(Arg->getType());
1785 ImpCastExprToType(Arg, ArgType);
1786 }
1787 }
1788
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001789 if (!Context.hasSameUnqualifiedType(ArgType,
1790 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001791 // We can't perform this conversion.
1792 Diag(Arg->getSourceRange().getBegin(),
1793 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001794 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001795 Diag(Param->getLocation(), diag::note_template_param_here);
1796 return true;
1797 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001798
Douglas Gregorad964b32009-02-17 01:05:43 +00001799 if (ParamType->isMemberPointerType()) {
1800 NamedDecl *Member = 0;
1801 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1802 return true;
1803
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001804 if (Member)
1805 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001806 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001807 return false;
1808 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001809
Douglas Gregorad964b32009-02-17 01:05:43 +00001810 NamedDecl *Entity = 0;
1811 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1812 return true;
1813
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001814 if (Entity)
1815 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001816 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001817 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001818 }
1819
Chris Lattner320dff22009-02-20 21:37:53 +00001820 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001821 // -- for a non-type template-parameter of type pointer to
1822 // object, qualification conversions (4.4) and the
1823 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001824 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001825 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001826 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001827
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001828 if (ArgType->isNullPtrType()) {
1829 ArgType = ParamType;
1830 ImpCastExprToType(Arg, ParamType);
1831 } else if (ArgType->isArrayType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001832 ArgType = Context.getArrayDecayedType(ArgType);
1833 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001834 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001835
Douglas Gregor3f411962009-02-11 01:18:59 +00001836 if (IsQualificationConversion(ArgType, ParamType)) {
1837 ArgType = ParamType;
1838 ImpCastExprToType(Arg, ParamType);
1839 }
1840
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001841 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001842 // We can't perform this conversion.
1843 Diag(Arg->getSourceRange().getBegin(),
1844 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001845 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001846 Diag(Param->getLocation(), diag::note_template_param_here);
1847 return true;
1848 }
1849
Douglas Gregorad964b32009-02-17 01:05:43 +00001850 NamedDecl *Entity = 0;
1851 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1852 return true;
1853
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001854 if (Entity)
1855 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001856 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001857 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001858 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001859
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001860 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001861 // -- For a non-type template-parameter of type reference to
1862 // object, no conversions apply. The type referred to by the
1863 // reference may be more cv-qualified than the (otherwise
1864 // identical) type of the template-argument. The
1865 // template-parameter is bound directly to the
1866 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001867 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001868 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001869
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001870 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001871 Diag(Arg->getSourceRange().getBegin(),
1872 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001873 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001874 << Arg->getSourceRange();
1875 Diag(Param->getLocation(), diag::note_template_param_here);
1876 return true;
1877 }
1878
1879 unsigned ParamQuals
1880 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1881 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1882
1883 if ((ParamQuals | ArgQuals) != ParamQuals) {
1884 Diag(Arg->getSourceRange().getBegin(),
1885 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001886 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001887 << Arg->getSourceRange();
1888 Diag(Param->getLocation(), diag::note_template_param_here);
1889 return true;
1890 }
1891
Douglas Gregorad964b32009-02-17 01:05:43 +00001892 NamedDecl *Entity = 0;
1893 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1894 return true;
1895
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001896 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001897 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregorad964b32009-02-17 01:05:43 +00001898 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001899 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001900
1901 // -- For a non-type template-parameter of type pointer to data
1902 // member, qualification conversions (4.4) are applied.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001903 // C++0x allows std::nullptr_t values.
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001904 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1905
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001906 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001907 // Types match exactly: nothing more to do here.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001908 } else if (ArgType->isNullPtrType()) {
1909 ImpCastExprToType(Arg, ParamType);
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001910 } else if (IsQualificationConversion(ArgType, ParamType)) {
1911 ImpCastExprToType(Arg, ParamType);
1912 } else {
1913 // We can't perform this conversion.
1914 Diag(Arg->getSourceRange().getBegin(),
1915 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001916 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001917 Diag(Param->getLocation(), diag::note_template_param_here);
1918 return true;
1919 }
1920
Douglas Gregorad964b32009-02-17 01:05:43 +00001921 NamedDecl *Member = 0;
1922 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1923 return true;
1924
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00001925 if (Member)
1926 Member = cast<NamedDecl>(Member->getCanonicalDecl());
Douglas Gregor8f378a92009-06-11 18:10:32 +00001927 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregorad964b32009-02-17 01:05:43 +00001928 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001929}
1930
1931/// \brief Check a template argument against its corresponding
1932/// template template parameter.
1933///
1934/// This routine implements the semantics of C++ [temp.arg.template].
1935/// It returns true if an error occurred, and false otherwise.
1936bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1937 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001938 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1939 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1940
1941 // C++ [temp.arg.template]p1:
1942 // A template-argument for a template template-parameter shall be
1943 // the name of a class template, expressed as id-expression. Only
1944 // primary class templates are considered when matching the
1945 // template template argument with the corresponding parameter;
1946 // partial specializations are not considered even if their
1947 // parameter lists match that of the template template parameter.
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00001948 //
1949 // Note that we also allow template template parameters here, which
1950 // will happen when we are dealing with, e.g., class template
1951 // partial specializations.
1952 if (!isa<ClassTemplateDecl>(Template) &&
1953 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001954 assert(isa<FunctionTemplateDecl>(Template) &&
1955 "Only function templates are possible here");
Douglas Gregorb60eb752009-06-25 22:08:12 +00001956 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
1957 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001958 << Template;
1959 }
1960
1961 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1962 Param->getTemplateParameters(),
1963 true, true,
1964 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001965}
1966
Douglas Gregord406b032009-02-06 22:42:48 +00001967/// \brief Determine whether the given template parameter lists are
1968/// equivalent.
1969///
1970/// \param New The new template parameter list, typically written in the
1971/// source code as part of a new template declaration.
1972///
1973/// \param Old The old template parameter list, typically found via
1974/// name lookup of the template declared with this template parameter
1975/// list.
1976///
1977/// \param Complain If true, this routine will produce a diagnostic if
1978/// the template parameter lists are not equivalent.
1979///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001980/// \param IsTemplateTemplateParm If true, this routine is being
1981/// called to compare the template parameter lists of a template
1982/// template parameter.
1983///
1984/// \param TemplateArgLoc If this source location is valid, then we
1985/// are actually checking the template parameter list of a template
1986/// argument (New) against the template parameter list of its
1987/// corresponding template template parameter (Old). We produce
1988/// slightly different diagnostics in this scenario.
1989///
Douglas Gregord406b032009-02-06 22:42:48 +00001990/// \returns True if the template parameter lists are equal, false
1991/// otherwise.
1992bool
1993Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1994 TemplateParameterList *Old,
1995 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001996 bool IsTemplateTemplateParm,
1997 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001998 if (Old->size() != New->size()) {
1999 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002000 unsigned NextDiag = diag::err_template_param_list_different_arity;
2001 if (TemplateArgLoc.isValid()) {
2002 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2003 NextDiag = diag::note_template_param_list_different_arity;
2004 }
2005 Diag(New->getTemplateLoc(), NextDiag)
2006 << (New->size() > Old->size())
2007 << IsTemplateTemplateParm
2008 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00002009 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2010 << IsTemplateTemplateParm
2011 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2012 }
2013
2014 return false;
2015 }
2016
2017 for (TemplateParameterList::iterator OldParm = Old->begin(),
2018 OldParmEnd = Old->end(), NewParm = New->begin();
2019 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2020 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +00002021 if (Complain) {
2022 unsigned NextDiag = diag::err_template_param_different_kind;
2023 if (TemplateArgLoc.isValid()) {
2024 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2025 NextDiag = diag::note_template_param_different_kind;
2026 }
2027 Diag((*NewParm)->getLocation(), NextDiag)
2028 << IsTemplateTemplateParm;
2029 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2030 << IsTemplateTemplateParm;
Douglas Gregore8e367f2009-02-10 00:24:35 +00002031 }
Douglas Gregord406b032009-02-06 22:42:48 +00002032 return false;
2033 }
2034
2035 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2036 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00002037 // know we're at the same index).
2038#if 0
Mike Stumpe127ae32009-05-16 07:39:55 +00002039 // FIXME: Enable this code in debug mode *after* we properly go through
2040 // and "instantiate" the template parameter lists of template template
2041 // parameters. It's only after this instantiation that (1) any dependent
2042 // types within the template parameter list of the template template
2043 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregore8e367f2009-02-10 00:24:35 +00002044 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00002045 QualType OldParmType
2046 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
2047 QualType NewParmType
2048 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
2049 assert(Context.getCanonicalType(OldParmType) ==
2050 Context.getCanonicalType(NewParmType) &&
2051 "type parameter mismatch?");
2052#endif
2053 } else if (NonTypeTemplateParmDecl *OldNTTP
2054 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2055 // The types of non-type template parameters must agree.
2056 NonTypeTemplateParmDecl *NewNTTP
2057 = cast<NonTypeTemplateParmDecl>(*NewParm);
2058 if (Context.getCanonicalType(OldNTTP->getType()) !=
2059 Context.getCanonicalType(NewNTTP->getType())) {
2060 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00002061 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2062 if (TemplateArgLoc.isValid()) {
2063 Diag(TemplateArgLoc,
2064 diag::err_template_arg_template_params_mismatch);
2065 NextDiag = diag::note_template_nontype_parm_different_type;
2066 }
2067 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00002068 << NewNTTP->getType()
2069 << IsTemplateTemplateParm;
2070 Diag(OldNTTP->getLocation(),
2071 diag::note_template_nontype_parm_prev_declaration)
2072 << OldNTTP->getType();
2073 }
2074 return false;
2075 }
2076 } else {
2077 // The template parameter lists of template template
2078 // parameters must agree.
2079 // FIXME: Could we perform a faster "type" comparison here?
2080 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
2081 "Only template template parameters handled here");
2082 TemplateTemplateParmDecl *OldTTP
2083 = cast<TemplateTemplateParmDecl>(*OldParm);
2084 TemplateTemplateParmDecl *NewTTP
2085 = cast<TemplateTemplateParmDecl>(*NewParm);
2086 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2087 OldTTP->getTemplateParameters(),
2088 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00002089 /*IsTemplateTemplateParm=*/true,
2090 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00002091 return false;
2092 }
2093 }
2094
2095 return true;
2096}
2097
2098/// \brief Check whether a template can be declared within this scope.
2099///
2100/// If the template declaration is valid in this scope, returns
2101/// false. Otherwise, issues a diagnostic and returns true.
2102bool
2103Sema::CheckTemplateDeclScope(Scope *S,
2104 MultiTemplateParamsArg &TemplateParameterLists) {
2105 assert(TemplateParameterLists.size() > 0 && "Not a template");
2106
2107 // Find the nearest enclosing declaration scope.
2108 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2109 (S->getFlags() & Scope::TemplateParamScope) != 0)
2110 S = S->getParent();
2111
2112 TemplateParameterList *TemplateParams =
2113 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2114 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
2115 SourceRange TemplateRange
2116 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
2117
2118 // C++ [temp]p2:
2119 // A template-declaration can appear only as a namespace scope or
2120 // class scope declaration.
2121 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandda81522009-07-31 01:43:05 +00002122 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2123 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
2124 return Diag(TemplateLoc, diag::err_template_linkage) << TemplateRange;
2125
2126 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregord406b032009-02-06 22:42:48 +00002127 Ctx = Ctx->getParent();
Douglas Gregord406b032009-02-06 22:42:48 +00002128
2129 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2130 return false;
2131
2132 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
2133 << TemplateRange;
2134}
Douglas Gregora08b6c72009-02-17 23:15:12 +00002135
Douglas Gregor90177912009-05-13 18:28:20 +00002136/// \brief Check whether a class template specialization or explicit
2137/// instantiation in the current context is well-formed.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002138///
Douglas Gregor90177912009-05-13 18:28:20 +00002139/// This routine determines whether a class template specialization or
2140/// explicit instantiation can be declared in the current context
2141/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
2142/// appropriate diagnostics if there was an error. It returns true if
2143// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor0d93f692009-02-25 22:02:03 +00002144bool
2145Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2146 ClassTemplateSpecializationDecl *PrevDecl,
2147 SourceLocation TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002148 SourceRange ScopeSpecifierRange,
Douglas Gregor4faa4262009-06-12 22:21:45 +00002149 bool PartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002150 bool ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002151 // C++ [temp.expl.spec]p2:
2152 // An explicit specialization shall be declared in the namespace
2153 // of which the template is a member, or, for member templates, in
2154 // the namespace of which the enclosing class or enclosing class
2155 // template is a member. An explicit specialization of a member
2156 // function, member class or static data member of a class
2157 // template shall be declared in the namespace of which the class
2158 // template is a member. Such a declaration may also be a
2159 // definition. If the declaration is not a definition, the
2160 // specialization may be defined later in the name- space in which
2161 // the explicit specialization was declared, or in a namespace
2162 // that encloses the one in which the explicit specialization was
2163 // declared.
2164 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor4faa4262009-06-12 22:21:45 +00002165 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002166 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002167 << Kind << ClassTemplate;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002168 return true;
2169 }
2170
2171 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2172 DeclContext *TemplateContext
2173 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor90177912009-05-13 18:28:20 +00002174 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2175 !ExplicitInstantiation) {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002176 // There is no prior declaration of this entity, so this
2177 // specialization must be in the same context as the template
2178 // itself.
2179 if (DC != TemplateContext) {
2180 if (isa<TranslationUnitDecl>(TemplateContext))
2181 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002182 << PartialSpecialization
Douglas Gregor0d93f692009-02-25 22:02:03 +00002183 << ClassTemplate << ScopeSpecifierRange;
2184 else if (isa<NamespaceDecl>(TemplateContext))
2185 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002186 << PartialSpecialization << ClassTemplate
2187 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002188
2189 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2190 }
2191
2192 return false;
2193 }
2194
2195 // We have a previous declaration of this entity. Make sure that
2196 // this redeclaration (or definition) occurs in an enclosing namespace.
2197 if (!CurContext->Encloses(TemplateContext)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002198 // FIXME: In C++98, we would like to turn these errors into warnings,
2199 // dependent on a -Wc++0x flag.
Douglas Gregor90177912009-05-13 18:28:20 +00002200 bool SuppressedDiag = false;
Douglas Gregor4faa4262009-06-12 22:21:45 +00002201 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor90177912009-05-13 18:28:20 +00002202 if (isa<TranslationUnitDecl>(TemplateContext)) {
2203 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2204 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002205 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregor90177912009-05-13 18:28:20 +00002206 else
2207 SuppressedDiag = true;
2208 } else if (isa<NamespaceDecl>(TemplateContext)) {
2209 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2210 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor4faa4262009-06-12 22:21:45 +00002211 << Kind << ClassTemplate
Douglas Gregor90177912009-05-13 18:28:20 +00002212 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2213 else
2214 SuppressedDiag = true;
2215 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002216
Douglas Gregor90177912009-05-13 18:28:20 +00002217 if (!SuppressedDiag)
2218 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor0d93f692009-02-25 22:02:03 +00002219 }
2220
2221 return false;
2222}
2223
Douglas Gregor76e79952009-06-12 21:21:02 +00002224/// \brief Check the non-type template arguments of a class template
2225/// partial specialization according to C++ [temp.class.spec]p9.
2226///
Douglas Gregor42476442009-06-12 22:08:06 +00002227/// \param TemplateParams the template parameters of the primary class
2228/// template.
2229///
2230/// \param TemplateArg the template arguments of the class template
2231/// partial specialization.
2232///
2233/// \param MirrorsPrimaryTemplate will be set true if the class
2234/// template partial specialization arguments are identical to the
2235/// implicit template arguments of the primary template. This is not
2236/// necessarily an error (C++0x), and it is left to the caller to diagnose
2237/// this condition when it is an error.
2238///
Douglas Gregor76e79952009-06-12 21:21:02 +00002239/// \returns true if there was an error, false otherwise.
2240bool Sema::CheckClassTemplatePartialSpecializationArgs(
2241 TemplateParameterList *TemplateParams,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002242 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor42476442009-06-12 22:08:06 +00002243 bool &MirrorsPrimaryTemplate) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002244 // FIXME: the interface to this function will have to change to
2245 // accommodate variadic templates.
Douglas Gregor42476442009-06-12 22:08:06 +00002246 MirrorsPrimaryTemplate = true;
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002247
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002248 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002249
Douglas Gregor76e79952009-06-12 21:21:02 +00002250 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor42476442009-06-12 22:08:06 +00002251 // Determine whether the template argument list of the partial
2252 // specialization is identical to the implicit argument list of
2253 // the primary template. The caller may need to diagnostic this as
2254 // an error per C++ [temp.class.spec]p9b3.
2255 if (MirrorsPrimaryTemplate) {
2256 if (TemplateTypeParmDecl *TTP
2257 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2258 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002259 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor42476442009-06-12 22:08:06 +00002260 MirrorsPrimaryTemplate = false;
2261 } else if (TemplateTemplateParmDecl *TTP
2262 = dyn_cast<TemplateTemplateParmDecl>(
2263 TemplateParams->getParam(I))) {
2264 // FIXME: We should settle on either Declaration storage or
2265 // Expression storage for template template parameters.
2266 TemplateTemplateParmDecl *ArgDecl
2267 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002268 ArgList[I].getAsDecl());
Douglas Gregor42476442009-06-12 22:08:06 +00002269 if (!ArgDecl)
2270 if (DeclRefExpr *DRE
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002271 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor42476442009-06-12 22:08:06 +00002272 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2273
2274 if (!ArgDecl ||
2275 ArgDecl->getIndex() != TTP->getIndex() ||
2276 ArgDecl->getDepth() != TTP->getDepth())
2277 MirrorsPrimaryTemplate = false;
2278 }
2279 }
2280
Douglas Gregor76e79952009-06-12 21:21:02 +00002281 NonTypeTemplateParmDecl *Param
2282 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor42476442009-06-12 22:08:06 +00002283 if (!Param) {
Douglas Gregor76e79952009-06-12 21:21:02 +00002284 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002285 }
2286
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002287 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor42476442009-06-12 22:08:06 +00002288 if (!ArgExpr) {
2289 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002290 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002291 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002292
2293 // C++ [temp.class.spec]p8:
2294 // A non-type argument is non-specialized if it is the name of a
2295 // non-type parameter. All other non-type arguments are
2296 // specialized.
2297 //
2298 // Below, we check the two conditions that only apply to
2299 // specialized non-type arguments, so skip any non-specialized
2300 // arguments.
2301 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor42476442009-06-12 22:08:06 +00002302 if (NonTypeTemplateParmDecl *NTTP
2303 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2304 if (MirrorsPrimaryTemplate &&
2305 (Param->getIndex() != NTTP->getIndex() ||
2306 Param->getDepth() != NTTP->getDepth()))
2307 MirrorsPrimaryTemplate = false;
2308
Douglas Gregor76e79952009-06-12 21:21:02 +00002309 continue;
Douglas Gregor42476442009-06-12 22:08:06 +00002310 }
Douglas Gregor76e79952009-06-12 21:21:02 +00002311
2312 // C++ [temp.class.spec]p9:
2313 // Within the argument list of a class template partial
2314 // specialization, the following restrictions apply:
2315 // -- A partially specialized non-type argument expression
2316 // shall not involve a template parameter of the partial
2317 // specialization except when the argument expression is a
2318 // simple identifier.
2319 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2320 Diag(ArgExpr->getLocStart(),
2321 diag::err_dependent_non_type_arg_in_partial_spec)
2322 << ArgExpr->getSourceRange();
2323 return true;
2324 }
2325
2326 // -- The type of a template parameter corresponding to a
2327 // specialized non-type argument shall not be dependent on a
2328 // parameter of the specialization.
2329 if (Param->getType()->isDependentType()) {
2330 Diag(ArgExpr->getLocStart(),
2331 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2332 << Param->getType()
2333 << ArgExpr->getSourceRange();
2334 Diag(Param->getLocation(), diag::note_template_param_here);
2335 return true;
2336 }
Douglas Gregor42476442009-06-12 22:08:06 +00002337
2338 MirrorsPrimaryTemplate = false;
Douglas Gregor76e79952009-06-12 21:21:02 +00002339 }
2340
2341 return false;
2342}
2343
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002344Sema::DeclResult
John McCall069c23a2009-07-31 02:45:11 +00002345Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2346 TagUseKind TUK,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002347 SourceLocation KWLoc,
2348 const CXXScopeSpec &SS,
Douglas Gregordd13e842009-03-30 22:58:21 +00002349 TemplateTy TemplateD,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002350 SourceLocation TemplateNameLoc,
2351 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002352 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002353 SourceLocation *TemplateArgLocs,
2354 SourceLocation RAngleLoc,
2355 AttributeList *Attr,
2356 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002357 // Find the class template we're specializing
Douglas Gregordd13e842009-03-30 22:58:21 +00002358 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002359 ClassTemplateDecl *ClassTemplate
Douglas Gregordd13e842009-03-30 22:58:21 +00002360 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002361
Douglas Gregor58944ac2009-05-31 09:31:02 +00002362 bool isPartialSpecialization = false;
2363
Douglas Gregor0d93f692009-02-25 22:02:03 +00002364 // Check the validity of the template headers that introduce this
2365 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00002366 // FIXME: Once we have member templates, we'll need to check
2367 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2368 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00002369 if (TemplateParameterLists.size() == 0)
2370 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00002371 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00002372 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00002373 TemplateParameterList *TemplateParams
2374 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattner5261d0c2009-03-28 19:18:32 +00002375 if (TemplateParameterLists.size() > 1) {
2376 Diag(TemplateParams->getTemplateLoc(),
2377 diag::err_template_spec_extra_headers);
2378 return true;
2379 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002380
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002381 if (TemplateParams->size() > 0) {
Douglas Gregor58944ac2009-05-31 09:31:02 +00002382 isPartialSpecialization = true;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002383
2384 // C++ [temp.class.spec]p10:
2385 // The template parameter list of a specialization shall not
2386 // contain default template argument values.
2387 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2388 Decl *Param = TemplateParams->getParam(I);
2389 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2390 if (TTP->hasDefaultArgument()) {
2391 Diag(TTP->getDefaultArgumentLoc(),
2392 diag::err_default_arg_in_partial_spec);
2393 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2394 }
2395 } else if (NonTypeTemplateParmDecl *NTTP
2396 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2397 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2398 Diag(NTTP->getDefaultArgumentLoc(),
2399 diag::err_default_arg_in_partial_spec)
2400 << DefArg->getSourceRange();
2401 NTTP->setDefaultArgument(0);
2402 DefArg->Destroy(Context);
2403 }
2404 } else {
2405 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2406 if (Expr *DefArg = TTP->getDefaultArgument()) {
2407 Diag(TTP->getDefaultArgumentLoc(),
2408 diag::err_default_arg_in_partial_spec)
2409 << DefArg->getSourceRange();
2410 TTP->setDefaultArgument(0);
2411 DefArg->Destroy(Context);
2412 }
2413 }
2414 }
2415 }
Douglas Gregor0d93f692009-02-25 22:02:03 +00002416 }
2417
Douglas Gregora08b6c72009-02-17 23:15:12 +00002418 // Check that the specialization uses the same tag kind as the
2419 // original template.
2420 TagDecl::TagKind Kind;
2421 switch (TagSpec) {
2422 default: assert(0 && "Unknown tag type!");
2423 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2424 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2425 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2426 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002427 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2428 Kind, KWLoc,
2429 *ClassTemplate->getIdentifier())) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00002430 Diag(KWLoc, diag::err_use_with_wrong_tag)
2431 << ClassTemplate
2432 << CodeModificationHint::CreateReplacement(KWLoc,
2433 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002434 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2435 diag::note_previous_use);
2436 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2437 }
2438
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002439 // Translate the parser's template argument list in our AST format.
2440 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2441 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2442
Douglas Gregora08b6c72009-02-17 23:15:12 +00002443 // Check that the template argument list is well-formed for this
2444 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002445 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2446 TemplateArgs.size());
Douglas Gregora08b6c72009-02-17 23:15:12 +00002447 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002448 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002449 RAngleLoc, false, Converted))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002450 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002451
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002452 assert((Converted.structuredSize() ==
Douglas Gregora08b6c72009-02-17 23:15:12 +00002453 ClassTemplate->getTemplateParameters()->size()) &&
2454 "Converted template argument list is too short!");
2455
Douglas Gregor58944ac2009-05-31 09:31:02 +00002456 // Find the class template (partial) specialization declaration that
Douglas Gregora08b6c72009-02-17 23:15:12 +00002457 // corresponds to these arguments.
2458 llvm::FoldingSetNodeID ID;
Douglas Gregorfbcc9e92009-06-12 19:43:02 +00002459 if (isPartialSpecialization) {
Douglas Gregor42476442009-06-12 22:08:06 +00002460 bool MirrorsPrimaryTemplate;
Douglas Gregor76e79952009-06-12 21:21:02 +00002461 if (CheckClassTemplatePartialSpecializationArgs(
2462 ClassTemplate->getTemplateParameters(),
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002463 Converted, MirrorsPrimaryTemplate))
Douglas Gregor76e79952009-06-12 21:21:02 +00002464 return true;
2465
Douglas Gregor42476442009-06-12 22:08:06 +00002466 if (MirrorsPrimaryTemplate) {
2467 // C++ [temp.class.spec]p9b3:
2468 //
2469 // -- The argument list of the specialization shall not be identical
2470 // to the implicit argument list of the primary template.
2471 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall069c23a2009-07-31 02:45:11 +00002472 << (TUK == TUK_Definition)
Douglas Gregor42476442009-06-12 22:08:06 +00002473 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2474 RAngleLoc));
John McCall069c23a2009-07-31 02:45:11 +00002475 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor42476442009-06-12 22:08:06 +00002476 ClassTemplate->getIdentifier(),
2477 TemplateNameLoc,
2478 Attr,
2479 move(TemplateParameterLists),
2480 AS_none);
2481 }
2482
Douglas Gregor58944ac2009-05-31 09:31:02 +00002483 // FIXME: Template parameter list matters, too
Anders Carlssona35faf92009-06-05 03:43:12 +00002484 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002485 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002486 Converted.flatSize(),
2487 Context);
Mike Stump90fc78e2009-08-04 21:02:39 +00002488 } else
Anders Carlssona35faf92009-06-05 03:43:12 +00002489 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002490 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002491 Converted.flatSize(),
2492 Context);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002493 void *InsertPos = 0;
Douglas Gregor58944ac2009-05-31 09:31:02 +00002494 ClassTemplateSpecializationDecl *PrevDecl = 0;
2495
2496 if (isPartialSpecialization)
2497 PrevDecl
2498 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2499 InsertPos);
2500 else
2501 PrevDecl
2502 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002503
2504 ClassTemplateSpecializationDecl *Specialization = 0;
2505
Douglas Gregor0d93f692009-02-25 22:02:03 +00002506 // Check whether we can declare a class template specialization in
2507 // the current scope.
2508 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2509 TemplateNameLoc,
Douglas Gregor90177912009-05-13 18:28:20 +00002510 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002511 isPartialSpecialization,
Douglas Gregor90177912009-05-13 18:28:20 +00002512 /*ExplicitInstantiation=*/false))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002513 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00002514
Douglas Gregor1930d202009-07-30 17:40:51 +00002515 // The canonical type
2516 QualType CanonType;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002517 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2518 // Since the only prior class template specialization with these
2519 // arguments was referenced but not declared, reuse that
2520 // declaration node as our own, updating its source location to
2521 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002522 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00002523 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002524 PrevDecl = 0;
Douglas Gregor1930d202009-07-30 17:40:51 +00002525 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002526 } else if (isPartialSpecialization) {
Douglas Gregor1930d202009-07-30 17:40:51 +00002527 // Build the canonical type that describes the converted template
2528 // arguments of the class template partial specialization.
2529 CanonType = Context.getTemplateSpecializationType(
2530 TemplateName(ClassTemplate),
2531 Converted.getFlatArguments(),
2532 Converted.flatSize());
2533
Douglas Gregor58944ac2009-05-31 09:31:02 +00002534 // Create a new class template partial specialization declaration node.
2535 TemplateParameterList *TemplateParams
2536 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2537 ClassTemplatePartialSpecializationDecl *PrevPartial
2538 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2539 ClassTemplatePartialSpecializationDecl *Partial
2540 = ClassTemplatePartialSpecializationDecl::Create(Context,
2541 ClassTemplate->getDeclContext(),
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002542 TemplateNameLoc,
2543 TemplateParams,
2544 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002545 Converted,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002546 PrevPartial);
Douglas Gregor58944ac2009-05-31 09:31:02 +00002547
2548 if (PrevPartial) {
2549 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2550 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2551 } else {
2552 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2553 }
2554 Specialization = Partial;
Douglas Gregorf90c2132009-06-13 00:26:55 +00002555
2556 // Check that all of the template parameters of the class template
2557 // partial specialization are deducible from the template
2558 // arguments. If not, this class template partial specialization
2559 // will never be used.
2560 llvm::SmallVector<bool, 8> DeducibleParams;
2561 DeducibleParams.resize(TemplateParams->size());
2562 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2563 unsigned NumNonDeducible = 0;
2564 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2565 if (!DeducibleParams[I])
2566 ++NumNonDeducible;
2567
2568 if (NumNonDeducible) {
2569 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2570 << (NumNonDeducible > 1)
2571 << SourceRange(TemplateNameLoc, RAngleLoc);
2572 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2573 if (!DeducibleParams[I]) {
2574 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2575 if (Param->getDeclName())
2576 Diag(Param->getLocation(),
2577 diag::note_partial_spec_unused_parameter)
2578 << Param->getDeclName();
2579 else
2580 Diag(Param->getLocation(),
2581 diag::note_partial_spec_unused_parameter)
2582 << std::string("<anonymous>");
2583 }
2584 }
2585 }
Douglas Gregora08b6c72009-02-17 23:15:12 +00002586 } else {
2587 // Create a new class template specialization declaration node for
2588 // this explicit specialization.
2589 Specialization
2590 = ClassTemplateSpecializationDecl::Create(Context,
2591 ClassTemplate->getDeclContext(),
2592 TemplateNameLoc,
Anders Carlsson6e9d02f2009-06-05 04:06:48 +00002593 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002594 Converted,
Douglas Gregora08b6c72009-02-17 23:15:12 +00002595 PrevDecl);
2596
2597 if (PrevDecl) {
2598 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2599 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2600 } else {
2601 ClassTemplate->getSpecializations().InsertNode(Specialization,
2602 InsertPos);
2603 }
Douglas Gregor1930d202009-07-30 17:40:51 +00002604
2605 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002606 }
2607
2608 // Note that this is an explicit specialization.
2609 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2610
2611 // Check that this isn't a redefinition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002612 if (TUK == TUK_Definition) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00002613 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002614 // FIXME: Should also handle explicit specialization after implicit
2615 // instantiation with a special diagnostic.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002616 SourceRange Range(TemplateNameLoc, RAngleLoc);
2617 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor58944ac2009-05-31 09:31:02 +00002618 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002619 Diag(Def->getLocation(), diag::note_previous_definition);
2620 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00002621 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00002622 }
2623 }
2624
Douglas Gregor9c7825b2009-02-26 22:19:44 +00002625 // Build the fully-sugared type for this class template
2626 // specialization as the user wrote in the specialization
2627 // itself. This means that we'll pretty-print the type retrieved
2628 // from the specialization's declaration the way that the user
2629 // actually wrote the specialization, rather than formatting the
2630 // name based on the "canonical" representation used to store the
2631 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00002632 QualType WrittenTy
Douglas Gregordd13e842009-03-30 22:58:21 +00002633 = Context.getTemplateSpecializationType(Name,
Anders Carlsson13fac3f2009-06-13 18:20:51 +00002634 TemplateArgs.data(),
Douglas Gregordd13e842009-03-30 22:58:21 +00002635 TemplateArgs.size(),
Douglas Gregor1930d202009-07-30 17:40:51 +00002636 CanonType);
Douglas Gregordd13e842009-03-30 22:58:21 +00002637 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00002638 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00002639
Douglas Gregor50113ca2009-02-25 22:18:32 +00002640 // C++ [temp.expl.spec]p9:
2641 // A template explicit specialization is in the scope of the
2642 // namespace in which the template was defined.
2643 //
2644 // We actually implement this paragraph where we set the semantic
2645 // context (in the creation of the ClassTemplateSpecializationDecl),
2646 // but we also maintain the lexical context where the actual
2647 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00002648 Specialization->setLexicalDeclContext(CurContext);
2649
2650 // We may be starting the definition of this specialization.
John McCall069c23a2009-07-31 02:45:11 +00002651 if (TUK == TUK_Definition)
Douglas Gregora08b6c72009-02-17 23:15:12 +00002652 Specialization->startDefinition();
2653
2654 // Add the specialization into its lexical context, so that it can
2655 // be seen when iterating through the list of declarations in that
2656 // context. However, specializations are not found by name lookup.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002657 CurContext->addDecl(Specialization);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002658 return DeclPtrTy::make(Specialization);
Douglas Gregora08b6c72009-02-17 23:15:12 +00002659}
Douglas Gregord3022602009-03-27 23:10:48 +00002660
Douglas Gregor2ae1d772009-06-23 23:11:28 +00002661Sema::DeclPtrTy
2662Sema::ActOnTemplateDeclarator(Scope *S,
2663 MultiTemplateParamsArg TemplateParameterLists,
2664 Declarator &D) {
2665 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2666}
2667
Douglas Gregor19d10652009-06-24 00:54:41 +00002668Sema::DeclPtrTy
2669Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
2670 MultiTemplateParamsArg TemplateParameterLists,
2671 Declarator &D) {
2672 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2673 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2674 "Not a function declarator!");
2675 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2676
2677 if (FTI.hasPrototype) {
2678 // FIXME: Diagnose arguments without names in C.
2679 }
2680
2681 Scope *ParentScope = FnBodyScope->getParent();
2682
2683 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
2684 move(TemplateParameterLists),
2685 /*IsFunctionDefinition=*/true);
Douglas Gregorb462c322009-07-21 23:53:31 +00002686 if (FunctionTemplateDecl *FunctionTemplate
2687 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002688 return ActOnStartOfFunctionDef(FnBodyScope,
2689 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorb462c322009-07-21 23:53:31 +00002690 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
2691 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002692 return DeclPtrTy();
Douglas Gregor19d10652009-06-24 00:54:41 +00002693}
2694
Douglas Gregor96b6df92009-05-14 00:28:11 +00002695// Explicit instantiation of a class template specialization
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002696Sema::DeclResult
2697Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2698 unsigned TagSpec,
2699 SourceLocation KWLoc,
2700 const CXXScopeSpec &SS,
2701 TemplateTy TemplateD,
2702 SourceLocation TemplateNameLoc,
2703 SourceLocation LAngleLoc,
2704 ASTTemplateArgsPtr TemplateArgsIn,
2705 SourceLocation *TemplateArgLocs,
2706 SourceLocation RAngleLoc,
2707 AttributeList *Attr) {
2708 // Find the class template we're specializing
2709 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2710 ClassTemplateDecl *ClassTemplate
2711 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2712
2713 // Check that the specialization uses the same tag kind as the
2714 // original template.
2715 TagDecl::TagKind Kind;
2716 switch (TagSpec) {
2717 default: assert(0 && "Unknown tag type!");
2718 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2719 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2720 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2721 }
Douglas Gregor625185c2009-05-14 16:41:31 +00002722 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2723 Kind, KWLoc,
2724 *ClassTemplate->getIdentifier())) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002725 Diag(KWLoc, diag::err_use_with_wrong_tag)
2726 << ClassTemplate
2727 << CodeModificationHint::CreateReplacement(KWLoc,
2728 ClassTemplate->getTemplatedDecl()->getKindName());
2729 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2730 diag::note_previous_use);
2731 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2732 }
2733
Douglas Gregor90177912009-05-13 18:28:20 +00002734 // C++0x [temp.explicit]p2:
2735 // [...] An explicit instantiation shall appear in an enclosing
2736 // namespace of its template. [...]
2737 //
2738 // This is C++ DR 275.
2739 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2740 TemplateNameLoc,
2741 SS.getRange(),
Douglas Gregor4faa4262009-06-12 22:21:45 +00002742 /*PartialSpecialization=*/false,
Douglas Gregor90177912009-05-13 18:28:20 +00002743 /*ExplicitInstantiation=*/true))
2744 return true;
2745
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002746 // Translate the parser's template argument list in our AST format.
2747 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2748 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2749
2750 // Check that the template argument list is well-formed for this
2751 // template.
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002752 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2753 TemplateArgs.size());
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002754 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssonb912b392009-06-05 02:12:32 +00002755 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregorecd63b82009-07-01 00:28:38 +00002756 RAngleLoc, false, Converted))
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002757 return true;
2758
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002759 assert((Converted.structuredSize() ==
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002760 ClassTemplate->getTemplateParameters()->size()) &&
2761 "Converted template argument list is too short!");
2762
2763 // Find the class template specialization declaration that
2764 // corresponds to these arguments.
2765 llvm::FoldingSetNodeID ID;
Anders Carlssona35faf92009-06-05 03:43:12 +00002766 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002767 Converted.getFlatArguments(),
Douglas Gregor99eef4a2009-07-29 16:09:57 +00002768 Converted.flatSize(),
2769 Context);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002770 void *InsertPos = 0;
2771 ClassTemplateSpecializationDecl *PrevDecl
2772 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2773
2774 ClassTemplateSpecializationDecl *Specialization = 0;
2775
Douglas Gregor90177912009-05-13 18:28:20 +00002776 bool SpecializationRequiresInstantiation = true;
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002777 if (PrevDecl) {
Douglas Gregor90177912009-05-13 18:28:20 +00002778 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002779 // This particular specialization has already been declared or
2780 // instantiated. We cannot explicitly instantiate it.
Douglas Gregor90177912009-05-13 18:28:20 +00002781 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2782 << Context.getTypeDeclType(PrevDecl);
2783 Diag(PrevDecl->getLocation(),
2784 diag::note_previous_explicit_instantiation);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002785 return DeclPtrTy::make(PrevDecl);
2786 }
2787
Douglas Gregor90177912009-05-13 18:28:20 +00002788 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor96b6df92009-05-14 00:28:11 +00002789 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregor90177912009-05-13 18:28:20 +00002790 // For a given set of template parameters, if an explicit
2791 // instantiation of a template appears after a declaration of
2792 // an explicit specialization for that template, the explicit
2793 // instantiation has no effect.
2794 if (!getLangOptions().CPlusPlus0x) {
2795 Diag(TemplateNameLoc,
2796 diag::ext_explicit_instantiation_after_specialization)
2797 << Context.getTypeDeclType(PrevDecl);
2798 Diag(PrevDecl->getLocation(),
2799 diag::note_previous_template_specialization);
2800 }
2801
2802 // Create a new class template specialization declaration node
2803 // for this explicit specialization. This node is only used to
2804 // record the existence of this explicit instantiation for
2805 // accurate reproduction of the source code; we don't actually
2806 // use it for anything, since it is semantically irrelevant.
2807 Specialization
2808 = ClassTemplateSpecializationDecl::Create(Context,
2809 ClassTemplate->getDeclContext(),
2810 TemplateNameLoc,
2811 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002812 Converted, 0);
Douglas Gregor90177912009-05-13 18:28:20 +00002813 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002814 CurContext->addDecl(Specialization);
Douglas Gregor90177912009-05-13 18:28:20 +00002815 return DeclPtrTy::make(Specialization);
2816 }
2817
2818 // If we have already (implicitly) instantiated this
2819 // specialization, there is less work to do.
2820 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2821 SpecializationRequiresInstantiation = false;
2822
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002823 // Since the only prior class template specialization with these
2824 // arguments was referenced but not declared, reuse that
2825 // declaration node as our own, updating its source location to
2826 // reflect our new declaration.
2827 Specialization = PrevDecl;
2828 Specialization->setLocation(TemplateNameLoc);
2829 PrevDecl = 0;
2830 } else {
2831 // Create a new class template specialization declaration node for
2832 // this explicit specialization.
2833 Specialization
2834 = ClassTemplateSpecializationDecl::Create(Context,
2835 ClassTemplate->getDeclContext(),
2836 TemplateNameLoc,
2837 ClassTemplate,
Anders Carlssonb0fc9992009-06-23 01:26:57 +00002838 Converted, 0);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002839
2840 ClassTemplate->getSpecializations().InsertNode(Specialization,
2841 InsertPos);
2842 }
2843
2844 // Build the fully-sugared type for this explicit instantiation as
2845 // the user wrote in the explicit instantiation itself. This means
2846 // that we'll pretty-print the type retrieved from the
2847 // specialization's declaration the way that the user actually wrote
2848 // the explicit instantiation, rather than formatting the name based
2849 // on the "canonical" representation used to store the template
2850 // arguments in the specialization.
2851 QualType WrittenTy
2852 = Context.getTemplateSpecializationType(Name,
Anders Carlssonefbff322009-06-05 02:45:24 +00002853 TemplateArgs.data(),
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002854 TemplateArgs.size(),
2855 Context.getTypeDeclType(Specialization));
2856 Specialization->setTypeAsWritten(WrittenTy);
2857 TemplateArgsIn.release();
2858
2859 // Add the explicit instantiation into its lexical context. However,
2860 // since explicit instantiations are never found by name lookup, we
2861 // just put it into the declaration context directly.
2862 Specialization->setLexicalDeclContext(CurContext);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002863 CurContext->addDecl(Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002864
2865 // C++ [temp.explicit]p3:
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002866 // A definition of a class template or class member template
2867 // shall be in scope at the point of the explicit instantiation of
2868 // the class template or class member template.
2869 //
2870 // This check comes when we actually try to perform the
2871 // instantiation.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002872 if (SpecializationRequiresInstantiation)
2873 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorb12249d2009-05-18 17:01:57 +00002874 else // Instantiate the members of this class template specialization.
Douglas Gregor556d8c72009-05-15 17:59:04 +00002875 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregorfd79ac62009-05-13 00:25:59 +00002876
2877 return DeclPtrTy::make(Specialization);
2878}
2879
Douglas Gregor96b6df92009-05-14 00:28:11 +00002880// Explicit instantiation of a member class of a class template.
2881Sema::DeclResult
2882Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2883 unsigned TagSpec,
2884 SourceLocation KWLoc,
2885 const CXXScopeSpec &SS,
2886 IdentifierInfo *Name,
2887 SourceLocation NameLoc,
2888 AttributeList *Attr) {
2889
Douglas Gregor71f06032009-05-28 23:31:59 +00002890 bool Owned = false;
John McCall069c23a2009-07-31 02:45:11 +00002891 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor84a20812009-07-22 23:48:44 +00002892 KWLoc, SS, Name, NameLoc, Attr, AS_none,
2893 MultiTemplateParamsArg(*this, 0, 0), Owned);
Douglas Gregor96b6df92009-05-14 00:28:11 +00002894 if (!TagD)
2895 return true;
2896
2897 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2898 if (Tag->isEnum()) {
2899 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2900 << Context.getTypeDeclType(Tag);
2901 return true;
2902 }
2903
Douglas Gregord769bfa2009-05-27 17:30:49 +00002904 if (Tag->isInvalidDecl())
2905 return true;
2906
Douglas Gregor96b6df92009-05-14 00:28:11 +00002907 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2908 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2909 if (!Pattern) {
2910 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2911 << Context.getTypeDeclType(Record);
2912 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2913 return true;
2914 }
2915
2916 // C++0x [temp.explicit]p2:
2917 // [...] An explicit instantiation shall appear in an enclosing
2918 // namespace of its template. [...]
2919 //
2920 // This is C++ DR 275.
2921 if (getLangOptions().CPlusPlus0x) {
Mike Stumpe127ae32009-05-16 07:39:55 +00002922 // FIXME: In C++98, we would like to turn these errors into warnings,
2923 // dependent on a -Wc++0x flag.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002924 DeclContext *PatternContext
2925 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2926 if (!CurContext->Encloses(PatternContext)) {
2927 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2928 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2929 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2930 }
2931 }
2932
Douglas Gregor96b6df92009-05-14 00:28:11 +00002933 if (!Record->getDefinition(Context)) {
2934 // If the class has a definition, instantiate it (and all of its
2935 // members, recursively).
2936 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2937 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002938 getTemplateInstantiationArgs(Record),
Douglas Gregor96b6df92009-05-14 00:28:11 +00002939 /*ExplicitInstantiation=*/true))
2940 return true;
Douglas Gregorb12249d2009-05-18 17:01:57 +00002941 } else // Instantiate all of the members of class.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002942 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor5f62c5e2009-05-14 23:26:13 +00002943 getTemplateInstantiationArgs(Record));
Douglas Gregor96b6df92009-05-14 00:28:11 +00002944
Mike Stumpe127ae32009-05-16 07:39:55 +00002945 // FIXME: We don't have any representation for explicit instantiations of
2946 // member classes. Such a representation is not needed for compilation, but it
2947 // should be available for clients that want to see all of the declarations in
2948 // the source code.
Douglas Gregor96b6df92009-05-14 00:28:11 +00002949 return TagD;
2950}
2951
Douglas Gregord3022602009-03-27 23:10:48 +00002952Sema::TypeResult
2953Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2954 const IdentifierInfo &II, SourceLocation IdLoc) {
2955 NestedNameSpecifier *NNS
2956 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2957 if (!NNS)
2958 return true;
2959
2960 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregord7cb0372009-04-01 21:51:26 +00002961 if (T.isNull())
2962 return true;
Douglas Gregord3022602009-03-27 23:10:48 +00002963 return T.getAsOpaquePtr();
2964}
2965
Douglas Gregor77da5802009-04-01 00:28:59 +00002966Sema::TypeResult
2967Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2968 SourceLocation TemplateLoc, TypeTy *Ty) {
2969 QualType T = QualType::getFromOpaquePtr(Ty);
2970 NestedNameSpecifier *NNS
2971 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2972 const TemplateSpecializationType *TemplateId
2973 = T->getAsTemplateSpecializationType();
2974 assert(TemplateId && "Expected a template specialization type");
2975
2976 if (NNS->isDependent())
2977 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2978
2979 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2980}
2981
Douglas Gregord3022602009-03-27 23:10:48 +00002982/// \brief Build the type that describes a C++ typename specifier,
2983/// e.g., "typename T::type".
2984QualType
2985Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2986 SourceRange Range) {
Douglas Gregor3eb20702009-05-11 19:58:34 +00002987 CXXRecordDecl *CurrentInstantiation = 0;
2988 if (NNS->isDependent()) {
2989 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord3022602009-03-27 23:10:48 +00002990
Douglas Gregor3eb20702009-05-11 19:58:34 +00002991 // If the nested-name-specifier does not refer to the current
2992 // instantiation, then build a typename type.
2993 if (!CurrentInstantiation)
2994 return Context.getTypenameType(NNS, &II);
2995 }
Douglas Gregord3022602009-03-27 23:10:48 +00002996
Douglas Gregor3eb20702009-05-11 19:58:34 +00002997 DeclContext *Ctx = 0;
2998
2999 if (CurrentInstantiation)
3000 Ctx = CurrentInstantiation;
3001 else {
3002 CXXScopeSpec SS;
3003 SS.setScopeRep(NNS);
3004 SS.setRange(Range);
3005 if (RequireCompleteDeclContext(SS))
3006 return QualType();
3007
3008 Ctx = computeDeclContext(SS);
3009 }
Douglas Gregord3022602009-03-27 23:10:48 +00003010 assert(Ctx && "No declaration context?");
3011
3012 DeclarationName Name(&II);
3013 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
3014 false);
3015 unsigned DiagID = 0;
3016 Decl *Referenced = 0;
3017 switch (Result.getKind()) {
3018 case LookupResult::NotFound:
3019 if (Ctx->isTranslationUnit())
3020 DiagID = diag::err_typename_nested_not_found_global;
3021 else
3022 DiagID = diag::err_typename_nested_not_found;
3023 break;
3024
3025 case LookupResult::Found:
3026 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
3027 // We found a type. Build a QualifiedNameType, since the
3028 // typename-specifier was just sugar. FIXME: Tell
3029 // QualifiedNameType that it has a "typename" prefix.
3030 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
3031 }
3032
3033 DiagID = diag::err_typename_nested_not_type;
3034 Referenced = Result.getAsDecl();
3035 break;
3036
3037 case LookupResult::FoundOverloaded:
3038 DiagID = diag::err_typename_nested_not_type;
3039 Referenced = *Result.begin();
3040 break;
3041
3042 case LookupResult::AmbiguousBaseSubobjectTypes:
3043 case LookupResult::AmbiguousBaseSubobjects:
3044 case LookupResult::AmbiguousReference:
3045 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
3046 return QualType();
3047 }
3048
3049 // If we get here, it's because name lookup did not find a
3050 // type. Emit an appropriate diagnostic and return an error.
3051 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
3052 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
3053 else
3054 Diag(Range.getEnd(), DiagID) << Range << Name;
3055 if (Referenced)
3056 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
3057 << Name;
3058 return QualType();
3059}