blob: ed50722d2fac7506794bc715b840e42b968531e7 [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");
45 }
Douglas Gregor279272e2009-02-04 19:02:06 +000046
Douglas Gregor8e458f42009-02-09 18:46:07 +000047 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000049 if (FD->getType()->isDependentType()) {
50 Template = FD;
51 return TNK_Function_template;
52 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000053 } else if (OverloadedFunctionDecl *Ovl
54 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
55 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
56 FEnd = Ovl->function_end();
57 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000058 if ((*F)->getType()->isDependentType()) {
59 Template = Ovl;
60 return TNK_Function_template;
61 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000062 }
63 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000064 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000065 return TNK_Non_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +000066}
67
Douglas Gregordd861062008-12-05 18:15:24 +000068/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
69/// that the template parameter 'PrevDecl' is being shadowed by a new
70/// declaration at location Loc. Returns true to indicate that this is
71/// an error, and false otherwise.
72bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +000073 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +000074
75 // Microsoft Visual C++ permits template parameters to be shadowed.
76 if (getLangOptions().Microsoft)
77 return false;
78
79 // C++ [temp.local]p4:
80 // A template-parameter shall not be redeclared within its
81 // scope (including nested scopes).
82 Diag(Loc, diag::err_template_param_shadow)
83 << cast<NamedDecl>(PrevDecl)->getDeclName();
84 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
85 return true;
86}
87
Douglas Gregored3a3982009-03-03 04:44:36 +000088/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +000089/// the parameter D to reference the templated declaration and return a pointer
90/// to the template declaration. Otherwise, do nothing to D and return null.
91TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
92{
93 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
94 D = Temp->getTemplatedDecl();
95 return Temp;
96 }
97 return 0;
98}
99
Douglas Gregordd861062008-12-05 18:15:24 +0000100/// ActOnTypeParameter - Called when a C++ template type parameter
101/// (e.g., "typename T") has been parsed. Typename specifies whether
102/// the keyword "typename" was used to declare the type parameter
103/// (otherwise, "class" was used), and KeyLoc is the location of the
104/// "class" or "typename" keyword. ParamName is the name of the
105/// parameter (NULL indicates an unnamed template parameter) and
106/// ParamName is the location of the parameter name (if any).
107/// If the type parameter has a default argument, it will be added
108/// later via ActOnTypeParameterDefault.
109Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
110 SourceLocation KeyLoc,
111 IdentifierInfo *ParamName,
Douglas Gregor52473432008-12-24 02:52:09 +0000112 SourceLocation ParamNameLoc,
113 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000114 assert(S->isTemplateParamScope() &&
115 "Template type parameter not in template parameter scope!");
116 bool Invalid = false;
117
118 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000119 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000120 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000121 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
122 PrevDecl);
123 }
124
Douglas Gregord406b032009-02-06 22:42:48 +0000125 SourceLocation Loc = ParamNameLoc;
126 if (!ParamName)
127 Loc = KeyLoc;
128
Douglas Gregordd861062008-12-05 18:15:24 +0000129 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000130 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000131 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000132 if (Invalid)
133 Param->setInvalidDecl();
134
135 if (ParamName) {
136 // Add the template parameter into the current scope.
137 S->AddDecl(Param);
138 IdResolver.AddDecl(Param);
139 }
140
141 return Param;
142}
143
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000144/// ActOnTypeParameterDefault - Adds a default argument (the type
145/// Default) to the given template type parameter (TypeParam).
146void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
147 SourceLocation EqualLoc,
148 SourceLocation DefaultLoc,
149 TypeTy *DefaultT) {
150 TemplateTypeParmDecl *Parm
151 = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
152 QualType Default = QualType::getFromOpaquePtr(DefaultT);
153
154 // C++ [temp.param]p14:
155 // A template-parameter shall not be used in its own default argument.
156 // FIXME: Implement this check! Needs a recursive walk over the types.
157
158 // Check the template argument itself.
159 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
160 Parm->setInvalidDecl();
161 return;
162 }
163
164 Parm->setDefaultArgument(Default, DefaultLoc, false);
165}
166
Douglas Gregored3a3982009-03-03 04:44:36 +0000167/// \brief Check that the type of a non-type template parameter is
168/// well-formed.
169///
170/// \returns the (possibly-promoted) parameter type if valid;
171/// otherwise, produces a diagnostic and returns a NULL type.
172QualType
173Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
174 // C++ [temp.param]p4:
175 //
176 // A non-type template-parameter shall have one of the following
177 // (optionally cv-qualified) types:
178 //
179 // -- integral or enumeration type,
180 if (T->isIntegralType() || T->isEnumeralType() ||
181 // -- pointer to object or pointer to function,
182 (T->isPointerType() &&
183 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
184 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
185 // -- reference to object or reference to function,
186 T->isReferenceType() ||
187 // -- pointer to member.
188 T->isMemberPointerType() ||
189 // If T is a dependent type, we can't do the check now, so we
190 // assume that it is well-formed.
191 T->isDependentType())
192 return T;
193 // C++ [temp.param]p8:
194 //
195 // A non-type template-parameter of type "array of T" or
196 // "function returning T" is adjusted to be of type "pointer to
197 // T" or "pointer to function returning T", respectively.
198 else if (T->isArrayType())
199 // FIXME: Keep the type prior to promotion?
200 return Context.getArrayDecayedType(T);
201 else if (T->isFunctionType())
202 // FIXME: Keep the type prior to promotion?
203 return Context.getPointerType(T);
204
205 Diag(Loc, diag::err_template_nontype_parm_bad_type)
206 << T;
207
208 return QualType();
209}
210
Douglas Gregordd861062008-12-05 18:15:24 +0000211/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
212/// template parameter (e.g., "int Size" in "template<int Size>
213/// class Array") has been parsed. S is the current scope and D is
214/// the parsed declarator.
Douglas Gregor52473432008-12-24 02:52:09 +0000215Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
216 unsigned Depth,
217 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000218 QualType T = GetTypeForDeclarator(D, S);
219
Douglas Gregor279272e2009-02-04 19:02:06 +0000220 assert(S->isTemplateParamScope() &&
221 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000222 bool Invalid = false;
223
224 IdentifierInfo *ParamName = D.getIdentifier();
225 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000226 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000227 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000228 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000229 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000230 }
231
Douglas Gregored3a3982009-03-03 04:44:36 +0000232 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
233 if (T.isNull())
234 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor62cdc792009-02-10 17:43:50 +0000235
Douglas Gregordd861062008-12-05 18:15:24 +0000236 NonTypeTemplateParmDecl *Param
237 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000238 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000239 if (Invalid)
240 Param->setInvalidDecl();
241
242 if (D.getIdentifier()) {
243 // Add the template parameter into the current scope.
244 S->AddDecl(Param);
245 IdResolver.AddDecl(Param);
246 }
247 return Param;
248}
Douglas Gregor52473432008-12-24 02:52:09 +0000249
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000250/// \brief Adds a default argument to the given non-type template
251/// parameter.
252void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
253 SourceLocation EqualLoc,
254 ExprArg DefaultE) {
255 NonTypeTemplateParmDecl *TemplateParm
256 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
257 Expr *Default = static_cast<Expr *>(DefaultE.get());
258
259 // C++ [temp.param]p14:
260 // A template-parameter shall not be used in its own default argument.
261 // FIXME: Implement this check! Needs a recursive walk over the types.
262
263 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000264 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000265 TemplateParm->setInvalidDecl();
266 return;
267 }
268
269 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
270}
271
Douglas Gregor279272e2009-02-04 19:02:06 +0000272
273/// ActOnTemplateTemplateParameter - Called when a C++ template template
274/// parameter (e.g. T in template <template <typename> class T> class array)
275/// has been parsed. S is the current scope.
276Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
277 SourceLocation TmpLoc,
278 TemplateParamsTy *Params,
279 IdentifierInfo *Name,
280 SourceLocation NameLoc,
281 unsigned Depth,
282 unsigned Position)
283{
284 assert(S->isTemplateParamScope() &&
285 "Template template parameter not in template parameter scope!");
286
287 // Construct the parameter object.
288 TemplateTemplateParmDecl *Param =
289 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
290 Position, Name,
291 (TemplateParameterList*)Params);
292
293 // Make sure the parameter is valid.
294 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
295 // do anything yet. However, if the template parameter list or (eventual)
296 // default value is ever invalidated, that will propagate here.
297 bool Invalid = false;
298 if (Invalid) {
299 Param->setInvalidDecl();
300 }
301
302 // If the tt-param has a name, then link the identifier into the scope
303 // and lookup mechanisms.
304 if (Name) {
305 S->AddDecl(Param);
306 IdResolver.AddDecl(Param);
307 }
308
309 return Param;
310}
311
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000312/// \brief Adds a default argument to the given template template
313/// parameter.
314void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
315 SourceLocation EqualLoc,
316 ExprArg DefaultE) {
317 TemplateTemplateParmDecl *TemplateParm
318 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
319
320 // Since a template-template parameter's default argument is an
321 // id-expression, it must be a DeclRefExpr.
322 DeclRefExpr *Default
323 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
324
325 // C++ [temp.param]p14:
326 // A template-parameter shall not be used in its own default argument.
327 // FIXME: Implement this check! Needs a recursive walk over the types.
328
329 // Check the well-formedness of the template argument.
330 if (!isa<TemplateDecl>(Default->getDecl())) {
331 Diag(Default->getSourceRange().getBegin(),
332 diag::err_template_arg_must_be_template)
333 << Default->getSourceRange();
334 TemplateParm->setInvalidDecl();
335 return;
336 }
337 if (CheckTemplateArgument(TemplateParm, Default)) {
338 TemplateParm->setInvalidDecl();
339 return;
340 }
341
342 DefaultE.release();
343 TemplateParm->setDefaultArgument(Default);
344}
345
Douglas Gregor52473432008-12-24 02:52:09 +0000346/// ActOnTemplateParameterList - Builds a TemplateParameterList that
347/// contains the template parameters in Params/NumParams.
348Sema::TemplateParamsTy *
349Sema::ActOnTemplateParameterList(unsigned Depth,
350 SourceLocation ExportLoc,
351 SourceLocation TemplateLoc,
352 SourceLocation LAngleLoc,
353 DeclTy **Params, unsigned NumParams,
354 SourceLocation RAngleLoc) {
355 if (ExportLoc.isValid())
356 Diag(ExportLoc, diag::note_template_export_unsupported);
357
Douglas Gregord406b032009-02-06 22:42:48 +0000358 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
359 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000360}
Douglas Gregor279272e2009-02-04 19:02:06 +0000361
Douglas Gregord406b032009-02-06 22:42:48 +0000362Sema::DeclTy *
363Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
364 SourceLocation KWLoc, const CXXScopeSpec &SS,
365 IdentifierInfo *Name, SourceLocation NameLoc,
366 AttributeList *Attr,
367 MultiTemplateParamsArg TemplateParameterLists) {
368 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
369 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000370 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000371
372 // Check that we can declare a template here.
373 if (CheckTemplateDeclScope(S, TemplateParameterLists))
374 return 0;
375
376 TagDecl::TagKind Kind;
377 switch (TagSpec) {
378 default: assert(0 && "Unknown tag type!");
379 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
380 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
381 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
382 }
383
384 // There is no such thing as an unnamed class template.
385 if (!Name) {
386 Diag(KWLoc, diag::err_template_unnamed_class);
387 return 0;
388 }
389
390 // Find any previous declaration with this name.
391 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
392 true);
393 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
394 NamedDecl *PrevDecl = 0;
395 if (Previous.begin() != Previous.end())
396 PrevDecl = *Previous.begin();
397
398 DeclContext *SemanticContext = CurContext;
399 if (SS.isNotEmpty() && !SS.isInvalid()) {
400 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
401
402 // FIXME: need to match up several levels of template parameter
403 // lists here.
404 }
405
406 // FIXME: member templates!
407 TemplateParameterList *TemplateParams
408 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
409
410 // If there is a previous declaration with the same name, check
411 // whether this is a valid redeclaration.
412 ClassTemplateDecl *PrevClassTemplate
413 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
414 if (PrevClassTemplate) {
415 // Ensure that the template parameter lists are compatible.
416 if (!TemplateParameterListsAreEqual(TemplateParams,
417 PrevClassTemplate->getTemplateParameters(),
418 /*Complain=*/true))
419 return 0;
420
421 // C++ [temp.class]p4:
422 // In a redeclaration, partial specialization, explicit
423 // specialization or explicit instantiation of a class template,
424 // the class-key shall agree in kind with the original class
425 // template declaration (7.1.5.3).
426 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
427 if (PrevRecordDecl->getTagKind() != Kind) {
428 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
429 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
430 return 0;
431 }
432
433
434 // Check for redefinition of this class template.
435 if (TK == TK_Definition) {
436 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
437 Diag(NameLoc, diag::err_redefinition) << Name;
438 Diag(Def->getLocation(), diag::note_previous_definition);
439 // FIXME: Would it make sense to try to "forget" the previous
440 // definition, as part of error recovery?
441 return 0;
442 }
443 }
444 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
445 // Maybe we will complain about the shadowed template parameter.
446 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
447 // Just pretend that we didn't see the previous declaration.
448 PrevDecl = 0;
449 } else if (PrevDecl) {
450 // C++ [temp]p5:
451 // A class template shall not have the same name as any other
452 // template, class, function, object, enumeration, enumerator,
453 // namespace, or type in the same scope (3.3), except as specified
454 // in (14.5.4).
455 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
456 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
457 return 0;
458 }
459
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000460 // Check the template parameter list of this declaration, possibly
461 // merging in the template parameter list from the previous class
462 // template declaration.
463 if (CheckTemplateParameterList(TemplateParams,
464 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
465 Invalid = true;
466
Douglas Gregord406b032009-02-06 22:42:48 +0000467 // If we had a scope specifier, we better have a previous template
468 // declaration!
469
470 TagDecl *NewClass =
471 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
472 PrevClassTemplate?
473 PrevClassTemplate->getTemplatedDecl() : 0);
474
475 ClassTemplateDecl *NewTemplate
476 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
477 DeclarationName(Name), TemplateParams,
478 NewClass);
479
480 // Set the lexical context of these templates
481 NewClass->setLexicalDeclContext(CurContext);
482 NewTemplate->setLexicalDeclContext(CurContext);
483
484 if (TK == TK_Definition)
485 NewClass->startDefinition();
486
487 if (Attr)
488 ProcessDeclAttributeList(NewClass, Attr);
489
490 PushOnScopeChains(NewTemplate, S);
491
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000492 if (Invalid) {
493 NewTemplate->setInvalidDecl();
494 NewClass->setInvalidDecl();
495 }
Douglas Gregord406b032009-02-06 22:42:48 +0000496 return NewTemplate;
497}
498
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000499/// \brief Checks the validity of a template parameter list, possibly
500/// considering the template parameter list from a previous
501/// declaration.
502///
503/// If an "old" template parameter list is provided, it must be
504/// equivalent (per TemplateParameterListsAreEqual) to the "new"
505/// template parameter list.
506///
507/// \param NewParams Template parameter list for a new template
508/// declaration. This template parameter list will be updated with any
509/// default arguments that are carried through from the previous
510/// template parameter list.
511///
512/// \param OldParams If provided, template parameter list from a
513/// previous declaration of the same template. Default template
514/// arguments will be merged from the old template parameter list to
515/// the new template parameter list.
516///
517/// \returns true if an error occurred, false otherwise.
518bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
519 TemplateParameterList *OldParams) {
520 bool Invalid = false;
521
522 // C++ [temp.param]p10:
523 // The set of default template-arguments available for use with a
524 // template declaration or definition is obtained by merging the
525 // default arguments from the definition (if in scope) and all
526 // declarations in scope in the same way default function
527 // arguments are (8.3.6).
528 bool SawDefaultArgument = false;
529 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000530
Mike Stumpe0b7e032009-02-11 23:03:27 +0000531 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000532 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000533 if (OldParams)
534 OldParam = OldParams->begin();
535
536 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
537 NewParamEnd = NewParams->end();
538 NewParam != NewParamEnd; ++NewParam) {
539 // Variables used to diagnose redundant default arguments
540 bool RedundantDefaultArg = false;
541 SourceLocation OldDefaultLoc;
542 SourceLocation NewDefaultLoc;
543
544 // Variables used to diagnose missing default arguments
545 bool MissingDefaultArg = false;
546
547 // Merge default arguments for template type parameters.
548 if (TemplateTypeParmDecl *NewTypeParm
549 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
550 TemplateTypeParmDecl *OldTypeParm
551 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
552
553 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
554 NewTypeParm->hasDefaultArgument()) {
555 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
556 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
557 SawDefaultArgument = true;
558 RedundantDefaultArg = true;
559 PreviousDefaultArgLoc = NewDefaultLoc;
560 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
561 // Merge the default argument from the old declaration to the
562 // new declaration.
563 SawDefaultArgument = true;
564 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
565 OldTypeParm->getDefaultArgumentLoc(),
566 true);
567 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
568 } else if (NewTypeParm->hasDefaultArgument()) {
569 SawDefaultArgument = true;
570 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
571 } else if (SawDefaultArgument)
572 MissingDefaultArg = true;
573 }
574 // Merge default arguments for non-type template parameters
575 else if (NonTypeTemplateParmDecl *NewNonTypeParm
576 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
577 NonTypeTemplateParmDecl *OldNonTypeParm
578 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
579 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
580 NewNonTypeParm->hasDefaultArgument()) {
581 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
582 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
583 SawDefaultArgument = true;
584 RedundantDefaultArg = true;
585 PreviousDefaultArgLoc = NewDefaultLoc;
586 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
587 // Merge the default argument from the old declaration to the
588 // new declaration.
589 SawDefaultArgument = true;
590 // FIXME: We need to create a new kind of "default argument"
591 // expression that points to a previous template template
592 // parameter.
593 NewNonTypeParm->setDefaultArgument(
594 OldNonTypeParm->getDefaultArgument());
595 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
596 } else if (NewNonTypeParm->hasDefaultArgument()) {
597 SawDefaultArgument = true;
598 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
599 } else if (SawDefaultArgument)
600 MissingDefaultArg = true;
601 }
602 // Merge default arguments for template template parameters
603 else {
604 TemplateTemplateParmDecl *NewTemplateParm
605 = cast<TemplateTemplateParmDecl>(*NewParam);
606 TemplateTemplateParmDecl *OldTemplateParm
607 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
608 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
609 NewTemplateParm->hasDefaultArgument()) {
610 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
611 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
612 SawDefaultArgument = true;
613 RedundantDefaultArg = true;
614 PreviousDefaultArgLoc = NewDefaultLoc;
615 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
616 // Merge the default argument from the old declaration to the
617 // new declaration.
618 SawDefaultArgument = true;
619 // FIXME: We need to create a new kind of "default argument"
620 // expression that points to a previous template template
621 // parameter.
622 NewTemplateParm->setDefaultArgument(
623 OldTemplateParm->getDefaultArgument());
624 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
625 } else if (NewTemplateParm->hasDefaultArgument()) {
626 SawDefaultArgument = true;
627 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
628 } else if (SawDefaultArgument)
629 MissingDefaultArg = true;
630 }
631
632 if (RedundantDefaultArg) {
633 // C++ [temp.param]p12:
634 // A template-parameter shall not be given default arguments
635 // by two different declarations in the same scope.
636 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
637 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
638 Invalid = true;
639 } else if (MissingDefaultArg) {
640 // C++ [temp.param]p11:
641 // If a template-parameter has a default template-argument,
642 // all subsequent template-parameters shall have a default
643 // template-argument supplied.
644 Diag((*NewParam)->getLocation(),
645 diag::err_template_param_default_arg_missing);
646 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
647 Invalid = true;
648 }
649
650 // If we have an old template parameter list that we're merging
651 // in, move on to the next parameter.
652 if (OldParams)
653 ++OldParam;
654 }
655
656 return Invalid;
657}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000658
Douglas Gregora08b6c72009-02-17 23:15:12 +0000659Action::TypeResult
660Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
661 SourceLocation LAngleLoc,
662 ASTTemplateArgsPtr TemplateArgs,
663 SourceLocation *TemplateArgLocs,
664 SourceLocation RAngleLoc,
665 const CXXScopeSpec *SS) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000666 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregorad964b32009-02-17 01:05:43 +0000667 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000668
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000669 // Check that the template argument list is well-formed for this
670 // template.
Douglas Gregorad964b32009-02-17 01:05:43 +0000671 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000672 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorad964b32009-02-17 01:05:43 +0000673 TemplateArgs, TemplateArgLocs, RAngleLoc,
674 ConvertedTemplateArgs))
Douglas Gregora08b6c72009-02-17 23:15:12 +0000675 return true;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000676
Douglas Gregorad964b32009-02-17 01:05:43 +0000677 assert((ConvertedTemplateArgs.size() ==
678 Template->getTemplateParameters()->size()) &&
679 "Converted template argument list is too short!");
680
681 // Find the class template specialization declaration that
682 // corresponds to these arguments.
683 llvm::FoldingSetNodeID ID;
684 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
685 ConvertedTemplateArgs.size());
686 void *InsertPos = 0;
687 ClassTemplateSpecializationDecl *Decl
688 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
689 if (!Decl) {
690 // This is the first time we have referenced this class template
Douglas Gregora08b6c72009-02-17 23:15:12 +0000691 // specialization. Create the canonical declaration and add it to
692 // the set of specializations.
Douglas Gregorad964b32009-02-17 01:05:43 +0000693 Decl = ClassTemplateSpecializationDecl::Create(Context,
694 ClassTemplate->getDeclContext(),
695 TemplateLoc,
696 ClassTemplate,
697 &ConvertedTemplateArgs[0],
Douglas Gregora08b6c72009-02-17 23:15:12 +0000698 ConvertedTemplateArgs.size(),
699 0);
Douglas Gregorad964b32009-02-17 01:05:43 +0000700 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
Douglas Gregor50113ca2009-02-25 22:18:32 +0000701 Decl->setLexicalDeclContext(CurContext);
Douglas Gregorad964b32009-02-17 01:05:43 +0000702 }
Douglas Gregor50113ca2009-02-25 22:18:32 +0000703
Douglas Gregorad964b32009-02-17 01:05:43 +0000704 // Build the fully-sugared type for this class template
705 // specialization, which refers back to the class template
706 // specialization we created or found.
Douglas Gregor6f37b582009-02-09 19:34:22 +0000707 QualType Result
708 = Context.getClassTemplateSpecializationType(Template,
709 TemplateArgs.size(),
710 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
711 TemplateArgs.getArgIsType(),
Douglas Gregorad964b32009-02-17 01:05:43 +0000712 Context.getTypeDeclType(Decl));
Douglas Gregor6f37b582009-02-09 19:34:22 +0000713 TemplateArgs.release();
714 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000715}
716
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000717/// \brief Check that the given template argument list is well-formed
718/// for specializing the given template.
719bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
720 SourceLocation TemplateLoc,
721 SourceLocation LAngleLoc,
722 ASTTemplateArgsPtr& Args,
723 SourceLocation *TemplateArgLocs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000724 SourceLocation RAngleLoc,
725 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000726 TemplateParameterList *Params = Template->getTemplateParameters();
727 unsigned NumParams = Params->size();
728 unsigned NumArgs = Args.size();
729 bool Invalid = false;
730
731 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000732 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000733 // FIXME: point at either the first arg beyond what we can handle,
734 // or the '>', depending on whether we have too many or too few
735 // arguments.
736 SourceRange Range;
737 if (NumArgs > NumParams)
738 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
739 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
740 << (NumArgs > NumParams)
741 << (isa<ClassTemplateDecl>(Template)? 0 :
742 isa<FunctionTemplateDecl>(Template)? 1 :
743 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
744 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000745 Diag(Template->getLocation(), diag::note_template_decl_here)
746 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000747 Invalid = true;
748 }
749
750 // C++ [temp.arg]p1:
751 // [...] The type and form of each template-argument specified in
752 // a template-id shall match the type and form specified for the
753 // corresponding parameter declared by the template in its
754 // template-parameter-list.
755 unsigned ArgIdx = 0;
756 for (TemplateParameterList::iterator Param = Params->begin(),
757 ParamEnd = Params->end();
758 Param != ParamEnd; ++Param, ++ArgIdx) {
759 // Decode the template argument
760 QualType ArgType;
761 Expr *ArgExpr = 0;
762 SourceLocation ArgLoc;
763 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000764 // Retrieve the default template argument from the template
765 // parameter.
766 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
767 if (!TTP->hasDefaultArgument())
768 break;
769
770 ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000771
772 // If the argument type is dependent, instantiate it now based
773 // on the previously-computed template arguments.
774 if (ArgType->isDependentType())
775 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
776 TTP->getDefaultArgumentLoc(),
777 TTP->getDeclName());
778
779 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000780 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000781
Douglas Gregorad964b32009-02-17 01:05:43 +0000782 ArgLoc = TTP->getDefaultArgumentLoc();
783 } else if (NonTypeTemplateParmDecl *NTTP
784 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
785 if (!NTTP->hasDefaultArgument())
786 break;
787
Douglas Gregored3a3982009-03-03 04:44:36 +0000788 // FIXME: Instantiate default argument
Douglas Gregorad964b32009-02-17 01:05:43 +0000789 ArgExpr = NTTP->getDefaultArgument();
790 ArgLoc = NTTP->getDefaultArgumentLoc();
791 } else {
792 TemplateTemplateParmDecl *TempParm
793 = cast<TemplateTemplateParmDecl>(*Param);
794
795 if (!TempParm->hasDefaultArgument())
796 break;
797
Douglas Gregored3a3982009-03-03 04:44:36 +0000798 // FIXME: Instantiate default argument
Douglas Gregorad964b32009-02-17 01:05:43 +0000799 ArgExpr = TempParm->getDefaultArgument();
800 ArgLoc = TempParm->getDefaultArgumentLoc();
801 }
802 } else {
803 // Retrieve the template argument produced by the user.
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000804 ArgLoc = TemplateArgLocs[ArgIdx];
805
Douglas Gregorad964b32009-02-17 01:05:43 +0000806 if (Args.getArgIsType()[ArgIdx])
807 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
808 else
809 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
810 }
811
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000812
813 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
814 // Check template type parameters.
815 if (!ArgType.isNull()) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000816 if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000817 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000818
819 // Add the converted template type argument.
820 Converted.push_back(
821 TemplateArgument(Context.getCanonicalType(ArgType)));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000822 continue;
823 }
824
825 // C++ [temp.arg.type]p1:
826 // A template-argument for a template-parameter which is a
827 // type shall be a type-id.
828
829 // We have a template type parameter but the template argument
830 // is an expression.
831 Diag(ArgExpr->getSourceRange().getBegin(),
832 diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000833 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000834 Invalid = true;
835 } else if (NonTypeTemplateParmDecl *NTTP
836 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
837 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +0000838
839 // Instantiate the type of the non-type template parameter with
840 // the template arguments we've seen thus far.
841 QualType NTTPType = NTTP->getType();
842 if (NTTPType->isDependentType()) {
843 // Instantiate the type of the non-type template parameter.
844 NTTPType = InstantiateType(NTTPType,
845 &Converted[0], Converted.size(),
846 NTTP->getLocation(),
847 NTTP->getDeclName());
848 // If that worked, check the non-type template parameter type
849 // for validity.
850 if (!NTTPType.isNull())
851 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
852 NTTP->getLocation());
853
854 if (NTTPType.isNull()) {
855 Invalid = true;
856 break;
857 }
858 }
859
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000860 if (ArgExpr) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000861 if (CheckTemplateArgument(NTTP, NTTPType, ArgExpr, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000862 Invalid = true;
863 continue;
864 }
865
866 // We have a non-type template parameter but the template
867 // argument is a type.
868
869 // C++ [temp.arg]p2:
870 // In a template-argument, an ambiguity between a type-id and
871 // an expression is resolved to a type-id, regardless of the
872 // form of the corresponding template-parameter.
873 //
874 // We warn specifically about this case, since it can be rather
875 // confusing for users.
876 if (ArgType->isFunctionType())
877 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
878 << ArgType;
879 else
880 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor341ac792009-02-10 00:53:15 +0000881 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000882 Invalid = true;
883 } else {
884 // Check template template parameters.
885 TemplateTemplateParmDecl *TempParm
886 = cast<TemplateTemplateParmDecl>(*Param);
887
888 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
889 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000890 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000891 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000892
893 // Add the converted template argument.
894 // FIXME: Need the "canonical" template declaration!
895 Converted.push_back(
896 TemplateArgument(cast<DeclRefExpr>(ArgExpr)->getDecl()));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000897 continue;
898 }
899
900 // We have a template template parameter but the template
901 // argument does not refer to a template.
902 Diag(ArgLoc, diag::err_template_arg_must_be_template);
903 Invalid = true;
904 }
905 }
906
907 return Invalid;
908}
909
910/// \brief Check a template argument against its corresponding
911/// template type parameter.
912///
913/// This routine implements the semantics of C++ [temp.arg.type]. It
914/// returns true if an error occurred, and false otherwise.
915bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
916 QualType Arg, SourceLocation ArgLoc) {
917 // C++ [temp.arg.type]p2:
918 // A local type, a type with no linkage, an unnamed type or a type
919 // compounded from any of these types shall not be used as a
920 // template-argument for a template type-parameter.
921 //
922 // FIXME: Perform the recursive and no-linkage type checks.
923 const TagType *Tag = 0;
924 if (const EnumType *EnumT = Arg->getAsEnumType())
925 Tag = EnumT;
926 else if (const RecordType *RecordT = Arg->getAsRecordType())
927 Tag = RecordT;
928 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
929 return Diag(ArgLoc, diag::err_template_arg_local_type)
930 << QualType(Tag, 0);
931 else if (Tag && !Tag->getDecl()->getDeclName()) {
932 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
933 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
934 return true;
935 }
936
937 return false;
938}
939
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +0000940/// \brief Checks whether the given template argument is the address
941/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +0000942bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
943 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +0000944 bool Invalid = false;
945
946 // See through any implicit casts we added to fix the type.
947 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
948 Arg = Cast->getSubExpr();
949
950 // C++ [temp.arg.nontype]p1:
951 //
952 // A template-argument for a non-type, non-template
953 // template-parameter shall be one of: [...]
954 //
955 // -- the address of an object or function with external
956 // linkage, including function templates and function
957 // template-ids but excluding non-static class members,
958 // expressed as & id-expression where the & is optional if
959 // the name refers to a function or array, or if the
960 // corresponding template-parameter is a reference; or
961 DeclRefExpr *DRE = 0;
962
963 // Ignore (and complain about) any excess parentheses.
964 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
965 if (!Invalid) {
966 Diag(Arg->getSourceRange().getBegin(),
967 diag::err_template_arg_extra_parens)
968 << Arg->getSourceRange();
969 Invalid = true;
970 }
971
972 Arg = Parens->getSubExpr();
973 }
974
975 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
976 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
977 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
978 } else
979 DRE = dyn_cast<DeclRefExpr>(Arg);
980
981 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
982 return Diag(Arg->getSourceRange().getBegin(),
983 diag::err_template_arg_not_object_or_func_form)
984 << Arg->getSourceRange();
985
986 // Cannot refer to non-static data members
987 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
988 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
989 << Field << Arg->getSourceRange();
990
991 // Cannot refer to non-static member functions
992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
993 if (!Method->isStatic())
994 return Diag(Arg->getSourceRange().getBegin(),
995 diag::err_template_arg_method)
996 << Method << Arg->getSourceRange();
997
998 // Functions must have external linkage.
999 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1000 if (Func->getStorageClass() == FunctionDecl::Static) {
1001 Diag(Arg->getSourceRange().getBegin(),
1002 diag::err_template_arg_function_not_extern)
1003 << Func << Arg->getSourceRange();
1004 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1005 << true;
1006 return true;
1007 }
1008
1009 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001010 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001011 return Invalid;
1012 }
1013
1014 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1015 if (!Var->hasGlobalStorage()) {
1016 Diag(Arg->getSourceRange().getBegin(),
1017 diag::err_template_arg_object_not_extern)
1018 << Var << Arg->getSourceRange();
1019 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1020 << true;
1021 return true;
1022 }
1023
1024 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001025 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001026 return Invalid;
1027 }
1028
1029 // We found something else, but we don't know specifically what it is.
1030 Diag(Arg->getSourceRange().getBegin(),
1031 diag::err_template_arg_not_object_or_func)
1032 << Arg->getSourceRange();
1033 Diag(DRE->getDecl()->getLocation(),
1034 diag::note_template_arg_refers_here);
1035 return true;
1036}
1037
1038/// \brief Checks whether the given template argument is a pointer to
1039/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001040bool
1041Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001042 bool Invalid = false;
1043
1044 // See through any implicit casts we added to fix the type.
1045 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1046 Arg = Cast->getSubExpr();
1047
1048 // C++ [temp.arg.nontype]p1:
1049 //
1050 // A template-argument for a non-type, non-template
1051 // template-parameter shall be one of: [...]
1052 //
1053 // -- a pointer to member expressed as described in 5.3.1.
1054 QualifiedDeclRefExpr *DRE = 0;
1055
1056 // Ignore (and complain about) any excess parentheses.
1057 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1058 if (!Invalid) {
1059 Diag(Arg->getSourceRange().getBegin(),
1060 diag::err_template_arg_extra_parens)
1061 << Arg->getSourceRange();
1062 Invalid = true;
1063 }
1064
1065 Arg = Parens->getSubExpr();
1066 }
1067
1068 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1069 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1070 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1071
1072 if (!DRE)
1073 return Diag(Arg->getSourceRange().getBegin(),
1074 diag::err_template_arg_not_pointer_to_member_form)
1075 << Arg->getSourceRange();
1076
1077 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1078 assert((isa<FieldDecl>(DRE->getDecl()) ||
1079 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1080 "Only non-static member pointers can make it here");
1081
1082 // Okay: this is the address of a non-static member, and therefore
1083 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001084 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001085 return Invalid;
1086 }
1087
1088 // We found something else, but we don't know specifically what it is.
1089 Diag(Arg->getSourceRange().getBegin(),
1090 diag::err_template_arg_not_pointer_to_member_form)
1091 << Arg->getSourceRange();
1092 Diag(DRE->getDecl()->getLocation(),
1093 diag::note_template_arg_refers_here);
1094 return true;
1095}
1096
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001097/// \brief Check a template argument against its corresponding
1098/// non-type template parameter.
1099///
Douglas Gregored3a3982009-03-03 04:44:36 +00001100/// This routine implements the semantics of C++ [temp.arg.nontype].
1101/// It returns true if an error occurred, and false otherwise. \p
1102/// InstantiatedParamType is the type of the non-type template
1103/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001104///
1105/// If Converted is non-NULL and no errors occur, the value
1106/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001107bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001108 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001109 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001110 // If either the parameter has a dependent type or the argument is
1111 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001112 // FIXME: Add template argument to Converted!
Douglas Gregored3a3982009-03-03 04:44:36 +00001113 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent())
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001114 return false;
1115
1116 // C++ [temp.arg.nontype]p5:
1117 // The following conversions are performed on each expression used
1118 // as a non-type template-argument. If a non-type
1119 // template-argument cannot be converted to the type of the
1120 // corresponding template-parameter then the program is
1121 // ill-formed.
1122 //
1123 // -- for a non-type template-parameter of integral or
1124 // enumeration type, integral promotions (4.5) and integral
1125 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001126 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001127 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001128 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001129 // C++ [temp.arg.nontype]p1:
1130 // A template-argument for a non-type, non-template
1131 // template-parameter shall be one of:
1132 //
1133 // -- an integral constant-expression of integral or enumeration
1134 // type; or
1135 // -- the name of a non-type template-parameter; or
1136 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001137 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001138 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1139 Diag(Arg->getSourceRange().getBegin(),
1140 diag::err_template_arg_not_integral_or_enumeral)
1141 << ArgType << Arg->getSourceRange();
1142 Diag(Param->getLocation(), diag::note_template_param_here);
1143 return true;
1144 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001145 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001146 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1147 << ArgType << Arg->getSourceRange();
1148 return true;
1149 }
1150
1151 // FIXME: We need some way to more easily get the unqualified form
1152 // of the types without going all the way to the
1153 // canonical type.
1154 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1155 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1156 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1157 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1158
1159 // Try to convert the argument to the parameter's type.
1160 if (ParamType == ArgType) {
1161 // Okay: no conversion necessary
1162 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1163 !ParamType->isEnumeralType()) {
1164 // This is an integral promotion or conversion.
1165 ImpCastExprToType(Arg, ParamType);
1166 } else {
1167 // We can't perform this conversion.
1168 Diag(Arg->getSourceRange().getBegin(),
1169 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001170 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001171 Diag(Param->getLocation(), diag::note_template_param_here);
1172 return true;
1173 }
1174
Douglas Gregorad964b32009-02-17 01:05:43 +00001175 // FIXME: Check overflow of template arguments?
1176
1177 if (Converted) {
1178 // Add the value of this argument to the list of converted
1179 // arguments. We use the bitwidth and signedness of the template
1180 // parameter.
1181 QualType IntegerType = Context.getCanonicalType(ParamType);
1182 if (const EnumType *Enum = IntegerType->getAsEnumType())
1183 IntegerType = Enum->getDecl()->getIntegerType();
1184
1185 llvm::APInt CanonicalArg(Context.getTypeSize(IntegerType), 0,
1186 IntegerType->isSignedIntegerType());
1187 CanonicalArg = Value;
1188
1189 Converted->push_back(TemplateArgument(CanonicalArg));
1190 }
1191
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001192 return false;
1193 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001194
Douglas Gregor3f411962009-02-11 01:18:59 +00001195 // Handle pointer-to-function, reference-to-function, and
1196 // pointer-to-member-function all in (roughly) the same way.
1197 if (// -- For a non-type template-parameter of type pointer to
1198 // function, only the function-to-pointer conversion (4.3) is
1199 // applied. If the template-argument represents a set of
1200 // overloaded functions (or a pointer to such), the matching
1201 // function is selected from the set (13.4).
1202 (ParamType->isPointerType() &&
1203 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1204 // -- For a non-type template-parameter of type reference to
1205 // function, no conversions apply. If the template-argument
1206 // represents a set of overloaded functions, the matching
1207 // function is selected from the set (13.4).
1208 (ParamType->isReferenceType() &&
1209 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1210 // -- For a non-type template-parameter of type pointer to
1211 // member function, no conversions apply. If the
1212 // template-argument represents a set of overloaded member
1213 // functions, the matching member function is selected from
1214 // the set (13.4).
1215 (ParamType->isMemberPointerType() &&
1216 ParamType->getAsMemberPointerType()->getPointeeType()
1217 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001218 if (Context.hasSameUnqualifiedType(ArgType,
1219 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001220 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001221 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001222 ArgType = Context.getPointerType(ArgType);
1223 ImpCastExprToType(Arg, ArgType);
1224 } else if (FunctionDecl *Fn
1225 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001226 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1227 return true;
1228
Douglas Gregor2eedd992009-02-11 00:19:33 +00001229 FixOverloadedFunctionReference(Arg, Fn);
1230 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001231 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001232 ArgType = Context.getPointerType(Arg->getType());
1233 ImpCastExprToType(Arg, ArgType);
1234 }
1235 }
1236
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001237 if (!Context.hasSameUnqualifiedType(ArgType,
1238 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001239 // We can't perform this conversion.
1240 Diag(Arg->getSourceRange().getBegin(),
1241 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001242 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001243 Diag(Param->getLocation(), diag::note_template_param_here);
1244 return true;
1245 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001246
Douglas Gregorad964b32009-02-17 01:05:43 +00001247 if (ParamType->isMemberPointerType()) {
1248 NamedDecl *Member = 0;
1249 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1250 return true;
1251
1252 if (Converted)
1253 Converted->push_back(TemplateArgument(Member));
1254
1255 return false;
1256 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001257
Douglas Gregorad964b32009-02-17 01:05:43 +00001258 NamedDecl *Entity = 0;
1259 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1260 return true;
1261
1262 if (Converted)
1263 Converted->push_back(TemplateArgument(Entity));
1264 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001265 }
1266
Chris Lattner320dff22009-02-20 21:37:53 +00001267 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001268 // -- for a non-type template-parameter of type pointer to
1269 // object, qualification conversions (4.4) and the
1270 // array-to-pointer conversion (4.2) are applied.
Chris Lattner320dff22009-02-20 21:37:53 +00001271 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001272 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001273
Douglas Gregor3f411962009-02-11 01:18:59 +00001274 if (ArgType->isArrayType()) {
1275 ArgType = Context.getArrayDecayedType(ArgType);
1276 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001277 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001278
1279 if (IsQualificationConversion(ArgType, ParamType)) {
1280 ArgType = ParamType;
1281 ImpCastExprToType(Arg, ParamType);
1282 }
1283
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001284 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001285 // We can't perform this conversion.
1286 Diag(Arg->getSourceRange().getBegin(),
1287 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001288 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001289 Diag(Param->getLocation(), diag::note_template_param_here);
1290 return true;
1291 }
1292
Douglas Gregorad964b32009-02-17 01:05:43 +00001293 NamedDecl *Entity = 0;
1294 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1295 return true;
1296
1297 if (Converted)
1298 Converted->push_back(TemplateArgument(Entity));
1299
1300 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001301 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001302
1303 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1304 // -- For a non-type template-parameter of type reference to
1305 // object, no conversions apply. The type referred to by the
1306 // reference may be more cv-qualified than the (otherwise
1307 // identical) type of the template-argument. The
1308 // template-parameter is bound directly to the
1309 // template-argument, which must be an lvalue.
1310 assert(ParamRefType->getPointeeType()->isObjectType() &&
1311 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001312
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001313 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001314 Diag(Arg->getSourceRange().getBegin(),
1315 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001316 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001317 << Arg->getSourceRange();
1318 Diag(Param->getLocation(), diag::note_template_param_here);
1319 return true;
1320 }
1321
1322 unsigned ParamQuals
1323 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1324 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1325
1326 if ((ParamQuals | ArgQuals) != ParamQuals) {
1327 Diag(Arg->getSourceRange().getBegin(),
1328 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001329 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001330 << Arg->getSourceRange();
1331 Diag(Param->getLocation(), diag::note_template_param_here);
1332 return true;
1333 }
1334
Douglas Gregorad964b32009-02-17 01:05:43 +00001335 NamedDecl *Entity = 0;
1336 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1337 return true;
1338
1339 if (Converted)
1340 Converted->push_back(TemplateArgument(Entity));
1341
1342 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001343 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001344
1345 // -- For a non-type template-parameter of type pointer to data
1346 // member, qualification conversions (4.4) are applied.
1347 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1348
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001349 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001350 // Types match exactly: nothing more to do here.
1351 } else if (IsQualificationConversion(ArgType, ParamType)) {
1352 ImpCastExprToType(Arg, ParamType);
1353 } else {
1354 // We can't perform this conversion.
1355 Diag(Arg->getSourceRange().getBegin(),
1356 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001357 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001358 Diag(Param->getLocation(), diag::note_template_param_here);
1359 return true;
1360 }
1361
Douglas Gregorad964b32009-02-17 01:05:43 +00001362 NamedDecl *Member = 0;
1363 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1364 return true;
1365
1366 if (Converted)
1367 Converted->push_back(TemplateArgument(Member));
1368
1369 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001370}
1371
1372/// \brief Check a template argument against its corresponding
1373/// template template parameter.
1374///
1375/// This routine implements the semantics of C++ [temp.arg.template].
1376/// It returns true if an error occurred, and false otherwise.
1377bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1378 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001379 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1380 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1381
1382 // C++ [temp.arg.template]p1:
1383 // A template-argument for a template template-parameter shall be
1384 // the name of a class template, expressed as id-expression. Only
1385 // primary class templates are considered when matching the
1386 // template template argument with the corresponding parameter;
1387 // partial specializations are not considered even if their
1388 // parameter lists match that of the template template parameter.
1389 if (!isa<ClassTemplateDecl>(Template)) {
1390 assert(isa<FunctionTemplateDecl>(Template) &&
1391 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001392 Diag(Arg->getSourceRange().getBegin(),
1393 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001394 << Template;
1395 }
1396
1397 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1398 Param->getTemplateParameters(),
1399 true, true,
1400 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001401}
1402
Douglas Gregord406b032009-02-06 22:42:48 +00001403/// \brief Determine whether the given template parameter lists are
1404/// equivalent.
1405///
1406/// \param New The new template parameter list, typically written in the
1407/// source code as part of a new template declaration.
1408///
1409/// \param Old The old template parameter list, typically found via
1410/// name lookup of the template declared with this template parameter
1411/// list.
1412///
1413/// \param Complain If true, this routine will produce a diagnostic if
1414/// the template parameter lists are not equivalent.
1415///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001416/// \param IsTemplateTemplateParm If true, this routine is being
1417/// called to compare the template parameter lists of a template
1418/// template parameter.
1419///
1420/// \param TemplateArgLoc If this source location is valid, then we
1421/// are actually checking the template parameter list of a template
1422/// argument (New) against the template parameter list of its
1423/// corresponding template template parameter (Old). We produce
1424/// slightly different diagnostics in this scenario.
1425///
Douglas Gregord406b032009-02-06 22:42:48 +00001426/// \returns True if the template parameter lists are equal, false
1427/// otherwise.
1428bool
1429Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1430 TemplateParameterList *Old,
1431 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001432 bool IsTemplateTemplateParm,
1433 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001434 if (Old->size() != New->size()) {
1435 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001436 unsigned NextDiag = diag::err_template_param_list_different_arity;
1437 if (TemplateArgLoc.isValid()) {
1438 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1439 NextDiag = diag::note_template_param_list_different_arity;
1440 }
1441 Diag(New->getTemplateLoc(), NextDiag)
1442 << (New->size() > Old->size())
1443 << IsTemplateTemplateParm
1444 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001445 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1446 << IsTemplateTemplateParm
1447 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1448 }
1449
1450 return false;
1451 }
1452
1453 for (TemplateParameterList::iterator OldParm = Old->begin(),
1454 OldParmEnd = Old->end(), NewParm = New->begin();
1455 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1456 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001457 unsigned NextDiag = diag::err_template_param_different_kind;
1458 if (TemplateArgLoc.isValid()) {
1459 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1460 NextDiag = diag::note_template_param_different_kind;
1461 }
1462 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001463 << IsTemplateTemplateParm;
1464 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1465 << IsTemplateTemplateParm;
1466 return false;
1467 }
1468
1469 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1470 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001471 // know we're at the same index).
1472#if 0
1473 // FIXME: Enable this code in debug mode *after* we properly go
1474 // through and "instantiate" the template parameter lists of
1475 // template template parameters. It's only after this
1476 // instantiation that (1) any dependent types within the
1477 // template parameter list of the template template parameter
1478 // can be checked, and (2) the template type parameter depths
1479 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001480 QualType OldParmType
1481 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1482 QualType NewParmType
1483 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1484 assert(Context.getCanonicalType(OldParmType) ==
1485 Context.getCanonicalType(NewParmType) &&
1486 "type parameter mismatch?");
1487#endif
1488 } else if (NonTypeTemplateParmDecl *OldNTTP
1489 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1490 // The types of non-type template parameters must agree.
1491 NonTypeTemplateParmDecl *NewNTTP
1492 = cast<NonTypeTemplateParmDecl>(*NewParm);
1493 if (Context.getCanonicalType(OldNTTP->getType()) !=
1494 Context.getCanonicalType(NewNTTP->getType())) {
1495 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001496 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1497 if (TemplateArgLoc.isValid()) {
1498 Diag(TemplateArgLoc,
1499 diag::err_template_arg_template_params_mismatch);
1500 NextDiag = diag::note_template_nontype_parm_different_type;
1501 }
1502 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001503 << NewNTTP->getType()
1504 << IsTemplateTemplateParm;
1505 Diag(OldNTTP->getLocation(),
1506 diag::note_template_nontype_parm_prev_declaration)
1507 << OldNTTP->getType();
1508 }
1509 return false;
1510 }
1511 } else {
1512 // The template parameter lists of template template
1513 // parameters must agree.
1514 // FIXME: Could we perform a faster "type" comparison here?
1515 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1516 "Only template template parameters handled here");
1517 TemplateTemplateParmDecl *OldTTP
1518 = cast<TemplateTemplateParmDecl>(*OldParm);
1519 TemplateTemplateParmDecl *NewTTP
1520 = cast<TemplateTemplateParmDecl>(*NewParm);
1521 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1522 OldTTP->getTemplateParameters(),
1523 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001524 /*IsTemplateTemplateParm=*/true,
1525 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001526 return false;
1527 }
1528 }
1529
1530 return true;
1531}
1532
1533/// \brief Check whether a template can be declared within this scope.
1534///
1535/// If the template declaration is valid in this scope, returns
1536/// false. Otherwise, issues a diagnostic and returns true.
1537bool
1538Sema::CheckTemplateDeclScope(Scope *S,
1539 MultiTemplateParamsArg &TemplateParameterLists) {
1540 assert(TemplateParameterLists.size() > 0 && "Not a template");
1541
1542 // Find the nearest enclosing declaration scope.
1543 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1544 (S->getFlags() & Scope::TemplateParamScope) != 0)
1545 S = S->getParent();
1546
1547 TemplateParameterList *TemplateParams =
1548 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1549 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1550 SourceRange TemplateRange
1551 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1552
1553 // C++ [temp]p2:
1554 // A template-declaration can appear only as a namespace scope or
1555 // class scope declaration.
1556 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1557 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1558 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1559 return Diag(TemplateLoc, diag::err_template_linkage)
1560 << TemplateRange;
1561
1562 Ctx = Ctx->getParent();
1563 }
1564
1565 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1566 return false;
1567
1568 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1569 << TemplateRange;
1570}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001571
Douglas Gregor0d93f692009-02-25 22:02:03 +00001572/// \brief Check whether a class template specialization in the
1573/// current context is well-formed.
1574///
1575/// This routine determines whether a class template specialization
1576/// can be declared in the current context (C++ [temp.expl.spec]p2)
1577/// and emits appropriate diagnostics if there was an error. It
1578/// returns true if there was an error that we cannot recover from,
1579/// and false otherwise.
1580bool
1581Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1582 ClassTemplateSpecializationDecl *PrevDecl,
1583 SourceLocation TemplateNameLoc,
1584 SourceRange ScopeSpecifierRange) {
1585 // C++ [temp.expl.spec]p2:
1586 // An explicit specialization shall be declared in the namespace
1587 // of which the template is a member, or, for member templates, in
1588 // the namespace of which the enclosing class or enclosing class
1589 // template is a member. An explicit specialization of a member
1590 // function, member class or static data member of a class
1591 // template shall be declared in the namespace of which the class
1592 // template is a member. Such a declaration may also be a
1593 // definition. If the declaration is not a definition, the
1594 // specialization may be defined later in the name- space in which
1595 // the explicit specialization was declared, or in a namespace
1596 // that encloses the one in which the explicit specialization was
1597 // declared.
1598 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1599 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1600 << ClassTemplate;
1601 return true;
1602 }
1603
1604 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1605 DeclContext *TemplateContext
1606 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1607 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1608 // There is no prior declaration of this entity, so this
1609 // specialization must be in the same context as the template
1610 // itself.
1611 if (DC != TemplateContext) {
1612 if (isa<TranslationUnitDecl>(TemplateContext))
1613 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1614 << ClassTemplate << ScopeSpecifierRange;
1615 else if (isa<NamespaceDecl>(TemplateContext))
1616 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1617 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1618 << ScopeSpecifierRange;
1619
1620 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1621 }
1622
1623 return false;
1624 }
1625
1626 // We have a previous declaration of this entity. Make sure that
1627 // this redeclaration (or definition) occurs in an enclosing namespace.
1628 if (!CurContext->Encloses(TemplateContext)) {
1629 if (isa<TranslationUnitDecl>(TemplateContext))
1630 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1631 << ClassTemplate << ScopeSpecifierRange;
1632 else if (isa<NamespaceDecl>(TemplateContext))
1633 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1634 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1635 << ScopeSpecifierRange;
1636
1637 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1638 }
1639
1640 return false;
1641}
1642
Douglas Gregora08b6c72009-02-17 23:15:12 +00001643Sema::DeclTy *
1644Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1645 SourceLocation KWLoc,
1646 const CXXScopeSpec &SS,
1647 DeclTy *TemplateD,
1648 SourceLocation TemplateNameLoc,
1649 SourceLocation LAngleLoc,
1650 ASTTemplateArgsPtr TemplateArgs,
1651 SourceLocation *TemplateArgLocs,
1652 SourceLocation RAngleLoc,
1653 AttributeList *Attr,
1654 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001655 // Find the class template we're specializing
1656 ClassTemplateDecl *ClassTemplate
1657 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1658 if (!ClassTemplate)
1659 return 0;
1660
Douglas Gregor0d93f692009-02-25 22:02:03 +00001661 // Check the validity of the template headers that introduce this
1662 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001663 // FIXME: Once we have member templates, we'll need to check
1664 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1665 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001666 if (TemplateParameterLists.size() == 0)
1667 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001668 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001669 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001670 TemplateParameterList *TemplateParams
1671 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1672 if (TemplateParameterLists.size() > 1) {
1673 Diag(TemplateParams->getTemplateLoc(),
1674 diag::err_template_spec_extra_headers);
1675 return 0;
1676 }
1677
1678 if (TemplateParams->size() > 0) {
1679 // FIXME: No support for class template partial specialization.
1680 Diag(TemplateParams->getTemplateLoc(),
1681 diag::unsup_template_partial_spec);
1682 return 0;
1683 }
1684 }
1685
Douglas Gregora08b6c72009-02-17 23:15:12 +00001686 // Check that the specialization uses the same tag kind as the
1687 // original template.
1688 TagDecl::TagKind Kind;
1689 switch (TagSpec) {
1690 default: assert(0 && "Unknown tag type!");
1691 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1692 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1693 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1694 }
1695 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1696 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1697 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1698 diag::note_previous_use);
1699 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1700 }
1701
1702 // Check that the template argument list is well-formed for this
1703 // template.
1704 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1705 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
1706 TemplateArgs, TemplateArgLocs, RAngleLoc,
1707 ConvertedTemplateArgs))
1708 return 0;
1709
1710 assert((ConvertedTemplateArgs.size() ==
1711 ClassTemplate->getTemplateParameters()->size()) &&
1712 "Converted template argument list is too short!");
1713
1714 // Find the class template specialization declaration that
1715 // corresponds to these arguments.
1716 llvm::FoldingSetNodeID ID;
1717 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1718 ConvertedTemplateArgs.size());
1719 void *InsertPos = 0;
1720 ClassTemplateSpecializationDecl *PrevDecl
1721 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1722
1723 ClassTemplateSpecializationDecl *Specialization = 0;
1724
Douglas Gregor0d93f692009-02-25 22:02:03 +00001725 // Check whether we can declare a class template specialization in
1726 // the current scope.
1727 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1728 TemplateNameLoc,
1729 SS.getRange()))
1730 return 0;
1731
Douglas Gregora08b6c72009-02-17 23:15:12 +00001732 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1733 // Since the only prior class template specialization with these
1734 // arguments was referenced but not declared, reuse that
1735 // declaration node as our own, updating its source location to
1736 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001737 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00001738 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001739 PrevDecl = 0;
1740 } else {
1741 // Create a new class template specialization declaration node for
1742 // this explicit specialization.
1743 Specialization
1744 = ClassTemplateSpecializationDecl::Create(Context,
1745 ClassTemplate->getDeclContext(),
1746 TemplateNameLoc,
1747 ClassTemplate,
1748 &ConvertedTemplateArgs[0],
1749 ConvertedTemplateArgs.size(),
1750 PrevDecl);
1751
1752 if (PrevDecl) {
1753 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1754 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1755 } else {
1756 ClassTemplate->getSpecializations().InsertNode(Specialization,
1757 InsertPos);
1758 }
1759 }
1760
1761 // Note that this is an explicit specialization.
1762 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1763
1764 // Check that this isn't a redefinition of this specialization.
1765 if (TK == TK_Definition) {
1766 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1767 // FIXME: Should also handle explicit specialization after
1768 // implicit instantiation with a special diagnostic.
1769 SourceRange Range(TemplateNameLoc, RAngleLoc);
1770 Diag(TemplateNameLoc, diag::err_redefinition)
1771 << Specialization << Range;
1772 Diag(Def->getLocation(), diag::note_previous_definition);
1773 Specialization->setInvalidDecl();
1774 return 0;
1775 }
1776 }
1777
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001778 // Build the fully-sugared type for this class template
1779 // specialization as the user wrote in the specialization
1780 // itself. This means that we'll pretty-print the type retrieved
1781 // from the specialization's declaration the way that the user
1782 // actually wrote the specialization, rather than formatting the
1783 // name based on the "canonical" representation used to store the
1784 // template arguments in the specialization.
1785 Specialization->setTypeAsWritten(
1786 Context.getClassTemplateSpecializationType(ClassTemplate,
1787 TemplateArgs.size(),
1788 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
1789 TemplateArgs.getArgIsType(),
1790 Context.getTypeDeclType(Specialization)));
1791 TemplateArgs.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001792
Douglas Gregor50113ca2009-02-25 22:18:32 +00001793 // C++ [temp.expl.spec]p9:
1794 // A template explicit specialization is in the scope of the
1795 // namespace in which the template was defined.
1796 //
1797 // We actually implement this paragraph where we set the semantic
1798 // context (in the creation of the ClassTemplateSpecializationDecl),
1799 // but we also maintain the lexical context where the actual
1800 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001801 Specialization->setLexicalDeclContext(CurContext);
1802
1803 // We may be starting the definition of this specialization.
1804 if (TK == TK_Definition)
1805 Specialization->startDefinition();
1806
1807 // Add the specialization into its lexical context, so that it can
1808 // be seen when iterating through the list of declarations in that
1809 // context. However, specializations are not found by name lookup.
1810 CurContext->addDecl(Specialization);
1811 return Specialization;
1812}