blob: 7aab4a585e099e08d05437898833ca6d832e73eb [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,
195 T->isPointerType() ||
196 // -- reference to object or reference to function,
197 T->isReferenceType() ||
198 // -- pointer to member.
199 T->isMemberPointerType() ||
200 // If T is a dependent type, we can't do the check now, so we
201 // assume that it is well-formed.
202 T->isDependentType()) {
203 // Okay: The template parameter is well-formed.
204 }
205 // C++ [temp.param]p8:
206 //
207 // A non-type template-parameter of type "array of T" or
208 // "function returning T" is adjusted to be of type "pointer to
209 // T" or "pointer to function returning T", respectively.
210 else if (T->isArrayType())
211 // FIXME: Keep the type prior to promotion?
212 T = Context.getArrayDecayedType(T);
213 else if (T->isFunctionType())
214 // FIXME: Keep the type prior to promotion?
215 T = Context.getPointerType(T);
216 else {
217 Diag(D.getIdentifierLoc(), diag::err_template_nontype_parm_bad_type)
218 << T;
219 return 0;
220 }
221
Douglas Gregordd861062008-12-05 18:15:24 +0000222 NonTypeTemplateParmDecl *Param
223 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000224 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000225 if (Invalid)
226 Param->setInvalidDecl();
227
228 if (D.getIdentifier()) {
229 // Add the template parameter into the current scope.
230 S->AddDecl(Param);
231 IdResolver.AddDecl(Param);
232 }
233 return Param;
234}
Douglas Gregor52473432008-12-24 02:52:09 +0000235
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000236/// \brief Adds a default argument to the given non-type template
237/// parameter.
238void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
239 SourceLocation EqualLoc,
240 ExprArg DefaultE) {
241 NonTypeTemplateParmDecl *TemplateParm
242 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
243 Expr *Default = static_cast<Expr *>(DefaultE.get());
244
245 // C++ [temp.param]p14:
246 // A template-parameter shall not be used in its own default argument.
247 // FIXME: Implement this check! Needs a recursive walk over the types.
248
249 // Check the well-formedness of the default template argument.
250 if (CheckTemplateArgument(TemplateParm, Default)) {
251 TemplateParm->setInvalidDecl();
252 return;
253 }
254
255 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
256}
257
Douglas Gregor279272e2009-02-04 19:02:06 +0000258
259/// ActOnTemplateTemplateParameter - Called when a C++ template template
260/// parameter (e.g. T in template <template <typename> class T> class array)
261/// has been parsed. S is the current scope.
262Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
263 SourceLocation TmpLoc,
264 TemplateParamsTy *Params,
265 IdentifierInfo *Name,
266 SourceLocation NameLoc,
267 unsigned Depth,
268 unsigned Position)
269{
270 assert(S->isTemplateParamScope() &&
271 "Template template parameter not in template parameter scope!");
272
273 // Construct the parameter object.
274 TemplateTemplateParmDecl *Param =
275 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
276 Position, Name,
277 (TemplateParameterList*)Params);
278
279 // Make sure the parameter is valid.
280 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
281 // do anything yet. However, if the template parameter list or (eventual)
282 // default value is ever invalidated, that will propagate here.
283 bool Invalid = false;
284 if (Invalid) {
285 Param->setInvalidDecl();
286 }
287
288 // If the tt-param has a name, then link the identifier into the scope
289 // and lookup mechanisms.
290 if (Name) {
291 S->AddDecl(Param);
292 IdResolver.AddDecl(Param);
293 }
294
295 return Param;
296}
297
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000298/// \brief Adds a default argument to the given template template
299/// parameter.
300void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
301 SourceLocation EqualLoc,
302 ExprArg DefaultE) {
303 TemplateTemplateParmDecl *TemplateParm
304 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
305
306 // Since a template-template parameter's default argument is an
307 // id-expression, it must be a DeclRefExpr.
308 DeclRefExpr *Default
309 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
310
311 // C++ [temp.param]p14:
312 // A template-parameter shall not be used in its own default argument.
313 // FIXME: Implement this check! Needs a recursive walk over the types.
314
315 // Check the well-formedness of the template argument.
316 if (!isa<TemplateDecl>(Default->getDecl())) {
317 Diag(Default->getSourceRange().getBegin(),
318 diag::err_template_arg_must_be_template)
319 << Default->getSourceRange();
320 TemplateParm->setInvalidDecl();
321 return;
322 }
323 if (CheckTemplateArgument(TemplateParm, Default)) {
324 TemplateParm->setInvalidDecl();
325 return;
326 }
327
328 DefaultE.release();
329 TemplateParm->setDefaultArgument(Default);
330}
331
Douglas Gregor52473432008-12-24 02:52:09 +0000332/// ActOnTemplateParameterList - Builds a TemplateParameterList that
333/// contains the template parameters in Params/NumParams.
334Sema::TemplateParamsTy *
335Sema::ActOnTemplateParameterList(unsigned Depth,
336 SourceLocation ExportLoc,
337 SourceLocation TemplateLoc,
338 SourceLocation LAngleLoc,
339 DeclTy **Params, unsigned NumParams,
340 SourceLocation RAngleLoc) {
341 if (ExportLoc.isValid())
342 Diag(ExportLoc, diag::note_template_export_unsupported);
343
Douglas Gregord406b032009-02-06 22:42:48 +0000344 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
345 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000346}
Douglas Gregor279272e2009-02-04 19:02:06 +0000347
Douglas Gregord406b032009-02-06 22:42:48 +0000348Sema::DeclTy *
349Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
350 SourceLocation KWLoc, const CXXScopeSpec &SS,
351 IdentifierInfo *Name, SourceLocation NameLoc,
352 AttributeList *Attr,
353 MultiTemplateParamsArg TemplateParameterLists) {
354 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
355 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000356 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000357
358 // Check that we can declare a template here.
359 if (CheckTemplateDeclScope(S, TemplateParameterLists))
360 return 0;
361
362 TagDecl::TagKind Kind;
363 switch (TagSpec) {
364 default: assert(0 && "Unknown tag type!");
365 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
366 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
367 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
368 }
369
370 // There is no such thing as an unnamed class template.
371 if (!Name) {
372 Diag(KWLoc, diag::err_template_unnamed_class);
373 return 0;
374 }
375
376 // Find any previous declaration with this name.
377 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
378 true);
379 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
380 NamedDecl *PrevDecl = 0;
381 if (Previous.begin() != Previous.end())
382 PrevDecl = *Previous.begin();
383
384 DeclContext *SemanticContext = CurContext;
385 if (SS.isNotEmpty() && !SS.isInvalid()) {
386 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
387
388 // FIXME: need to match up several levels of template parameter
389 // lists here.
390 }
391
392 // FIXME: member templates!
393 TemplateParameterList *TemplateParams
394 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
395
396 // If there is a previous declaration with the same name, check
397 // whether this is a valid redeclaration.
398 ClassTemplateDecl *PrevClassTemplate
399 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
400 if (PrevClassTemplate) {
401 // Ensure that the template parameter lists are compatible.
402 if (!TemplateParameterListsAreEqual(TemplateParams,
403 PrevClassTemplate->getTemplateParameters(),
404 /*Complain=*/true))
405 return 0;
406
407 // C++ [temp.class]p4:
408 // In a redeclaration, partial specialization, explicit
409 // specialization or explicit instantiation of a class template,
410 // the class-key shall agree in kind with the original class
411 // template declaration (7.1.5.3).
412 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
413 if (PrevRecordDecl->getTagKind() != Kind) {
414 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
415 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
416 return 0;
417 }
418
419
420 // Check for redefinition of this class template.
421 if (TK == TK_Definition) {
422 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
423 Diag(NameLoc, diag::err_redefinition) << Name;
424 Diag(Def->getLocation(), diag::note_previous_definition);
425 // FIXME: Would it make sense to try to "forget" the previous
426 // definition, as part of error recovery?
427 return 0;
428 }
429 }
430 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
431 // Maybe we will complain about the shadowed template parameter.
432 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
433 // Just pretend that we didn't see the previous declaration.
434 PrevDecl = 0;
435 } else if (PrevDecl) {
436 // C++ [temp]p5:
437 // A class template shall not have the same name as any other
438 // template, class, function, object, enumeration, enumerator,
439 // namespace, or type in the same scope (3.3), except as specified
440 // in (14.5.4).
441 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
442 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
443 return 0;
444 }
445
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000446 // Check the template parameter list of this declaration, possibly
447 // merging in the template parameter list from the previous class
448 // template declaration.
449 if (CheckTemplateParameterList(TemplateParams,
450 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
451 Invalid = true;
452
Douglas Gregord406b032009-02-06 22:42:48 +0000453 // If we had a scope specifier, we better have a previous template
454 // declaration!
455
456 TagDecl *NewClass =
457 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
458 PrevClassTemplate?
459 PrevClassTemplate->getTemplatedDecl() : 0);
460
461 ClassTemplateDecl *NewTemplate
462 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
463 DeclarationName(Name), TemplateParams,
464 NewClass);
465
466 // Set the lexical context of these templates
467 NewClass->setLexicalDeclContext(CurContext);
468 NewTemplate->setLexicalDeclContext(CurContext);
469
470 if (TK == TK_Definition)
471 NewClass->startDefinition();
472
473 if (Attr)
474 ProcessDeclAttributeList(NewClass, Attr);
475
476 PushOnScopeChains(NewTemplate, S);
477
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000478 if (Invalid) {
479 NewTemplate->setInvalidDecl();
480 NewClass->setInvalidDecl();
481 }
Douglas Gregord406b032009-02-06 22:42:48 +0000482 return NewTemplate;
483}
484
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000485/// \brief Checks the validity of a template parameter list, possibly
486/// considering the template parameter list from a previous
487/// declaration.
488///
489/// If an "old" template parameter list is provided, it must be
490/// equivalent (per TemplateParameterListsAreEqual) to the "new"
491/// template parameter list.
492///
493/// \param NewParams Template parameter list for a new template
494/// declaration. This template parameter list will be updated with any
495/// default arguments that are carried through from the previous
496/// template parameter list.
497///
498/// \param OldParams If provided, template parameter list from a
499/// previous declaration of the same template. Default template
500/// arguments will be merged from the old template parameter list to
501/// the new template parameter list.
502///
503/// \returns true if an error occurred, false otherwise.
504bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
505 TemplateParameterList *OldParams) {
506 bool Invalid = false;
507
508 // C++ [temp.param]p10:
509 // The set of default template-arguments available for use with a
510 // template declaration or definition is obtained by merging the
511 // default arguments from the definition (if in scope) and all
512 // declarations in scope in the same way default function
513 // arguments are (8.3.6).
514 bool SawDefaultArgument = false;
515 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000516
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000517 TemplateParameterList::iterator OldParam;
518 if (OldParams)
519 OldParam = OldParams->begin();
520
521 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
522 NewParamEnd = NewParams->end();
523 NewParam != NewParamEnd; ++NewParam) {
524 // Variables used to diagnose redundant default arguments
525 bool RedundantDefaultArg = false;
526 SourceLocation OldDefaultLoc;
527 SourceLocation NewDefaultLoc;
528
529 // Variables used to diagnose missing default arguments
530 bool MissingDefaultArg = false;
531
532 // Merge default arguments for template type parameters.
533 if (TemplateTypeParmDecl *NewTypeParm
534 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
535 TemplateTypeParmDecl *OldTypeParm
536 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
537
538 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
539 NewTypeParm->hasDefaultArgument()) {
540 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
541 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
542 SawDefaultArgument = true;
543 RedundantDefaultArg = true;
544 PreviousDefaultArgLoc = NewDefaultLoc;
545 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
546 // Merge the default argument from the old declaration to the
547 // new declaration.
548 SawDefaultArgument = true;
549 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
550 OldTypeParm->getDefaultArgumentLoc(),
551 true);
552 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
553 } else if (NewTypeParm->hasDefaultArgument()) {
554 SawDefaultArgument = true;
555 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
556 } else if (SawDefaultArgument)
557 MissingDefaultArg = true;
558 }
559 // Merge default arguments for non-type template parameters
560 else if (NonTypeTemplateParmDecl *NewNonTypeParm
561 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
562 NonTypeTemplateParmDecl *OldNonTypeParm
563 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
564 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
565 NewNonTypeParm->hasDefaultArgument()) {
566 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
567 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
568 SawDefaultArgument = true;
569 RedundantDefaultArg = true;
570 PreviousDefaultArgLoc = NewDefaultLoc;
571 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
572 // Merge the default argument from the old declaration to the
573 // new declaration.
574 SawDefaultArgument = true;
575 // FIXME: We need to create a new kind of "default argument"
576 // expression that points to a previous template template
577 // parameter.
578 NewNonTypeParm->setDefaultArgument(
579 OldNonTypeParm->getDefaultArgument());
580 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
581 } else if (NewNonTypeParm->hasDefaultArgument()) {
582 SawDefaultArgument = true;
583 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
584 } else if (SawDefaultArgument)
585 MissingDefaultArg = true;
586 }
587 // Merge default arguments for template template parameters
588 else {
589 TemplateTemplateParmDecl *NewTemplateParm
590 = cast<TemplateTemplateParmDecl>(*NewParam);
591 TemplateTemplateParmDecl *OldTemplateParm
592 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
593 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
594 NewTemplateParm->hasDefaultArgument()) {
595 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
596 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
597 SawDefaultArgument = true;
598 RedundantDefaultArg = true;
599 PreviousDefaultArgLoc = NewDefaultLoc;
600 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
601 // Merge the default argument from the old declaration to the
602 // new declaration.
603 SawDefaultArgument = true;
604 // FIXME: We need to create a new kind of "default argument"
605 // expression that points to a previous template template
606 // parameter.
607 NewTemplateParm->setDefaultArgument(
608 OldTemplateParm->getDefaultArgument());
609 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
610 } else if (NewTemplateParm->hasDefaultArgument()) {
611 SawDefaultArgument = true;
612 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
613 } else if (SawDefaultArgument)
614 MissingDefaultArg = true;
615 }
616
617 if (RedundantDefaultArg) {
618 // C++ [temp.param]p12:
619 // A template-parameter shall not be given default arguments
620 // by two different declarations in the same scope.
621 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
622 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
623 Invalid = true;
624 } else if (MissingDefaultArg) {
625 // C++ [temp.param]p11:
626 // If a template-parameter has a default template-argument,
627 // all subsequent template-parameters shall have a default
628 // template-argument supplied.
629 Diag((*NewParam)->getLocation(),
630 diag::err_template_param_default_arg_missing);
631 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
632 Invalid = true;
633 }
634
635 // If we have an old template parameter list that we're merging
636 // in, move on to the next parameter.
637 if (OldParams)
638 ++OldParam;
639 }
640
641 return Invalid;
642}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000643
Douglas Gregor8e458f42009-02-09 18:46:07 +0000644Action::TypeTy *
645Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000646 SourceLocation TemplateLoc,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000647 SourceLocation LAngleLoc,
Douglas Gregor6f37b582009-02-09 19:34:22 +0000648 ASTTemplateArgsPtr TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000649 SourceLocation *TemplateArgLocs,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000650 SourceLocation RAngleLoc,
651 const CXXScopeSpec *SS) {
652 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
653
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000654 // Check that the template argument list is well-formed for this
655 // template.
656 if (!CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
657 TemplateArgs, TemplateArgLocs, RAngleLoc))
658 return 0;
659
Douglas Gregor8e458f42009-02-09 18:46:07 +0000660 // Yes, all class template specializations are just silly sugar for
661 // 'int'. Gotta problem wit dat?
Douglas Gregor6f37b582009-02-09 19:34:22 +0000662 QualType Result
663 = Context.getClassTemplateSpecializationType(Template,
664 TemplateArgs.size(),
665 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
666 TemplateArgs.getArgIsType(),
667 Context.IntTy);
668 TemplateArgs.release();
669 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000670}
671
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000672/// \brief Check that the given template argument list is well-formed
673/// for specializing the given template.
674bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
675 SourceLocation TemplateLoc,
676 SourceLocation LAngleLoc,
677 ASTTemplateArgsPtr& Args,
678 SourceLocation *TemplateArgLocs,
679 SourceLocation RAngleLoc) {
680 TemplateParameterList *Params = Template->getTemplateParameters();
681 unsigned NumParams = Params->size();
682 unsigned NumArgs = Args.size();
683 bool Invalid = false;
684
685 if (NumArgs > NumParams ||
686 NumArgs < NumParams /*FIXME: default arguments! */) {
687 // FIXME: point at either the first arg beyond what we can handle,
688 // or the '>', depending on whether we have too many or too few
689 // arguments.
690 SourceRange Range;
691 if (NumArgs > NumParams)
692 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
693 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
694 << (NumArgs > NumParams)
695 << (isa<ClassTemplateDecl>(Template)? 0 :
696 isa<FunctionTemplateDecl>(Template)? 1 :
697 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
698 << Template << Range;
699
700 Invalid = true;
701 }
702
703 // C++ [temp.arg]p1:
704 // [...] The type and form of each template-argument specified in
705 // a template-id shall match the type and form specified for the
706 // corresponding parameter declared by the template in its
707 // template-parameter-list.
708 unsigned ArgIdx = 0;
709 for (TemplateParameterList::iterator Param = Params->begin(),
710 ParamEnd = Params->end();
711 Param != ParamEnd; ++Param, ++ArgIdx) {
712 // Decode the template argument
713 QualType ArgType;
714 Expr *ArgExpr = 0;
715 SourceLocation ArgLoc;
716 if (ArgIdx >= NumArgs) {
717 // FIXME: Get the default argument here, which might
718 // (eventually) require instantiation.
719 break;
720 } else
721 ArgLoc = TemplateArgLocs[ArgIdx];
722
723 if (Args.getArgIsType()[ArgIdx])
724 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
725 else
726 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
727
728 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
729 // Check template type parameters.
730 if (!ArgType.isNull()) {
731 if (!CheckTemplateArgument(TTP, ArgType, ArgLoc))
732 Invalid = true;
733 continue;
734 }
735
736 // C++ [temp.arg.type]p1:
737 // A template-argument for a template-parameter which is a
738 // type shall be a type-id.
739
740 // We have a template type parameter but the template argument
741 // is an expression.
742 Diag(ArgExpr->getSourceRange().getBegin(),
743 diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000744 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000745 Invalid = true;
746 } else if (NonTypeTemplateParmDecl *NTTP
747 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
748 // Check non-type template parameters.
749 if (ArgExpr) {
750 if (!CheckTemplateArgument(NTTP, ArgExpr))
751 Invalid = true;
752 continue;
753 }
754
755 // We have a non-type template parameter but the template
756 // argument is a type.
757
758 // C++ [temp.arg]p2:
759 // In a template-argument, an ambiguity between a type-id and
760 // an expression is resolved to a type-id, regardless of the
761 // form of the corresponding template-parameter.
762 //
763 // We warn specifically about this case, since it can be rather
764 // confusing for users.
765 if (ArgType->isFunctionType())
766 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
767 << ArgType;
768 else
769 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor341ac792009-02-10 00:53:15 +0000770 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000771 Invalid = true;
772 } else {
773 // Check template template parameters.
774 TemplateTemplateParmDecl *TempParm
775 = cast<TemplateTemplateParmDecl>(*Param);
776
777 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
778 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
779 if (!CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
780 Invalid = true;
781 continue;
782 }
783
784 // We have a template template parameter but the template
785 // argument does not refer to a template.
786 Diag(ArgLoc, diag::err_template_arg_must_be_template);
787 Invalid = true;
788 }
789 }
790
791 return Invalid;
792}
793
794/// \brief Check a template argument against its corresponding
795/// template type parameter.
796///
797/// This routine implements the semantics of C++ [temp.arg.type]. It
798/// returns true if an error occurred, and false otherwise.
799bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
800 QualType Arg, SourceLocation ArgLoc) {
801 // C++ [temp.arg.type]p2:
802 // A local type, a type with no linkage, an unnamed type or a type
803 // compounded from any of these types shall not be used as a
804 // template-argument for a template type-parameter.
805 //
806 // FIXME: Perform the recursive and no-linkage type checks.
807 const TagType *Tag = 0;
808 if (const EnumType *EnumT = Arg->getAsEnumType())
809 Tag = EnumT;
810 else if (const RecordType *RecordT = Arg->getAsRecordType())
811 Tag = RecordT;
812 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
813 return Diag(ArgLoc, diag::err_template_arg_local_type)
814 << QualType(Tag, 0);
815 else if (Tag && !Tag->getDecl()->getDeclName()) {
816 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
817 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
818 return true;
819 }
820
821 return false;
822}
823
824/// \brief Check a template argument against its corresponding
825/// non-type template parameter.
826///
827/// This routine implements the semantics of C++ [temp.arg.nontype].
828/// It returns true if an error occurred, and false otherwise.
829bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000830 Expr *&Arg) {
831 // If either the parameter has a dependent type or the argument is
832 // type-dependent, there's nothing we can check now.
833 if (Param->getType()->isDependentType() || Arg->isTypeDependent())
834 return false;
835
836 // C++ [temp.arg.nontype]p5:
837 // The following conversions are performed on each expression used
838 // as a non-type template-argument. If a non-type
839 // template-argument cannot be converted to the type of the
840 // corresponding template-parameter then the program is
841 // ill-formed.
842 //
843 // -- for a non-type template-parameter of integral or
844 // enumeration type, integral promotions (4.5) and integral
845 // conversions (4.7) are applied.
846 QualType ParamType = Param->getType();
847 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
848 QualType ArgType = Arg->getType();
849
850 // C++ [temp.arg.nontype]p1:
851 // A template-argument for a non-type, non-template
852 // template-parameter shall be one of:
853 //
854 // -- an integral constant-expression of integral or enumeration
855 // type; or
856 // -- the name of a non-type template-parameter; or
857 SourceLocation NonConstantLoc;
858 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
859 Diag(Arg->getSourceRange().getBegin(),
860 diag::err_template_arg_not_integral_or_enumeral)
861 << ArgType << Arg->getSourceRange();
862 Diag(Param->getLocation(), diag::note_template_param_here);
863 return true;
864 } else if (!Arg->isValueDependent() &&
865 !Arg->isIntegerConstantExpr(Context, &NonConstantLoc)) {
866 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
867 << ArgType << Arg->getSourceRange();
868 return true;
869 }
870
871 // FIXME: We need some way to more easily get the unqualified form
872 // of the types without going all the way to the
873 // canonical type.
874 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
875 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
876 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
877 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
878
879 // Try to convert the argument to the parameter's type.
880 if (ParamType == ArgType) {
881 // Okay: no conversion necessary
882 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
883 !ParamType->isEnumeralType()) {
884 // This is an integral promotion or conversion.
885 ImpCastExprToType(Arg, ParamType);
886 } else {
887 // We can't perform this conversion.
888 Diag(Arg->getSourceRange().getBegin(),
889 diag::err_template_arg_not_convertible)
890 << Arg->getType() << Param->getType() << Arg->getSourceRange();
891 Diag(Param->getLocation(), diag::note_template_param_here);
892 return true;
893 }
894
895 return false;
896 }
897 // FIXME: p5 has a lot more checks to perform!
898
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000899 return false;
900}
901
902/// \brief Check a template argument against its corresponding
903/// template template parameter.
904///
905/// This routine implements the semantics of C++ [temp.arg.template].
906/// It returns true if an error occurred, and false otherwise.
907bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
908 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +0000909 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
910 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
911
912 // C++ [temp.arg.template]p1:
913 // A template-argument for a template template-parameter shall be
914 // the name of a class template, expressed as id-expression. Only
915 // primary class templates are considered when matching the
916 // template template argument with the corresponding parameter;
917 // partial specializations are not considered even if their
918 // parameter lists match that of the template template parameter.
919 if (!isa<ClassTemplateDecl>(Template)) {
920 assert(isa<FunctionTemplateDecl>(Template) &&
921 "Only function templates are possible here");
922 Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here)
923 << Template;
924 }
925
926 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
927 Param->getTemplateParameters(),
928 true, true,
929 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000930}
931
Douglas Gregord406b032009-02-06 22:42:48 +0000932/// \brief Determine whether the given template parameter lists are
933/// equivalent.
934///
935/// \param New The new template parameter list, typically written in the
936/// source code as part of a new template declaration.
937///
938/// \param Old The old template parameter list, typically found via
939/// name lookup of the template declared with this template parameter
940/// list.
941///
942/// \param Complain If true, this routine will produce a diagnostic if
943/// the template parameter lists are not equivalent.
944///
Douglas Gregore8e367f2009-02-10 00:24:35 +0000945/// \param IsTemplateTemplateParm If true, this routine is being
946/// called to compare the template parameter lists of a template
947/// template parameter.
948///
949/// \param TemplateArgLoc If this source location is valid, then we
950/// are actually checking the template parameter list of a template
951/// argument (New) against the template parameter list of its
952/// corresponding template template parameter (Old). We produce
953/// slightly different diagnostics in this scenario.
954///
Douglas Gregord406b032009-02-06 22:42:48 +0000955/// \returns True if the template parameter lists are equal, false
956/// otherwise.
957bool
958Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
959 TemplateParameterList *Old,
960 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +0000961 bool IsTemplateTemplateParm,
962 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +0000963 if (Old->size() != New->size()) {
964 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +0000965 unsigned NextDiag = diag::err_template_param_list_different_arity;
966 if (TemplateArgLoc.isValid()) {
967 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
968 NextDiag = diag::note_template_param_list_different_arity;
969 }
970 Diag(New->getTemplateLoc(), NextDiag)
971 << (New->size() > Old->size())
972 << IsTemplateTemplateParm
973 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +0000974 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
975 << IsTemplateTemplateParm
976 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
977 }
978
979 return false;
980 }
981
982 for (TemplateParameterList::iterator OldParm = Old->begin(),
983 OldParmEnd = Old->end(), NewParm = New->begin();
984 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
985 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +0000986 unsigned NextDiag = diag::err_template_param_different_kind;
987 if (TemplateArgLoc.isValid()) {
988 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
989 NextDiag = diag::note_template_param_different_kind;
990 }
991 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +0000992 << IsTemplateTemplateParm;
993 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
994 << IsTemplateTemplateParm;
995 return false;
996 }
997
998 if (isa<TemplateTypeParmDecl>(*OldParm)) {
999 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001000 // know we're at the same index).
1001#if 0
1002 // FIXME: Enable this code in debug mode *after* we properly go
1003 // through and "instantiate" the template parameter lists of
1004 // template template parameters. It's only after this
1005 // instantiation that (1) any dependent types within the
1006 // template parameter list of the template template parameter
1007 // can be checked, and (2) the template type parameter depths
1008 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001009 QualType OldParmType
1010 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1011 QualType NewParmType
1012 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1013 assert(Context.getCanonicalType(OldParmType) ==
1014 Context.getCanonicalType(NewParmType) &&
1015 "type parameter mismatch?");
1016#endif
1017 } else if (NonTypeTemplateParmDecl *OldNTTP
1018 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1019 // The types of non-type template parameters must agree.
1020 NonTypeTemplateParmDecl *NewNTTP
1021 = cast<NonTypeTemplateParmDecl>(*NewParm);
1022 if (Context.getCanonicalType(OldNTTP->getType()) !=
1023 Context.getCanonicalType(NewNTTP->getType())) {
1024 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001025 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1026 if (TemplateArgLoc.isValid()) {
1027 Diag(TemplateArgLoc,
1028 diag::err_template_arg_template_params_mismatch);
1029 NextDiag = diag::note_template_nontype_parm_different_type;
1030 }
1031 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001032 << NewNTTP->getType()
1033 << IsTemplateTemplateParm;
1034 Diag(OldNTTP->getLocation(),
1035 diag::note_template_nontype_parm_prev_declaration)
1036 << OldNTTP->getType();
1037 }
1038 return false;
1039 }
1040 } else {
1041 // The template parameter lists of template template
1042 // parameters must agree.
1043 // FIXME: Could we perform a faster "type" comparison here?
1044 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1045 "Only template template parameters handled here");
1046 TemplateTemplateParmDecl *OldTTP
1047 = cast<TemplateTemplateParmDecl>(*OldParm);
1048 TemplateTemplateParmDecl *NewTTP
1049 = cast<TemplateTemplateParmDecl>(*NewParm);
1050 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1051 OldTTP->getTemplateParameters(),
1052 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001053 /*IsTemplateTemplateParm=*/true,
1054 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001055 return false;
1056 }
1057 }
1058
1059 return true;
1060}
1061
1062/// \brief Check whether a template can be declared within this scope.
1063///
1064/// If the template declaration is valid in this scope, returns
1065/// false. Otherwise, issues a diagnostic and returns true.
1066bool
1067Sema::CheckTemplateDeclScope(Scope *S,
1068 MultiTemplateParamsArg &TemplateParameterLists) {
1069 assert(TemplateParameterLists.size() > 0 && "Not a template");
1070
1071 // Find the nearest enclosing declaration scope.
1072 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1073 (S->getFlags() & Scope::TemplateParamScope) != 0)
1074 S = S->getParent();
1075
1076 TemplateParameterList *TemplateParams =
1077 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1078 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1079 SourceRange TemplateRange
1080 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1081
1082 // C++ [temp]p2:
1083 // A template-declaration can appear only as a namespace scope or
1084 // class scope declaration.
1085 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1086 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1087 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1088 return Diag(TemplateLoc, diag::err_template_linkage)
1089 << TemplateRange;
1090
1091 Ctx = Ctx->getParent();
1092 }
1093
1094 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1095 return false;
1096
1097 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1098 << TemplateRange;
1099}