blob: c78d8876dae1f50dac0a7dd351066d40dd3cc36b [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
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000519 TemplateParameterList::iterator OldParam;
520 if (OldParams)
521 OldParam = OldParams->begin();
522
523 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
524 NewParamEnd = NewParams->end();
525 NewParam != NewParamEnd; ++NewParam) {
526 // Variables used to diagnose redundant default arguments
527 bool RedundantDefaultArg = false;
528 SourceLocation OldDefaultLoc;
529 SourceLocation NewDefaultLoc;
530
531 // Variables used to diagnose missing default arguments
532 bool MissingDefaultArg = false;
533
534 // Merge default arguments for template type parameters.
535 if (TemplateTypeParmDecl *NewTypeParm
536 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
537 TemplateTypeParmDecl *OldTypeParm
538 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
539
540 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
541 NewTypeParm->hasDefaultArgument()) {
542 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
543 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
544 SawDefaultArgument = true;
545 RedundantDefaultArg = true;
546 PreviousDefaultArgLoc = NewDefaultLoc;
547 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
548 // Merge the default argument from the old declaration to the
549 // new declaration.
550 SawDefaultArgument = true;
551 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
552 OldTypeParm->getDefaultArgumentLoc(),
553 true);
554 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
555 } else if (NewTypeParm->hasDefaultArgument()) {
556 SawDefaultArgument = true;
557 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
558 } else if (SawDefaultArgument)
559 MissingDefaultArg = true;
560 }
561 // Merge default arguments for non-type template parameters
562 else if (NonTypeTemplateParmDecl *NewNonTypeParm
563 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
564 NonTypeTemplateParmDecl *OldNonTypeParm
565 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
566 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
567 NewNonTypeParm->hasDefaultArgument()) {
568 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
569 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
570 SawDefaultArgument = true;
571 RedundantDefaultArg = true;
572 PreviousDefaultArgLoc = NewDefaultLoc;
573 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
574 // Merge the default argument from the old declaration to the
575 // new declaration.
576 SawDefaultArgument = true;
577 // FIXME: We need to create a new kind of "default argument"
578 // expression that points to a previous template template
579 // parameter.
580 NewNonTypeParm->setDefaultArgument(
581 OldNonTypeParm->getDefaultArgument());
582 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
583 } else if (NewNonTypeParm->hasDefaultArgument()) {
584 SawDefaultArgument = true;
585 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
586 } else if (SawDefaultArgument)
587 MissingDefaultArg = true;
588 }
589 // Merge default arguments for template template parameters
590 else {
591 TemplateTemplateParmDecl *NewTemplateParm
592 = cast<TemplateTemplateParmDecl>(*NewParam);
593 TemplateTemplateParmDecl *OldTemplateParm
594 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
595 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
596 NewTemplateParm->hasDefaultArgument()) {
597 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
598 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
599 SawDefaultArgument = true;
600 RedundantDefaultArg = true;
601 PreviousDefaultArgLoc = NewDefaultLoc;
602 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
603 // Merge the default argument from the old declaration to the
604 // new declaration.
605 SawDefaultArgument = true;
606 // FIXME: We need to create a new kind of "default argument"
607 // expression that points to a previous template template
608 // parameter.
609 NewTemplateParm->setDefaultArgument(
610 OldTemplateParm->getDefaultArgument());
611 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
612 } else if (NewTemplateParm->hasDefaultArgument()) {
613 SawDefaultArgument = true;
614 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
615 } else if (SawDefaultArgument)
616 MissingDefaultArg = true;
617 }
618
619 if (RedundantDefaultArg) {
620 // C++ [temp.param]p12:
621 // A template-parameter shall not be given default arguments
622 // by two different declarations in the same scope.
623 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
624 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
625 Invalid = true;
626 } else if (MissingDefaultArg) {
627 // C++ [temp.param]p11:
628 // If a template-parameter has a default template-argument,
629 // all subsequent template-parameters shall have a default
630 // template-argument supplied.
631 Diag((*NewParam)->getLocation(),
632 diag::err_template_param_default_arg_missing);
633 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
634 Invalid = true;
635 }
636
637 // If we have an old template parameter list that we're merging
638 // in, move on to the next parameter.
639 if (OldParams)
640 ++OldParam;
641 }
642
643 return Invalid;
644}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000645
Douglas Gregor8e458f42009-02-09 18:46:07 +0000646Action::TypeTy *
647Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000648 SourceLocation TemplateLoc,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000649 SourceLocation LAngleLoc,
Douglas Gregor6f37b582009-02-09 19:34:22 +0000650 ASTTemplateArgsPtr TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000651 SourceLocation *TemplateArgLocs,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000652 SourceLocation RAngleLoc,
653 const CXXScopeSpec *SS) {
654 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
655
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000656 // Check that the template argument list is well-formed for this
657 // template.
658 if (!CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
659 TemplateArgs, TemplateArgLocs, RAngleLoc))
660 return 0;
661
Douglas Gregor8e458f42009-02-09 18:46:07 +0000662 // Yes, all class template specializations are just silly sugar for
663 // 'int'. Gotta problem wit dat?
Douglas Gregor6f37b582009-02-09 19:34:22 +0000664 QualType Result
665 = Context.getClassTemplateSpecializationType(Template,
666 TemplateArgs.size(),
667 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
668 TemplateArgs.getArgIsType(),
669 Context.IntTy);
670 TemplateArgs.release();
671 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000672}
673
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000674/// \brief Check that the given template argument list is well-formed
675/// for specializing the given template.
676bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
677 SourceLocation TemplateLoc,
678 SourceLocation LAngleLoc,
679 ASTTemplateArgsPtr& Args,
680 SourceLocation *TemplateArgLocs,
681 SourceLocation RAngleLoc) {
682 TemplateParameterList *Params = Template->getTemplateParameters();
683 unsigned NumParams = Params->size();
684 unsigned NumArgs = Args.size();
685 bool Invalid = false;
686
687 if (NumArgs > NumParams ||
688 NumArgs < NumParams /*FIXME: default arguments! */) {
689 // FIXME: point at either the first arg beyond what we can handle,
690 // or the '>', depending on whether we have too many or too few
691 // arguments.
692 SourceRange Range;
693 if (NumArgs > NumParams)
694 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
695 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
696 << (NumArgs > NumParams)
697 << (isa<ClassTemplateDecl>(Template)? 0 :
698 isa<FunctionTemplateDecl>(Template)? 1 :
699 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
700 << Template << Range;
701
702 Invalid = true;
703 }
704
705 // C++ [temp.arg]p1:
706 // [...] The type and form of each template-argument specified in
707 // a template-id shall match the type and form specified for the
708 // corresponding parameter declared by the template in its
709 // template-parameter-list.
710 unsigned ArgIdx = 0;
711 for (TemplateParameterList::iterator Param = Params->begin(),
712 ParamEnd = Params->end();
713 Param != ParamEnd; ++Param, ++ArgIdx) {
714 // Decode the template argument
715 QualType ArgType;
716 Expr *ArgExpr = 0;
717 SourceLocation ArgLoc;
718 if (ArgIdx >= NumArgs) {
719 // FIXME: Get the default argument here, which might
720 // (eventually) require instantiation.
721 break;
722 } else
723 ArgLoc = TemplateArgLocs[ArgIdx];
724
725 if (Args.getArgIsType()[ArgIdx])
726 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
727 else
728 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
729
730 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
731 // Check template type parameters.
732 if (!ArgType.isNull()) {
733 if (!CheckTemplateArgument(TTP, ArgType, ArgLoc))
734 Invalid = true;
735 continue;
736 }
737
738 // C++ [temp.arg.type]p1:
739 // A template-argument for a template-parameter which is a
740 // type shall be a type-id.
741
742 // We have a template type parameter but the template argument
743 // is an expression.
744 Diag(ArgExpr->getSourceRange().getBegin(),
745 diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000746 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000747 Invalid = true;
748 } else if (NonTypeTemplateParmDecl *NTTP
749 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
750 // Check non-type template parameters.
751 if (ArgExpr) {
752 if (!CheckTemplateArgument(NTTP, ArgExpr))
753 Invalid = true;
754 continue;
755 }
756
757 // We have a non-type template parameter but the template
758 // argument is a type.
759
760 // C++ [temp.arg]p2:
761 // In a template-argument, an ambiguity between a type-id and
762 // an expression is resolved to a type-id, regardless of the
763 // form of the corresponding template-parameter.
764 //
765 // We warn specifically about this case, since it can be rather
766 // confusing for users.
767 if (ArgType->isFunctionType())
768 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
769 << ArgType;
770 else
771 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor341ac792009-02-10 00:53:15 +0000772 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000773 Invalid = true;
774 } else {
775 // Check template template parameters.
776 TemplateTemplateParmDecl *TempParm
777 = cast<TemplateTemplateParmDecl>(*Param);
778
779 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
780 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
781 if (!CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
782 Invalid = true;
783 continue;
784 }
785
786 // We have a template template parameter but the template
787 // argument does not refer to a template.
788 Diag(ArgLoc, diag::err_template_arg_must_be_template);
789 Invalid = true;
790 }
791 }
792
793 return Invalid;
794}
795
796/// \brief Check a template argument against its corresponding
797/// template type parameter.
798///
799/// This routine implements the semantics of C++ [temp.arg.type]. It
800/// returns true if an error occurred, and false otherwise.
801bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
802 QualType Arg, SourceLocation ArgLoc) {
803 // C++ [temp.arg.type]p2:
804 // A local type, a type with no linkage, an unnamed type or a type
805 // compounded from any of these types shall not be used as a
806 // template-argument for a template type-parameter.
807 //
808 // FIXME: Perform the recursive and no-linkage type checks.
809 const TagType *Tag = 0;
810 if (const EnumType *EnumT = Arg->getAsEnumType())
811 Tag = EnumT;
812 else if (const RecordType *RecordT = Arg->getAsRecordType())
813 Tag = RecordT;
814 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
815 return Diag(ArgLoc, diag::err_template_arg_local_type)
816 << QualType(Tag, 0);
817 else if (Tag && !Tag->getDecl()->getDeclName()) {
818 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
819 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
820 return true;
821 }
822
823 return false;
824}
825
826/// \brief Check a template argument against its corresponding
827/// non-type template parameter.
828///
829/// This routine implements the semantics of C++ [temp.arg.nontype].
830/// It returns true if an error occurred, and false otherwise.
831bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000832 Expr *&Arg) {
833 // If either the parameter has a dependent type or the argument is
834 // type-dependent, there's nothing we can check now.
835 if (Param->getType()->isDependentType() || Arg->isTypeDependent())
836 return false;
837
838 // C++ [temp.arg.nontype]p5:
839 // The following conversions are performed on each expression used
840 // as a non-type template-argument. If a non-type
841 // template-argument cannot be converted to the type of the
842 // corresponding template-parameter then the program is
843 // ill-formed.
844 //
845 // -- for a non-type template-parameter of integral or
846 // enumeration type, integral promotions (4.5) and integral
847 // conversions (4.7) are applied.
848 QualType ParamType = Param->getType();
Douglas Gregor2eedd992009-02-11 00:19:33 +0000849 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000850 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000851 // C++ [temp.arg.nontype]p1:
852 // A template-argument for a non-type, non-template
853 // template-parameter shall be one of:
854 //
855 // -- an integral constant-expression of integral or enumeration
856 // type; or
857 // -- the name of a non-type template-parameter; or
858 SourceLocation NonConstantLoc;
859 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
860 Diag(Arg->getSourceRange().getBegin(),
861 diag::err_template_arg_not_integral_or_enumeral)
862 << ArgType << Arg->getSourceRange();
863 Diag(Param->getLocation(), diag::note_template_param_here);
864 return true;
865 } else if (!Arg->isValueDependent() &&
866 !Arg->isIntegerConstantExpr(Context, &NonConstantLoc)) {
867 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
868 << ArgType << Arg->getSourceRange();
869 return true;
870 }
871
872 // FIXME: We need some way to more easily get the unqualified form
873 // of the types without going all the way to the
874 // canonical type.
875 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
876 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
877 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
878 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
879
880 // Try to convert the argument to the parameter's type.
881 if (ParamType == ArgType) {
882 // Okay: no conversion necessary
883 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
884 !ParamType->isEnumeralType()) {
885 // This is an integral promotion or conversion.
886 ImpCastExprToType(Arg, ParamType);
887 } else {
888 // We can't perform this conversion.
889 Diag(Arg->getSourceRange().getBegin(),
890 diag::err_template_arg_not_convertible)
891 << Arg->getType() << Param->getType() << Arg->getSourceRange();
892 Diag(Param->getLocation(), diag::note_template_param_here);
893 return true;
894 }
895
896 return false;
897 }
Douglas Gregor2eedd992009-02-11 00:19:33 +0000898
899 if (const PointerType *ParamPtrType = ParamType->getAsPointerType()) {
900 // -- for a non-type template-parameter of type pointer to
901 // object, qualification conversions (4.4) and the
902 // array-to-pointer conversion (4.2) are applied.
903 if (ParamPtrType->getPointeeType()->isObjectType()) {
904 if (ArgType->isArrayType()) {
905 ArgType = Context.getArrayDecayedType(ArgType);
906 ImpCastExprToType(Arg, ArgType);
907 }
908
909 if (IsQualificationConversion(ArgType, ParamType)) {
910 ArgType = ParamType;
911 ImpCastExprToType(Arg, ParamType);
912 }
913
914 if (!hasSameUnqualifiedType(ArgType, ParamType)) {
915 // We can't perform this conversion.
916 Diag(Arg->getSourceRange().getBegin(),
917 diag::err_template_arg_not_convertible)
918 << Arg->getType() << Param->getType() << Arg->getSourceRange();
919 Diag(Param->getLocation(), diag::note_template_param_here);
920 return true;
921 }
922
923 // FIXME: Check the restrictions in p1!
924 return false;
925 }
926
927 assert(ParamPtrType->getPointeeType()->isFunctionType() &&
928 "Only function pointers remain");
929 // -- For a non-type template-parameter of type pointer to
930 // function, only the function-to-pointer conversion (4.3) is
931 // applied. If the template-argument represents a set of
932 // overloaded functions (or a pointer to such), the matching
933 // function is selected from the set (13.4).
934 if (hasSameUnqualifiedType(ArgType, ParamType)) {
935 // We don't have to do anything: the types already match.
936 }
937 else if (ArgType->isFunctionType()) {
938 ArgType = Context.getPointerType(ArgType);
939 ImpCastExprToType(Arg, ArgType);
940 } else if (FunctionDecl *Fn
941 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
942 FixOverloadedFunctionReference(Arg, Fn);
943 ArgType = Arg->getType();
944 if (ArgType->isFunctionType()) {
945 ArgType = Context.getPointerType(Arg->getType());
946 ImpCastExprToType(Arg, ArgType);
947 }
948 }
949
950 if (!hasSameUnqualifiedType(ArgType, ParamType)) {
951 // We can't perform this conversion.
952 Diag(Arg->getSourceRange().getBegin(),
953 diag::err_template_arg_not_convertible)
954 << Arg->getType() << Param->getType() << Arg->getSourceRange();
955 Diag(Param->getLocation(), diag::note_template_param_here);
956 return true;
957 }
958
959 // FIXME: Check the restrictions in p1!
960 return false;
961 }
962
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000963 // FIXME: p5 has a lot more checks to perform!
964
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000965 return false;
966}
967
968/// \brief Check a template argument against its corresponding
969/// template template parameter.
970///
971/// This routine implements the semantics of C++ [temp.arg.template].
972/// It returns true if an error occurred, and false otherwise.
973bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
974 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +0000975 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
976 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
977
978 // C++ [temp.arg.template]p1:
979 // A template-argument for a template template-parameter shall be
980 // the name of a class template, expressed as id-expression. Only
981 // primary class templates are considered when matching the
982 // template template argument with the corresponding parameter;
983 // partial specializations are not considered even if their
984 // parameter lists match that of the template template parameter.
985 if (!isa<ClassTemplateDecl>(Template)) {
986 assert(isa<FunctionTemplateDecl>(Template) &&
987 "Only function templates are possible here");
988 Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here)
989 << Template;
990 }
991
992 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
993 Param->getTemplateParameters(),
994 true, true,
995 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000996}
997
Douglas Gregord406b032009-02-06 22:42:48 +0000998/// \brief Determine whether the given template parameter lists are
999/// equivalent.
1000///
1001/// \param New The new template parameter list, typically written in the
1002/// source code as part of a new template declaration.
1003///
1004/// \param Old The old template parameter list, typically found via
1005/// name lookup of the template declared with this template parameter
1006/// list.
1007///
1008/// \param Complain If true, this routine will produce a diagnostic if
1009/// the template parameter lists are not equivalent.
1010///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001011/// \param IsTemplateTemplateParm If true, this routine is being
1012/// called to compare the template parameter lists of a template
1013/// template parameter.
1014///
1015/// \param TemplateArgLoc If this source location is valid, then we
1016/// are actually checking the template parameter list of a template
1017/// argument (New) against the template parameter list of its
1018/// corresponding template template parameter (Old). We produce
1019/// slightly different diagnostics in this scenario.
1020///
Douglas Gregord406b032009-02-06 22:42:48 +00001021/// \returns True if the template parameter lists are equal, false
1022/// otherwise.
1023bool
1024Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1025 TemplateParameterList *Old,
1026 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001027 bool IsTemplateTemplateParm,
1028 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001029 if (Old->size() != New->size()) {
1030 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001031 unsigned NextDiag = diag::err_template_param_list_different_arity;
1032 if (TemplateArgLoc.isValid()) {
1033 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1034 NextDiag = diag::note_template_param_list_different_arity;
1035 }
1036 Diag(New->getTemplateLoc(), NextDiag)
1037 << (New->size() > Old->size())
1038 << IsTemplateTemplateParm
1039 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001040 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1041 << IsTemplateTemplateParm
1042 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1043 }
1044
1045 return false;
1046 }
1047
1048 for (TemplateParameterList::iterator OldParm = Old->begin(),
1049 OldParmEnd = Old->end(), NewParm = New->begin();
1050 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1051 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001052 unsigned NextDiag = diag::err_template_param_different_kind;
1053 if (TemplateArgLoc.isValid()) {
1054 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1055 NextDiag = diag::note_template_param_different_kind;
1056 }
1057 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001058 << IsTemplateTemplateParm;
1059 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1060 << IsTemplateTemplateParm;
1061 return false;
1062 }
1063
1064 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1065 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001066 // know we're at the same index).
1067#if 0
1068 // FIXME: Enable this code in debug mode *after* we properly go
1069 // through and "instantiate" the template parameter lists of
1070 // template template parameters. It's only after this
1071 // instantiation that (1) any dependent types within the
1072 // template parameter list of the template template parameter
1073 // can be checked, and (2) the template type parameter depths
1074 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001075 QualType OldParmType
1076 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1077 QualType NewParmType
1078 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1079 assert(Context.getCanonicalType(OldParmType) ==
1080 Context.getCanonicalType(NewParmType) &&
1081 "type parameter mismatch?");
1082#endif
1083 } else if (NonTypeTemplateParmDecl *OldNTTP
1084 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1085 // The types of non-type template parameters must agree.
1086 NonTypeTemplateParmDecl *NewNTTP
1087 = cast<NonTypeTemplateParmDecl>(*NewParm);
1088 if (Context.getCanonicalType(OldNTTP->getType()) !=
1089 Context.getCanonicalType(NewNTTP->getType())) {
1090 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001091 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1092 if (TemplateArgLoc.isValid()) {
1093 Diag(TemplateArgLoc,
1094 diag::err_template_arg_template_params_mismatch);
1095 NextDiag = diag::note_template_nontype_parm_different_type;
1096 }
1097 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001098 << NewNTTP->getType()
1099 << IsTemplateTemplateParm;
1100 Diag(OldNTTP->getLocation(),
1101 diag::note_template_nontype_parm_prev_declaration)
1102 << OldNTTP->getType();
1103 }
1104 return false;
1105 }
1106 } else {
1107 // The template parameter lists of template template
1108 // parameters must agree.
1109 // FIXME: Could we perform a faster "type" comparison here?
1110 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1111 "Only template template parameters handled here");
1112 TemplateTemplateParmDecl *OldTTP
1113 = cast<TemplateTemplateParmDecl>(*OldParm);
1114 TemplateTemplateParmDecl *NewTTP
1115 = cast<TemplateTemplateParmDecl>(*NewParm);
1116 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1117 OldTTP->getTemplateParameters(),
1118 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001119 /*IsTemplateTemplateParm=*/true,
1120 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001121 return false;
1122 }
1123 }
1124
1125 return true;
1126}
1127
1128/// \brief Check whether a template can be declared within this scope.
1129///
1130/// If the template declaration is valid in this scope, returns
1131/// false. Otherwise, issues a diagnostic and returns true.
1132bool
1133Sema::CheckTemplateDeclScope(Scope *S,
1134 MultiTemplateParamsArg &TemplateParameterLists) {
1135 assert(TemplateParameterLists.size() > 0 && "Not a template");
1136
1137 // Find the nearest enclosing declaration scope.
1138 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1139 (S->getFlags() & Scope::TemplateParamScope) != 0)
1140 S = S->getParent();
1141
1142 TemplateParameterList *TemplateParams =
1143 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1144 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1145 SourceRange TemplateRange
1146 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1147
1148 // C++ [temp]p2:
1149 // A template-declaration can appear only as a namespace scope or
1150 // class scope declaration.
1151 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1152 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1153 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1154 return Diag(TemplateLoc, diag::err_template_linkage)
1155 << TemplateRange;
1156
1157 Ctx = Ctx->getParent();
1158 }
1159
1160 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1161 return false;
1162
1163 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1164 << TemplateRange;
1165}