blob: b8b1f3a5bb58753849fae2100696050708d8a7c0 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregor0c281a82009-02-25 19:37:18 +000029TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
30 DeclTy *&Template,
31 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
34 if (IIDecl) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000035 if (isa<TemplateDecl>(IIDecl)) {
36 Template = IIDecl;
37 if (isa<FunctionTemplateDecl>(IIDecl))
38 return TNK_Function_template;
39 else if (isa<ClassTemplateDecl>(IIDecl))
40 return TNK_Class_template;
41 else if (isa<TemplateTemplateParmDecl>(IIDecl))
42 return TNK_Template_template_parm;
43 else
44 assert(false && "Unknown TemplateDecl");
Douglas Gregor55216ac2009-03-26 00:10:35 +000045 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
46 // C++ [temp.local]p1:
47 // Like normal (non-template) classes, class templates have an
48 // injected-class-name (Clause 9). The injected-class-name
49 // can be used with or without a template-argument-list. When
50 // it is used without a template-argument-list, it is
51 // equivalent to the injected-class-name followed by the
52 // template-parameters of the class template enclosed in
53 // <>. When it is used with a template-argument-list, it
54 // refers to the specified class template specialization,
55 // which could be the current specialization or another
56 // specialization.
57 if (Record->isInjectedClassName()) {
58 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
59 if ((Template = Record->getDescribedClassTemplate()))
60 return TNK_Class_template;
61 else if (ClassTemplateSpecializationDecl *Spec
62 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
63 Template = Spec->getSpecializedTemplate();
64 return TNK_Class_template;
65 }
66 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000067 }
Douglas Gregor279272e2009-02-04 19:02:06 +000068
Douglas Gregor8e458f42009-02-09 18:46:07 +000069 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000071 if (FD->getType()->isDependentType()) {
72 Template = FD;
73 return TNK_Function_template;
74 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000075 } else if (OverloadedFunctionDecl *Ovl
76 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
77 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
78 FEnd = Ovl->function_end();
79 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000080 if ((*F)->getType()->isDependentType()) {
81 Template = Ovl;
82 return TNK_Function_template;
83 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000084 }
85 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000086 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000087 return TNK_Non_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +000088}
89
Douglas Gregordd861062008-12-05 18:15:24 +000090/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
91/// that the template parameter 'PrevDecl' is being shadowed by a new
92/// declaration at location Loc. Returns true to indicate that this is
93/// an error, and false otherwise.
94bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +000095 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +000096
97 // Microsoft Visual C++ permits template parameters to be shadowed.
98 if (getLangOptions().Microsoft)
99 return false;
100
101 // C++ [temp.local]p4:
102 // A template-parameter shall not be redeclared within its
103 // scope (including nested scopes).
104 Diag(Loc, diag::err_template_param_shadow)
105 << cast<NamedDecl>(PrevDecl)->getDeclName();
106 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
107 return true;
108}
109
Douglas Gregored3a3982009-03-03 04:44:36 +0000110/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000111/// the parameter D to reference the templated declaration and return a pointer
112/// to the template declaration. Otherwise, do nothing to D and return null.
113TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
114{
115 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
116 D = Temp->getTemplatedDecl();
117 return Temp;
118 }
119 return 0;
120}
121
Douglas Gregordd861062008-12-05 18:15:24 +0000122/// ActOnTypeParameter - Called when a C++ template type parameter
123/// (e.g., "typename T") has been parsed. Typename specifies whether
124/// the keyword "typename" was used to declare the type parameter
125/// (otherwise, "class" was used), and KeyLoc is the location of the
126/// "class" or "typename" keyword. ParamName is the name of the
127/// parameter (NULL indicates an unnamed template parameter) and
128/// ParamName is the location of the parameter name (if any).
129/// If the type parameter has a default argument, it will be added
130/// later via ActOnTypeParameterDefault.
131Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
132 SourceLocation KeyLoc,
133 IdentifierInfo *ParamName,
Douglas Gregor52473432008-12-24 02:52:09 +0000134 SourceLocation ParamNameLoc,
135 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000136 assert(S->isTemplateParamScope() &&
137 "Template type parameter not in template parameter scope!");
138 bool Invalid = false;
139
140 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000141 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000142 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000143 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
144 PrevDecl);
145 }
146
Douglas Gregord406b032009-02-06 22:42:48 +0000147 SourceLocation Loc = ParamNameLoc;
148 if (!ParamName)
149 Loc = KeyLoc;
150
Douglas Gregordd861062008-12-05 18:15:24 +0000151 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000152 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000153 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000154 if (Invalid)
155 Param->setInvalidDecl();
156
157 if (ParamName) {
158 // Add the template parameter into the current scope.
159 S->AddDecl(Param);
160 IdResolver.AddDecl(Param);
161 }
162
163 return Param;
164}
165
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000166/// ActOnTypeParameterDefault - Adds a default argument (the type
167/// Default) to the given template type parameter (TypeParam).
168void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
169 SourceLocation EqualLoc,
170 SourceLocation DefaultLoc,
171 TypeTy *DefaultT) {
172 TemplateTypeParmDecl *Parm
173 = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
174 QualType Default = QualType::getFromOpaquePtr(DefaultT);
175
176 // C++ [temp.param]p14:
177 // A template-parameter shall not be used in its own default argument.
178 // FIXME: Implement this check! Needs a recursive walk over the types.
179
180 // Check the template argument itself.
181 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
182 Parm->setInvalidDecl();
183 return;
184 }
185
186 Parm->setDefaultArgument(Default, DefaultLoc, false);
187}
188
Douglas Gregored3a3982009-03-03 04:44:36 +0000189/// \brief Check that the type of a non-type template parameter is
190/// well-formed.
191///
192/// \returns the (possibly-promoted) parameter type if valid;
193/// otherwise, produces a diagnostic and returns a NULL type.
194QualType
195Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
196 // C++ [temp.param]p4:
197 //
198 // A non-type template-parameter shall have one of the following
199 // (optionally cv-qualified) types:
200 //
201 // -- integral or enumeration type,
202 if (T->isIntegralType() || T->isEnumeralType() ||
203 // -- pointer to object or pointer to function,
204 (T->isPointerType() &&
205 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
206 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
207 // -- reference to object or reference to function,
208 T->isReferenceType() ||
209 // -- pointer to member.
210 T->isMemberPointerType() ||
211 // If T is a dependent type, we can't do the check now, so we
212 // assume that it is well-formed.
213 T->isDependentType())
214 return T;
215 // C++ [temp.param]p8:
216 //
217 // A non-type template-parameter of type "array of T" or
218 // "function returning T" is adjusted to be of type "pointer to
219 // T" or "pointer to function returning T", respectively.
220 else if (T->isArrayType())
221 // FIXME: Keep the type prior to promotion?
222 return Context.getArrayDecayedType(T);
223 else if (T->isFunctionType())
224 // FIXME: Keep the type prior to promotion?
225 return Context.getPointerType(T);
226
227 Diag(Loc, diag::err_template_nontype_parm_bad_type)
228 << T;
229
230 return QualType();
231}
232
Douglas Gregordd861062008-12-05 18:15:24 +0000233/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
234/// template parameter (e.g., "int Size" in "template<int Size>
235/// class Array") has been parsed. S is the current scope and D is
236/// the parsed declarator.
Douglas Gregor52473432008-12-24 02:52:09 +0000237Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
238 unsigned Depth,
239 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000240 QualType T = GetTypeForDeclarator(D, S);
241
Douglas Gregor279272e2009-02-04 19:02:06 +0000242 assert(S->isTemplateParamScope() &&
243 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000244 bool Invalid = false;
245
246 IdentifierInfo *ParamName = D.getIdentifier();
247 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000248 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000249 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000250 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000251 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000252 }
253
Douglas Gregored3a3982009-03-03 04:44:36 +0000254 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000255 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000256 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000257 Invalid = true;
258 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000259
Douglas Gregordd861062008-12-05 18:15:24 +0000260 NonTypeTemplateParmDecl *Param
261 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000262 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000263 if (Invalid)
264 Param->setInvalidDecl();
265
266 if (D.getIdentifier()) {
267 // Add the template parameter into the current scope.
268 S->AddDecl(Param);
269 IdResolver.AddDecl(Param);
270 }
271 return Param;
272}
Douglas Gregor52473432008-12-24 02:52:09 +0000273
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000274/// \brief Adds a default argument to the given non-type template
275/// parameter.
276void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
277 SourceLocation EqualLoc,
278 ExprArg DefaultE) {
279 NonTypeTemplateParmDecl *TemplateParm
280 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
281 Expr *Default = static_cast<Expr *>(DefaultE.get());
282
283 // C++ [temp.param]p14:
284 // A template-parameter shall not be used in its own default argument.
285 // FIXME: Implement this check! Needs a recursive walk over the types.
286
287 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000288 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000289 TemplateParm->setInvalidDecl();
290 return;
291 }
292
293 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
294}
295
Douglas Gregor279272e2009-02-04 19:02:06 +0000296
297/// ActOnTemplateTemplateParameter - Called when a C++ template template
298/// parameter (e.g. T in template <template <typename> class T> class array)
299/// has been parsed. S is the current scope.
300Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
301 SourceLocation TmpLoc,
302 TemplateParamsTy *Params,
303 IdentifierInfo *Name,
304 SourceLocation NameLoc,
305 unsigned Depth,
306 unsigned Position)
307{
308 assert(S->isTemplateParamScope() &&
309 "Template template parameter not in template parameter scope!");
310
311 // Construct the parameter object.
312 TemplateTemplateParmDecl *Param =
313 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
314 Position, Name,
315 (TemplateParameterList*)Params);
316
317 // Make sure the parameter is valid.
318 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
319 // do anything yet. However, if the template parameter list or (eventual)
320 // default value is ever invalidated, that will propagate here.
321 bool Invalid = false;
322 if (Invalid) {
323 Param->setInvalidDecl();
324 }
325
326 // If the tt-param has a name, then link the identifier into the scope
327 // and lookup mechanisms.
328 if (Name) {
329 S->AddDecl(Param);
330 IdResolver.AddDecl(Param);
331 }
332
333 return Param;
334}
335
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000336/// \brief Adds a default argument to the given template template
337/// parameter.
338void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
339 SourceLocation EqualLoc,
340 ExprArg DefaultE) {
341 TemplateTemplateParmDecl *TemplateParm
342 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
343
344 // Since a template-template parameter's default argument is an
345 // id-expression, it must be a DeclRefExpr.
346 DeclRefExpr *Default
347 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
348
349 // C++ [temp.param]p14:
350 // A template-parameter shall not be used in its own default argument.
351 // FIXME: Implement this check! Needs a recursive walk over the types.
352
353 // Check the well-formedness of the template argument.
354 if (!isa<TemplateDecl>(Default->getDecl())) {
355 Diag(Default->getSourceRange().getBegin(),
356 diag::err_template_arg_must_be_template)
357 << Default->getSourceRange();
358 TemplateParm->setInvalidDecl();
359 return;
360 }
361 if (CheckTemplateArgument(TemplateParm, Default)) {
362 TemplateParm->setInvalidDecl();
363 return;
364 }
365
366 DefaultE.release();
367 TemplateParm->setDefaultArgument(Default);
368}
369
Douglas Gregor52473432008-12-24 02:52:09 +0000370/// ActOnTemplateParameterList - Builds a TemplateParameterList that
371/// contains the template parameters in Params/NumParams.
372Sema::TemplateParamsTy *
373Sema::ActOnTemplateParameterList(unsigned Depth,
374 SourceLocation ExportLoc,
375 SourceLocation TemplateLoc,
376 SourceLocation LAngleLoc,
377 DeclTy **Params, unsigned NumParams,
378 SourceLocation RAngleLoc) {
379 if (ExportLoc.isValid())
380 Diag(ExportLoc, diag::note_template_export_unsupported);
381
Douglas Gregord406b032009-02-06 22:42:48 +0000382 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
383 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000384}
Douglas Gregor279272e2009-02-04 19:02:06 +0000385
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000386Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000387Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
388 SourceLocation KWLoc, const CXXScopeSpec &SS,
389 IdentifierInfo *Name, SourceLocation NameLoc,
390 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000391 MultiTemplateParamsArg TemplateParameterLists,
392 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000393 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
394 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000395 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000396
397 // Check that we can declare a template here.
398 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000399 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000400
401 TagDecl::TagKind Kind;
402 switch (TagSpec) {
403 default: assert(0 && "Unknown tag type!");
404 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
405 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
406 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
407 }
408
409 // There is no such thing as an unnamed class template.
410 if (!Name) {
411 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000412 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000413 }
414
415 // Find any previous declaration with this name.
416 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
417 true);
418 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
419 NamedDecl *PrevDecl = 0;
420 if (Previous.begin() != Previous.end())
421 PrevDecl = *Previous.begin();
422
423 DeclContext *SemanticContext = CurContext;
424 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000425 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000426
427 // FIXME: need to match up several levels of template parameter
428 // lists here.
429 }
430
431 // FIXME: member templates!
432 TemplateParameterList *TemplateParams
433 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
434
435 // If there is a previous declaration with the same name, check
436 // whether this is a valid redeclaration.
437 ClassTemplateDecl *PrevClassTemplate
438 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
439 if (PrevClassTemplate) {
440 // Ensure that the template parameter lists are compatible.
441 if (!TemplateParameterListsAreEqual(TemplateParams,
442 PrevClassTemplate->getTemplateParameters(),
443 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000444 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000445
446 // C++ [temp.class]p4:
447 // In a redeclaration, partial specialization, explicit
448 // specialization or explicit instantiation of a class template,
449 // the class-key shall agree in kind with the original class
450 // template declaration (7.1.5.3).
451 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
452 if (PrevRecordDecl->getTagKind() != Kind) {
453 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
454 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000455 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000456 }
457
458
459 // Check for redefinition of this class template.
460 if (TK == TK_Definition) {
461 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
462 Diag(NameLoc, diag::err_redefinition) << Name;
463 Diag(Def->getLocation(), diag::note_previous_definition);
464 // FIXME: Would it make sense to try to "forget" the previous
465 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000466 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000467 }
468 }
469 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
470 // Maybe we will complain about the shadowed template parameter.
471 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
472 // Just pretend that we didn't see the previous declaration.
473 PrevDecl = 0;
474 } else if (PrevDecl) {
475 // C++ [temp]p5:
476 // A class template shall not have the same name as any other
477 // template, class, function, object, enumeration, enumerator,
478 // namespace, or type in the same scope (3.3), except as specified
479 // in (14.5.4).
480 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
481 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000482 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000483 }
484
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000485 // Check the template parameter list of this declaration, possibly
486 // merging in the template parameter list from the previous class
487 // template declaration.
488 if (CheckTemplateParameterList(TemplateParams,
489 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
490 Invalid = true;
491
Douglas Gregord406b032009-02-06 22:42:48 +0000492 // If we had a scope specifier, we better have a previous template
493 // declaration!
494
Douglas Gregor55216ac2009-03-26 00:10:35 +0000495 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000496 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
497 PrevClassTemplate?
498 PrevClassTemplate->getTemplatedDecl() : 0);
499
500 ClassTemplateDecl *NewTemplate
501 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
502 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000503 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000504 NewClass->setDescribedClassTemplate(NewTemplate);
505
Douglas Gregord406b032009-02-06 22:42:48 +0000506 // Set the lexical context of these templates
507 NewClass->setLexicalDeclContext(CurContext);
508 NewTemplate->setLexicalDeclContext(CurContext);
509
510 if (TK == TK_Definition)
511 NewClass->startDefinition();
512
513 if (Attr)
514 ProcessDeclAttributeList(NewClass, Attr);
515
516 PushOnScopeChains(NewTemplate, S);
517
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000518 if (Invalid) {
519 NewTemplate->setInvalidDecl();
520 NewClass->setInvalidDecl();
521 }
Douglas Gregord406b032009-02-06 22:42:48 +0000522 return NewTemplate;
523}
524
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000525/// \brief Checks the validity of a template parameter list, possibly
526/// considering the template parameter list from a previous
527/// declaration.
528///
529/// If an "old" template parameter list is provided, it must be
530/// equivalent (per TemplateParameterListsAreEqual) to the "new"
531/// template parameter list.
532///
533/// \param NewParams Template parameter list for a new template
534/// declaration. This template parameter list will be updated with any
535/// default arguments that are carried through from the previous
536/// template parameter list.
537///
538/// \param OldParams If provided, template parameter list from a
539/// previous declaration of the same template. Default template
540/// arguments will be merged from the old template parameter list to
541/// the new template parameter list.
542///
543/// \returns true if an error occurred, false otherwise.
544bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
545 TemplateParameterList *OldParams) {
546 bool Invalid = false;
547
548 // C++ [temp.param]p10:
549 // The set of default template-arguments available for use with a
550 // template declaration or definition is obtained by merging the
551 // default arguments from the definition (if in scope) and all
552 // declarations in scope in the same way default function
553 // arguments are (8.3.6).
554 bool SawDefaultArgument = false;
555 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000556
Mike Stumpe0b7e032009-02-11 23:03:27 +0000557 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000558 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000559 if (OldParams)
560 OldParam = OldParams->begin();
561
562 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
563 NewParamEnd = NewParams->end();
564 NewParam != NewParamEnd; ++NewParam) {
565 // Variables used to diagnose redundant default arguments
566 bool RedundantDefaultArg = false;
567 SourceLocation OldDefaultLoc;
568 SourceLocation NewDefaultLoc;
569
570 // Variables used to diagnose missing default arguments
571 bool MissingDefaultArg = false;
572
573 // Merge default arguments for template type parameters.
574 if (TemplateTypeParmDecl *NewTypeParm
575 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
576 TemplateTypeParmDecl *OldTypeParm
577 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
578
579 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
580 NewTypeParm->hasDefaultArgument()) {
581 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
582 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
583 SawDefaultArgument = true;
584 RedundantDefaultArg = true;
585 PreviousDefaultArgLoc = NewDefaultLoc;
586 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
587 // Merge the default argument from the old declaration to the
588 // new declaration.
589 SawDefaultArgument = true;
590 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
591 OldTypeParm->getDefaultArgumentLoc(),
592 true);
593 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
594 } else if (NewTypeParm->hasDefaultArgument()) {
595 SawDefaultArgument = true;
596 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
597 } else if (SawDefaultArgument)
598 MissingDefaultArg = true;
599 }
600 // Merge default arguments for non-type template parameters
601 else if (NonTypeTemplateParmDecl *NewNonTypeParm
602 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
603 NonTypeTemplateParmDecl *OldNonTypeParm
604 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
605 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
606 NewNonTypeParm->hasDefaultArgument()) {
607 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
608 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
609 SawDefaultArgument = true;
610 RedundantDefaultArg = true;
611 PreviousDefaultArgLoc = NewDefaultLoc;
612 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
613 // Merge the default argument from the old declaration to the
614 // new declaration.
615 SawDefaultArgument = true;
616 // FIXME: We need to create a new kind of "default argument"
617 // expression that points to a previous template template
618 // parameter.
619 NewNonTypeParm->setDefaultArgument(
620 OldNonTypeParm->getDefaultArgument());
621 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
622 } else if (NewNonTypeParm->hasDefaultArgument()) {
623 SawDefaultArgument = true;
624 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
625 } else if (SawDefaultArgument)
626 MissingDefaultArg = true;
627 }
628 // Merge default arguments for template template parameters
629 else {
630 TemplateTemplateParmDecl *NewTemplateParm
631 = cast<TemplateTemplateParmDecl>(*NewParam);
632 TemplateTemplateParmDecl *OldTemplateParm
633 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
634 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
635 NewTemplateParm->hasDefaultArgument()) {
636 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
637 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
638 SawDefaultArgument = true;
639 RedundantDefaultArg = true;
640 PreviousDefaultArgLoc = NewDefaultLoc;
641 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
642 // Merge the default argument from the old declaration to the
643 // new declaration.
644 SawDefaultArgument = true;
645 // FIXME: We need to create a new kind of "default argument"
646 // expression that points to a previous template template
647 // parameter.
648 NewTemplateParm->setDefaultArgument(
649 OldTemplateParm->getDefaultArgument());
650 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
651 } else if (NewTemplateParm->hasDefaultArgument()) {
652 SawDefaultArgument = true;
653 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
654 } else if (SawDefaultArgument)
655 MissingDefaultArg = true;
656 }
657
658 if (RedundantDefaultArg) {
659 // C++ [temp.param]p12:
660 // A template-parameter shall not be given default arguments
661 // by two different declarations in the same scope.
662 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
663 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
664 Invalid = true;
665 } else if (MissingDefaultArg) {
666 // C++ [temp.param]p11:
667 // If a template-parameter has a default template-argument,
668 // all subsequent template-parameters shall have a default
669 // template-argument supplied.
670 Diag((*NewParam)->getLocation(),
671 diag::err_template_param_default_arg_missing);
672 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
673 Invalid = true;
674 }
675
676 // If we have an old template parameter list that we're merging
677 // in, move on to the next parameter.
678 if (OldParams)
679 ++OldParam;
680 }
681
682 return Invalid;
683}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000684
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000685/// \brief Translates template arguments as provided by the parser
686/// into template arguments used by semantic analysis.
687static void
688translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
689 SourceLocation *TemplateArgLocs,
690 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
691 TemplateArgs.reserve(TemplateArgsIn.size());
692
693 void **Args = TemplateArgsIn.getArgs();
694 bool *ArgIsType = TemplateArgsIn.getArgIsType();
695 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
696 TemplateArgs.push_back(
697 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
698 QualType::getFromOpaquePtr(Args[Arg]))
699 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
700 }
701}
702
703QualType Sema::CheckClassTemplateId(ClassTemplateDecl *ClassTemplate,
704 SourceLocation TemplateLoc,
705 SourceLocation LAngleLoc,
706 const TemplateArgument *TemplateArgs,
707 unsigned NumTemplateArgs,
708 SourceLocation RAngleLoc) {
709 // Check that the template argument list is well-formed for this
710 // template.
711 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
712 if (CheckTemplateArgumentList(ClassTemplate, TemplateLoc, LAngleLoc,
713 TemplateArgs, NumTemplateArgs, RAngleLoc,
714 ConvertedTemplateArgs))
715 return QualType();
716
717 assert((ConvertedTemplateArgs.size() ==
718 ClassTemplate->getTemplateParameters()->size()) &&
719 "Converted template argument list is too short!");
720
721 QualType CanonType;
722
723 if (ClassTemplateSpecializationType::anyDependentTemplateArguments(
724 TemplateArgs,
725 NumTemplateArgs)) {
726 // This class template specialization is a dependent
727 // type. Therefore, its canonical type is another class template
728 // specialization type that contains all of the converted
729 // arguments in canonical form. This ensures that, e.g., A<T> and
730 // A<T, T> have identical types when A is declared as:
731 //
732 // template<typename T, typename U = T> struct A;
733
734 CanonType = Context.getClassTemplateSpecializationType(ClassTemplate,
735 &ConvertedTemplateArgs[0],
736 ConvertedTemplateArgs.size());
737 } else {
738 // Find the class template specialization declaration that
739 // corresponds to these arguments.
740 llvm::FoldingSetNodeID ID;
741 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
742 ConvertedTemplateArgs.size());
743 void *InsertPos = 0;
744 ClassTemplateSpecializationDecl *Decl
745 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
746 if (!Decl) {
747 // This is the first time we have referenced this class template
748 // specialization. Create the canonical declaration and add it to
749 // the set of specializations.
750 Decl = ClassTemplateSpecializationDecl::Create(Context,
751 ClassTemplate->getDeclContext(),
752 TemplateLoc,
753 ClassTemplate,
754 &ConvertedTemplateArgs[0],
755 ConvertedTemplateArgs.size(),
756 0);
757 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
758 Decl->setLexicalDeclContext(CurContext);
759 }
760
761 CanonType = Context.getTypeDeclType(Decl);
762 }
763
764 // Build the fully-sugared type for this class template
765 // specialization, which refers back to the class template
766 // specialization we created or found.
767 return Context.getClassTemplateSpecializationType(ClassTemplate,
768 TemplateArgs,
769 NumTemplateArgs,
770 CanonType);
771}
772
Douglas Gregora08b6c72009-02-17 23:15:12 +0000773Action::TypeResult
774Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
775 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000776 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000777 SourceLocation *TemplateArgLocs,
778 SourceLocation RAngleLoc,
779 const CXXScopeSpec *SS) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000780 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregorad964b32009-02-17 01:05:43 +0000781 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000782
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000783 // Translate the parser's template argument list in our AST format.
784 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
785 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000786
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000787 QualType Result = CheckClassTemplateId(ClassTemplate, TemplateLoc,
788 LAngleLoc,
789 &TemplateArgs[0],
790 TemplateArgs.size(),
791 RAngleLoc);
Douglas Gregor8c795a12009-03-19 00:39:20 +0000792
793 if (SS)
794 Result = getQualifiedNameType(*SS, Result);
Douglas Gregorad964b32009-02-17 01:05:43 +0000795
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000796 TemplateArgsIn.release();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000797 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000798}
799
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000800/// \brief Check that the given template argument list is well-formed
801/// for specializing the given template.
802bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
803 SourceLocation TemplateLoc,
804 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000805 const TemplateArgument *TemplateArgs,
806 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000807 SourceLocation RAngleLoc,
808 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000809 TemplateParameterList *Params = Template->getTemplateParameters();
810 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000811 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000812 bool Invalid = false;
813
814 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000815 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000816 // FIXME: point at either the first arg beyond what we can handle,
817 // or the '>', depending on whether we have too many or too few
818 // arguments.
819 SourceRange Range;
820 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000821 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000822 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
823 << (NumArgs > NumParams)
824 << (isa<ClassTemplateDecl>(Template)? 0 :
825 isa<FunctionTemplateDecl>(Template)? 1 :
826 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
827 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000828 Diag(Template->getLocation(), diag::note_template_decl_here)
829 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000830 Invalid = true;
831 }
832
833 // C++ [temp.arg]p1:
834 // [...] The type and form of each template-argument specified in
835 // a template-id shall match the type and form specified for the
836 // corresponding parameter declared by the template in its
837 // template-parameter-list.
838 unsigned ArgIdx = 0;
839 for (TemplateParameterList::iterator Param = Params->begin(),
840 ParamEnd = Params->end();
841 Param != ParamEnd; ++Param, ++ArgIdx) {
842 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000843 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000844 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000845 // Retrieve the default template argument from the template
846 // parameter.
847 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
848 if (!TTP->hasDefaultArgument())
849 break;
850
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000851 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000852
853 // If the argument type is dependent, instantiate it now based
854 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000855 if (ArgType->isDependentType()) {
856 InstantiatingTemplate Inst(*this, TemplateLoc,
857 Template, &Converted[0],
858 Converted.size(),
859 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor74296542009-02-27 19:31:52 +0000860 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
861 TTP->getDefaultArgumentLoc(),
862 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +0000863 }
Douglas Gregor74296542009-02-27 19:31:52 +0000864
865 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000866 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000867
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000868 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +0000869 } else if (NonTypeTemplateParmDecl *NTTP
870 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
871 if (!NTTP->hasDefaultArgument())
872 break;
873
Douglas Gregored3a3982009-03-03 04:44:36 +0000874 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000875 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000876 } else {
877 TemplateTemplateParmDecl *TempParm
878 = cast<TemplateTemplateParmDecl>(*Param);
879
880 if (!TempParm->hasDefaultArgument())
881 break;
882
Douglas Gregored3a3982009-03-03 04:44:36 +0000883 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000884 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000885 }
886 } else {
887 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000888 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +0000889 }
890
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000891
892 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
893 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000894 if (Arg.getKind() == TemplateArgument::Type) {
895 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000896 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000897
898 // Add the converted template type argument.
899 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000900 TemplateArgument(Arg.getLocation(),
901 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000902 continue;
903 }
904
905 // C++ [temp.arg.type]p1:
906 // A template-argument for a template-parameter which is a
907 // type shall be a type-id.
908
909 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000910 // is not a type.
911 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000912 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000913 Invalid = true;
914 } else if (NonTypeTemplateParmDecl *NTTP
915 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
916 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +0000917
918 // Instantiate the type of the non-type template parameter with
919 // the template arguments we've seen thus far.
920 QualType NTTPType = NTTP->getType();
921 if (NTTPType->isDependentType()) {
922 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000923 InstantiatingTemplate Inst(*this, TemplateLoc,
924 Template, &Converted[0],
925 Converted.size(),
926 SourceRange(TemplateLoc, RAngleLoc));
927
Douglas Gregored3a3982009-03-03 04:44:36 +0000928 NTTPType = InstantiateType(NTTPType,
929 &Converted[0], Converted.size(),
930 NTTP->getLocation(),
931 NTTP->getDeclName());
932 // If that worked, check the non-type template parameter type
933 // for validity.
934 if (!NTTPType.isNull())
935 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
936 NTTP->getLocation());
937
938 if (NTTPType.isNull()) {
939 Invalid = true;
940 break;
941 }
942 }
943
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000944 switch (Arg.getKind()) {
945 case TemplateArgument::Expression: {
946 Expr *E = Arg.getAsExpr();
947 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000948 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000949 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000950 }
951
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000952 case TemplateArgument::Declaration:
953 case TemplateArgument::Integral:
954 // We've already checked this template argument, so just copy
955 // it to the list of converted arguments.
956 Converted.push_back(Arg);
957 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000958
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000959 case TemplateArgument::Type:
960 // We have a non-type template parameter but the template
961 // argument is a type.
962
963 // C++ [temp.arg]p2:
964 // In a template-argument, an ambiguity between a type-id and
965 // an expression is resolved to a type-id, regardless of the
966 // form of the corresponding template-parameter.
967 //
968 // We warn specifically about this case, since it can be rather
969 // confusing for users.
970 if (Arg.getAsType()->isFunctionType())
971 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
972 << Arg.getAsType();
973 else
974 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
975 Diag((*Param)->getLocation(), diag::note_template_param_here);
976 Invalid = true;
977 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000978 } else {
979 // Check template template parameters.
980 TemplateTemplateParmDecl *TempParm
981 = cast<TemplateTemplateParmDecl>(*Param);
982
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000983 switch (Arg.getKind()) {
984 case TemplateArgument::Expression: {
985 Expr *ArgExpr = Arg.getAsExpr();
986 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
987 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
988 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
989 Invalid = true;
990
991 // Add the converted template argument.
992 // FIXME: Need the "canonical" template declaration!
993 Converted.push_back(
994 TemplateArgument(Arg.getLocation(),
995 cast<DeclRefExpr>(ArgExpr)->getDecl()));
996 continue;
997 }
998 }
999 // fall through
1000
1001 case TemplateArgument::Type: {
1002 // We have a template template parameter but the template
1003 // argument does not refer to a template.
1004 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1005 Invalid = true;
1006 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001007 }
1008
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001009 case TemplateArgument::Declaration:
1010 // We've already checked this template argument, so just copy
1011 // it to the list of converted arguments.
1012 Converted.push_back(Arg);
1013 break;
1014
1015 case TemplateArgument::Integral:
1016 assert(false && "Integral argument with template template parameter");
1017 break;
1018 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001019 }
1020 }
1021
1022 return Invalid;
1023}
1024
1025/// \brief Check a template argument against its corresponding
1026/// template type parameter.
1027///
1028/// This routine implements the semantics of C++ [temp.arg.type]. It
1029/// returns true if an error occurred, and false otherwise.
1030bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1031 QualType Arg, SourceLocation ArgLoc) {
1032 // C++ [temp.arg.type]p2:
1033 // A local type, a type with no linkage, an unnamed type or a type
1034 // compounded from any of these types shall not be used as a
1035 // template-argument for a template type-parameter.
1036 //
1037 // FIXME: Perform the recursive and no-linkage type checks.
1038 const TagType *Tag = 0;
1039 if (const EnumType *EnumT = Arg->getAsEnumType())
1040 Tag = EnumT;
1041 else if (const RecordType *RecordT = Arg->getAsRecordType())
1042 Tag = RecordT;
1043 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1044 return Diag(ArgLoc, diag::err_template_arg_local_type)
1045 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001046 else if (Tag && !Tag->getDecl()->getDeclName() &&
1047 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001048 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1049 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1050 return true;
1051 }
1052
1053 return false;
1054}
1055
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001056/// \brief Checks whether the given template argument is the address
1057/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001058bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1059 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001060 bool Invalid = false;
1061
1062 // See through any implicit casts we added to fix the type.
1063 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1064 Arg = Cast->getSubExpr();
1065
1066 // C++ [temp.arg.nontype]p1:
1067 //
1068 // A template-argument for a non-type, non-template
1069 // template-parameter shall be one of: [...]
1070 //
1071 // -- the address of an object or function with external
1072 // linkage, including function templates and function
1073 // template-ids but excluding non-static class members,
1074 // expressed as & id-expression where the & is optional if
1075 // the name refers to a function or array, or if the
1076 // corresponding template-parameter is a reference; or
1077 DeclRefExpr *DRE = 0;
1078
1079 // Ignore (and complain about) any excess parentheses.
1080 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1081 if (!Invalid) {
1082 Diag(Arg->getSourceRange().getBegin(),
1083 diag::err_template_arg_extra_parens)
1084 << Arg->getSourceRange();
1085 Invalid = true;
1086 }
1087
1088 Arg = Parens->getSubExpr();
1089 }
1090
1091 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1092 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1093 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1094 } else
1095 DRE = dyn_cast<DeclRefExpr>(Arg);
1096
1097 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1098 return Diag(Arg->getSourceRange().getBegin(),
1099 diag::err_template_arg_not_object_or_func_form)
1100 << Arg->getSourceRange();
1101
1102 // Cannot refer to non-static data members
1103 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1104 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1105 << Field << Arg->getSourceRange();
1106
1107 // Cannot refer to non-static member functions
1108 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1109 if (!Method->isStatic())
1110 return Diag(Arg->getSourceRange().getBegin(),
1111 diag::err_template_arg_method)
1112 << Method << Arg->getSourceRange();
1113
1114 // Functions must have external linkage.
1115 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1116 if (Func->getStorageClass() == FunctionDecl::Static) {
1117 Diag(Arg->getSourceRange().getBegin(),
1118 diag::err_template_arg_function_not_extern)
1119 << Func << Arg->getSourceRange();
1120 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1121 << true;
1122 return true;
1123 }
1124
1125 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001126 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001127 return Invalid;
1128 }
1129
1130 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1131 if (!Var->hasGlobalStorage()) {
1132 Diag(Arg->getSourceRange().getBegin(),
1133 diag::err_template_arg_object_not_extern)
1134 << Var << Arg->getSourceRange();
1135 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1136 << true;
1137 return true;
1138 }
1139
1140 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001141 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001142 return Invalid;
1143 }
1144
1145 // We found something else, but we don't know specifically what it is.
1146 Diag(Arg->getSourceRange().getBegin(),
1147 diag::err_template_arg_not_object_or_func)
1148 << Arg->getSourceRange();
1149 Diag(DRE->getDecl()->getLocation(),
1150 diag::note_template_arg_refers_here);
1151 return true;
1152}
1153
1154/// \brief Checks whether the given template argument is a pointer to
1155/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001156bool
1157Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001158 bool Invalid = false;
1159
1160 // See through any implicit casts we added to fix the type.
1161 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1162 Arg = Cast->getSubExpr();
1163
1164 // C++ [temp.arg.nontype]p1:
1165 //
1166 // A template-argument for a non-type, non-template
1167 // template-parameter shall be one of: [...]
1168 //
1169 // -- a pointer to member expressed as described in 5.3.1.
1170 QualifiedDeclRefExpr *DRE = 0;
1171
1172 // Ignore (and complain about) any excess parentheses.
1173 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1174 if (!Invalid) {
1175 Diag(Arg->getSourceRange().getBegin(),
1176 diag::err_template_arg_extra_parens)
1177 << Arg->getSourceRange();
1178 Invalid = true;
1179 }
1180
1181 Arg = Parens->getSubExpr();
1182 }
1183
1184 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1185 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1186 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1187
1188 if (!DRE)
1189 return Diag(Arg->getSourceRange().getBegin(),
1190 diag::err_template_arg_not_pointer_to_member_form)
1191 << Arg->getSourceRange();
1192
1193 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1194 assert((isa<FieldDecl>(DRE->getDecl()) ||
1195 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1196 "Only non-static member pointers can make it here");
1197
1198 // Okay: this is the address of a non-static member, and therefore
1199 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001200 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001201 return Invalid;
1202 }
1203
1204 // We found something else, but we don't know specifically what it is.
1205 Diag(Arg->getSourceRange().getBegin(),
1206 diag::err_template_arg_not_pointer_to_member_form)
1207 << Arg->getSourceRange();
1208 Diag(DRE->getDecl()->getLocation(),
1209 diag::note_template_arg_refers_here);
1210 return true;
1211}
1212
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001213/// \brief Check a template argument against its corresponding
1214/// non-type template parameter.
1215///
Douglas Gregored3a3982009-03-03 04:44:36 +00001216/// This routine implements the semantics of C++ [temp.arg.nontype].
1217/// It returns true if an error occurred, and false otherwise. \p
1218/// InstantiatedParamType is the type of the non-type template
1219/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001220///
1221/// If Converted is non-NULL and no errors occur, the value
1222/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001223bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001224 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001225 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001226 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1227
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001228 // If either the parameter has a dependent type or the argument is
1229 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001230 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001231 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1232 // FIXME: Produce a cloned, canonical expression?
1233 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001234 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001235 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001236
1237 // C++ [temp.arg.nontype]p5:
1238 // The following conversions are performed on each expression used
1239 // as a non-type template-argument. If a non-type
1240 // template-argument cannot be converted to the type of the
1241 // corresponding template-parameter then the program is
1242 // ill-formed.
1243 //
1244 // -- for a non-type template-parameter of integral or
1245 // enumeration type, integral promotions (4.5) and integral
1246 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001247 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001248 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001249 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001250 // C++ [temp.arg.nontype]p1:
1251 // A template-argument for a non-type, non-template
1252 // template-parameter shall be one of:
1253 //
1254 // -- an integral constant-expression of integral or enumeration
1255 // type; or
1256 // -- the name of a non-type template-parameter; or
1257 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001258 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001259 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1260 Diag(Arg->getSourceRange().getBegin(),
1261 diag::err_template_arg_not_integral_or_enumeral)
1262 << ArgType << Arg->getSourceRange();
1263 Diag(Param->getLocation(), diag::note_template_param_here);
1264 return true;
1265 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001266 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001267 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1268 << ArgType << Arg->getSourceRange();
1269 return true;
1270 }
1271
1272 // FIXME: We need some way to more easily get the unqualified form
1273 // of the types without going all the way to the
1274 // canonical type.
1275 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1276 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1277 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1278 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1279
1280 // Try to convert the argument to the parameter's type.
1281 if (ParamType == ArgType) {
1282 // Okay: no conversion necessary
1283 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1284 !ParamType->isEnumeralType()) {
1285 // This is an integral promotion or conversion.
1286 ImpCastExprToType(Arg, ParamType);
1287 } else {
1288 // We can't perform this conversion.
1289 Diag(Arg->getSourceRange().getBegin(),
1290 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001291 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001292 Diag(Param->getLocation(), diag::note_template_param_here);
1293 return true;
1294 }
1295
Douglas Gregorafc86942009-03-14 00:20:21 +00001296 QualType IntegerType = Context.getCanonicalType(ParamType);
1297 if (const EnumType *Enum = IntegerType->getAsEnumType())
1298 IntegerType = Enum->getDecl()->getIntegerType();
1299
1300 if (!Arg->isValueDependent()) {
1301 // Check that an unsigned parameter does not receive a negative
1302 // value.
1303 if (IntegerType->isUnsignedIntegerType()
1304 && (Value.isSigned() && Value.isNegative())) {
1305 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1306 << Value.toString(10) << Param->getType()
1307 << Arg->getSourceRange();
1308 Diag(Param->getLocation(), diag::note_template_param_here);
1309 return true;
1310 }
1311
1312 // Check that we don't overflow the template parameter type.
1313 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1314 if (Value.getActiveBits() > AllowedBits) {
1315 Diag(Arg->getSourceRange().getBegin(),
1316 diag::err_template_arg_too_large)
1317 << Value.toString(10) << Param->getType()
1318 << Arg->getSourceRange();
1319 Diag(Param->getLocation(), diag::note_template_param_here);
1320 return true;
1321 }
1322
1323 if (Value.getBitWidth() != AllowedBits)
1324 Value.extOrTrunc(AllowedBits);
1325 Value.setIsSigned(IntegerType->isSignedIntegerType());
1326 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001327
1328 if (Converted) {
1329 // Add the value of this argument to the list of converted
1330 // arguments. We use the bitwidth and signedness of the template
1331 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001332 if (Arg->isValueDependent()) {
1333 // The argument is value-dependent. Create a new
1334 // TemplateArgument with the converted expression.
1335 Converted->push_back(TemplateArgument(Arg));
1336 return false;
1337 }
1338
Douglas Gregor544cda62009-03-14 00:03:48 +00001339 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001340 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001341 }
1342
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001343 return false;
1344 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001345
Douglas Gregor3f411962009-02-11 01:18:59 +00001346 // Handle pointer-to-function, reference-to-function, and
1347 // pointer-to-member-function all in (roughly) the same way.
1348 if (// -- For a non-type template-parameter of type pointer to
1349 // function, only the function-to-pointer conversion (4.3) is
1350 // applied. If the template-argument represents a set of
1351 // overloaded functions (or a pointer to such), the matching
1352 // function is selected from the set (13.4).
1353 (ParamType->isPointerType() &&
1354 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1355 // -- For a non-type template-parameter of type reference to
1356 // function, no conversions apply. If the template-argument
1357 // represents a set of overloaded functions, the matching
1358 // function is selected from the set (13.4).
1359 (ParamType->isReferenceType() &&
1360 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1361 // -- For a non-type template-parameter of type pointer to
1362 // member function, no conversions apply. If the
1363 // template-argument represents a set of overloaded member
1364 // functions, the matching member function is selected from
1365 // the set (13.4).
1366 (ParamType->isMemberPointerType() &&
1367 ParamType->getAsMemberPointerType()->getPointeeType()
1368 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001369 if (Context.hasSameUnqualifiedType(ArgType,
1370 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001371 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001372 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001373 ArgType = Context.getPointerType(ArgType);
1374 ImpCastExprToType(Arg, ArgType);
1375 } else if (FunctionDecl *Fn
1376 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001377 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1378 return true;
1379
Douglas Gregor2eedd992009-02-11 00:19:33 +00001380 FixOverloadedFunctionReference(Arg, Fn);
1381 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001382 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001383 ArgType = Context.getPointerType(Arg->getType());
1384 ImpCastExprToType(Arg, ArgType);
1385 }
1386 }
1387
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001388 if (!Context.hasSameUnqualifiedType(ArgType,
1389 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001390 // We can't perform this conversion.
1391 Diag(Arg->getSourceRange().getBegin(),
1392 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001393 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001394 Diag(Param->getLocation(), diag::note_template_param_here);
1395 return true;
1396 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001397
Douglas Gregorad964b32009-02-17 01:05:43 +00001398 if (ParamType->isMemberPointerType()) {
1399 NamedDecl *Member = 0;
1400 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1401 return true;
1402
1403 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001404 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001405
1406 return false;
1407 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001408
Douglas Gregorad964b32009-02-17 01:05:43 +00001409 NamedDecl *Entity = 0;
1410 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1411 return true;
1412
1413 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001414 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001415 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001416 }
1417
Chris Lattner320dff22009-02-20 21:37:53 +00001418 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001419 // -- for a non-type template-parameter of type pointer to
1420 // object, qualification conversions (4.4) and the
1421 // array-to-pointer conversion (4.2) are applied.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001422 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001423 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001424
Douglas Gregor3f411962009-02-11 01:18:59 +00001425 if (ArgType->isArrayType()) {
1426 ArgType = Context.getArrayDecayedType(ArgType);
1427 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001428 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001429
1430 if (IsQualificationConversion(ArgType, ParamType)) {
1431 ArgType = ParamType;
1432 ImpCastExprToType(Arg, ParamType);
1433 }
1434
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001435 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001436 // We can't perform this conversion.
1437 Diag(Arg->getSourceRange().getBegin(),
1438 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001439 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001440 Diag(Param->getLocation(), diag::note_template_param_here);
1441 return true;
1442 }
1443
Douglas Gregorad964b32009-02-17 01:05:43 +00001444 NamedDecl *Entity = 0;
1445 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1446 return true;
1447
1448 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001449 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001450
1451 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001452 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001453
1454 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1455 // -- For a non-type template-parameter of type reference to
1456 // object, no conversions apply. The type referred to by the
1457 // reference may be more cv-qualified than the (otherwise
1458 // identical) type of the template-argument. The
1459 // template-parameter is bound directly to the
1460 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001461 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001462 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001463
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001464 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001465 Diag(Arg->getSourceRange().getBegin(),
1466 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001467 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001468 << Arg->getSourceRange();
1469 Diag(Param->getLocation(), diag::note_template_param_here);
1470 return true;
1471 }
1472
1473 unsigned ParamQuals
1474 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1475 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1476
1477 if ((ParamQuals | ArgQuals) != ParamQuals) {
1478 Diag(Arg->getSourceRange().getBegin(),
1479 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001480 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001481 << Arg->getSourceRange();
1482 Diag(Param->getLocation(), diag::note_template_param_here);
1483 return true;
1484 }
1485
Douglas Gregorad964b32009-02-17 01:05:43 +00001486 NamedDecl *Entity = 0;
1487 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1488 return true;
1489
1490 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001491 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001492
1493 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001494 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001495
1496 // -- For a non-type template-parameter of type pointer to data
1497 // member, qualification conversions (4.4) are applied.
1498 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1499
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001500 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001501 // Types match exactly: nothing more to do here.
1502 } else if (IsQualificationConversion(ArgType, ParamType)) {
1503 ImpCastExprToType(Arg, ParamType);
1504 } else {
1505 // We can't perform this conversion.
1506 Diag(Arg->getSourceRange().getBegin(),
1507 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001508 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001509 Diag(Param->getLocation(), diag::note_template_param_here);
1510 return true;
1511 }
1512
Douglas Gregorad964b32009-02-17 01:05:43 +00001513 NamedDecl *Member = 0;
1514 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1515 return true;
1516
1517 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001518 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001519
1520 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001521}
1522
1523/// \brief Check a template argument against its corresponding
1524/// template template parameter.
1525///
1526/// This routine implements the semantics of C++ [temp.arg.template].
1527/// It returns true if an error occurred, and false otherwise.
1528bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1529 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001530 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1531 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1532
1533 // C++ [temp.arg.template]p1:
1534 // A template-argument for a template template-parameter shall be
1535 // the name of a class template, expressed as id-expression. Only
1536 // primary class templates are considered when matching the
1537 // template template argument with the corresponding parameter;
1538 // partial specializations are not considered even if their
1539 // parameter lists match that of the template template parameter.
1540 if (!isa<ClassTemplateDecl>(Template)) {
1541 assert(isa<FunctionTemplateDecl>(Template) &&
1542 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001543 Diag(Arg->getSourceRange().getBegin(),
1544 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001545 << Template;
1546 }
1547
1548 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1549 Param->getTemplateParameters(),
1550 true, true,
1551 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001552}
1553
Douglas Gregord406b032009-02-06 22:42:48 +00001554/// \brief Determine whether the given template parameter lists are
1555/// equivalent.
1556///
1557/// \param New The new template parameter list, typically written in the
1558/// source code as part of a new template declaration.
1559///
1560/// \param Old The old template parameter list, typically found via
1561/// name lookup of the template declared with this template parameter
1562/// list.
1563///
1564/// \param Complain If true, this routine will produce a diagnostic if
1565/// the template parameter lists are not equivalent.
1566///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001567/// \param IsTemplateTemplateParm If true, this routine is being
1568/// called to compare the template parameter lists of a template
1569/// template parameter.
1570///
1571/// \param TemplateArgLoc If this source location is valid, then we
1572/// are actually checking the template parameter list of a template
1573/// argument (New) against the template parameter list of its
1574/// corresponding template template parameter (Old). We produce
1575/// slightly different diagnostics in this scenario.
1576///
Douglas Gregord406b032009-02-06 22:42:48 +00001577/// \returns True if the template parameter lists are equal, false
1578/// otherwise.
1579bool
1580Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1581 TemplateParameterList *Old,
1582 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001583 bool IsTemplateTemplateParm,
1584 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001585 if (Old->size() != New->size()) {
1586 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001587 unsigned NextDiag = diag::err_template_param_list_different_arity;
1588 if (TemplateArgLoc.isValid()) {
1589 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1590 NextDiag = diag::note_template_param_list_different_arity;
1591 }
1592 Diag(New->getTemplateLoc(), NextDiag)
1593 << (New->size() > Old->size())
1594 << IsTemplateTemplateParm
1595 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001596 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1597 << IsTemplateTemplateParm
1598 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1599 }
1600
1601 return false;
1602 }
1603
1604 for (TemplateParameterList::iterator OldParm = Old->begin(),
1605 OldParmEnd = Old->end(), NewParm = New->begin();
1606 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1607 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001608 unsigned NextDiag = diag::err_template_param_different_kind;
1609 if (TemplateArgLoc.isValid()) {
1610 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1611 NextDiag = diag::note_template_param_different_kind;
1612 }
1613 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001614 << IsTemplateTemplateParm;
1615 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1616 << IsTemplateTemplateParm;
1617 return false;
1618 }
1619
1620 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1621 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001622 // know we're at the same index).
1623#if 0
1624 // FIXME: Enable this code in debug mode *after* we properly go
1625 // through and "instantiate" the template parameter lists of
1626 // template template parameters. It's only after this
1627 // instantiation that (1) any dependent types within the
1628 // template parameter list of the template template parameter
1629 // can be checked, and (2) the template type parameter depths
1630 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001631 QualType OldParmType
1632 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1633 QualType NewParmType
1634 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1635 assert(Context.getCanonicalType(OldParmType) ==
1636 Context.getCanonicalType(NewParmType) &&
1637 "type parameter mismatch?");
1638#endif
1639 } else if (NonTypeTemplateParmDecl *OldNTTP
1640 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1641 // The types of non-type template parameters must agree.
1642 NonTypeTemplateParmDecl *NewNTTP
1643 = cast<NonTypeTemplateParmDecl>(*NewParm);
1644 if (Context.getCanonicalType(OldNTTP->getType()) !=
1645 Context.getCanonicalType(NewNTTP->getType())) {
1646 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001647 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1648 if (TemplateArgLoc.isValid()) {
1649 Diag(TemplateArgLoc,
1650 diag::err_template_arg_template_params_mismatch);
1651 NextDiag = diag::note_template_nontype_parm_different_type;
1652 }
1653 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001654 << NewNTTP->getType()
1655 << IsTemplateTemplateParm;
1656 Diag(OldNTTP->getLocation(),
1657 diag::note_template_nontype_parm_prev_declaration)
1658 << OldNTTP->getType();
1659 }
1660 return false;
1661 }
1662 } else {
1663 // The template parameter lists of template template
1664 // parameters must agree.
1665 // FIXME: Could we perform a faster "type" comparison here?
1666 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1667 "Only template template parameters handled here");
1668 TemplateTemplateParmDecl *OldTTP
1669 = cast<TemplateTemplateParmDecl>(*OldParm);
1670 TemplateTemplateParmDecl *NewTTP
1671 = cast<TemplateTemplateParmDecl>(*NewParm);
1672 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1673 OldTTP->getTemplateParameters(),
1674 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001675 /*IsTemplateTemplateParm=*/true,
1676 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001677 return false;
1678 }
1679 }
1680
1681 return true;
1682}
1683
1684/// \brief Check whether a template can be declared within this scope.
1685///
1686/// If the template declaration is valid in this scope, returns
1687/// false. Otherwise, issues a diagnostic and returns true.
1688bool
1689Sema::CheckTemplateDeclScope(Scope *S,
1690 MultiTemplateParamsArg &TemplateParameterLists) {
1691 assert(TemplateParameterLists.size() > 0 && "Not a template");
1692
1693 // Find the nearest enclosing declaration scope.
1694 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1695 (S->getFlags() & Scope::TemplateParamScope) != 0)
1696 S = S->getParent();
1697
1698 TemplateParameterList *TemplateParams =
1699 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1700 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1701 SourceRange TemplateRange
1702 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1703
1704 // C++ [temp]p2:
1705 // A template-declaration can appear only as a namespace scope or
1706 // class scope declaration.
1707 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1708 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1709 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1710 return Diag(TemplateLoc, diag::err_template_linkage)
1711 << TemplateRange;
1712
1713 Ctx = Ctx->getParent();
1714 }
1715
1716 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1717 return false;
1718
1719 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1720 << TemplateRange;
1721}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001722
Douglas Gregor0d93f692009-02-25 22:02:03 +00001723/// \brief Check whether a class template specialization in the
1724/// current context is well-formed.
1725///
1726/// This routine determines whether a class template specialization
1727/// can be declared in the current context (C++ [temp.expl.spec]p2)
1728/// and emits appropriate diagnostics if there was an error. It
1729/// returns true if there was an error that we cannot recover from,
1730/// and false otherwise.
1731bool
1732Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1733 ClassTemplateSpecializationDecl *PrevDecl,
1734 SourceLocation TemplateNameLoc,
1735 SourceRange ScopeSpecifierRange) {
1736 // C++ [temp.expl.spec]p2:
1737 // An explicit specialization shall be declared in the namespace
1738 // of which the template is a member, or, for member templates, in
1739 // the namespace of which the enclosing class or enclosing class
1740 // template is a member. An explicit specialization of a member
1741 // function, member class or static data member of a class
1742 // template shall be declared in the namespace of which the class
1743 // template is a member. Such a declaration may also be a
1744 // definition. If the declaration is not a definition, the
1745 // specialization may be defined later in the name- space in which
1746 // the explicit specialization was declared, or in a namespace
1747 // that encloses the one in which the explicit specialization was
1748 // declared.
1749 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1750 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1751 << ClassTemplate;
1752 return true;
1753 }
1754
1755 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1756 DeclContext *TemplateContext
1757 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1758 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1759 // There is no prior declaration of this entity, so this
1760 // specialization must be in the same context as the template
1761 // itself.
1762 if (DC != TemplateContext) {
1763 if (isa<TranslationUnitDecl>(TemplateContext))
1764 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1765 << ClassTemplate << ScopeSpecifierRange;
1766 else if (isa<NamespaceDecl>(TemplateContext))
1767 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1768 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1769 << ScopeSpecifierRange;
1770
1771 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1772 }
1773
1774 return false;
1775 }
1776
1777 // We have a previous declaration of this entity. Make sure that
1778 // this redeclaration (or definition) occurs in an enclosing namespace.
1779 if (!CurContext->Encloses(TemplateContext)) {
1780 if (isa<TranslationUnitDecl>(TemplateContext))
1781 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1782 << ClassTemplate << ScopeSpecifierRange;
1783 else if (isa<NamespaceDecl>(TemplateContext))
1784 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1785 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1786 << ScopeSpecifierRange;
1787
1788 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1789 }
1790
1791 return false;
1792}
1793
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001794Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001795Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1796 SourceLocation KWLoc,
1797 const CXXScopeSpec &SS,
1798 DeclTy *TemplateD,
1799 SourceLocation TemplateNameLoc,
1800 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001801 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001802 SourceLocation *TemplateArgLocs,
1803 SourceLocation RAngleLoc,
1804 AttributeList *Attr,
1805 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001806 // Find the class template we're specializing
1807 ClassTemplateDecl *ClassTemplate
1808 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1809 if (!ClassTemplate)
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001810 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001811
Douglas Gregor0d93f692009-02-25 22:02:03 +00001812 // Check the validity of the template headers that introduce this
1813 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001814 // FIXME: Once we have member templates, we'll need to check
1815 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1816 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001817 if (TemplateParameterLists.size() == 0)
1818 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001819 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001820 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001821 TemplateParameterList *TemplateParams
1822 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001823 if (TemplateParameterLists.size() > 1)
1824 return Diag(TemplateParams->getTemplateLoc(),
1825 diag::err_template_spec_extra_headers);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001826
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001827 if (TemplateParams->size() > 0)
Douglas Gregor0d93f692009-02-25 22:02:03 +00001828 // FIXME: No support for class template partial specialization.
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001829 return Diag(TemplateParams->getTemplateLoc(),
1830 diag::unsup_template_partial_spec);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001831 }
1832
Douglas Gregora08b6c72009-02-17 23:15:12 +00001833 // Check that the specialization uses the same tag kind as the
1834 // original template.
1835 TagDecl::TagKind Kind;
1836 switch (TagSpec) {
1837 default: assert(0 && "Unknown tag type!");
1838 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1839 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1840 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1841 }
1842 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1843 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1844 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1845 diag::note_previous_use);
1846 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1847 }
1848
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001849 // Translate the parser's template argument list in our AST format.
1850 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1851 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1852
Douglas Gregora08b6c72009-02-17 23:15:12 +00001853 // Check that the template argument list is well-formed for this
1854 // template.
1855 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1856 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001857 &TemplateArgs[0], TemplateArgs.size(),
1858 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001859 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001860
1861 assert((ConvertedTemplateArgs.size() ==
1862 ClassTemplate->getTemplateParameters()->size()) &&
1863 "Converted template argument list is too short!");
1864
1865 // Find the class template specialization declaration that
1866 // corresponds to these arguments.
1867 llvm::FoldingSetNodeID ID;
1868 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1869 ConvertedTemplateArgs.size());
1870 void *InsertPos = 0;
1871 ClassTemplateSpecializationDecl *PrevDecl
1872 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1873
1874 ClassTemplateSpecializationDecl *Specialization = 0;
1875
Douglas Gregor0d93f692009-02-25 22:02:03 +00001876 // Check whether we can declare a class template specialization in
1877 // the current scope.
1878 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1879 TemplateNameLoc,
1880 SS.getRange()))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001881 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001882
Douglas Gregora08b6c72009-02-17 23:15:12 +00001883 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1884 // Since the only prior class template specialization with these
1885 // arguments was referenced but not declared, reuse that
1886 // declaration node as our own, updating its source location to
1887 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001888 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00001889 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001890 PrevDecl = 0;
1891 } else {
1892 // Create a new class template specialization declaration node for
1893 // this explicit specialization.
1894 Specialization
1895 = ClassTemplateSpecializationDecl::Create(Context,
1896 ClassTemplate->getDeclContext(),
1897 TemplateNameLoc,
1898 ClassTemplate,
1899 &ConvertedTemplateArgs[0],
1900 ConvertedTemplateArgs.size(),
1901 PrevDecl);
1902
1903 if (PrevDecl) {
1904 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1905 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1906 } else {
1907 ClassTemplate->getSpecializations().InsertNode(Specialization,
1908 InsertPos);
1909 }
1910 }
1911
1912 // Note that this is an explicit specialization.
1913 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1914
1915 // Check that this isn't a redefinition of this specialization.
1916 if (TK == TK_Definition) {
1917 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1918 // FIXME: Should also handle explicit specialization after
1919 // implicit instantiation with a special diagnostic.
1920 SourceRange Range(TemplateNameLoc, RAngleLoc);
1921 Diag(TemplateNameLoc, diag::err_redefinition)
1922 << Specialization << Range;
1923 Diag(Def->getLocation(), diag::note_previous_definition);
1924 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001925 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001926 }
1927 }
1928
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001929 // Build the fully-sugared type for this class template
1930 // specialization as the user wrote in the specialization
1931 // itself. This means that we'll pretty-print the type retrieved
1932 // from the specialization's declaration the way that the user
1933 // actually wrote the specialization, rather than formatting the
1934 // name based on the "canonical" representation used to store the
1935 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00001936 QualType WrittenTy
1937 = Context.getClassTemplateSpecializationType(ClassTemplate,
1938 &TemplateArgs[0],
1939 TemplateArgs.size(),
1940 Context.getTypeDeclType(Specialization));
1941 Specialization->setTypeAsWritten(getQualifiedNameType(SS, WrittenTy));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001942 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001943
Douglas Gregor50113ca2009-02-25 22:18:32 +00001944 // C++ [temp.expl.spec]p9:
1945 // A template explicit specialization is in the scope of the
1946 // namespace in which the template was defined.
1947 //
1948 // We actually implement this paragraph where we set the semantic
1949 // context (in the creation of the ClassTemplateSpecializationDecl),
1950 // but we also maintain the lexical context where the actual
1951 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001952 Specialization->setLexicalDeclContext(CurContext);
1953
1954 // We may be starting the definition of this specialization.
1955 if (TK == TK_Definition)
1956 Specialization->startDefinition();
1957
1958 // Add the specialization into its lexical context, so that it can
1959 // be seen when iterating through the list of declarations in that
1960 // context. However, specializations are not found by name lookup.
1961 CurContext->addDecl(Specialization);
1962 return Specialization;
1963}