blob: 223094b06682f13c62df4007ad9b15a6f1dc8d37 [file] [log] [blame]
Douglas Gregor72c3f312008-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 Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregor55f6b142009-02-09 18:46:07 +000029Sema::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
30 DeclTy *&Template,
31 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
34 if (IIDecl) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000035 if (isa<TemplateDecl>(IIDecl)) {
36 Template = IIDecl;
37 if (isa<FunctionTemplateDecl>(IIDecl))
38 return TNK_Function_template;
39 else if (isa<ClassTemplateDecl>(IIDecl))
40 return TNK_Class_template;
41 else if (isa<TemplateTemplateParmDecl>(IIDecl))
42 return TNK_Template_template_parm;
43 else
44 assert(false && "Unknown TemplateDecl");
45 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000046
Douglas Gregor55f6b142009-02-09 18:46:07 +000047 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000049 if (FD->getType()->isDependentType()) {
50 Template = FD;
51 return TNK_Function_template;
52 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000053 } else if (OverloadedFunctionDecl *Ovl
54 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
55 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
56 FEnd = Ovl->function_end();
57 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000058 if ((*F)->getType()->isDependentType()) {
59 Template = Ovl;
60 return TNK_Function_template;
61 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000062 }
63 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000064 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000065 return TNK_Non_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000066}
67
Douglas Gregor72c3f312008-12-05 18:15:24 +000068/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
69/// that the template parameter 'PrevDecl' is being shadowed by a new
70/// declaration at location Loc. Returns true to indicate that this is
71/// an error, and false otherwise.
72bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +000073 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +000074
75 // Microsoft Visual C++ permits template parameters to be shadowed.
76 if (getLangOptions().Microsoft)
77 return false;
78
79 // C++ [temp.local]p4:
80 // A template-parameter shall not be redeclared within its
81 // scope (including nested scopes).
82 Diag(Loc, diag::err_template_param_shadow)
83 << cast<NamedDecl>(PrevDecl)->getDeclName();
84 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
85 return true;
86}
87
Douglas Gregoraaba5e32009-02-04 19:02:06 +000088/// AdjustDeclForTemplates - If the given decl happens to be a template, reset
89/// the parameter D to reference the templated declaration and return a pointer
90/// to the template declaration. Otherwise, do nothing to D and return null.
91TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
92{
93 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
94 D = Temp->getTemplatedDecl();
95 return Temp;
96 }
97 return 0;
98}
99
Douglas Gregor72c3f312008-12-05 18:15:24 +0000100/// ActOnTypeParameter - Called when a C++ template type parameter
101/// (e.g., "typename T") has been parsed. Typename specifies whether
102/// the keyword "typename" was used to declare the type parameter
103/// (otherwise, "class" was used), and KeyLoc is the location of the
104/// "class" or "typename" keyword. ParamName is the name of the
105/// parameter (NULL indicates an unnamed template parameter) and
106/// ParamName is the location of the parameter name (if any).
107/// If the type parameter has a default argument, it will be added
108/// later via ActOnTypeParameterDefault.
109Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
110 SourceLocation KeyLoc,
111 IdentifierInfo *ParamName,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000112 SourceLocation ParamNameLoc,
113 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000114 assert(S->isTemplateParamScope() &&
115 "Template type parameter not in template parameter scope!");
116 bool Invalid = false;
117
118 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000119 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000120 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000121 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
122 PrevDecl);
123 }
124
Douglas Gregorddc29e12009-02-06 22:42:48 +0000125 SourceLocation Loc = ParamNameLoc;
126 if (!ParamName)
127 Loc = KeyLoc;
128
Douglas Gregor72c3f312008-12-05 18:15:24 +0000129 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000130 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000131 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000132 if (Invalid)
133 Param->setInvalidDecl();
134
135 if (ParamName) {
136 // Add the template parameter into the current scope.
137 S->AddDecl(Param);
138 IdResolver.AddDecl(Param);
139 }
140
141 return Param;
142}
143
Douglas Gregord684b002009-02-10 19:49:53 +0000144/// ActOnTypeParameterDefault - Adds a default argument (the type
145/// Default) to the given template type parameter (TypeParam).
146void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
147 SourceLocation EqualLoc,
148 SourceLocation DefaultLoc,
149 TypeTy *DefaultT) {
150 TemplateTypeParmDecl *Parm
151 = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
152 QualType Default = QualType::getFromOpaquePtr(DefaultT);
153
154 // C++ [temp.param]p14:
155 // A template-parameter shall not be used in its own default argument.
156 // FIXME: Implement this check! Needs a recursive walk over the types.
157
158 // Check the template argument itself.
159 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
160 Parm->setInvalidDecl();
161 return;
162 }
163
164 Parm->setDefaultArgument(Default, DefaultLoc, false);
165}
166
Douglas Gregor72c3f312008-12-05 18:15:24 +0000167/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
168/// template parameter (e.g., "int Size" in "template<int Size>
169/// class Array") has been parsed. S is the current scope and D is
170/// the parsed declarator.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000171Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
172 unsigned Depth,
173 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000174 QualType T = GetTypeForDeclarator(D, S);
175
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000176 assert(S->isTemplateParamScope() &&
177 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000178 bool Invalid = false;
179
180 IdentifierInfo *ParamName = D.getIdentifier();
181 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000182 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000183 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000184 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000185 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000186 }
187
Douglas Gregor5d290d52009-02-10 17:43:50 +0000188 // C++ [temp.param]p4:
189 //
190 // A non-type template-parameter shall have one of the following
191 // (optionally cv-qualified) types:
192 //
193 // -- integral or enumeration type,
194 if (T->isIntegralType() || T->isEnumeralType() ||
195 // -- pointer to object or pointer to function,
Douglas Gregora35284b2009-02-11 00:19:33 +0000196 (T->isPointerType() &&
197 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
198 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregor5d290d52009-02-10 17:43:50 +0000199 // -- reference to object or reference to function,
200 T->isReferenceType() ||
201 // -- pointer to member.
202 T->isMemberPointerType() ||
203 // If T is a dependent type, we can't do the check now, so we
204 // assume that it is well-formed.
205 T->isDependentType()) {
206 // Okay: The template parameter is well-formed.
207 }
208 // C++ [temp.param]p8:
209 //
210 // A non-type template-parameter of type "array of T" or
211 // "function returning T" is adjusted to be of type "pointer to
212 // T" or "pointer to function returning T", respectively.
213 else if (T->isArrayType())
214 // FIXME: Keep the type prior to promotion?
215 T = Context.getArrayDecayedType(T);
216 else if (T->isFunctionType())
217 // FIXME: Keep the type prior to promotion?
218 T = Context.getPointerType(T);
219 else {
220 Diag(D.getIdentifierLoc(), diag::err_template_nontype_parm_bad_type)
221 << T;
222 return 0;
223 }
224
Douglas Gregor72c3f312008-12-05 18:15:24 +0000225 NonTypeTemplateParmDecl *Param
226 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000227 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000228 if (Invalid)
229 Param->setInvalidDecl();
230
231 if (D.getIdentifier()) {
232 // Add the template parameter into the current scope.
233 S->AddDecl(Param);
234 IdResolver.AddDecl(Param);
235 }
236 return Param;
237}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000238
Douglas Gregord684b002009-02-10 19:49:53 +0000239/// \brief Adds a default argument to the given non-type template
240/// parameter.
241void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
242 SourceLocation EqualLoc,
243 ExprArg DefaultE) {
244 NonTypeTemplateParmDecl *TemplateParm
245 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
246 Expr *Default = static_cast<Expr *>(DefaultE.get());
247
248 // C++ [temp.param]p14:
249 // A template-parameter shall not be used in its own default argument.
250 // FIXME: Implement this check! Needs a recursive walk over the types.
251
252 // Check the well-formedness of the default template argument.
253 if (CheckTemplateArgument(TemplateParm, Default)) {
254 TemplateParm->setInvalidDecl();
255 return;
256 }
257
258 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
259}
260
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000261
262/// ActOnTemplateTemplateParameter - Called when a C++ template template
263/// parameter (e.g. T in template <template <typename> class T> class array)
264/// has been parsed. S is the current scope.
265Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
266 SourceLocation TmpLoc,
267 TemplateParamsTy *Params,
268 IdentifierInfo *Name,
269 SourceLocation NameLoc,
270 unsigned Depth,
271 unsigned Position)
272{
273 assert(S->isTemplateParamScope() &&
274 "Template template parameter not in template parameter scope!");
275
276 // Construct the parameter object.
277 TemplateTemplateParmDecl *Param =
278 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
279 Position, Name,
280 (TemplateParameterList*)Params);
281
282 // Make sure the parameter is valid.
283 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
284 // do anything yet. However, if the template parameter list or (eventual)
285 // default value is ever invalidated, that will propagate here.
286 bool Invalid = false;
287 if (Invalid) {
288 Param->setInvalidDecl();
289 }
290
291 // If the tt-param has a name, then link the identifier into the scope
292 // and lookup mechanisms.
293 if (Name) {
294 S->AddDecl(Param);
295 IdResolver.AddDecl(Param);
296 }
297
298 return Param;
299}
300
Douglas Gregord684b002009-02-10 19:49:53 +0000301/// \brief Adds a default argument to the given template template
302/// parameter.
303void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
304 SourceLocation EqualLoc,
305 ExprArg DefaultE) {
306 TemplateTemplateParmDecl *TemplateParm
307 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
308
309 // Since a template-template parameter's default argument is an
310 // id-expression, it must be a DeclRefExpr.
311 DeclRefExpr *Default
312 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
313
314 // C++ [temp.param]p14:
315 // A template-parameter shall not be used in its own default argument.
316 // FIXME: Implement this check! Needs a recursive walk over the types.
317
318 // Check the well-formedness of the template argument.
319 if (!isa<TemplateDecl>(Default->getDecl())) {
320 Diag(Default->getSourceRange().getBegin(),
321 diag::err_template_arg_must_be_template)
322 << Default->getSourceRange();
323 TemplateParm->setInvalidDecl();
324 return;
325 }
326 if (CheckTemplateArgument(TemplateParm, Default)) {
327 TemplateParm->setInvalidDecl();
328 return;
329 }
330
331 DefaultE.release();
332 TemplateParm->setDefaultArgument(Default);
333}
334
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000335/// ActOnTemplateParameterList - Builds a TemplateParameterList that
336/// contains the template parameters in Params/NumParams.
337Sema::TemplateParamsTy *
338Sema::ActOnTemplateParameterList(unsigned Depth,
339 SourceLocation ExportLoc,
340 SourceLocation TemplateLoc,
341 SourceLocation LAngleLoc,
342 DeclTy **Params, unsigned NumParams,
343 SourceLocation RAngleLoc) {
344 if (ExportLoc.isValid())
345 Diag(ExportLoc, diag::note_template_export_unsupported);
346
Douglas Gregorddc29e12009-02-06 22:42:48 +0000347 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
348 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000349}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000350
Douglas Gregorddc29e12009-02-06 22:42:48 +0000351Sema::DeclTy *
352Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
353 SourceLocation KWLoc, const CXXScopeSpec &SS,
354 IdentifierInfo *Name, SourceLocation NameLoc,
355 AttributeList *Attr,
356 MultiTemplateParamsArg TemplateParameterLists) {
357 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
358 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000359 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000360
361 // Check that we can declare a template here.
362 if (CheckTemplateDeclScope(S, TemplateParameterLists))
363 return 0;
364
365 TagDecl::TagKind Kind;
366 switch (TagSpec) {
367 default: assert(0 && "Unknown tag type!");
368 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
369 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
370 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
371 }
372
373 // There is no such thing as an unnamed class template.
374 if (!Name) {
375 Diag(KWLoc, diag::err_template_unnamed_class);
376 return 0;
377 }
378
379 // Find any previous declaration with this name.
380 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
381 true);
382 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
383 NamedDecl *PrevDecl = 0;
384 if (Previous.begin() != Previous.end())
385 PrevDecl = *Previous.begin();
386
387 DeclContext *SemanticContext = CurContext;
388 if (SS.isNotEmpty() && !SS.isInvalid()) {
389 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
390
391 // FIXME: need to match up several levels of template parameter
392 // lists here.
393 }
394
395 // FIXME: member templates!
396 TemplateParameterList *TemplateParams
397 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
398
399 // If there is a previous declaration with the same name, check
400 // whether this is a valid redeclaration.
401 ClassTemplateDecl *PrevClassTemplate
402 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
403 if (PrevClassTemplate) {
404 // Ensure that the template parameter lists are compatible.
405 if (!TemplateParameterListsAreEqual(TemplateParams,
406 PrevClassTemplate->getTemplateParameters(),
407 /*Complain=*/true))
408 return 0;
409
410 // C++ [temp.class]p4:
411 // In a redeclaration, partial specialization, explicit
412 // specialization or explicit instantiation of a class template,
413 // the class-key shall agree in kind with the original class
414 // template declaration (7.1.5.3).
415 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
416 if (PrevRecordDecl->getTagKind() != Kind) {
417 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
418 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
419 return 0;
420 }
421
422
423 // Check for redefinition of this class template.
424 if (TK == TK_Definition) {
425 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
426 Diag(NameLoc, diag::err_redefinition) << Name;
427 Diag(Def->getLocation(), diag::note_previous_definition);
428 // FIXME: Would it make sense to try to "forget" the previous
429 // definition, as part of error recovery?
430 return 0;
431 }
432 }
433 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
434 // Maybe we will complain about the shadowed template parameter.
435 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
436 // Just pretend that we didn't see the previous declaration.
437 PrevDecl = 0;
438 } else if (PrevDecl) {
439 // C++ [temp]p5:
440 // A class template shall not have the same name as any other
441 // template, class, function, object, enumeration, enumerator,
442 // namespace, or type in the same scope (3.3), except as specified
443 // in (14.5.4).
444 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
445 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
446 return 0;
447 }
448
Douglas Gregord684b002009-02-10 19:49:53 +0000449 // Check the template parameter list of this declaration, possibly
450 // merging in the template parameter list from the previous class
451 // template declaration.
452 if (CheckTemplateParameterList(TemplateParams,
453 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
454 Invalid = true;
455
Douglas Gregorddc29e12009-02-06 22:42:48 +0000456 // If we had a scope specifier, we better have a previous template
457 // declaration!
458
459 TagDecl *NewClass =
460 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
461 PrevClassTemplate?
462 PrevClassTemplate->getTemplatedDecl() : 0);
463
464 ClassTemplateDecl *NewTemplate
465 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
466 DeclarationName(Name), TemplateParams,
467 NewClass);
468
469 // Set the lexical context of these templates
470 NewClass->setLexicalDeclContext(CurContext);
471 NewTemplate->setLexicalDeclContext(CurContext);
472
473 if (TK == TK_Definition)
474 NewClass->startDefinition();
475
476 if (Attr)
477 ProcessDeclAttributeList(NewClass, Attr);
478
479 PushOnScopeChains(NewTemplate, S);
480
Douglas Gregord684b002009-02-10 19:49:53 +0000481 if (Invalid) {
482 NewTemplate->setInvalidDecl();
483 NewClass->setInvalidDecl();
484 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000485 return NewTemplate;
486}
487
Douglas Gregord684b002009-02-10 19:49:53 +0000488/// \brief Checks the validity of a template parameter list, possibly
489/// considering the template parameter list from a previous
490/// declaration.
491///
492/// If an "old" template parameter list is provided, it must be
493/// equivalent (per TemplateParameterListsAreEqual) to the "new"
494/// template parameter list.
495///
496/// \param NewParams Template parameter list for a new template
497/// declaration. This template parameter list will be updated with any
498/// default arguments that are carried through from the previous
499/// template parameter list.
500///
501/// \param OldParams If provided, template parameter list from a
502/// previous declaration of the same template. Default template
503/// arguments will be merged from the old template parameter list to
504/// the new template parameter list.
505///
506/// \returns true if an error occurred, false otherwise.
507bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
508 TemplateParameterList *OldParams) {
509 bool Invalid = false;
510
511 // C++ [temp.param]p10:
512 // The set of default template-arguments available for use with a
513 // template declaration or definition is obtained by merging the
514 // default arguments from the definition (if in scope) and all
515 // declarations in scope in the same way default function
516 // arguments are (8.3.6).
517 bool SawDefaultArgument = false;
518 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000519
Mike Stump1a35fde2009-02-11 23:03:27 +0000520 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000521 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000522 if (OldParams)
523 OldParam = OldParams->begin();
524
525 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
526 NewParamEnd = NewParams->end();
527 NewParam != NewParamEnd; ++NewParam) {
528 // Variables used to diagnose redundant default arguments
529 bool RedundantDefaultArg = false;
530 SourceLocation OldDefaultLoc;
531 SourceLocation NewDefaultLoc;
532
533 // Variables used to diagnose missing default arguments
534 bool MissingDefaultArg = false;
535
536 // Merge default arguments for template type parameters.
537 if (TemplateTypeParmDecl *NewTypeParm
538 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
539 TemplateTypeParmDecl *OldTypeParm
540 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
541
542 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
543 NewTypeParm->hasDefaultArgument()) {
544 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
545 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
546 SawDefaultArgument = true;
547 RedundantDefaultArg = true;
548 PreviousDefaultArgLoc = NewDefaultLoc;
549 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
550 // Merge the default argument from the old declaration to the
551 // new declaration.
552 SawDefaultArgument = true;
553 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
554 OldTypeParm->getDefaultArgumentLoc(),
555 true);
556 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
557 } else if (NewTypeParm->hasDefaultArgument()) {
558 SawDefaultArgument = true;
559 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
560 } else if (SawDefaultArgument)
561 MissingDefaultArg = true;
562 }
563 // Merge default arguments for non-type template parameters
564 else if (NonTypeTemplateParmDecl *NewNonTypeParm
565 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
566 NonTypeTemplateParmDecl *OldNonTypeParm
567 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
568 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
569 NewNonTypeParm->hasDefaultArgument()) {
570 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
571 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
572 SawDefaultArgument = true;
573 RedundantDefaultArg = true;
574 PreviousDefaultArgLoc = NewDefaultLoc;
575 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
576 // Merge the default argument from the old declaration to the
577 // new declaration.
578 SawDefaultArgument = true;
579 // FIXME: We need to create a new kind of "default argument"
580 // expression that points to a previous template template
581 // parameter.
582 NewNonTypeParm->setDefaultArgument(
583 OldNonTypeParm->getDefaultArgument());
584 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
585 } else if (NewNonTypeParm->hasDefaultArgument()) {
586 SawDefaultArgument = true;
587 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
588 } else if (SawDefaultArgument)
589 MissingDefaultArg = true;
590 }
591 // Merge default arguments for template template parameters
592 else {
593 TemplateTemplateParmDecl *NewTemplateParm
594 = cast<TemplateTemplateParmDecl>(*NewParam);
595 TemplateTemplateParmDecl *OldTemplateParm
596 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
597 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
598 NewTemplateParm->hasDefaultArgument()) {
599 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
600 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
601 SawDefaultArgument = true;
602 RedundantDefaultArg = true;
603 PreviousDefaultArgLoc = NewDefaultLoc;
604 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
605 // Merge the default argument from the old declaration to the
606 // new declaration.
607 SawDefaultArgument = true;
608 // FIXME: We need to create a new kind of "default argument"
609 // expression that points to a previous template template
610 // parameter.
611 NewTemplateParm->setDefaultArgument(
612 OldTemplateParm->getDefaultArgument());
613 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
614 } else if (NewTemplateParm->hasDefaultArgument()) {
615 SawDefaultArgument = true;
616 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
617 } else if (SawDefaultArgument)
618 MissingDefaultArg = true;
619 }
620
621 if (RedundantDefaultArg) {
622 // C++ [temp.param]p12:
623 // A template-parameter shall not be given default arguments
624 // by two different declarations in the same scope.
625 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
626 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
627 Invalid = true;
628 } else if (MissingDefaultArg) {
629 // C++ [temp.param]p11:
630 // If a template-parameter has a default template-argument,
631 // all subsequent template-parameters shall have a default
632 // template-argument supplied.
633 Diag((*NewParam)->getLocation(),
634 diag::err_template_param_default_arg_missing);
635 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
636 Invalid = true;
637 }
638
639 // If we have an old template parameter list that we're merging
640 // in, move on to the next parameter.
641 if (OldParams)
642 ++OldParam;
643 }
644
645 return Invalid;
646}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000647
Douglas Gregorcc636682009-02-17 23:15:12 +0000648Action::TypeResult
649Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
650 SourceLocation LAngleLoc,
651 ASTTemplateArgsPtr TemplateArgs,
652 SourceLocation *TemplateArgLocs,
653 SourceLocation RAngleLoc,
654 const CXXScopeSpec *SS) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000655 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000656 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000657
Douglas Gregorc15cb382009-02-09 23:23:08 +0000658 // Check that the template argument list is well-formed for this
659 // template.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000660 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregor658bbb52009-02-11 16:16:59 +0000661 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000662 TemplateArgs, TemplateArgLocs, RAngleLoc,
663 ConvertedTemplateArgs))
Douglas Gregorcc636682009-02-17 23:15:12 +0000664 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000665
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000666 assert((ConvertedTemplateArgs.size() ==
667 Template->getTemplateParameters()->size()) &&
668 "Converted template argument list is too short!");
669
670 // Find the class template specialization declaration that
671 // corresponds to these arguments.
672 llvm::FoldingSetNodeID ID;
673 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
674 ConvertedTemplateArgs.size());
675 void *InsertPos = 0;
676 ClassTemplateSpecializationDecl *Decl
677 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
678 if (!Decl) {
679 // This is the first time we have referenced this class template
Douglas Gregorcc636682009-02-17 23:15:12 +0000680 // specialization. Create the canonical declaration and add it to
681 // the set of specializations.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000682 Decl = ClassTemplateSpecializationDecl::Create(Context,
683 ClassTemplate->getDeclContext(),
684 TemplateLoc,
685 ClassTemplate,
686 &ConvertedTemplateArgs[0],
Douglas Gregorcc636682009-02-17 23:15:12 +0000687 ConvertedTemplateArgs.size(),
688 0);
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000689 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
690 }
691
692 // Build the fully-sugared type for this class template
693 // specialization, which refers back to the class template
694 // specialization we created or found.
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000695 QualType Result
696 = Context.getClassTemplateSpecializationType(Template,
697 TemplateArgs.size(),
698 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
699 TemplateArgs.getArgIsType(),
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000700 Context.getTypeDeclType(Decl));
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000701 TemplateArgs.release();
702 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000703}
704
Douglas Gregorc15cb382009-02-09 23:23:08 +0000705/// \brief Check that the given template argument list is well-formed
706/// for specializing the given template.
707bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
708 SourceLocation TemplateLoc,
709 SourceLocation LAngleLoc,
710 ASTTemplateArgsPtr& Args,
711 SourceLocation *TemplateArgLocs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000712 SourceLocation RAngleLoc,
713 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000714 TemplateParameterList *Params = Template->getTemplateParameters();
715 unsigned NumParams = Params->size();
716 unsigned NumArgs = Args.size();
717 bool Invalid = false;
718
719 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000720 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000721 // FIXME: point at either the first arg beyond what we can handle,
722 // or the '>', depending on whether we have too many or too few
723 // arguments.
724 SourceRange Range;
725 if (NumArgs > NumParams)
726 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
727 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
728 << (NumArgs > NumParams)
729 << (isa<ClassTemplateDecl>(Template)? 0 :
730 isa<FunctionTemplateDecl>(Template)? 1 :
731 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
732 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000733 Diag(Template->getLocation(), diag::note_template_decl_here)
734 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000735 Invalid = true;
736 }
737
738 // C++ [temp.arg]p1:
739 // [...] The type and form of each template-argument specified in
740 // a template-id shall match the type and form specified for the
741 // corresponding parameter declared by the template in its
742 // template-parameter-list.
743 unsigned ArgIdx = 0;
744 for (TemplateParameterList::iterator Param = Params->begin(),
745 ParamEnd = Params->end();
746 Param != ParamEnd; ++Param, ++ArgIdx) {
747 // Decode the template argument
748 QualType ArgType;
749 Expr *ArgExpr = 0;
750 SourceLocation ArgLoc;
751 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000752 // Retrieve the default template argument from the template
753 // parameter.
754 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
755 if (!TTP->hasDefaultArgument())
756 break;
757
758 ArgType = TTP->getDefaultArgument();
759 ArgLoc = TTP->getDefaultArgumentLoc();
760 } else if (NonTypeTemplateParmDecl *NTTP
761 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
762 if (!NTTP->hasDefaultArgument())
763 break;
764
765 ArgExpr = NTTP->getDefaultArgument();
766 ArgLoc = NTTP->getDefaultArgumentLoc();
767 } else {
768 TemplateTemplateParmDecl *TempParm
769 = cast<TemplateTemplateParmDecl>(*Param);
770
771 if (!TempParm->hasDefaultArgument())
772 break;
773
774 ArgExpr = TempParm->getDefaultArgument();
775 ArgLoc = TempParm->getDefaultArgumentLoc();
776 }
777 } else {
778 // Retrieve the template argument produced by the user.
Douglas Gregorc15cb382009-02-09 23:23:08 +0000779 ArgLoc = TemplateArgLocs[ArgIdx];
780
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000781 if (Args.getArgIsType()[ArgIdx])
782 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
783 else
784 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
785 }
786
Douglas Gregorc15cb382009-02-09 23:23:08 +0000787
788 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
789 // Check template type parameters.
790 if (!ArgType.isNull()) {
Douglas Gregor658bbb52009-02-11 16:16:59 +0000791 if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000792 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000793
794 // Add the converted template type argument.
795 Converted.push_back(
796 TemplateArgument(Context.getCanonicalType(ArgType)));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000797 continue;
798 }
799
800 // C++ [temp.arg.type]p1:
801 // A template-argument for a template-parameter which is a
802 // type shall be a type-id.
803
804 // We have a template type parameter but the template argument
805 // is an expression.
806 Diag(ArgExpr->getSourceRange().getBegin(),
807 diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +0000808 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000809 Invalid = true;
810 } else if (NonTypeTemplateParmDecl *NTTP
811 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
812 // Check non-type template parameters.
813 if (ArgExpr) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000814 if (CheckTemplateArgument(NTTP, ArgExpr, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000815 Invalid = true;
816 continue;
817 }
818
819 // We have a non-type template parameter but the template
820 // argument is a type.
821
822 // C++ [temp.arg]p2:
823 // In a template-argument, an ambiguity between a type-id and
824 // an expression is resolved to a type-id, regardless of the
825 // form of the corresponding template-parameter.
826 //
827 // We warn specifically about this case, since it can be rather
828 // confusing for users.
829 if (ArgType->isFunctionType())
830 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
831 << ArgType;
832 else
833 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor8b642592009-02-10 00:53:15 +0000834 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000835 Invalid = true;
836 } else {
837 // Check template template parameters.
838 TemplateTemplateParmDecl *TempParm
839 = cast<TemplateTemplateParmDecl>(*Param);
840
841 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
842 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
Douglas Gregor658bbb52009-02-11 16:16:59 +0000843 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000844 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000845
846 // Add the converted template argument.
847 // FIXME: Need the "canonical" template declaration!
848 Converted.push_back(
849 TemplateArgument(cast<DeclRefExpr>(ArgExpr)->getDecl()));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000850 continue;
851 }
852
853 // We have a template template parameter but the template
854 // argument does not refer to a template.
855 Diag(ArgLoc, diag::err_template_arg_must_be_template);
856 Invalid = true;
857 }
858 }
859
860 return Invalid;
861}
862
863/// \brief Check a template argument against its corresponding
864/// template type parameter.
865///
866/// This routine implements the semantics of C++ [temp.arg.type]. It
867/// returns true if an error occurred, and false otherwise.
868bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
869 QualType Arg, SourceLocation ArgLoc) {
870 // C++ [temp.arg.type]p2:
871 // A local type, a type with no linkage, an unnamed type or a type
872 // compounded from any of these types shall not be used as a
873 // template-argument for a template type-parameter.
874 //
875 // FIXME: Perform the recursive and no-linkage type checks.
876 const TagType *Tag = 0;
877 if (const EnumType *EnumT = Arg->getAsEnumType())
878 Tag = EnumT;
879 else if (const RecordType *RecordT = Arg->getAsRecordType())
880 Tag = RecordT;
881 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
882 return Diag(ArgLoc, diag::err_template_arg_local_type)
883 << QualType(Tag, 0);
884 else if (Tag && !Tag->getDecl()->getDeclName()) {
885 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
886 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
887 return true;
888 }
889
890 return false;
891}
892
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000893/// \brief Checks whether the given template argument is the address
894/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000895bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
896 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000897 bool Invalid = false;
898
899 // See through any implicit casts we added to fix the type.
900 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
901 Arg = Cast->getSubExpr();
902
903 // C++ [temp.arg.nontype]p1:
904 //
905 // A template-argument for a non-type, non-template
906 // template-parameter shall be one of: [...]
907 //
908 // -- the address of an object or function with external
909 // linkage, including function templates and function
910 // template-ids but excluding non-static class members,
911 // expressed as & id-expression where the & is optional if
912 // the name refers to a function or array, or if the
913 // corresponding template-parameter is a reference; or
914 DeclRefExpr *DRE = 0;
915
916 // Ignore (and complain about) any excess parentheses.
917 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
918 if (!Invalid) {
919 Diag(Arg->getSourceRange().getBegin(),
920 diag::err_template_arg_extra_parens)
921 << Arg->getSourceRange();
922 Invalid = true;
923 }
924
925 Arg = Parens->getSubExpr();
926 }
927
928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
929 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
930 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
931 } else
932 DRE = dyn_cast<DeclRefExpr>(Arg);
933
934 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
935 return Diag(Arg->getSourceRange().getBegin(),
936 diag::err_template_arg_not_object_or_func_form)
937 << Arg->getSourceRange();
938
939 // Cannot refer to non-static data members
940 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
941 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
942 << Field << Arg->getSourceRange();
943
944 // Cannot refer to non-static member functions
945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
946 if (!Method->isStatic())
947 return Diag(Arg->getSourceRange().getBegin(),
948 diag::err_template_arg_method)
949 << Method << Arg->getSourceRange();
950
951 // Functions must have external linkage.
952 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
953 if (Func->getStorageClass() == FunctionDecl::Static) {
954 Diag(Arg->getSourceRange().getBegin(),
955 diag::err_template_arg_function_not_extern)
956 << Func << Arg->getSourceRange();
957 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
958 << true;
959 return true;
960 }
961
962 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000963 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000964 return Invalid;
965 }
966
967 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
968 if (!Var->hasGlobalStorage()) {
969 Diag(Arg->getSourceRange().getBegin(),
970 diag::err_template_arg_object_not_extern)
971 << Var << Arg->getSourceRange();
972 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
973 << true;
974 return true;
975 }
976
977 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000978 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000979 return Invalid;
980 }
981
982 // We found something else, but we don't know specifically what it is.
983 Diag(Arg->getSourceRange().getBegin(),
984 diag::err_template_arg_not_object_or_func)
985 << Arg->getSourceRange();
986 Diag(DRE->getDecl()->getLocation(),
987 diag::note_template_arg_refers_here);
988 return true;
989}
990
991/// \brief Checks whether the given template argument is a pointer to
992/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000993bool
994Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000995 bool Invalid = false;
996
997 // See through any implicit casts we added to fix the type.
998 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
999 Arg = Cast->getSubExpr();
1000
1001 // C++ [temp.arg.nontype]p1:
1002 //
1003 // A template-argument for a non-type, non-template
1004 // template-parameter shall be one of: [...]
1005 //
1006 // -- a pointer to member expressed as described in 5.3.1.
1007 QualifiedDeclRefExpr *DRE = 0;
1008
1009 // Ignore (and complain about) any excess parentheses.
1010 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1011 if (!Invalid) {
1012 Diag(Arg->getSourceRange().getBegin(),
1013 diag::err_template_arg_extra_parens)
1014 << Arg->getSourceRange();
1015 Invalid = true;
1016 }
1017
1018 Arg = Parens->getSubExpr();
1019 }
1020
1021 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1022 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1023 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1024
1025 if (!DRE)
1026 return Diag(Arg->getSourceRange().getBegin(),
1027 diag::err_template_arg_not_pointer_to_member_form)
1028 << Arg->getSourceRange();
1029
1030 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1031 assert((isa<FieldDecl>(DRE->getDecl()) ||
1032 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1033 "Only non-static member pointers can make it here");
1034
1035 // Okay: this is the address of a non-static member, and therefore
1036 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001037 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001038 return Invalid;
1039 }
1040
1041 // We found something else, but we don't know specifically what it is.
1042 Diag(Arg->getSourceRange().getBegin(),
1043 diag::err_template_arg_not_pointer_to_member_form)
1044 << Arg->getSourceRange();
1045 Diag(DRE->getDecl()->getLocation(),
1046 diag::note_template_arg_refers_here);
1047 return true;
1048}
1049
Douglas Gregorc15cb382009-02-09 23:23:08 +00001050/// \brief Check a template argument against its corresponding
1051/// non-type template parameter.
1052///
1053/// This routine implements the semantics of C++ [temp.arg.nontype].
1054/// It returns true if an error occurred, and false otherwise.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001055///
1056/// If Converted is non-NULL and no errors occur, the value
1057/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001058bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001059 Expr *&Arg,
1060 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001061 // If either the parameter has a dependent type or the argument is
1062 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001063 // FIXME: Add template argument to Converted!
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001064 if (Param->getType()->isDependentType() || Arg->isTypeDependent())
1065 return false;
1066
1067 // C++ [temp.arg.nontype]p5:
1068 // The following conversions are performed on each expression used
1069 // as a non-type template-argument. If a non-type
1070 // template-argument cannot be converted to the type of the
1071 // corresponding template-parameter then the program is
1072 // ill-formed.
1073 //
1074 // -- for a non-type template-parameter of integral or
1075 // enumeration type, integral promotions (4.5) and integral
1076 // conversions (4.7) are applied.
1077 QualType ParamType = Param->getType();
Douglas Gregora35284b2009-02-11 00:19:33 +00001078 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001079 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001080 // C++ [temp.arg.nontype]p1:
1081 // A template-argument for a non-type, non-template
1082 // template-parameter shall be one of:
1083 //
1084 // -- an integral constant-expression of integral or enumeration
1085 // type; or
1086 // -- the name of a non-type template-parameter; or
1087 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001088 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001089 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1090 Diag(Arg->getSourceRange().getBegin(),
1091 diag::err_template_arg_not_integral_or_enumeral)
1092 << ArgType << Arg->getSourceRange();
1093 Diag(Param->getLocation(), diag::note_template_param_here);
1094 return true;
1095 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001096 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001097 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1098 << ArgType << Arg->getSourceRange();
1099 return true;
1100 }
1101
1102 // FIXME: We need some way to more easily get the unqualified form
1103 // of the types without going all the way to the
1104 // canonical type.
1105 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1106 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1107 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1108 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1109
1110 // Try to convert the argument to the parameter's type.
1111 if (ParamType == ArgType) {
1112 // Okay: no conversion necessary
1113 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1114 !ParamType->isEnumeralType()) {
1115 // This is an integral promotion or conversion.
1116 ImpCastExprToType(Arg, ParamType);
1117 } else {
1118 // We can't perform this conversion.
1119 Diag(Arg->getSourceRange().getBegin(),
1120 diag::err_template_arg_not_convertible)
1121 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1122 Diag(Param->getLocation(), diag::note_template_param_here);
1123 return true;
1124 }
1125
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001126 // FIXME: Check overflow of template arguments?
1127
1128 if (Converted) {
1129 // Add the value of this argument to the list of converted
1130 // arguments. We use the bitwidth and signedness of the template
1131 // parameter.
1132 QualType IntegerType = Context.getCanonicalType(ParamType);
1133 if (const EnumType *Enum = IntegerType->getAsEnumType())
1134 IntegerType = Enum->getDecl()->getIntegerType();
1135
1136 llvm::APInt CanonicalArg(Context.getTypeSize(IntegerType), 0,
1137 IntegerType->isSignedIntegerType());
1138 CanonicalArg = Value;
1139
1140 Converted->push_back(TemplateArgument(CanonicalArg));
1141 }
1142
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001143 return false;
1144 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001145
Douglas Gregorb86b0572009-02-11 01:18:59 +00001146 // Handle pointer-to-function, reference-to-function, and
1147 // pointer-to-member-function all in (roughly) the same way.
1148 if (// -- For a non-type template-parameter of type pointer to
1149 // function, only the function-to-pointer conversion (4.3) is
1150 // applied. If the template-argument represents a set of
1151 // overloaded functions (or a pointer to such), the matching
1152 // function is selected from the set (13.4).
1153 (ParamType->isPointerType() &&
1154 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1155 // -- For a non-type template-parameter of type reference to
1156 // function, no conversions apply. If the template-argument
1157 // represents a set of overloaded functions, the matching
1158 // function is selected from the set (13.4).
1159 (ParamType->isReferenceType() &&
1160 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1161 // -- For a non-type template-parameter of type pointer to
1162 // member function, no conversions apply. If the
1163 // template-argument represents a set of overloaded member
1164 // functions, the matching member function is selected from
1165 // the set (13.4).
1166 (ParamType->isMemberPointerType() &&
1167 ParamType->getAsMemberPointerType()->getPointeeType()
1168 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001169 if (Context.hasSameUnqualifiedType(ArgType,
1170 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001171 // We don't have to do anything: the types already match.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001172 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001173 ArgType = Context.getPointerType(ArgType);
1174 ImpCastExprToType(Arg, ArgType);
1175 } else if (FunctionDecl *Fn
1176 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001177 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1178 return true;
1179
Douglas Gregora35284b2009-02-11 00:19:33 +00001180 FixOverloadedFunctionReference(Arg, Fn);
1181 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001182 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001183 ArgType = Context.getPointerType(Arg->getType());
1184 ImpCastExprToType(Arg, ArgType);
1185 }
1186 }
1187
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001188 if (!Context.hasSameUnqualifiedType(ArgType,
1189 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001190 // We can't perform this conversion.
1191 Diag(Arg->getSourceRange().getBegin(),
1192 diag::err_template_arg_not_convertible)
1193 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1194 Diag(Param->getLocation(), diag::note_template_param_here);
1195 return true;
1196 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001197
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001198 if (ParamType->isMemberPointerType()) {
1199 NamedDecl *Member = 0;
1200 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1201 return true;
1202
1203 if (Converted)
1204 Converted->push_back(TemplateArgument(Member));
1205
1206 return false;
1207 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001208
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001209 NamedDecl *Entity = 0;
1210 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1211 return true;
1212
1213 if (Converted)
1214 Converted->push_back(TemplateArgument(Entity));
1215 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001216 }
1217
Chris Lattnerfe90de72009-02-20 21:37:53 +00001218 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001219 // -- for a non-type template-parameter of type pointer to
1220 // object, qualification conversions (4.4) and the
1221 // array-to-pointer conversion (4.2) are applied.
Chris Lattnerfe90de72009-02-20 21:37:53 +00001222 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001223 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001224
Douglas Gregorb86b0572009-02-11 01:18:59 +00001225 if (ArgType->isArrayType()) {
1226 ArgType = Context.getArrayDecayedType(ArgType);
1227 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001228 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001229
1230 if (IsQualificationConversion(ArgType, ParamType)) {
1231 ArgType = ParamType;
1232 ImpCastExprToType(Arg, ParamType);
1233 }
1234
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001235 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001236 // We can't perform this conversion.
1237 Diag(Arg->getSourceRange().getBegin(),
1238 diag::err_template_arg_not_convertible)
1239 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1240 Diag(Param->getLocation(), diag::note_template_param_here);
1241 return true;
1242 }
1243
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001244 NamedDecl *Entity = 0;
1245 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1246 return true;
1247
1248 if (Converted)
1249 Converted->push_back(TemplateArgument(Entity));
1250
1251 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001252 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001253
1254 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1255 // -- For a non-type template-parameter of type reference to
1256 // object, no conversions apply. The type referred to by the
1257 // reference may be more cv-qualified than the (otherwise
1258 // identical) type of the template-argument. The
1259 // template-parameter is bound directly to the
1260 // template-argument, which must be an lvalue.
1261 assert(ParamRefType->getPointeeType()->isObjectType() &&
1262 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001263
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001264 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001265 Diag(Arg->getSourceRange().getBegin(),
1266 diag::err_template_arg_no_ref_bind)
1267 << Param->getType() << Arg->getType()
1268 << Arg->getSourceRange();
1269 Diag(Param->getLocation(), diag::note_template_param_here);
1270 return true;
1271 }
1272
1273 unsigned ParamQuals
1274 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1275 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1276
1277 if ((ParamQuals | ArgQuals) != ParamQuals) {
1278 Diag(Arg->getSourceRange().getBegin(),
1279 diag::err_template_arg_ref_bind_ignores_quals)
1280 << Param->getType() << Arg->getType()
1281 << Arg->getSourceRange();
1282 Diag(Param->getLocation(), diag::note_template_param_here);
1283 return true;
1284 }
1285
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001286 NamedDecl *Entity = 0;
1287 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1288 return true;
1289
1290 if (Converted)
1291 Converted->push_back(TemplateArgument(Entity));
1292
1293 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001294 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001295
1296 // -- For a non-type template-parameter of type pointer to data
1297 // member, qualification conversions (4.4) are applied.
1298 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1299
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001300 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001301 // Types match exactly: nothing more to do here.
1302 } else if (IsQualificationConversion(ArgType, ParamType)) {
1303 ImpCastExprToType(Arg, ParamType);
1304 } else {
1305 // We can't perform this conversion.
1306 Diag(Arg->getSourceRange().getBegin(),
1307 diag::err_template_arg_not_convertible)
1308 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1309 Diag(Param->getLocation(), diag::note_template_param_here);
1310 return true;
1311 }
1312
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001313 NamedDecl *Member = 0;
1314 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1315 return true;
1316
1317 if (Converted)
1318 Converted->push_back(TemplateArgument(Member));
1319
1320 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001321}
1322
1323/// \brief Check a template argument against its corresponding
1324/// template template parameter.
1325///
1326/// This routine implements the semantics of C++ [temp.arg.template].
1327/// It returns true if an error occurred, and false otherwise.
1328bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1329 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001330 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1331 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1332
1333 // C++ [temp.arg.template]p1:
1334 // A template-argument for a template template-parameter shall be
1335 // the name of a class template, expressed as id-expression. Only
1336 // primary class templates are considered when matching the
1337 // template template argument with the corresponding parameter;
1338 // partial specializations are not considered even if their
1339 // parameter lists match that of the template template parameter.
1340 if (!isa<ClassTemplateDecl>(Template)) {
1341 assert(isa<FunctionTemplateDecl>(Template) &&
1342 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001343 Diag(Arg->getSourceRange().getBegin(),
1344 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001345 << Template;
1346 }
1347
1348 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1349 Param->getTemplateParameters(),
1350 true, true,
1351 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001352}
1353
Douglas Gregorddc29e12009-02-06 22:42:48 +00001354/// \brief Determine whether the given template parameter lists are
1355/// equivalent.
1356///
1357/// \param New The new template parameter list, typically written in the
1358/// source code as part of a new template declaration.
1359///
1360/// \param Old The old template parameter list, typically found via
1361/// name lookup of the template declared with this template parameter
1362/// list.
1363///
1364/// \param Complain If true, this routine will produce a diagnostic if
1365/// the template parameter lists are not equivalent.
1366///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001367/// \param IsTemplateTemplateParm If true, this routine is being
1368/// called to compare the template parameter lists of a template
1369/// template parameter.
1370///
1371/// \param TemplateArgLoc If this source location is valid, then we
1372/// are actually checking the template parameter list of a template
1373/// argument (New) against the template parameter list of its
1374/// corresponding template template parameter (Old). We produce
1375/// slightly different diagnostics in this scenario.
1376///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001377/// \returns True if the template parameter lists are equal, false
1378/// otherwise.
1379bool
1380Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1381 TemplateParameterList *Old,
1382 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001383 bool IsTemplateTemplateParm,
1384 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001385 if (Old->size() != New->size()) {
1386 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001387 unsigned NextDiag = diag::err_template_param_list_different_arity;
1388 if (TemplateArgLoc.isValid()) {
1389 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1390 NextDiag = diag::note_template_param_list_different_arity;
1391 }
1392 Diag(New->getTemplateLoc(), NextDiag)
1393 << (New->size() > Old->size())
1394 << IsTemplateTemplateParm
1395 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001396 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1397 << IsTemplateTemplateParm
1398 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1399 }
1400
1401 return false;
1402 }
1403
1404 for (TemplateParameterList::iterator OldParm = Old->begin(),
1405 OldParmEnd = Old->end(), NewParm = New->begin();
1406 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1407 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001408 unsigned NextDiag = diag::err_template_param_different_kind;
1409 if (TemplateArgLoc.isValid()) {
1410 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1411 NextDiag = diag::note_template_param_different_kind;
1412 }
1413 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001414 << IsTemplateTemplateParm;
1415 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1416 << IsTemplateTemplateParm;
1417 return false;
1418 }
1419
1420 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1421 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001422 // know we're at the same index).
1423#if 0
1424 // FIXME: Enable this code in debug mode *after* we properly go
1425 // through and "instantiate" the template parameter lists of
1426 // template template parameters. It's only after this
1427 // instantiation that (1) any dependent types within the
1428 // template parameter list of the template template parameter
1429 // can be checked, and (2) the template type parameter depths
1430 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001431 QualType OldParmType
1432 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1433 QualType NewParmType
1434 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1435 assert(Context.getCanonicalType(OldParmType) ==
1436 Context.getCanonicalType(NewParmType) &&
1437 "type parameter mismatch?");
1438#endif
1439 } else if (NonTypeTemplateParmDecl *OldNTTP
1440 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1441 // The types of non-type template parameters must agree.
1442 NonTypeTemplateParmDecl *NewNTTP
1443 = cast<NonTypeTemplateParmDecl>(*NewParm);
1444 if (Context.getCanonicalType(OldNTTP->getType()) !=
1445 Context.getCanonicalType(NewNTTP->getType())) {
1446 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001447 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1448 if (TemplateArgLoc.isValid()) {
1449 Diag(TemplateArgLoc,
1450 diag::err_template_arg_template_params_mismatch);
1451 NextDiag = diag::note_template_nontype_parm_different_type;
1452 }
1453 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001454 << NewNTTP->getType()
1455 << IsTemplateTemplateParm;
1456 Diag(OldNTTP->getLocation(),
1457 diag::note_template_nontype_parm_prev_declaration)
1458 << OldNTTP->getType();
1459 }
1460 return false;
1461 }
1462 } else {
1463 // The template parameter lists of template template
1464 // parameters must agree.
1465 // FIXME: Could we perform a faster "type" comparison here?
1466 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1467 "Only template template parameters handled here");
1468 TemplateTemplateParmDecl *OldTTP
1469 = cast<TemplateTemplateParmDecl>(*OldParm);
1470 TemplateTemplateParmDecl *NewTTP
1471 = cast<TemplateTemplateParmDecl>(*NewParm);
1472 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1473 OldTTP->getTemplateParameters(),
1474 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001475 /*IsTemplateTemplateParm=*/true,
1476 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001477 return false;
1478 }
1479 }
1480
1481 return true;
1482}
1483
1484/// \brief Check whether a template can be declared within this scope.
1485///
1486/// If the template declaration is valid in this scope, returns
1487/// false. Otherwise, issues a diagnostic and returns true.
1488bool
1489Sema::CheckTemplateDeclScope(Scope *S,
1490 MultiTemplateParamsArg &TemplateParameterLists) {
1491 assert(TemplateParameterLists.size() > 0 && "Not a template");
1492
1493 // Find the nearest enclosing declaration scope.
1494 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1495 (S->getFlags() & Scope::TemplateParamScope) != 0)
1496 S = S->getParent();
1497
1498 TemplateParameterList *TemplateParams =
1499 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1500 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1501 SourceRange TemplateRange
1502 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1503
1504 // C++ [temp]p2:
1505 // A template-declaration can appear only as a namespace scope or
1506 // class scope declaration.
1507 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1508 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1509 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1510 return Diag(TemplateLoc, diag::err_template_linkage)
1511 << TemplateRange;
1512
1513 Ctx = Ctx->getParent();
1514 }
1515
1516 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1517 return false;
1518
1519 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1520 << TemplateRange;
1521}
Douglas Gregorcc636682009-02-17 23:15:12 +00001522
1523Sema::DeclTy *
1524Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1525 SourceLocation KWLoc,
1526 const CXXScopeSpec &SS,
1527 DeclTy *TemplateD,
1528 SourceLocation TemplateNameLoc,
1529 SourceLocation LAngleLoc,
1530 ASTTemplateArgsPtr TemplateArgs,
1531 SourceLocation *TemplateArgLocs,
1532 SourceLocation RAngleLoc,
1533 AttributeList *Attr,
1534 MultiTemplateParamsArg TemplateParameterLists) {
1535 // FIXME: We need to match up the scope-specifier with the template
1536 // parameter lists, and will eventually end up with a single
1537 // template parameter list remaining (which applies to
1538 // TemplateIdType).
1539 assert(TemplateParameterLists.size() == 1 &&
1540 "Clang doesn't handle with ill-formed specializations yet.");
1541
Chris Lattnerfe90de72009-02-20 21:37:53 +00001542 assert(static_cast<TemplateParameterList*>(*TemplateParameterLists.get())
1543 ->size() == 0 &&
Douglas Gregorcc636682009-02-17 23:15:12 +00001544 "Clang doesn't handle class template partial specializations yet");
1545
1546 // Find the class template we're specializing
1547 ClassTemplateDecl *ClassTemplate
1548 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1549 if (!ClassTemplate)
1550 return 0;
1551
1552 // Check that the specialization uses the same tag kind as the
1553 // original template.
1554 TagDecl::TagKind Kind;
1555 switch (TagSpec) {
1556 default: assert(0 && "Unknown tag type!");
1557 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1558 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1559 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1560 }
1561 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1562 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1563 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1564 diag::note_previous_use);
1565 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1566 }
1567
1568 // Check that the template argument list is well-formed for this
1569 // template.
1570 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1571 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
1572 TemplateArgs, TemplateArgLocs, RAngleLoc,
1573 ConvertedTemplateArgs))
1574 return 0;
1575
1576 assert((ConvertedTemplateArgs.size() ==
1577 ClassTemplate->getTemplateParameters()->size()) &&
1578 "Converted template argument list is too short!");
1579
1580 // Find the class template specialization declaration that
1581 // corresponds to these arguments.
1582 llvm::FoldingSetNodeID ID;
1583 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1584 ConvertedTemplateArgs.size());
1585 void *InsertPos = 0;
1586 ClassTemplateSpecializationDecl *PrevDecl
1587 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1588
1589 ClassTemplateSpecializationDecl *Specialization = 0;
1590
1591 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1592 // Since the only prior class template specialization with these
1593 // arguments was referenced but not declared, reuse that
1594 // declaration node as our own, updating its source location to
1595 // reflect our new declaration.
1596 // FIXME: update source locations
1597 Specialization = PrevDecl;
1598 PrevDecl = 0;
1599 } else {
1600 // Create a new class template specialization declaration node for
1601 // this explicit specialization.
1602 Specialization
1603 = ClassTemplateSpecializationDecl::Create(Context,
1604 ClassTemplate->getDeclContext(),
1605 TemplateNameLoc,
1606 ClassTemplate,
1607 &ConvertedTemplateArgs[0],
1608 ConvertedTemplateArgs.size(),
1609 PrevDecl);
1610
1611 if (PrevDecl) {
1612 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1613 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1614 } else {
1615 ClassTemplate->getSpecializations().InsertNode(Specialization,
1616 InsertPos);
1617 }
1618 }
1619
1620 // Note that this is an explicit specialization.
1621 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1622
1623 // Check that this isn't a redefinition of this specialization.
1624 if (TK == TK_Definition) {
1625 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1626 // FIXME: Should also handle explicit specialization after
1627 // implicit instantiation with a special diagnostic.
1628 SourceRange Range(TemplateNameLoc, RAngleLoc);
1629 Diag(TemplateNameLoc, diag::err_redefinition)
1630 << Specialization << Range;
1631 Diag(Def->getLocation(), diag::note_previous_definition);
1632 Specialization->setInvalidDecl();
1633 return 0;
1634 }
1635 }
1636
1637 // FIXME: Do we want to create a nicely sugared type to use as the
1638 // type for this explicit specialization?
1639
1640 // Set the lexical context. If the tag has a C++ scope specifier,
1641 // the lexical context will be different from the semantic context.
1642 Specialization->setLexicalDeclContext(CurContext);
1643
1644 // We may be starting the definition of this specialization.
1645 if (TK == TK_Definition)
1646 Specialization->startDefinition();
1647
1648 // Add the specialization into its lexical context, so that it can
1649 // be seen when iterating through the list of declarations in that
1650 // context. However, specializations are not found by name lookup.
1651 CurContext->addDecl(Specialization);
1652 return Specialization;
1653}