blob: c0476a8d3fdc9fda106002962c75da5d555eab1f [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,
391 MultiTemplateParamsArg TemplateParameterLists) {
392 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
393 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000394 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000395
396 // Check that we can declare a template here.
397 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000398 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000399
400 TagDecl::TagKind Kind;
401 switch (TagSpec) {
402 default: assert(0 && "Unknown tag type!");
403 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
404 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
405 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
406 }
407
408 // There is no such thing as an unnamed class template.
409 if (!Name) {
410 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000411 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000412 }
413
414 // Find any previous declaration with this name.
415 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
416 true);
417 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
418 NamedDecl *PrevDecl = 0;
419 if (Previous.begin() != Previous.end())
420 PrevDecl = *Previous.begin();
421
422 DeclContext *SemanticContext = CurContext;
423 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000424 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000425
426 // FIXME: need to match up several levels of template parameter
427 // lists here.
428 }
429
430 // FIXME: member templates!
431 TemplateParameterList *TemplateParams
432 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
433
434 // If there is a previous declaration with the same name, check
435 // whether this is a valid redeclaration.
436 ClassTemplateDecl *PrevClassTemplate
437 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
438 if (PrevClassTemplate) {
439 // Ensure that the template parameter lists are compatible.
440 if (!TemplateParameterListsAreEqual(TemplateParams,
441 PrevClassTemplate->getTemplateParameters(),
442 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000443 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000444
445 // C++ [temp.class]p4:
446 // In a redeclaration, partial specialization, explicit
447 // specialization or explicit instantiation of a class template,
448 // the class-key shall agree in kind with the original class
449 // template declaration (7.1.5.3).
450 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
451 if (PrevRecordDecl->getTagKind() != Kind) {
452 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
453 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000454 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000455 }
456
457
458 // Check for redefinition of this class template.
459 if (TK == TK_Definition) {
460 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
461 Diag(NameLoc, diag::err_redefinition) << Name;
462 Diag(Def->getLocation(), diag::note_previous_definition);
463 // FIXME: Would it make sense to try to "forget" the previous
464 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000465 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000466 }
467 }
468 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
469 // Maybe we will complain about the shadowed template parameter.
470 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
471 // Just pretend that we didn't see the previous declaration.
472 PrevDecl = 0;
473 } else if (PrevDecl) {
474 // C++ [temp]p5:
475 // A class template shall not have the same name as any other
476 // template, class, function, object, enumeration, enumerator,
477 // namespace, or type in the same scope (3.3), except as specified
478 // in (14.5.4).
479 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
480 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000481 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000482 }
483
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000484 // Check the template parameter list of this declaration, possibly
485 // merging in the template parameter list from the previous class
486 // template declaration.
487 if (CheckTemplateParameterList(TemplateParams,
488 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
489 Invalid = true;
490
Douglas Gregord406b032009-02-06 22:42:48 +0000491 // If we had a scope specifier, we better have a previous template
492 // declaration!
493
Douglas Gregor55216ac2009-03-26 00:10:35 +0000494 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000495 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
496 PrevClassTemplate?
497 PrevClassTemplate->getTemplatedDecl() : 0);
498
499 ClassTemplateDecl *NewTemplate
500 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
501 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000502 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000503 NewClass->setDescribedClassTemplate(NewTemplate);
504
Douglas Gregord406b032009-02-06 22:42:48 +0000505 // Set the lexical context of these templates
506 NewClass->setLexicalDeclContext(CurContext);
507 NewTemplate->setLexicalDeclContext(CurContext);
508
509 if (TK == TK_Definition)
510 NewClass->startDefinition();
511
512 if (Attr)
513 ProcessDeclAttributeList(NewClass, Attr);
514
515 PushOnScopeChains(NewTemplate, S);
516
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000517 if (Invalid) {
518 NewTemplate->setInvalidDecl();
519 NewClass->setInvalidDecl();
520 }
Douglas Gregord406b032009-02-06 22:42:48 +0000521 return NewTemplate;
522}
523
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000524/// \brief Checks the validity of a template parameter list, possibly
525/// considering the template parameter list from a previous
526/// declaration.
527///
528/// If an "old" template parameter list is provided, it must be
529/// equivalent (per TemplateParameterListsAreEqual) to the "new"
530/// template parameter list.
531///
532/// \param NewParams Template parameter list for a new template
533/// declaration. This template parameter list will be updated with any
534/// default arguments that are carried through from the previous
535/// template parameter list.
536///
537/// \param OldParams If provided, template parameter list from a
538/// previous declaration of the same template. Default template
539/// arguments will be merged from the old template parameter list to
540/// the new template parameter list.
541///
542/// \returns true if an error occurred, false otherwise.
543bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
544 TemplateParameterList *OldParams) {
545 bool Invalid = false;
546
547 // C++ [temp.param]p10:
548 // The set of default template-arguments available for use with a
549 // template declaration or definition is obtained by merging the
550 // default arguments from the definition (if in scope) and all
551 // declarations in scope in the same way default function
552 // arguments are (8.3.6).
553 bool SawDefaultArgument = false;
554 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000555
Mike Stumpe0b7e032009-02-11 23:03:27 +0000556 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000557 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000558 if (OldParams)
559 OldParam = OldParams->begin();
560
561 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
562 NewParamEnd = NewParams->end();
563 NewParam != NewParamEnd; ++NewParam) {
564 // Variables used to diagnose redundant default arguments
565 bool RedundantDefaultArg = false;
566 SourceLocation OldDefaultLoc;
567 SourceLocation NewDefaultLoc;
568
569 // Variables used to diagnose missing default arguments
570 bool MissingDefaultArg = false;
571
572 // Merge default arguments for template type parameters.
573 if (TemplateTypeParmDecl *NewTypeParm
574 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
575 TemplateTypeParmDecl *OldTypeParm
576 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
577
578 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
579 NewTypeParm->hasDefaultArgument()) {
580 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
581 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
582 SawDefaultArgument = true;
583 RedundantDefaultArg = true;
584 PreviousDefaultArgLoc = NewDefaultLoc;
585 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
586 // Merge the default argument from the old declaration to the
587 // new declaration.
588 SawDefaultArgument = true;
589 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
590 OldTypeParm->getDefaultArgumentLoc(),
591 true);
592 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
593 } else if (NewTypeParm->hasDefaultArgument()) {
594 SawDefaultArgument = true;
595 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
596 } else if (SawDefaultArgument)
597 MissingDefaultArg = true;
598 }
599 // Merge default arguments for non-type template parameters
600 else if (NonTypeTemplateParmDecl *NewNonTypeParm
601 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
602 NonTypeTemplateParmDecl *OldNonTypeParm
603 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
604 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
605 NewNonTypeParm->hasDefaultArgument()) {
606 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
607 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
608 SawDefaultArgument = true;
609 RedundantDefaultArg = true;
610 PreviousDefaultArgLoc = NewDefaultLoc;
611 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
612 // Merge the default argument from the old declaration to the
613 // new declaration.
614 SawDefaultArgument = true;
615 // FIXME: We need to create a new kind of "default argument"
616 // expression that points to a previous template template
617 // parameter.
618 NewNonTypeParm->setDefaultArgument(
619 OldNonTypeParm->getDefaultArgument());
620 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
621 } else if (NewNonTypeParm->hasDefaultArgument()) {
622 SawDefaultArgument = true;
623 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
624 } else if (SawDefaultArgument)
625 MissingDefaultArg = true;
626 }
627 // Merge default arguments for template template parameters
628 else {
629 TemplateTemplateParmDecl *NewTemplateParm
630 = cast<TemplateTemplateParmDecl>(*NewParam);
631 TemplateTemplateParmDecl *OldTemplateParm
632 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
633 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
634 NewTemplateParm->hasDefaultArgument()) {
635 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
636 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
637 SawDefaultArgument = true;
638 RedundantDefaultArg = true;
639 PreviousDefaultArgLoc = NewDefaultLoc;
640 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
641 // Merge the default argument from the old declaration to the
642 // new declaration.
643 SawDefaultArgument = true;
644 // FIXME: We need to create a new kind of "default argument"
645 // expression that points to a previous template template
646 // parameter.
647 NewTemplateParm->setDefaultArgument(
648 OldTemplateParm->getDefaultArgument());
649 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
650 } else if (NewTemplateParm->hasDefaultArgument()) {
651 SawDefaultArgument = true;
652 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
653 } else if (SawDefaultArgument)
654 MissingDefaultArg = true;
655 }
656
657 if (RedundantDefaultArg) {
658 // C++ [temp.param]p12:
659 // A template-parameter shall not be given default arguments
660 // by two different declarations in the same scope.
661 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
662 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
663 Invalid = true;
664 } else if (MissingDefaultArg) {
665 // C++ [temp.param]p11:
666 // If a template-parameter has a default template-argument,
667 // all subsequent template-parameters shall have a default
668 // template-argument supplied.
669 Diag((*NewParam)->getLocation(),
670 diag::err_template_param_default_arg_missing);
671 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
672 Invalid = true;
673 }
674
675 // If we have an old template parameter list that we're merging
676 // in, move on to the next parameter.
677 if (OldParams)
678 ++OldParam;
679 }
680
681 return Invalid;
682}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000683
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000684/// \brief Translates template arguments as provided by the parser
685/// into template arguments used by semantic analysis.
686static void
687translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
688 SourceLocation *TemplateArgLocs,
689 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
690 TemplateArgs.reserve(TemplateArgsIn.size());
691
692 void **Args = TemplateArgsIn.getArgs();
693 bool *ArgIsType = TemplateArgsIn.getArgIsType();
694 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
695 TemplateArgs.push_back(
696 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
697 QualType::getFromOpaquePtr(Args[Arg]))
698 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
699 }
700}
701
702QualType Sema::CheckClassTemplateId(ClassTemplateDecl *ClassTemplate,
703 SourceLocation TemplateLoc,
704 SourceLocation LAngleLoc,
705 const TemplateArgument *TemplateArgs,
706 unsigned NumTemplateArgs,
707 SourceLocation RAngleLoc) {
708 // Check that the template argument list is well-formed for this
709 // template.
710 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
711 if (CheckTemplateArgumentList(ClassTemplate, TemplateLoc, LAngleLoc,
712 TemplateArgs, NumTemplateArgs, RAngleLoc,
713 ConvertedTemplateArgs))
714 return QualType();
715
716 assert((ConvertedTemplateArgs.size() ==
717 ClassTemplate->getTemplateParameters()->size()) &&
718 "Converted template argument list is too short!");
719
720 QualType CanonType;
721
722 if (ClassTemplateSpecializationType::anyDependentTemplateArguments(
723 TemplateArgs,
724 NumTemplateArgs)) {
725 // This class template specialization is a dependent
726 // type. Therefore, its canonical type is another class template
727 // specialization type that contains all of the converted
728 // arguments in canonical form. This ensures that, e.g., A<T> and
729 // A<T, T> have identical types when A is declared as:
730 //
731 // template<typename T, typename U = T> struct A;
732
733 CanonType = Context.getClassTemplateSpecializationType(ClassTemplate,
734 &ConvertedTemplateArgs[0],
735 ConvertedTemplateArgs.size());
736 } else {
737 // Find the class template specialization declaration that
738 // corresponds to these arguments.
739 llvm::FoldingSetNodeID ID;
740 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
741 ConvertedTemplateArgs.size());
742 void *InsertPos = 0;
743 ClassTemplateSpecializationDecl *Decl
744 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
745 if (!Decl) {
746 // This is the first time we have referenced this class template
747 // specialization. Create the canonical declaration and add it to
748 // the set of specializations.
749 Decl = ClassTemplateSpecializationDecl::Create(Context,
750 ClassTemplate->getDeclContext(),
751 TemplateLoc,
752 ClassTemplate,
753 &ConvertedTemplateArgs[0],
754 ConvertedTemplateArgs.size(),
755 0);
756 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
757 Decl->setLexicalDeclContext(CurContext);
758 }
759
760 CanonType = Context.getTypeDeclType(Decl);
761 }
762
763 // Build the fully-sugared type for this class template
764 // specialization, which refers back to the class template
765 // specialization we created or found.
766 return Context.getClassTemplateSpecializationType(ClassTemplate,
767 TemplateArgs,
768 NumTemplateArgs,
769 CanonType);
770}
771
Douglas Gregora08b6c72009-02-17 23:15:12 +0000772Action::TypeResult
773Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
774 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000775 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000776 SourceLocation *TemplateArgLocs,
777 SourceLocation RAngleLoc,
778 const CXXScopeSpec *SS) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000779 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregorad964b32009-02-17 01:05:43 +0000780 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000781
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000782 // Translate the parser's template argument list in our AST format.
783 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
784 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000785
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000786 QualType Result = CheckClassTemplateId(ClassTemplate, TemplateLoc,
787 LAngleLoc,
788 &TemplateArgs[0],
789 TemplateArgs.size(),
790 RAngleLoc);
Douglas Gregor8c795a12009-03-19 00:39:20 +0000791
792 if (SS)
793 Result = getQualifiedNameType(*SS, Result);
Douglas Gregorad964b32009-02-17 01:05:43 +0000794
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000795 TemplateArgsIn.release();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000796 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000797}
798
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000799/// \brief Check that the given template argument list is well-formed
800/// for specializing the given template.
801bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
802 SourceLocation TemplateLoc,
803 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000804 const TemplateArgument *TemplateArgs,
805 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000806 SourceLocation RAngleLoc,
807 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000808 TemplateParameterList *Params = Template->getTemplateParameters();
809 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000810 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000811 bool Invalid = false;
812
813 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000814 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000815 // FIXME: point at either the first arg beyond what we can handle,
816 // or the '>', depending on whether we have too many or too few
817 // arguments.
818 SourceRange Range;
819 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000820 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000821 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
822 << (NumArgs > NumParams)
823 << (isa<ClassTemplateDecl>(Template)? 0 :
824 isa<FunctionTemplateDecl>(Template)? 1 :
825 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
826 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000827 Diag(Template->getLocation(), diag::note_template_decl_here)
828 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000829 Invalid = true;
830 }
831
832 // C++ [temp.arg]p1:
833 // [...] The type and form of each template-argument specified in
834 // a template-id shall match the type and form specified for the
835 // corresponding parameter declared by the template in its
836 // template-parameter-list.
837 unsigned ArgIdx = 0;
838 for (TemplateParameterList::iterator Param = Params->begin(),
839 ParamEnd = Params->end();
840 Param != ParamEnd; ++Param, ++ArgIdx) {
841 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000842 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000843 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000844 // Retrieve the default template argument from the template
845 // parameter.
846 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
847 if (!TTP->hasDefaultArgument())
848 break;
849
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000850 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000851
852 // If the argument type is dependent, instantiate it now based
853 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000854 if (ArgType->isDependentType()) {
855 InstantiatingTemplate Inst(*this, TemplateLoc,
856 Template, &Converted[0],
857 Converted.size(),
858 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor74296542009-02-27 19:31:52 +0000859 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
860 TTP->getDefaultArgumentLoc(),
861 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +0000862 }
Douglas Gregor74296542009-02-27 19:31:52 +0000863
864 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000865 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000866
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000867 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +0000868 } else if (NonTypeTemplateParmDecl *NTTP
869 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
870 if (!NTTP->hasDefaultArgument())
871 break;
872
Douglas Gregored3a3982009-03-03 04:44:36 +0000873 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000874 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000875 } else {
876 TemplateTemplateParmDecl *TempParm
877 = cast<TemplateTemplateParmDecl>(*Param);
878
879 if (!TempParm->hasDefaultArgument())
880 break;
881
Douglas Gregored3a3982009-03-03 04:44:36 +0000882 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000883 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000884 }
885 } else {
886 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000887 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +0000888 }
889
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000890
891 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
892 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000893 if (Arg.getKind() == TemplateArgument::Type) {
894 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000895 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000896
897 // Add the converted template type argument.
898 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000899 TemplateArgument(Arg.getLocation(),
900 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000901 continue;
902 }
903
904 // C++ [temp.arg.type]p1:
905 // A template-argument for a template-parameter which is a
906 // type shall be a type-id.
907
908 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000909 // is not a type.
910 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000911 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000912 Invalid = true;
913 } else if (NonTypeTemplateParmDecl *NTTP
914 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
915 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +0000916
917 // Instantiate the type of the non-type template parameter with
918 // the template arguments we've seen thus far.
919 QualType NTTPType = NTTP->getType();
920 if (NTTPType->isDependentType()) {
921 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000922 InstantiatingTemplate Inst(*this, TemplateLoc,
923 Template, &Converted[0],
924 Converted.size(),
925 SourceRange(TemplateLoc, RAngleLoc));
926
Douglas Gregored3a3982009-03-03 04:44:36 +0000927 NTTPType = InstantiateType(NTTPType,
928 &Converted[0], Converted.size(),
929 NTTP->getLocation(),
930 NTTP->getDeclName());
931 // If that worked, check the non-type template parameter type
932 // for validity.
933 if (!NTTPType.isNull())
934 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
935 NTTP->getLocation());
936
937 if (NTTPType.isNull()) {
938 Invalid = true;
939 break;
940 }
941 }
942
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000943 switch (Arg.getKind()) {
944 case TemplateArgument::Expression: {
945 Expr *E = Arg.getAsExpr();
946 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000947 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000948 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000949 }
950
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000951 case TemplateArgument::Declaration:
952 case TemplateArgument::Integral:
953 // We've already checked this template argument, so just copy
954 // it to the list of converted arguments.
955 Converted.push_back(Arg);
956 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000957
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000958 case TemplateArgument::Type:
959 // We have a non-type template parameter but the template
960 // argument is a type.
961
962 // C++ [temp.arg]p2:
963 // In a template-argument, an ambiguity between a type-id and
964 // an expression is resolved to a type-id, regardless of the
965 // form of the corresponding template-parameter.
966 //
967 // We warn specifically about this case, since it can be rather
968 // confusing for users.
969 if (Arg.getAsType()->isFunctionType())
970 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
971 << Arg.getAsType();
972 else
973 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
974 Diag((*Param)->getLocation(), diag::note_template_param_here);
975 Invalid = true;
976 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000977 } else {
978 // Check template template parameters.
979 TemplateTemplateParmDecl *TempParm
980 = cast<TemplateTemplateParmDecl>(*Param);
981
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000982 switch (Arg.getKind()) {
983 case TemplateArgument::Expression: {
984 Expr *ArgExpr = Arg.getAsExpr();
985 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
986 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
987 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
988 Invalid = true;
989
990 // Add the converted template argument.
991 // FIXME: Need the "canonical" template declaration!
992 Converted.push_back(
993 TemplateArgument(Arg.getLocation(),
994 cast<DeclRefExpr>(ArgExpr)->getDecl()));
995 continue;
996 }
997 }
998 // fall through
999
1000 case TemplateArgument::Type: {
1001 // We have a template template parameter but the template
1002 // argument does not refer to a template.
1003 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1004 Invalid = true;
1005 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001006 }
1007
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001008 case TemplateArgument::Declaration:
1009 // We've already checked this template argument, so just copy
1010 // it to the list of converted arguments.
1011 Converted.push_back(Arg);
1012 break;
1013
1014 case TemplateArgument::Integral:
1015 assert(false && "Integral argument with template template parameter");
1016 break;
1017 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001018 }
1019 }
1020
1021 return Invalid;
1022}
1023
1024/// \brief Check a template argument against its corresponding
1025/// template type parameter.
1026///
1027/// This routine implements the semantics of C++ [temp.arg.type]. It
1028/// returns true if an error occurred, and false otherwise.
1029bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1030 QualType Arg, SourceLocation ArgLoc) {
1031 // C++ [temp.arg.type]p2:
1032 // A local type, a type with no linkage, an unnamed type or a type
1033 // compounded from any of these types shall not be used as a
1034 // template-argument for a template type-parameter.
1035 //
1036 // FIXME: Perform the recursive and no-linkage type checks.
1037 const TagType *Tag = 0;
1038 if (const EnumType *EnumT = Arg->getAsEnumType())
1039 Tag = EnumT;
1040 else if (const RecordType *RecordT = Arg->getAsRecordType())
1041 Tag = RecordT;
1042 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1043 return Diag(ArgLoc, diag::err_template_arg_local_type)
1044 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001045 else if (Tag && !Tag->getDecl()->getDeclName() &&
1046 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001047 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1048 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1049 return true;
1050 }
1051
1052 return false;
1053}
1054
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001055/// \brief Checks whether the given template argument is the address
1056/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001057bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1058 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001059 bool Invalid = false;
1060
1061 // See through any implicit casts we added to fix the type.
1062 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1063 Arg = Cast->getSubExpr();
1064
1065 // C++ [temp.arg.nontype]p1:
1066 //
1067 // A template-argument for a non-type, non-template
1068 // template-parameter shall be one of: [...]
1069 //
1070 // -- the address of an object or function with external
1071 // linkage, including function templates and function
1072 // template-ids but excluding non-static class members,
1073 // expressed as & id-expression where the & is optional if
1074 // the name refers to a function or array, or if the
1075 // corresponding template-parameter is a reference; or
1076 DeclRefExpr *DRE = 0;
1077
1078 // Ignore (and complain about) any excess parentheses.
1079 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1080 if (!Invalid) {
1081 Diag(Arg->getSourceRange().getBegin(),
1082 diag::err_template_arg_extra_parens)
1083 << Arg->getSourceRange();
1084 Invalid = true;
1085 }
1086
1087 Arg = Parens->getSubExpr();
1088 }
1089
1090 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1091 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1092 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1093 } else
1094 DRE = dyn_cast<DeclRefExpr>(Arg);
1095
1096 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1097 return Diag(Arg->getSourceRange().getBegin(),
1098 diag::err_template_arg_not_object_or_func_form)
1099 << Arg->getSourceRange();
1100
1101 // Cannot refer to non-static data members
1102 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1103 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1104 << Field << Arg->getSourceRange();
1105
1106 // Cannot refer to non-static member functions
1107 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1108 if (!Method->isStatic())
1109 return Diag(Arg->getSourceRange().getBegin(),
1110 diag::err_template_arg_method)
1111 << Method << Arg->getSourceRange();
1112
1113 // Functions must have external linkage.
1114 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1115 if (Func->getStorageClass() == FunctionDecl::Static) {
1116 Diag(Arg->getSourceRange().getBegin(),
1117 diag::err_template_arg_function_not_extern)
1118 << Func << Arg->getSourceRange();
1119 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1120 << true;
1121 return true;
1122 }
1123
1124 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001125 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001126 return Invalid;
1127 }
1128
1129 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1130 if (!Var->hasGlobalStorage()) {
1131 Diag(Arg->getSourceRange().getBegin(),
1132 diag::err_template_arg_object_not_extern)
1133 << Var << Arg->getSourceRange();
1134 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1135 << true;
1136 return true;
1137 }
1138
1139 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001140 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001141 return Invalid;
1142 }
1143
1144 // We found something else, but we don't know specifically what it is.
1145 Diag(Arg->getSourceRange().getBegin(),
1146 diag::err_template_arg_not_object_or_func)
1147 << Arg->getSourceRange();
1148 Diag(DRE->getDecl()->getLocation(),
1149 diag::note_template_arg_refers_here);
1150 return true;
1151}
1152
1153/// \brief Checks whether the given template argument is a pointer to
1154/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001155bool
1156Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001157 bool Invalid = false;
1158
1159 // See through any implicit casts we added to fix the type.
1160 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1161 Arg = Cast->getSubExpr();
1162
1163 // C++ [temp.arg.nontype]p1:
1164 //
1165 // A template-argument for a non-type, non-template
1166 // template-parameter shall be one of: [...]
1167 //
1168 // -- a pointer to member expressed as described in 5.3.1.
1169 QualifiedDeclRefExpr *DRE = 0;
1170
1171 // Ignore (and complain about) any excess parentheses.
1172 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1173 if (!Invalid) {
1174 Diag(Arg->getSourceRange().getBegin(),
1175 diag::err_template_arg_extra_parens)
1176 << Arg->getSourceRange();
1177 Invalid = true;
1178 }
1179
1180 Arg = Parens->getSubExpr();
1181 }
1182
1183 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1184 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1185 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1186
1187 if (!DRE)
1188 return Diag(Arg->getSourceRange().getBegin(),
1189 diag::err_template_arg_not_pointer_to_member_form)
1190 << Arg->getSourceRange();
1191
1192 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1193 assert((isa<FieldDecl>(DRE->getDecl()) ||
1194 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1195 "Only non-static member pointers can make it here");
1196
1197 // Okay: this is the address of a non-static member, and therefore
1198 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001199 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001200 return Invalid;
1201 }
1202
1203 // We found something else, but we don't know specifically what it is.
1204 Diag(Arg->getSourceRange().getBegin(),
1205 diag::err_template_arg_not_pointer_to_member_form)
1206 << Arg->getSourceRange();
1207 Diag(DRE->getDecl()->getLocation(),
1208 diag::note_template_arg_refers_here);
1209 return true;
1210}
1211
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001212/// \brief Check a template argument against its corresponding
1213/// non-type template parameter.
1214///
Douglas Gregored3a3982009-03-03 04:44:36 +00001215/// This routine implements the semantics of C++ [temp.arg.nontype].
1216/// It returns true if an error occurred, and false otherwise. \p
1217/// InstantiatedParamType is the type of the non-type template
1218/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001219///
1220/// If Converted is non-NULL and no errors occur, the value
1221/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001222bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001223 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001224 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001225 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1226
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001227 // If either the parameter has a dependent type or the argument is
1228 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001229 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001230 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1231 // FIXME: Produce a cloned, canonical expression?
1232 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001233 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001234 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001235
1236 // C++ [temp.arg.nontype]p5:
1237 // The following conversions are performed on each expression used
1238 // as a non-type template-argument. If a non-type
1239 // template-argument cannot be converted to the type of the
1240 // corresponding template-parameter then the program is
1241 // ill-formed.
1242 //
1243 // -- for a non-type template-parameter of integral or
1244 // enumeration type, integral promotions (4.5) and integral
1245 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001246 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001247 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001248 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001249 // C++ [temp.arg.nontype]p1:
1250 // A template-argument for a non-type, non-template
1251 // template-parameter shall be one of:
1252 //
1253 // -- an integral constant-expression of integral or enumeration
1254 // type; or
1255 // -- the name of a non-type template-parameter; or
1256 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001257 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001258 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1259 Diag(Arg->getSourceRange().getBegin(),
1260 diag::err_template_arg_not_integral_or_enumeral)
1261 << ArgType << Arg->getSourceRange();
1262 Diag(Param->getLocation(), diag::note_template_param_here);
1263 return true;
1264 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001265 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001266 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1267 << ArgType << Arg->getSourceRange();
1268 return true;
1269 }
1270
1271 // FIXME: We need some way to more easily get the unqualified form
1272 // of the types without going all the way to the
1273 // canonical type.
1274 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1275 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1276 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1277 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1278
1279 // Try to convert the argument to the parameter's type.
1280 if (ParamType == ArgType) {
1281 // Okay: no conversion necessary
1282 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1283 !ParamType->isEnumeralType()) {
1284 // This is an integral promotion or conversion.
1285 ImpCastExprToType(Arg, ParamType);
1286 } else {
1287 // We can't perform this conversion.
1288 Diag(Arg->getSourceRange().getBegin(),
1289 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001290 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001291 Diag(Param->getLocation(), diag::note_template_param_here);
1292 return true;
1293 }
1294
Douglas Gregorafc86942009-03-14 00:20:21 +00001295 QualType IntegerType = Context.getCanonicalType(ParamType);
1296 if (const EnumType *Enum = IntegerType->getAsEnumType())
1297 IntegerType = Enum->getDecl()->getIntegerType();
1298
1299 if (!Arg->isValueDependent()) {
1300 // Check that an unsigned parameter does not receive a negative
1301 // value.
1302 if (IntegerType->isUnsignedIntegerType()
1303 && (Value.isSigned() && Value.isNegative())) {
1304 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1305 << Value.toString(10) << Param->getType()
1306 << Arg->getSourceRange();
1307 Diag(Param->getLocation(), diag::note_template_param_here);
1308 return true;
1309 }
1310
1311 // Check that we don't overflow the template parameter type.
1312 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1313 if (Value.getActiveBits() > AllowedBits) {
1314 Diag(Arg->getSourceRange().getBegin(),
1315 diag::err_template_arg_too_large)
1316 << Value.toString(10) << Param->getType()
1317 << Arg->getSourceRange();
1318 Diag(Param->getLocation(), diag::note_template_param_here);
1319 return true;
1320 }
1321
1322 if (Value.getBitWidth() != AllowedBits)
1323 Value.extOrTrunc(AllowedBits);
1324 Value.setIsSigned(IntegerType->isSignedIntegerType());
1325 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001326
1327 if (Converted) {
1328 // Add the value of this argument to the list of converted
1329 // arguments. We use the bitwidth and signedness of the template
1330 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001331 if (Arg->isValueDependent()) {
1332 // The argument is value-dependent. Create a new
1333 // TemplateArgument with the converted expression.
1334 Converted->push_back(TemplateArgument(Arg));
1335 return false;
1336 }
1337
Douglas Gregor544cda62009-03-14 00:03:48 +00001338 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001339 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001340 }
1341
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001342 return false;
1343 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001344
Douglas Gregor3f411962009-02-11 01:18:59 +00001345 // Handle pointer-to-function, reference-to-function, and
1346 // pointer-to-member-function all in (roughly) the same way.
1347 if (// -- For a non-type template-parameter of type pointer to
1348 // function, only the function-to-pointer conversion (4.3) is
1349 // applied. If the template-argument represents a set of
1350 // overloaded functions (or a pointer to such), the matching
1351 // function is selected from the set (13.4).
1352 (ParamType->isPointerType() &&
1353 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1354 // -- For a non-type template-parameter of type reference to
1355 // function, no conversions apply. If the template-argument
1356 // represents a set of overloaded functions, the matching
1357 // function is selected from the set (13.4).
1358 (ParamType->isReferenceType() &&
1359 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1360 // -- For a non-type template-parameter of type pointer to
1361 // member function, no conversions apply. If the
1362 // template-argument represents a set of overloaded member
1363 // functions, the matching member function is selected from
1364 // the set (13.4).
1365 (ParamType->isMemberPointerType() &&
1366 ParamType->getAsMemberPointerType()->getPointeeType()
1367 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001368 if (Context.hasSameUnqualifiedType(ArgType,
1369 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001370 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001371 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001372 ArgType = Context.getPointerType(ArgType);
1373 ImpCastExprToType(Arg, ArgType);
1374 } else if (FunctionDecl *Fn
1375 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001376 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1377 return true;
1378
Douglas Gregor2eedd992009-02-11 00:19:33 +00001379 FixOverloadedFunctionReference(Arg, Fn);
1380 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001381 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001382 ArgType = Context.getPointerType(Arg->getType());
1383 ImpCastExprToType(Arg, ArgType);
1384 }
1385 }
1386
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001387 if (!Context.hasSameUnqualifiedType(ArgType,
1388 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001389 // We can't perform this conversion.
1390 Diag(Arg->getSourceRange().getBegin(),
1391 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001392 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001393 Diag(Param->getLocation(), diag::note_template_param_here);
1394 return true;
1395 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001396
Douglas Gregorad964b32009-02-17 01:05:43 +00001397 if (ParamType->isMemberPointerType()) {
1398 NamedDecl *Member = 0;
1399 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1400 return true;
1401
1402 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001403 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001404
1405 return false;
1406 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001407
Douglas Gregorad964b32009-02-17 01:05:43 +00001408 NamedDecl *Entity = 0;
1409 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1410 return true;
1411
1412 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001413 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001414 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001415 }
1416
Chris Lattner320dff22009-02-20 21:37:53 +00001417 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001418 // -- for a non-type template-parameter of type pointer to
1419 // object, qualification conversions (4.4) and the
1420 // array-to-pointer conversion (4.2) are applied.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001421 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001422 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001423
Douglas Gregor3f411962009-02-11 01:18:59 +00001424 if (ArgType->isArrayType()) {
1425 ArgType = Context.getArrayDecayedType(ArgType);
1426 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001427 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001428
1429 if (IsQualificationConversion(ArgType, ParamType)) {
1430 ArgType = ParamType;
1431 ImpCastExprToType(Arg, ParamType);
1432 }
1433
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001434 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001435 // We can't perform this conversion.
1436 Diag(Arg->getSourceRange().getBegin(),
1437 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001438 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001439 Diag(Param->getLocation(), diag::note_template_param_here);
1440 return true;
1441 }
1442
Douglas Gregorad964b32009-02-17 01:05:43 +00001443 NamedDecl *Entity = 0;
1444 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1445 return true;
1446
1447 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001448 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001449
1450 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001451 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001452
1453 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1454 // -- For a non-type template-parameter of type reference to
1455 // object, no conversions apply. The type referred to by the
1456 // reference may be more cv-qualified than the (otherwise
1457 // identical) type of the template-argument. The
1458 // template-parameter is bound directly to the
1459 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001460 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001461 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001462
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001463 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001464 Diag(Arg->getSourceRange().getBegin(),
1465 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001466 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001467 << Arg->getSourceRange();
1468 Diag(Param->getLocation(), diag::note_template_param_here);
1469 return true;
1470 }
1471
1472 unsigned ParamQuals
1473 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1474 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1475
1476 if ((ParamQuals | ArgQuals) != ParamQuals) {
1477 Diag(Arg->getSourceRange().getBegin(),
1478 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001479 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001480 << Arg->getSourceRange();
1481 Diag(Param->getLocation(), diag::note_template_param_here);
1482 return true;
1483 }
1484
Douglas Gregorad964b32009-02-17 01:05:43 +00001485 NamedDecl *Entity = 0;
1486 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1487 return true;
1488
1489 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001490 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001491
1492 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001493 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001494
1495 // -- For a non-type template-parameter of type pointer to data
1496 // member, qualification conversions (4.4) are applied.
1497 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1498
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001499 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001500 // Types match exactly: nothing more to do here.
1501 } else if (IsQualificationConversion(ArgType, ParamType)) {
1502 ImpCastExprToType(Arg, ParamType);
1503 } else {
1504 // We can't perform this conversion.
1505 Diag(Arg->getSourceRange().getBegin(),
1506 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001507 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001508 Diag(Param->getLocation(), diag::note_template_param_here);
1509 return true;
1510 }
1511
Douglas Gregorad964b32009-02-17 01:05:43 +00001512 NamedDecl *Member = 0;
1513 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1514 return true;
1515
1516 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001517 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001518
1519 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001520}
1521
1522/// \brief Check a template argument against its corresponding
1523/// template template parameter.
1524///
1525/// This routine implements the semantics of C++ [temp.arg.template].
1526/// It returns true if an error occurred, and false otherwise.
1527bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1528 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001529 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1530 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1531
1532 // C++ [temp.arg.template]p1:
1533 // A template-argument for a template template-parameter shall be
1534 // the name of a class template, expressed as id-expression. Only
1535 // primary class templates are considered when matching the
1536 // template template argument with the corresponding parameter;
1537 // partial specializations are not considered even if their
1538 // parameter lists match that of the template template parameter.
1539 if (!isa<ClassTemplateDecl>(Template)) {
1540 assert(isa<FunctionTemplateDecl>(Template) &&
1541 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001542 Diag(Arg->getSourceRange().getBegin(),
1543 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001544 << Template;
1545 }
1546
1547 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1548 Param->getTemplateParameters(),
1549 true, true,
1550 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001551}
1552
Douglas Gregord406b032009-02-06 22:42:48 +00001553/// \brief Determine whether the given template parameter lists are
1554/// equivalent.
1555///
1556/// \param New The new template parameter list, typically written in the
1557/// source code as part of a new template declaration.
1558///
1559/// \param Old The old template parameter list, typically found via
1560/// name lookup of the template declared with this template parameter
1561/// list.
1562///
1563/// \param Complain If true, this routine will produce a diagnostic if
1564/// the template parameter lists are not equivalent.
1565///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001566/// \param IsTemplateTemplateParm If true, this routine is being
1567/// called to compare the template parameter lists of a template
1568/// template parameter.
1569///
1570/// \param TemplateArgLoc If this source location is valid, then we
1571/// are actually checking the template parameter list of a template
1572/// argument (New) against the template parameter list of its
1573/// corresponding template template parameter (Old). We produce
1574/// slightly different diagnostics in this scenario.
1575///
Douglas Gregord406b032009-02-06 22:42:48 +00001576/// \returns True if the template parameter lists are equal, false
1577/// otherwise.
1578bool
1579Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1580 TemplateParameterList *Old,
1581 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001582 bool IsTemplateTemplateParm,
1583 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001584 if (Old->size() != New->size()) {
1585 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001586 unsigned NextDiag = diag::err_template_param_list_different_arity;
1587 if (TemplateArgLoc.isValid()) {
1588 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1589 NextDiag = diag::note_template_param_list_different_arity;
1590 }
1591 Diag(New->getTemplateLoc(), NextDiag)
1592 << (New->size() > Old->size())
1593 << IsTemplateTemplateParm
1594 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001595 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1596 << IsTemplateTemplateParm
1597 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1598 }
1599
1600 return false;
1601 }
1602
1603 for (TemplateParameterList::iterator OldParm = Old->begin(),
1604 OldParmEnd = Old->end(), NewParm = New->begin();
1605 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1606 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001607 unsigned NextDiag = diag::err_template_param_different_kind;
1608 if (TemplateArgLoc.isValid()) {
1609 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1610 NextDiag = diag::note_template_param_different_kind;
1611 }
1612 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001613 << IsTemplateTemplateParm;
1614 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1615 << IsTemplateTemplateParm;
1616 return false;
1617 }
1618
1619 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1620 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001621 // know we're at the same index).
1622#if 0
1623 // FIXME: Enable this code in debug mode *after* we properly go
1624 // through and "instantiate" the template parameter lists of
1625 // template template parameters. It's only after this
1626 // instantiation that (1) any dependent types within the
1627 // template parameter list of the template template parameter
1628 // can be checked, and (2) the template type parameter depths
1629 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001630 QualType OldParmType
1631 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1632 QualType NewParmType
1633 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1634 assert(Context.getCanonicalType(OldParmType) ==
1635 Context.getCanonicalType(NewParmType) &&
1636 "type parameter mismatch?");
1637#endif
1638 } else if (NonTypeTemplateParmDecl *OldNTTP
1639 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1640 // The types of non-type template parameters must agree.
1641 NonTypeTemplateParmDecl *NewNTTP
1642 = cast<NonTypeTemplateParmDecl>(*NewParm);
1643 if (Context.getCanonicalType(OldNTTP->getType()) !=
1644 Context.getCanonicalType(NewNTTP->getType())) {
1645 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001646 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1647 if (TemplateArgLoc.isValid()) {
1648 Diag(TemplateArgLoc,
1649 diag::err_template_arg_template_params_mismatch);
1650 NextDiag = diag::note_template_nontype_parm_different_type;
1651 }
1652 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001653 << NewNTTP->getType()
1654 << IsTemplateTemplateParm;
1655 Diag(OldNTTP->getLocation(),
1656 diag::note_template_nontype_parm_prev_declaration)
1657 << OldNTTP->getType();
1658 }
1659 return false;
1660 }
1661 } else {
1662 // The template parameter lists of template template
1663 // parameters must agree.
1664 // FIXME: Could we perform a faster "type" comparison here?
1665 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1666 "Only template template parameters handled here");
1667 TemplateTemplateParmDecl *OldTTP
1668 = cast<TemplateTemplateParmDecl>(*OldParm);
1669 TemplateTemplateParmDecl *NewTTP
1670 = cast<TemplateTemplateParmDecl>(*NewParm);
1671 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1672 OldTTP->getTemplateParameters(),
1673 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001674 /*IsTemplateTemplateParm=*/true,
1675 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001676 return false;
1677 }
1678 }
1679
1680 return true;
1681}
1682
1683/// \brief Check whether a template can be declared within this scope.
1684///
1685/// If the template declaration is valid in this scope, returns
1686/// false. Otherwise, issues a diagnostic and returns true.
1687bool
1688Sema::CheckTemplateDeclScope(Scope *S,
1689 MultiTemplateParamsArg &TemplateParameterLists) {
1690 assert(TemplateParameterLists.size() > 0 && "Not a template");
1691
1692 // Find the nearest enclosing declaration scope.
1693 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1694 (S->getFlags() & Scope::TemplateParamScope) != 0)
1695 S = S->getParent();
1696
1697 TemplateParameterList *TemplateParams =
1698 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1699 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1700 SourceRange TemplateRange
1701 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1702
1703 // C++ [temp]p2:
1704 // A template-declaration can appear only as a namespace scope or
1705 // class scope declaration.
1706 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1707 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1708 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1709 return Diag(TemplateLoc, diag::err_template_linkage)
1710 << TemplateRange;
1711
1712 Ctx = Ctx->getParent();
1713 }
1714
1715 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1716 return false;
1717
1718 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1719 << TemplateRange;
1720}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001721
Douglas Gregor0d93f692009-02-25 22:02:03 +00001722/// \brief Check whether a class template specialization in the
1723/// current context is well-formed.
1724///
1725/// This routine determines whether a class template specialization
1726/// can be declared in the current context (C++ [temp.expl.spec]p2)
1727/// and emits appropriate diagnostics if there was an error. It
1728/// returns true if there was an error that we cannot recover from,
1729/// and false otherwise.
1730bool
1731Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1732 ClassTemplateSpecializationDecl *PrevDecl,
1733 SourceLocation TemplateNameLoc,
1734 SourceRange ScopeSpecifierRange) {
1735 // C++ [temp.expl.spec]p2:
1736 // An explicit specialization shall be declared in the namespace
1737 // of which the template is a member, or, for member templates, in
1738 // the namespace of which the enclosing class or enclosing class
1739 // template is a member. An explicit specialization of a member
1740 // function, member class or static data member of a class
1741 // template shall be declared in the namespace of which the class
1742 // template is a member. Such a declaration may also be a
1743 // definition. If the declaration is not a definition, the
1744 // specialization may be defined later in the name- space in which
1745 // the explicit specialization was declared, or in a namespace
1746 // that encloses the one in which the explicit specialization was
1747 // declared.
1748 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1749 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1750 << ClassTemplate;
1751 return true;
1752 }
1753
1754 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1755 DeclContext *TemplateContext
1756 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1757 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1758 // There is no prior declaration of this entity, so this
1759 // specialization must be in the same context as the template
1760 // itself.
1761 if (DC != TemplateContext) {
1762 if (isa<TranslationUnitDecl>(TemplateContext))
1763 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1764 << ClassTemplate << ScopeSpecifierRange;
1765 else if (isa<NamespaceDecl>(TemplateContext))
1766 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1767 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1768 << ScopeSpecifierRange;
1769
1770 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1771 }
1772
1773 return false;
1774 }
1775
1776 // We have a previous declaration of this entity. Make sure that
1777 // this redeclaration (or definition) occurs in an enclosing namespace.
1778 if (!CurContext->Encloses(TemplateContext)) {
1779 if (isa<TranslationUnitDecl>(TemplateContext))
1780 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1781 << ClassTemplate << ScopeSpecifierRange;
1782 else if (isa<NamespaceDecl>(TemplateContext))
1783 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1784 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1785 << ScopeSpecifierRange;
1786
1787 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1788 }
1789
1790 return false;
1791}
1792
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001793Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001794Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1795 SourceLocation KWLoc,
1796 const CXXScopeSpec &SS,
1797 DeclTy *TemplateD,
1798 SourceLocation TemplateNameLoc,
1799 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001800 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001801 SourceLocation *TemplateArgLocs,
1802 SourceLocation RAngleLoc,
1803 AttributeList *Attr,
1804 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001805 // Find the class template we're specializing
1806 ClassTemplateDecl *ClassTemplate
1807 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1808 if (!ClassTemplate)
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001809 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001810
Douglas Gregor0d93f692009-02-25 22:02:03 +00001811 // Check the validity of the template headers that introduce this
1812 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001813 // FIXME: Once we have member templates, we'll need to check
1814 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1815 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001816 if (TemplateParameterLists.size() == 0)
1817 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001818 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001819 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001820 TemplateParameterList *TemplateParams
1821 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001822 if (TemplateParameterLists.size() > 1)
1823 return Diag(TemplateParams->getTemplateLoc(),
1824 diag::err_template_spec_extra_headers);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001825
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001826 if (TemplateParams->size() > 0)
Douglas Gregor0d93f692009-02-25 22:02:03 +00001827 // FIXME: No support for class template partial specialization.
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001828 return Diag(TemplateParams->getTemplateLoc(),
1829 diag::unsup_template_partial_spec);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001830 }
1831
Douglas Gregora08b6c72009-02-17 23:15:12 +00001832 // Check that the specialization uses the same tag kind as the
1833 // original template.
1834 TagDecl::TagKind Kind;
1835 switch (TagSpec) {
1836 default: assert(0 && "Unknown tag type!");
1837 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1838 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1839 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1840 }
1841 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1842 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1843 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1844 diag::note_previous_use);
1845 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1846 }
1847
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001848 // Translate the parser's template argument list in our AST format.
1849 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1850 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1851
Douglas Gregora08b6c72009-02-17 23:15:12 +00001852 // Check that the template argument list is well-formed for this
1853 // template.
1854 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1855 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001856 &TemplateArgs[0], TemplateArgs.size(),
1857 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001858 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001859
1860 assert((ConvertedTemplateArgs.size() ==
1861 ClassTemplate->getTemplateParameters()->size()) &&
1862 "Converted template argument list is too short!");
1863
1864 // Find the class template specialization declaration that
1865 // corresponds to these arguments.
1866 llvm::FoldingSetNodeID ID;
1867 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1868 ConvertedTemplateArgs.size());
1869 void *InsertPos = 0;
1870 ClassTemplateSpecializationDecl *PrevDecl
1871 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1872
1873 ClassTemplateSpecializationDecl *Specialization = 0;
1874
Douglas Gregor0d93f692009-02-25 22:02:03 +00001875 // Check whether we can declare a class template specialization in
1876 // the current scope.
1877 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1878 TemplateNameLoc,
1879 SS.getRange()))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001880 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001881
Douglas Gregora08b6c72009-02-17 23:15:12 +00001882 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1883 // Since the only prior class template specialization with these
1884 // arguments was referenced but not declared, reuse that
1885 // declaration node as our own, updating its source location to
1886 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001887 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00001888 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001889 PrevDecl = 0;
1890 } else {
1891 // Create a new class template specialization declaration node for
1892 // this explicit specialization.
1893 Specialization
1894 = ClassTemplateSpecializationDecl::Create(Context,
1895 ClassTemplate->getDeclContext(),
1896 TemplateNameLoc,
1897 ClassTemplate,
1898 &ConvertedTemplateArgs[0],
1899 ConvertedTemplateArgs.size(),
1900 PrevDecl);
1901
1902 if (PrevDecl) {
1903 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1904 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1905 } else {
1906 ClassTemplate->getSpecializations().InsertNode(Specialization,
1907 InsertPos);
1908 }
1909 }
1910
1911 // Note that this is an explicit specialization.
1912 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1913
1914 // Check that this isn't a redefinition of this specialization.
1915 if (TK == TK_Definition) {
1916 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1917 // FIXME: Should also handle explicit specialization after
1918 // implicit instantiation with a special diagnostic.
1919 SourceRange Range(TemplateNameLoc, RAngleLoc);
1920 Diag(TemplateNameLoc, diag::err_redefinition)
1921 << Specialization << Range;
1922 Diag(Def->getLocation(), diag::note_previous_definition);
1923 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001924 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001925 }
1926 }
1927
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001928 // Build the fully-sugared type for this class template
1929 // specialization as the user wrote in the specialization
1930 // itself. This means that we'll pretty-print the type retrieved
1931 // from the specialization's declaration the way that the user
1932 // actually wrote the specialization, rather than formatting the
1933 // name based on the "canonical" representation used to store the
1934 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00001935 QualType WrittenTy
1936 = Context.getClassTemplateSpecializationType(ClassTemplate,
1937 &TemplateArgs[0],
1938 TemplateArgs.size(),
1939 Context.getTypeDeclType(Specialization));
1940 Specialization->setTypeAsWritten(getQualifiedNameType(SS, WrittenTy));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001941 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001942
Douglas Gregor50113ca2009-02-25 22:18:32 +00001943 // C++ [temp.expl.spec]p9:
1944 // A template explicit specialization is in the scope of the
1945 // namespace in which the template was defined.
1946 //
1947 // We actually implement this paragraph where we set the semantic
1948 // context (in the creation of the ClassTemplateSpecializationDecl),
1949 // but we also maintain the lexical context where the actual
1950 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001951 Specialization->setLexicalDeclContext(CurContext);
1952
1953 // We may be starting the definition of this specialization.
1954 if (TK == TK_Definition)
1955 Specialization->startDefinition();
1956
1957 // Add the specialization into its lexical context, so that it can
1958 // be seen when iterating through the list of declarations in that
1959 // context. However, specializations are not found by name lookup.
1960 CurContext->addDecl(Specialization);
1961 return Specialization;
1962}