blob: 429dc8e1e302c79011a25bc27f6a99abb0003a64 [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.
8//+//===----------------------------------------------------------------------===/
9
10//
11// This file implements semantic analysis for C++ templates.
12//+//===----------------------------------------------------------------------===/
13
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 Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20
21using namespace clang;
22
Douglas Gregor2fa10442008-12-18 19:37:40 +000023/// isTemplateName - Determines whether the identifier II is a
24/// template name in the current scope, and returns the template
25/// declaration if II names a template. An optional CXXScope can be
26/// passed to indicate the C++ scope in which the identifier will be
27/// found.
Douglas Gregor8e458f42009-02-09 18:46:07 +000028Sema::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
29 DeclTy *&Template,
30 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000031 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000032
33 if (IIDecl) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000034 if (isa<TemplateDecl>(IIDecl)) {
35 Template = IIDecl;
36 if (isa<FunctionTemplateDecl>(IIDecl))
37 return TNK_Function_template;
38 else if (isa<ClassTemplateDecl>(IIDecl))
39 return TNK_Class_template;
40 else if (isa<TemplateTemplateParmDecl>(IIDecl))
41 return TNK_Template_template_parm;
42 else
43 assert(false && "Unknown TemplateDecl");
44 }
Douglas Gregor279272e2009-02-04 19:02:06 +000045
Douglas Gregor8e458f42009-02-09 18:46:07 +000046 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000048 if (FD->getType()->isDependentType()) {
49 Template = FD;
50 return TNK_Function_template;
51 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000052 } else if (OverloadedFunctionDecl *Ovl
53 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
54 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
55 FEnd = Ovl->function_end();
56 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000057 if ((*F)->getType()->isDependentType()) {
58 Template = Ovl;
59 return TNK_Function_template;
60 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000061 }
62 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000063 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000064 return TNK_Non_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +000065}
66
Douglas Gregordd861062008-12-05 18:15:24 +000067/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
68/// that the template parameter 'PrevDecl' is being shadowed by a new
69/// declaration at location Loc. Returns true to indicate that this is
70/// an error, and false otherwise.
71bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +000072 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +000073
74 // Microsoft Visual C++ permits template parameters to be shadowed.
75 if (getLangOptions().Microsoft)
76 return false;
77
78 // C++ [temp.local]p4:
79 // A template-parameter shall not be redeclared within its
80 // scope (including nested scopes).
81 Diag(Loc, diag::err_template_param_shadow)
82 << cast<NamedDecl>(PrevDecl)->getDeclName();
83 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
84 return true;
85}
86
Douglas Gregor279272e2009-02-04 19:02:06 +000087/// AdjustDeclForTemplates - If the given decl happens to be a template, reset
88/// the parameter D to reference the templated declaration and return a pointer
89/// to the template declaration. Otherwise, do nothing to D and return null.
90TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
91{
92 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
93 D = Temp->getTemplatedDecl();
94 return Temp;
95 }
96 return 0;
97}
98
Douglas Gregordd861062008-12-05 18:15:24 +000099/// ActOnTypeParameter - Called when a C++ template type parameter
100/// (e.g., "typename T") has been parsed. Typename specifies whether
101/// the keyword "typename" was used to declare the type parameter
102/// (otherwise, "class" was used), and KeyLoc is the location of the
103/// "class" or "typename" keyword. ParamName is the name of the
104/// parameter (NULL indicates an unnamed template parameter) and
105/// ParamName is the location of the parameter name (if any).
106/// If the type parameter has a default argument, it will be added
107/// later via ActOnTypeParameterDefault.
108Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
109 SourceLocation KeyLoc,
110 IdentifierInfo *ParamName,
Douglas Gregor52473432008-12-24 02:52:09 +0000111 SourceLocation ParamNameLoc,
112 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000113 assert(S->isTemplateParamScope() &&
114 "Template type parameter not in template parameter scope!");
115 bool Invalid = false;
116
117 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000118 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000119 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000120 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
121 PrevDecl);
122 }
123
Douglas Gregord406b032009-02-06 22:42:48 +0000124 SourceLocation Loc = ParamNameLoc;
125 if (!ParamName)
126 Loc = KeyLoc;
127
Douglas Gregordd861062008-12-05 18:15:24 +0000128 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000129 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000130 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000131 if (Invalid)
132 Param->setInvalidDecl();
133
134 if (ParamName) {
135 // Add the template parameter into the current scope.
136 S->AddDecl(Param);
137 IdResolver.AddDecl(Param);
138 }
139
140 return Param;
141}
142
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000143/// ActOnTypeParameterDefault - Adds a default argument (the type
144/// Default) to the given template type parameter (TypeParam).
145void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
146 SourceLocation EqualLoc,
147 SourceLocation DefaultLoc,
148 TypeTy *DefaultT) {
149 TemplateTypeParmDecl *Parm
150 = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
151 QualType Default = QualType::getFromOpaquePtr(DefaultT);
152
153 // C++ [temp.param]p14:
154 // A template-parameter shall not be used in its own default argument.
155 // FIXME: Implement this check! Needs a recursive walk over the types.
156
157 // Check the template argument itself.
158 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
159 Parm->setInvalidDecl();
160 return;
161 }
162
163 Parm->setDefaultArgument(Default, DefaultLoc, false);
164}
165
Douglas Gregordd861062008-12-05 18:15:24 +0000166/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
167/// template parameter (e.g., "int Size" in "template<int Size>
168/// class Array") has been parsed. S is the current scope and D is
169/// the parsed declarator.
Douglas Gregor52473432008-12-24 02:52:09 +0000170Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
171 unsigned Depth,
172 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000173 QualType T = GetTypeForDeclarator(D, S);
174
Douglas Gregor279272e2009-02-04 19:02:06 +0000175 assert(S->isTemplateParamScope() &&
176 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000177 bool Invalid = false;
178
179 IdentifierInfo *ParamName = D.getIdentifier();
180 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000181 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000182 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000183 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000184 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000185 }
186
Douglas Gregor62cdc792009-02-10 17:43:50 +0000187 // C++ [temp.param]p4:
188 //
189 // A non-type template-parameter shall have one of the following
190 // (optionally cv-qualified) types:
191 //
192 // -- integral or enumeration type,
193 if (T->isIntegralType() || T->isEnumeralType() ||
194 // -- pointer to object or pointer to function,
Douglas Gregor2eedd992009-02-11 00:19:33 +0000195 (T->isPointerType() &&
196 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
197 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregor62cdc792009-02-10 17:43:50 +0000198 // -- reference to object or reference to function,
199 T->isReferenceType() ||
200 // -- pointer to member.
201 T->isMemberPointerType() ||
202 // If T is a dependent type, we can't do the check now, so we
203 // assume that it is well-formed.
204 T->isDependentType()) {
205 // Okay: The template parameter is well-formed.
206 }
207 // C++ [temp.param]p8:
208 //
209 // A non-type template-parameter of type "array of T" or
210 // "function returning T" is adjusted to be of type "pointer to
211 // T" or "pointer to function returning T", respectively.
212 else if (T->isArrayType())
213 // FIXME: Keep the type prior to promotion?
214 T = Context.getArrayDecayedType(T);
215 else if (T->isFunctionType())
216 // FIXME: Keep the type prior to promotion?
217 T = Context.getPointerType(T);
218 else {
219 Diag(D.getIdentifierLoc(), diag::err_template_nontype_parm_bad_type)
220 << T;
221 return 0;
222 }
223
Douglas Gregordd861062008-12-05 18:15:24 +0000224 NonTypeTemplateParmDecl *Param
225 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000226 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000227 if (Invalid)
228 Param->setInvalidDecl();
229
230 if (D.getIdentifier()) {
231 // Add the template parameter into the current scope.
232 S->AddDecl(Param);
233 IdResolver.AddDecl(Param);
234 }
235 return Param;
236}
Douglas Gregor52473432008-12-24 02:52:09 +0000237
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000238/// \brief Adds a default argument to the given non-type template
239/// parameter.
240void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
241 SourceLocation EqualLoc,
242 ExprArg DefaultE) {
243 NonTypeTemplateParmDecl *TemplateParm
244 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
245 Expr *Default = static_cast<Expr *>(DefaultE.get());
246
247 // C++ [temp.param]p14:
248 // A template-parameter shall not be used in its own default argument.
249 // FIXME: Implement this check! Needs a recursive walk over the types.
250
251 // Check the well-formedness of the default template argument.
252 if (CheckTemplateArgument(TemplateParm, Default)) {
253 TemplateParm->setInvalidDecl();
254 return;
255 }
256
257 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
258}
259
Douglas Gregor279272e2009-02-04 19:02:06 +0000260
261/// ActOnTemplateTemplateParameter - Called when a C++ template template
262/// parameter (e.g. T in template <template <typename> class T> class array)
263/// has been parsed. S is the current scope.
264Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
265 SourceLocation TmpLoc,
266 TemplateParamsTy *Params,
267 IdentifierInfo *Name,
268 SourceLocation NameLoc,
269 unsigned Depth,
270 unsigned Position)
271{
272 assert(S->isTemplateParamScope() &&
273 "Template template parameter not in template parameter scope!");
274
275 // Construct the parameter object.
276 TemplateTemplateParmDecl *Param =
277 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
278 Position, Name,
279 (TemplateParameterList*)Params);
280
281 // Make sure the parameter is valid.
282 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
283 // do anything yet. However, if the template parameter list or (eventual)
284 // default value is ever invalidated, that will propagate here.
285 bool Invalid = false;
286 if (Invalid) {
287 Param->setInvalidDecl();
288 }
289
290 // If the tt-param has a name, then link the identifier into the scope
291 // and lookup mechanisms.
292 if (Name) {
293 S->AddDecl(Param);
294 IdResolver.AddDecl(Param);
295 }
296
297 return Param;
298}
299
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000300/// \brief Adds a default argument to the given template template
301/// parameter.
302void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
303 SourceLocation EqualLoc,
304 ExprArg DefaultE) {
305 TemplateTemplateParmDecl *TemplateParm
306 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
307
308 // Since a template-template parameter's default argument is an
309 // id-expression, it must be a DeclRefExpr.
310 DeclRefExpr *Default
311 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
312
313 // C++ [temp.param]p14:
314 // A template-parameter shall not be used in its own default argument.
315 // FIXME: Implement this check! Needs a recursive walk over the types.
316
317 // Check the well-formedness of the template argument.
318 if (!isa<TemplateDecl>(Default->getDecl())) {
319 Diag(Default->getSourceRange().getBegin(),
320 diag::err_template_arg_must_be_template)
321 << Default->getSourceRange();
322 TemplateParm->setInvalidDecl();
323 return;
324 }
325 if (CheckTemplateArgument(TemplateParm, Default)) {
326 TemplateParm->setInvalidDecl();
327 return;
328 }
329
330 DefaultE.release();
331 TemplateParm->setDefaultArgument(Default);
332}
333
Douglas Gregor52473432008-12-24 02:52:09 +0000334/// ActOnTemplateParameterList - Builds a TemplateParameterList that
335/// contains the template parameters in Params/NumParams.
336Sema::TemplateParamsTy *
337Sema::ActOnTemplateParameterList(unsigned Depth,
338 SourceLocation ExportLoc,
339 SourceLocation TemplateLoc,
340 SourceLocation LAngleLoc,
341 DeclTy **Params, unsigned NumParams,
342 SourceLocation RAngleLoc) {
343 if (ExportLoc.isValid())
344 Diag(ExportLoc, diag::note_template_export_unsupported);
345
Douglas Gregord406b032009-02-06 22:42:48 +0000346 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
347 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000348}
Douglas Gregor279272e2009-02-04 19:02:06 +0000349
Douglas Gregord406b032009-02-06 22:42:48 +0000350Sema::DeclTy *
351Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
352 SourceLocation KWLoc, const CXXScopeSpec &SS,
353 IdentifierInfo *Name, SourceLocation NameLoc,
354 AttributeList *Attr,
355 MultiTemplateParamsArg TemplateParameterLists) {
356 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
357 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000358 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000359
360 // Check that we can declare a template here.
361 if (CheckTemplateDeclScope(S, TemplateParameterLists))
362 return 0;
363
364 TagDecl::TagKind Kind;
365 switch (TagSpec) {
366 default: assert(0 && "Unknown tag type!");
367 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
368 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
369 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
370 }
371
372 // There is no such thing as an unnamed class template.
373 if (!Name) {
374 Diag(KWLoc, diag::err_template_unnamed_class);
375 return 0;
376 }
377
378 // Find any previous declaration with this name.
379 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
380 true);
381 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
382 NamedDecl *PrevDecl = 0;
383 if (Previous.begin() != Previous.end())
384 PrevDecl = *Previous.begin();
385
386 DeclContext *SemanticContext = CurContext;
387 if (SS.isNotEmpty() && !SS.isInvalid()) {
388 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
389
390 // FIXME: need to match up several levels of template parameter
391 // lists here.
392 }
393
394 // FIXME: member templates!
395 TemplateParameterList *TemplateParams
396 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
397
398 // If there is a previous declaration with the same name, check
399 // whether this is a valid redeclaration.
400 ClassTemplateDecl *PrevClassTemplate
401 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
402 if (PrevClassTemplate) {
403 // Ensure that the template parameter lists are compatible.
404 if (!TemplateParameterListsAreEqual(TemplateParams,
405 PrevClassTemplate->getTemplateParameters(),
406 /*Complain=*/true))
407 return 0;
408
409 // C++ [temp.class]p4:
410 // In a redeclaration, partial specialization, explicit
411 // specialization or explicit instantiation of a class template,
412 // the class-key shall agree in kind with the original class
413 // template declaration (7.1.5.3).
414 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
415 if (PrevRecordDecl->getTagKind() != Kind) {
416 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
417 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
418 return 0;
419 }
420
421
422 // Check for redefinition of this class template.
423 if (TK == TK_Definition) {
424 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
425 Diag(NameLoc, diag::err_redefinition) << Name;
426 Diag(Def->getLocation(), diag::note_previous_definition);
427 // FIXME: Would it make sense to try to "forget" the previous
428 // definition, as part of error recovery?
429 return 0;
430 }
431 }
432 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
433 // Maybe we will complain about the shadowed template parameter.
434 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
435 // Just pretend that we didn't see the previous declaration.
436 PrevDecl = 0;
437 } else if (PrevDecl) {
438 // C++ [temp]p5:
439 // A class template shall not have the same name as any other
440 // template, class, function, object, enumeration, enumerator,
441 // namespace, or type in the same scope (3.3), except as specified
442 // in (14.5.4).
443 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
444 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
445 return 0;
446 }
447
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000448 // Check the template parameter list of this declaration, possibly
449 // merging in the template parameter list from the previous class
450 // template declaration.
451 if (CheckTemplateParameterList(TemplateParams,
452 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
453 Invalid = true;
454
Douglas Gregord406b032009-02-06 22:42:48 +0000455 // If we had a scope specifier, we better have a previous template
456 // declaration!
457
458 TagDecl *NewClass =
459 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
460 PrevClassTemplate?
461 PrevClassTemplate->getTemplatedDecl() : 0);
462
463 ClassTemplateDecl *NewTemplate
464 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
465 DeclarationName(Name), TemplateParams,
466 NewClass);
467
468 // Set the lexical context of these templates
469 NewClass->setLexicalDeclContext(CurContext);
470 NewTemplate->setLexicalDeclContext(CurContext);
471
472 if (TK == TK_Definition)
473 NewClass->startDefinition();
474
475 if (Attr)
476 ProcessDeclAttributeList(NewClass, Attr);
477
478 PushOnScopeChains(NewTemplate, S);
479
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000480 if (Invalid) {
481 NewTemplate->setInvalidDecl();
482 NewClass->setInvalidDecl();
483 }
Douglas Gregord406b032009-02-06 22:42:48 +0000484 return NewTemplate;
485}
486
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000487/// \brief Checks the validity of a template parameter list, possibly
488/// considering the template parameter list from a previous
489/// declaration.
490///
491/// If an "old" template parameter list is provided, it must be
492/// equivalent (per TemplateParameterListsAreEqual) to the "new"
493/// template parameter list.
494///
495/// \param NewParams Template parameter list for a new template
496/// declaration. This template parameter list will be updated with any
497/// default arguments that are carried through from the previous
498/// template parameter list.
499///
500/// \param OldParams If provided, template parameter list from a
501/// previous declaration of the same template. Default template
502/// arguments will be merged from the old template parameter list to
503/// the new template parameter list.
504///
505/// \returns true if an error occurred, false otherwise.
506bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
507 TemplateParameterList *OldParams) {
508 bool Invalid = false;
509
510 // C++ [temp.param]p10:
511 // The set of default template-arguments available for use with a
512 // template declaration or definition is obtained by merging the
513 // default arguments from the definition (if in scope) and all
514 // declarations in scope in the same way default function
515 // arguments are (8.3.6).
516 bool SawDefaultArgument = false;
517 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000518
Mike Stump98cb72a2009-02-11 18:58:46 +0000519 // Self initialization to avoid warnings.
520 TemplateParameterList::iterator OldParam = OldParam;
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000521 if (OldParams)
522 OldParam = OldParams->begin();
523
524 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
525 NewParamEnd = NewParams->end();
526 NewParam != NewParamEnd; ++NewParam) {
527 // Variables used to diagnose redundant default arguments
528 bool RedundantDefaultArg = false;
529 SourceLocation OldDefaultLoc;
530 SourceLocation NewDefaultLoc;
531
532 // Variables used to diagnose missing default arguments
533 bool MissingDefaultArg = false;
534
535 // Merge default arguments for template type parameters.
536 if (TemplateTypeParmDecl *NewTypeParm
537 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
538 TemplateTypeParmDecl *OldTypeParm
539 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
540
541 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
542 NewTypeParm->hasDefaultArgument()) {
543 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
544 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
545 SawDefaultArgument = true;
546 RedundantDefaultArg = true;
547 PreviousDefaultArgLoc = NewDefaultLoc;
548 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
549 // Merge the default argument from the old declaration to the
550 // new declaration.
551 SawDefaultArgument = true;
552 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
553 OldTypeParm->getDefaultArgumentLoc(),
554 true);
555 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
556 } else if (NewTypeParm->hasDefaultArgument()) {
557 SawDefaultArgument = true;
558 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
559 } else if (SawDefaultArgument)
560 MissingDefaultArg = true;
561 }
562 // Merge default arguments for non-type template parameters
563 else if (NonTypeTemplateParmDecl *NewNonTypeParm
564 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
565 NonTypeTemplateParmDecl *OldNonTypeParm
566 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
567 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
568 NewNonTypeParm->hasDefaultArgument()) {
569 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
570 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
571 SawDefaultArgument = true;
572 RedundantDefaultArg = true;
573 PreviousDefaultArgLoc = NewDefaultLoc;
574 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
575 // Merge the default argument from the old declaration to the
576 // new declaration.
577 SawDefaultArgument = true;
578 // FIXME: We need to create a new kind of "default argument"
579 // expression that points to a previous template template
580 // parameter.
581 NewNonTypeParm->setDefaultArgument(
582 OldNonTypeParm->getDefaultArgument());
583 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
584 } else if (NewNonTypeParm->hasDefaultArgument()) {
585 SawDefaultArgument = true;
586 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
587 } else if (SawDefaultArgument)
588 MissingDefaultArg = true;
589 }
590 // Merge default arguments for template template parameters
591 else {
592 TemplateTemplateParmDecl *NewTemplateParm
593 = cast<TemplateTemplateParmDecl>(*NewParam);
594 TemplateTemplateParmDecl *OldTemplateParm
595 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
596 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
597 NewTemplateParm->hasDefaultArgument()) {
598 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
599 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
600 SawDefaultArgument = true;
601 RedundantDefaultArg = true;
602 PreviousDefaultArgLoc = NewDefaultLoc;
603 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
604 // Merge the default argument from the old declaration to the
605 // new declaration.
606 SawDefaultArgument = true;
607 // FIXME: We need to create a new kind of "default argument"
608 // expression that points to a previous template template
609 // parameter.
610 NewTemplateParm->setDefaultArgument(
611 OldTemplateParm->getDefaultArgument());
612 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
613 } else if (NewTemplateParm->hasDefaultArgument()) {
614 SawDefaultArgument = true;
615 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
616 } else if (SawDefaultArgument)
617 MissingDefaultArg = true;
618 }
619
620 if (RedundantDefaultArg) {
621 // C++ [temp.param]p12:
622 // A template-parameter shall not be given default arguments
623 // by two different declarations in the same scope.
624 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
625 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
626 Invalid = true;
627 } else if (MissingDefaultArg) {
628 // C++ [temp.param]p11:
629 // If a template-parameter has a default template-argument,
630 // all subsequent template-parameters shall have a default
631 // template-argument supplied.
632 Diag((*NewParam)->getLocation(),
633 diag::err_template_param_default_arg_missing);
634 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
635 Invalid = true;
636 }
637
638 // If we have an old template parameter list that we're merging
639 // in, move on to the next parameter.
640 if (OldParams)
641 ++OldParam;
642 }
643
644 return Invalid;
645}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000646
Douglas Gregor8e458f42009-02-09 18:46:07 +0000647Action::TypeTy *
648Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000649 SourceLocation TemplateLoc,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000650 SourceLocation LAngleLoc,
Douglas Gregor6f37b582009-02-09 19:34:22 +0000651 ASTTemplateArgsPtr TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000652 SourceLocation *TemplateArgLocs,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000653 SourceLocation RAngleLoc,
654 const CXXScopeSpec *SS) {
655 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
656
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000657 // Check that the template argument list is well-formed for this
658 // template.
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000659 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
660 TemplateArgs, TemplateArgLocs, RAngleLoc))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000661 return 0;
662
Douglas Gregor8e458f42009-02-09 18:46:07 +0000663 // Yes, all class template specializations are just silly sugar for
664 // 'int'. Gotta problem wit dat?
Douglas Gregor6f37b582009-02-09 19:34:22 +0000665 QualType Result
666 = Context.getClassTemplateSpecializationType(Template,
667 TemplateArgs.size(),
668 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
669 TemplateArgs.getArgIsType(),
670 Context.IntTy);
671 TemplateArgs.release();
672 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000673}
674
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000675/// \brief Check that the given template argument list is well-formed
676/// for specializing the given template.
677bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
678 SourceLocation TemplateLoc,
679 SourceLocation LAngleLoc,
680 ASTTemplateArgsPtr& Args,
681 SourceLocation *TemplateArgLocs,
682 SourceLocation RAngleLoc) {
683 TemplateParameterList *Params = Template->getTemplateParameters();
684 unsigned NumParams = Params->size();
685 unsigned NumArgs = Args.size();
686 bool Invalid = false;
687
688 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000689 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000690 // FIXME: point at either the first arg beyond what we can handle,
691 // or the '>', depending on whether we have too many or too few
692 // arguments.
693 SourceRange Range;
694 if (NumArgs > NumParams)
695 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
696 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
697 << (NumArgs > NumParams)
698 << (isa<ClassTemplateDecl>(Template)? 0 :
699 isa<FunctionTemplateDecl>(Template)? 1 :
700 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
701 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000702 Diag(Template->getLocation(), diag::note_template_decl_here)
703 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000704 Invalid = true;
705 }
706
707 // C++ [temp.arg]p1:
708 // [...] The type and form of each template-argument specified in
709 // a template-id shall match the type and form specified for the
710 // corresponding parameter declared by the template in its
711 // template-parameter-list.
712 unsigned ArgIdx = 0;
713 for (TemplateParameterList::iterator Param = Params->begin(),
714 ParamEnd = Params->end();
715 Param != ParamEnd; ++Param, ++ArgIdx) {
716 // Decode the template argument
717 QualType ArgType;
718 Expr *ArgExpr = 0;
719 SourceLocation ArgLoc;
720 if (ArgIdx >= NumArgs) {
721 // FIXME: Get the default argument here, which might
722 // (eventually) require instantiation.
723 break;
724 } else
725 ArgLoc = TemplateArgLocs[ArgIdx];
726
727 if (Args.getArgIsType()[ArgIdx])
728 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
729 else
730 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
731
732 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
733 // Check template type parameters.
734 if (!ArgType.isNull()) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000735 if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000736 Invalid = true;
737 continue;
738 }
739
740 // C++ [temp.arg.type]p1:
741 // A template-argument for a template-parameter which is a
742 // type shall be a type-id.
743
744 // We have a template type parameter but the template argument
745 // is an expression.
746 Diag(ArgExpr->getSourceRange().getBegin(),
747 diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000748 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000749 Invalid = true;
750 } else if (NonTypeTemplateParmDecl *NTTP
751 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
752 // Check non-type template parameters.
753 if (ArgExpr) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000754 if (CheckTemplateArgument(NTTP, ArgExpr))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000755 Invalid = true;
756 continue;
757 }
758
759 // We have a non-type template parameter but the template
760 // argument is a type.
761
762 // C++ [temp.arg]p2:
763 // In a template-argument, an ambiguity between a type-id and
764 // an expression is resolved to a type-id, regardless of the
765 // form of the corresponding template-parameter.
766 //
767 // We warn specifically about this case, since it can be rather
768 // confusing for users.
769 if (ArgType->isFunctionType())
770 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
771 << ArgType;
772 else
773 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor341ac792009-02-10 00:53:15 +0000774 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000775 Invalid = true;
776 } else {
777 // Check template template parameters.
778 TemplateTemplateParmDecl *TempParm
779 = cast<TemplateTemplateParmDecl>(*Param);
780
781 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
782 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000783 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000784 Invalid = true;
785 continue;
786 }
787
788 // We have a template template parameter but the template
789 // argument does not refer to a template.
790 Diag(ArgLoc, diag::err_template_arg_must_be_template);
791 Invalid = true;
792 }
793 }
794
795 return Invalid;
796}
797
798/// \brief Check a template argument against its corresponding
799/// template type parameter.
800///
801/// This routine implements the semantics of C++ [temp.arg.type]. It
802/// returns true if an error occurred, and false otherwise.
803bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
804 QualType Arg, SourceLocation ArgLoc) {
805 // C++ [temp.arg.type]p2:
806 // A local type, a type with no linkage, an unnamed type or a type
807 // compounded from any of these types shall not be used as a
808 // template-argument for a template type-parameter.
809 //
810 // FIXME: Perform the recursive and no-linkage type checks.
811 const TagType *Tag = 0;
812 if (const EnumType *EnumT = Arg->getAsEnumType())
813 Tag = EnumT;
814 else if (const RecordType *RecordT = Arg->getAsRecordType())
815 Tag = RecordT;
816 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
817 return Diag(ArgLoc, diag::err_template_arg_local_type)
818 << QualType(Tag, 0);
819 else if (Tag && !Tag->getDecl()->getDeclName()) {
820 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
821 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
822 return true;
823 }
824
825 return false;
826}
827
828/// \brief Check a template argument against its corresponding
829/// non-type template parameter.
830///
831/// This routine implements the semantics of C++ [temp.arg.nontype].
832/// It returns true if an error occurred, and false otherwise.
833bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000834 Expr *&Arg) {
835 // If either the parameter has a dependent type or the argument is
836 // type-dependent, there's nothing we can check now.
837 if (Param->getType()->isDependentType() || Arg->isTypeDependent())
838 return false;
839
840 // C++ [temp.arg.nontype]p5:
841 // The following conversions are performed on each expression used
842 // as a non-type template-argument. If a non-type
843 // template-argument cannot be converted to the type of the
844 // corresponding template-parameter then the program is
845 // ill-formed.
846 //
847 // -- for a non-type template-parameter of integral or
848 // enumeration type, integral promotions (4.5) and integral
849 // conversions (4.7) are applied.
850 QualType ParamType = Param->getType();
Douglas Gregor2eedd992009-02-11 00:19:33 +0000851 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000852 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000853 // C++ [temp.arg.nontype]p1:
854 // A template-argument for a non-type, non-template
855 // template-parameter shall be one of:
856 //
857 // -- an integral constant-expression of integral or enumeration
858 // type; or
859 // -- the name of a non-type template-parameter; or
860 SourceLocation NonConstantLoc;
861 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
862 Diag(Arg->getSourceRange().getBegin(),
863 diag::err_template_arg_not_integral_or_enumeral)
864 << ArgType << Arg->getSourceRange();
865 Diag(Param->getLocation(), diag::note_template_param_here);
866 return true;
867 } else if (!Arg->isValueDependent() &&
868 !Arg->isIntegerConstantExpr(Context, &NonConstantLoc)) {
869 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
870 << ArgType << Arg->getSourceRange();
871 return true;
872 }
873
874 // FIXME: We need some way to more easily get the unqualified form
875 // of the types without going all the way to the
876 // canonical type.
877 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
878 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
879 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
880 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
881
882 // Try to convert the argument to the parameter's type.
883 if (ParamType == ArgType) {
884 // Okay: no conversion necessary
885 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
886 !ParamType->isEnumeralType()) {
887 // This is an integral promotion or conversion.
888 ImpCastExprToType(Arg, ParamType);
889 } else {
890 // We can't perform this conversion.
891 Diag(Arg->getSourceRange().getBegin(),
892 diag::err_template_arg_not_convertible)
893 << Arg->getType() << Param->getType() << Arg->getSourceRange();
894 Diag(Param->getLocation(), diag::note_template_param_here);
895 return true;
896 }
897
898 return false;
899 }
Douglas Gregor2eedd992009-02-11 00:19:33 +0000900
Douglas Gregor3f411962009-02-11 01:18:59 +0000901 // Handle pointer-to-function, reference-to-function, and
902 // pointer-to-member-function all in (roughly) the same way.
903 if (// -- For a non-type template-parameter of type pointer to
904 // function, only the function-to-pointer conversion (4.3) is
905 // applied. If the template-argument represents a set of
906 // overloaded functions (or a pointer to such), the matching
907 // function is selected from the set (13.4).
908 (ParamType->isPointerType() &&
909 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
910 // -- For a non-type template-parameter of type reference to
911 // function, no conversions apply. If the template-argument
912 // represents a set of overloaded functions, the matching
913 // function is selected from the set (13.4).
914 (ParamType->isReferenceType() &&
915 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
916 // -- For a non-type template-parameter of type pointer to
917 // member function, no conversions apply. If the
918 // template-argument represents a set of overloaded member
919 // functions, the matching member function is selected from
920 // the set (13.4).
921 (ParamType->isMemberPointerType() &&
922 ParamType->getAsMemberPointerType()->getPointeeType()
923 ->isFunctionType())) {
Douglas Gregor0ea4e302009-02-11 18:22:40 +0000924 if (Context.hasSameUnqualifiedType(ArgType, ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +0000925 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +0000926 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +0000927 ArgType = Context.getPointerType(ArgType);
928 ImpCastExprToType(Arg, ArgType);
929 } else if (FunctionDecl *Fn
930 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
931 FixOverloadedFunctionReference(Arg, Fn);
932 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +0000933 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +0000934 ArgType = Context.getPointerType(Arg->getType());
935 ImpCastExprToType(Arg, ArgType);
936 }
937 }
938
Douglas Gregor0ea4e302009-02-11 18:22:40 +0000939 if (!Context.hasSameUnqualifiedType(ArgType, ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +0000940 // We can't perform this conversion.
941 Diag(Arg->getSourceRange().getBegin(),
942 diag::err_template_arg_not_convertible)
943 << Arg->getType() << Param->getType() << Arg->getSourceRange();
944 Diag(Param->getLocation(), diag::note_template_param_here);
945 return true;
946 }
947
948 // FIXME: Check the restrictions in p1!
949 return false;
950 }
951
Douglas Gregor3f411962009-02-11 01:18:59 +0000952 if (const PointerType *ParamPtrType = ParamType->getAsPointerType()) {
953 // -- for a non-type template-parameter of type pointer to
954 // object, qualification conversions (4.4) and the
955 // array-to-pointer conversion (4.2) are applied.
956 assert(ParamPtrType->getPointeeType()->isObjectType() &&
957 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +0000958
Douglas Gregor3f411962009-02-11 01:18:59 +0000959 if (ArgType->isArrayType()) {
960 ArgType = Context.getArrayDecayedType(ArgType);
961 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +0000962 }
Douglas Gregor3f411962009-02-11 01:18:59 +0000963
964 if (IsQualificationConversion(ArgType, ParamType)) {
965 ArgType = ParamType;
966 ImpCastExprToType(Arg, ParamType);
967 }
968
Douglas Gregor0ea4e302009-02-11 18:22:40 +0000969 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +0000970 // We can't perform this conversion.
971 Diag(Arg->getSourceRange().getBegin(),
972 diag::err_template_arg_not_convertible)
973 << Arg->getType() << Param->getType() << Arg->getSourceRange();
974 Diag(Param->getLocation(), diag::note_template_param_here);
975 return true;
976 }
977
978 // FIXME: Check the restrictions in p1!
979 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +0000980 }
Douglas Gregor3f411962009-02-11 01:18:59 +0000981
982 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
983 // -- For a non-type template-parameter of type reference to
984 // object, no conversions apply. The type referred to by the
985 // reference may be more cv-qualified than the (otherwise
986 // identical) type of the template-argument. The
987 // template-parameter is bound directly to the
988 // template-argument, which must be an lvalue.
989 assert(ParamRefType->getPointeeType()->isObjectType() &&
990 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +0000991
Douglas Gregor0ea4e302009-02-11 18:22:40 +0000992 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +0000993 Diag(Arg->getSourceRange().getBegin(),
994 diag::err_template_arg_no_ref_bind)
995 << Param->getType() << Arg->getType()
996 << Arg->getSourceRange();
997 Diag(Param->getLocation(), diag::note_template_param_here);
998 return true;
999 }
1000
1001 unsigned ParamQuals
1002 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1003 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1004
1005 if ((ParamQuals | ArgQuals) != ParamQuals) {
1006 Diag(Arg->getSourceRange().getBegin(),
1007 diag::err_template_arg_ref_bind_ignores_quals)
1008 << Param->getType() << Arg->getType()
1009 << Arg->getSourceRange();
1010 Diag(Param->getLocation(), diag::note_template_param_here);
1011 return true;
1012 }
1013
1014 // FIXME: Check the restrictions in p1!
1015 // CheckAddressConstantExpression(Lvalue) can be modified to do
1016 // this.
1017 return false;
1018 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001019
1020 // -- For a non-type template-parameter of type pointer to data
1021 // member, qualification conversions (4.4) are applied.
1022 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1023
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001024 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001025 // Types match exactly: nothing more to do here.
1026 } else if (IsQualificationConversion(ArgType, ParamType)) {
1027 ImpCastExprToType(Arg, ParamType);
1028 } else {
1029 // We can't perform this conversion.
1030 Diag(Arg->getSourceRange().getBegin(),
1031 diag::err_template_arg_not_convertible)
1032 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1033 Diag(Param->getLocation(), diag::note_template_param_here);
1034 return true;
1035 }
1036
1037 // FIXME: Check the restrictions in p1.
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001038
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001039 return false;
1040}
1041
1042/// \brief Check a template argument against its corresponding
1043/// template template parameter.
1044///
1045/// This routine implements the semantics of C++ [temp.arg.template].
1046/// It returns true if an error occurred, and false otherwise.
1047bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1048 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001049 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1050 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1051
1052 // C++ [temp.arg.template]p1:
1053 // A template-argument for a template template-parameter shall be
1054 // the name of a class template, expressed as id-expression. Only
1055 // primary class templates are considered when matching the
1056 // template template argument with the corresponding parameter;
1057 // partial specializations are not considered even if their
1058 // parameter lists match that of the template template parameter.
1059 if (!isa<ClassTemplateDecl>(Template)) {
1060 assert(isa<FunctionTemplateDecl>(Template) &&
1061 "Only function templates are possible here");
1062 Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here)
1063 << Template;
1064 }
1065
1066 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1067 Param->getTemplateParameters(),
1068 true, true,
1069 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001070}
1071
Douglas Gregord406b032009-02-06 22:42:48 +00001072/// \brief Determine whether the given template parameter lists are
1073/// equivalent.
1074///
1075/// \param New The new template parameter list, typically written in the
1076/// source code as part of a new template declaration.
1077///
1078/// \param Old The old template parameter list, typically found via
1079/// name lookup of the template declared with this template parameter
1080/// list.
1081///
1082/// \param Complain If true, this routine will produce a diagnostic if
1083/// the template parameter lists are not equivalent.
1084///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001085/// \param IsTemplateTemplateParm If true, this routine is being
1086/// called to compare the template parameter lists of a template
1087/// template parameter.
1088///
1089/// \param TemplateArgLoc If this source location is valid, then we
1090/// are actually checking the template parameter list of a template
1091/// argument (New) against the template parameter list of its
1092/// corresponding template template parameter (Old). We produce
1093/// slightly different diagnostics in this scenario.
1094///
Douglas Gregord406b032009-02-06 22:42:48 +00001095/// \returns True if the template parameter lists are equal, false
1096/// otherwise.
1097bool
1098Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1099 TemplateParameterList *Old,
1100 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001101 bool IsTemplateTemplateParm,
1102 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001103 if (Old->size() != New->size()) {
1104 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001105 unsigned NextDiag = diag::err_template_param_list_different_arity;
1106 if (TemplateArgLoc.isValid()) {
1107 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1108 NextDiag = diag::note_template_param_list_different_arity;
1109 }
1110 Diag(New->getTemplateLoc(), NextDiag)
1111 << (New->size() > Old->size())
1112 << IsTemplateTemplateParm
1113 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001114 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1115 << IsTemplateTemplateParm
1116 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1117 }
1118
1119 return false;
1120 }
1121
1122 for (TemplateParameterList::iterator OldParm = Old->begin(),
1123 OldParmEnd = Old->end(), NewParm = New->begin();
1124 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1125 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001126 unsigned NextDiag = diag::err_template_param_different_kind;
1127 if (TemplateArgLoc.isValid()) {
1128 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1129 NextDiag = diag::note_template_param_different_kind;
1130 }
1131 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001132 << IsTemplateTemplateParm;
1133 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1134 << IsTemplateTemplateParm;
1135 return false;
1136 }
1137
1138 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1139 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001140 // know we're at the same index).
1141#if 0
1142 // FIXME: Enable this code in debug mode *after* we properly go
1143 // through and "instantiate" the template parameter lists of
1144 // template template parameters. It's only after this
1145 // instantiation that (1) any dependent types within the
1146 // template parameter list of the template template parameter
1147 // can be checked, and (2) the template type parameter depths
1148 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001149 QualType OldParmType
1150 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1151 QualType NewParmType
1152 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1153 assert(Context.getCanonicalType(OldParmType) ==
1154 Context.getCanonicalType(NewParmType) &&
1155 "type parameter mismatch?");
1156#endif
1157 } else if (NonTypeTemplateParmDecl *OldNTTP
1158 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1159 // The types of non-type template parameters must agree.
1160 NonTypeTemplateParmDecl *NewNTTP
1161 = cast<NonTypeTemplateParmDecl>(*NewParm);
1162 if (Context.getCanonicalType(OldNTTP->getType()) !=
1163 Context.getCanonicalType(NewNTTP->getType())) {
1164 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001165 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1166 if (TemplateArgLoc.isValid()) {
1167 Diag(TemplateArgLoc,
1168 diag::err_template_arg_template_params_mismatch);
1169 NextDiag = diag::note_template_nontype_parm_different_type;
1170 }
1171 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001172 << NewNTTP->getType()
1173 << IsTemplateTemplateParm;
1174 Diag(OldNTTP->getLocation(),
1175 diag::note_template_nontype_parm_prev_declaration)
1176 << OldNTTP->getType();
1177 }
1178 return false;
1179 }
1180 } else {
1181 // The template parameter lists of template template
1182 // parameters must agree.
1183 // FIXME: Could we perform a faster "type" comparison here?
1184 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1185 "Only template template parameters handled here");
1186 TemplateTemplateParmDecl *OldTTP
1187 = cast<TemplateTemplateParmDecl>(*OldParm);
1188 TemplateTemplateParmDecl *NewTTP
1189 = cast<TemplateTemplateParmDecl>(*NewParm);
1190 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1191 OldTTP->getTemplateParameters(),
1192 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001193 /*IsTemplateTemplateParm=*/true,
1194 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001195 return false;
1196 }
1197 }
1198
1199 return true;
1200}
1201
1202/// \brief Check whether a template can be declared within this scope.
1203///
1204/// If the template declaration is valid in this scope, returns
1205/// false. Otherwise, issues a diagnostic and returns true.
1206bool
1207Sema::CheckTemplateDeclScope(Scope *S,
1208 MultiTemplateParamsArg &TemplateParameterLists) {
1209 assert(TemplateParameterLists.size() > 0 && "Not a template");
1210
1211 // Find the nearest enclosing declaration scope.
1212 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1213 (S->getFlags() & Scope::TemplateParamScope) != 0)
1214 S = S->getParent();
1215
1216 TemplateParameterList *TemplateParams =
1217 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1218 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1219 SourceRange TemplateRange
1220 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1221
1222 // C++ [temp]p2:
1223 // A template-declaration can appear only as a namespace scope or
1224 // class scope declaration.
1225 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1226 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1227 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1228 return Diag(TemplateLoc, diag::err_template_linkage)
1229 << TemplateRange;
1230
1231 Ctx = Ctx->getParent();
1232 }
1233
1234 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1235 return false;
1236
1237 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1238 << TemplateRange;
1239}