blob: aabbffa4c3d8a3014605680f780fa4633828c06d [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.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
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 Gregor39a8de12009-02-25 19:37:18 +000029TemplateNameKind 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);
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +0000690 Decl->setLexicalDeclContext(CurContext);
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000691 }
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +0000692
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000693 // Build the fully-sugared type for this class template
694 // specialization, which refers back to the class template
695 // specialization we created or found.
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000696 QualType Result
697 = Context.getClassTemplateSpecializationType(Template,
698 TemplateArgs.size(),
699 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
700 TemplateArgs.getArgIsType(),
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000701 Context.getTypeDeclType(Decl));
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000702 TemplateArgs.release();
703 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000704}
705
Douglas Gregorc15cb382009-02-09 23:23:08 +0000706/// \brief Check that the given template argument list is well-formed
707/// for specializing the given template.
708bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
709 SourceLocation TemplateLoc,
710 SourceLocation LAngleLoc,
711 ASTTemplateArgsPtr& Args,
712 SourceLocation *TemplateArgLocs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000713 SourceLocation RAngleLoc,
714 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000715 TemplateParameterList *Params = Template->getTemplateParameters();
716 unsigned NumParams = Params->size();
717 unsigned NumArgs = Args.size();
718 bool Invalid = false;
719
720 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000721 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000722 // FIXME: point at either the first arg beyond what we can handle,
723 // or the '>', depending on whether we have too many or too few
724 // arguments.
725 SourceRange Range;
726 if (NumArgs > NumParams)
727 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
728 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
729 << (NumArgs > NumParams)
730 << (isa<ClassTemplateDecl>(Template)? 0 :
731 isa<FunctionTemplateDecl>(Template)? 1 :
732 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
733 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000734 Diag(Template->getLocation(), diag::note_template_decl_here)
735 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000736 Invalid = true;
737 }
738
739 // C++ [temp.arg]p1:
740 // [...] The type and form of each template-argument specified in
741 // a template-id shall match the type and form specified for the
742 // corresponding parameter declared by the template in its
743 // template-parameter-list.
744 unsigned ArgIdx = 0;
745 for (TemplateParameterList::iterator Param = Params->begin(),
746 ParamEnd = Params->end();
747 Param != ParamEnd; ++Param, ++ArgIdx) {
748 // Decode the template argument
749 QualType ArgType;
750 Expr *ArgExpr = 0;
751 SourceLocation ArgLoc;
752 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000753 // Retrieve the default template argument from the template
754 // parameter.
755 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
756 if (!TTP->hasDefaultArgument())
757 break;
758
759 ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000760
761 // If the argument type is dependent, instantiate it now based
762 // on the previously-computed template arguments.
763 if (ArgType->isDependentType())
764 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
765 TTP->getDefaultArgumentLoc(),
766 TTP->getDeclName());
767
768 if (ArgType.isNull())
769 break;
770
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000771 ArgLoc = TTP->getDefaultArgumentLoc();
772 } else if (NonTypeTemplateParmDecl *NTTP
773 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
774 if (!NTTP->hasDefaultArgument())
775 break;
776
777 ArgExpr = NTTP->getDefaultArgument();
778 ArgLoc = NTTP->getDefaultArgumentLoc();
779 } else {
780 TemplateTemplateParmDecl *TempParm
781 = cast<TemplateTemplateParmDecl>(*Param);
782
783 if (!TempParm->hasDefaultArgument())
784 break;
785
786 ArgExpr = TempParm->getDefaultArgument();
787 ArgLoc = TempParm->getDefaultArgumentLoc();
788 }
789 } else {
790 // Retrieve the template argument produced by the user.
Douglas Gregorc15cb382009-02-09 23:23:08 +0000791 ArgLoc = TemplateArgLocs[ArgIdx];
792
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000793 if (Args.getArgIsType()[ArgIdx])
794 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
795 else
796 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
797 }
798
Douglas Gregorc15cb382009-02-09 23:23:08 +0000799
800 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
801 // Check template type parameters.
802 if (!ArgType.isNull()) {
Douglas Gregor658bbb52009-02-11 16:16:59 +0000803 if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000804 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000805
806 // Add the converted template type argument.
807 Converted.push_back(
808 TemplateArgument(Context.getCanonicalType(ArgType)));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000809 continue;
810 }
811
812 // C++ [temp.arg.type]p1:
813 // A template-argument for a template-parameter which is a
814 // type shall be a type-id.
815
816 // We have a template type parameter but the template argument
817 // is an expression.
818 Diag(ArgExpr->getSourceRange().getBegin(),
819 diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +0000820 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000821 Invalid = true;
822 } else if (NonTypeTemplateParmDecl *NTTP
823 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
824 // Check non-type template parameters.
825 if (ArgExpr) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000826 if (CheckTemplateArgument(NTTP, ArgExpr, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000827 Invalid = true;
828 continue;
829 }
830
831 // We have a non-type template parameter but the template
832 // argument is a type.
833
834 // C++ [temp.arg]p2:
835 // In a template-argument, an ambiguity between a type-id and
836 // an expression is resolved to a type-id, regardless of the
837 // form of the corresponding template-parameter.
838 //
839 // We warn specifically about this case, since it can be rather
840 // confusing for users.
841 if (ArgType->isFunctionType())
842 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
843 << ArgType;
844 else
845 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor8b642592009-02-10 00:53:15 +0000846 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000847 Invalid = true;
848 } else {
849 // Check template template parameters.
850 TemplateTemplateParmDecl *TempParm
851 = cast<TemplateTemplateParmDecl>(*Param);
852
853 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
854 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
Douglas Gregor658bbb52009-02-11 16:16:59 +0000855 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000856 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000857
858 // Add the converted template argument.
859 // FIXME: Need the "canonical" template declaration!
860 Converted.push_back(
861 TemplateArgument(cast<DeclRefExpr>(ArgExpr)->getDecl()));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000862 continue;
863 }
864
865 // We have a template template parameter but the template
866 // argument does not refer to a template.
867 Diag(ArgLoc, diag::err_template_arg_must_be_template);
868 Invalid = true;
869 }
870 }
871
872 return Invalid;
873}
874
875/// \brief Check a template argument against its corresponding
876/// template type parameter.
877///
878/// This routine implements the semantics of C++ [temp.arg.type]. It
879/// returns true if an error occurred, and false otherwise.
880bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
881 QualType Arg, SourceLocation ArgLoc) {
882 // C++ [temp.arg.type]p2:
883 // A local type, a type with no linkage, an unnamed type or a type
884 // compounded from any of these types shall not be used as a
885 // template-argument for a template type-parameter.
886 //
887 // FIXME: Perform the recursive and no-linkage type checks.
888 const TagType *Tag = 0;
889 if (const EnumType *EnumT = Arg->getAsEnumType())
890 Tag = EnumT;
891 else if (const RecordType *RecordT = Arg->getAsRecordType())
892 Tag = RecordT;
893 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
894 return Diag(ArgLoc, diag::err_template_arg_local_type)
895 << QualType(Tag, 0);
896 else if (Tag && !Tag->getDecl()->getDeclName()) {
897 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
898 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
899 return true;
900 }
901
902 return false;
903}
904
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000905/// \brief Checks whether the given template argument is the address
906/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000907bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
908 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000909 bool Invalid = false;
910
911 // See through any implicit casts we added to fix the type.
912 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
913 Arg = Cast->getSubExpr();
914
915 // C++ [temp.arg.nontype]p1:
916 //
917 // A template-argument for a non-type, non-template
918 // template-parameter shall be one of: [...]
919 //
920 // -- the address of an object or function with external
921 // linkage, including function templates and function
922 // template-ids but excluding non-static class members,
923 // expressed as & id-expression where the & is optional if
924 // the name refers to a function or array, or if the
925 // corresponding template-parameter is a reference; or
926 DeclRefExpr *DRE = 0;
927
928 // Ignore (and complain about) any excess parentheses.
929 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
930 if (!Invalid) {
931 Diag(Arg->getSourceRange().getBegin(),
932 diag::err_template_arg_extra_parens)
933 << Arg->getSourceRange();
934 Invalid = true;
935 }
936
937 Arg = Parens->getSubExpr();
938 }
939
940 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
941 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
942 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
943 } else
944 DRE = dyn_cast<DeclRefExpr>(Arg);
945
946 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
947 return Diag(Arg->getSourceRange().getBegin(),
948 diag::err_template_arg_not_object_or_func_form)
949 << Arg->getSourceRange();
950
951 // Cannot refer to non-static data members
952 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
953 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
954 << Field << Arg->getSourceRange();
955
956 // Cannot refer to non-static member functions
957 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
958 if (!Method->isStatic())
959 return Diag(Arg->getSourceRange().getBegin(),
960 diag::err_template_arg_method)
961 << Method << Arg->getSourceRange();
962
963 // Functions must have external linkage.
964 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
965 if (Func->getStorageClass() == FunctionDecl::Static) {
966 Diag(Arg->getSourceRange().getBegin(),
967 diag::err_template_arg_function_not_extern)
968 << Func << Arg->getSourceRange();
969 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
970 << true;
971 return true;
972 }
973
974 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000975 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000976 return Invalid;
977 }
978
979 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
980 if (!Var->hasGlobalStorage()) {
981 Diag(Arg->getSourceRange().getBegin(),
982 diag::err_template_arg_object_not_extern)
983 << Var << Arg->getSourceRange();
984 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
985 << true;
986 return true;
987 }
988
989 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000990 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +0000991 return Invalid;
992 }
993
994 // We found something else, but we don't know specifically what it is.
995 Diag(Arg->getSourceRange().getBegin(),
996 diag::err_template_arg_not_object_or_func)
997 << Arg->getSourceRange();
998 Diag(DRE->getDecl()->getLocation(),
999 diag::note_template_arg_refers_here);
1000 return true;
1001}
1002
1003/// \brief Checks whether the given template argument is a pointer to
1004/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001005bool
1006Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001007 bool Invalid = false;
1008
1009 // See through any implicit casts we added to fix the type.
1010 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1011 Arg = Cast->getSubExpr();
1012
1013 // C++ [temp.arg.nontype]p1:
1014 //
1015 // A template-argument for a non-type, non-template
1016 // template-parameter shall be one of: [...]
1017 //
1018 // -- a pointer to member expressed as described in 5.3.1.
1019 QualifiedDeclRefExpr *DRE = 0;
1020
1021 // Ignore (and complain about) any excess parentheses.
1022 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1023 if (!Invalid) {
1024 Diag(Arg->getSourceRange().getBegin(),
1025 diag::err_template_arg_extra_parens)
1026 << Arg->getSourceRange();
1027 Invalid = true;
1028 }
1029
1030 Arg = Parens->getSubExpr();
1031 }
1032
1033 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1034 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1035 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1036
1037 if (!DRE)
1038 return Diag(Arg->getSourceRange().getBegin(),
1039 diag::err_template_arg_not_pointer_to_member_form)
1040 << Arg->getSourceRange();
1041
1042 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1043 assert((isa<FieldDecl>(DRE->getDecl()) ||
1044 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1045 "Only non-static member pointers can make it here");
1046
1047 // Okay: this is the address of a non-static member, and therefore
1048 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001049 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001050 return Invalid;
1051 }
1052
1053 // We found something else, but we don't know specifically what it is.
1054 Diag(Arg->getSourceRange().getBegin(),
1055 diag::err_template_arg_not_pointer_to_member_form)
1056 << Arg->getSourceRange();
1057 Diag(DRE->getDecl()->getLocation(),
1058 diag::note_template_arg_refers_here);
1059 return true;
1060}
1061
Douglas Gregorc15cb382009-02-09 23:23:08 +00001062/// \brief Check a template argument against its corresponding
1063/// non-type template parameter.
1064///
1065/// This routine implements the semantics of C++ [temp.arg.nontype].
1066/// It returns true if an error occurred, and false otherwise.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001067///
1068/// If Converted is non-NULL and no errors occur, the value
1069/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001070bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001071 Expr *&Arg,
1072 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001073 // If either the parameter has a dependent type or the argument is
1074 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001075 // FIXME: Add template argument to Converted!
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001076 if (Param->getType()->isDependentType() || Arg->isTypeDependent())
1077 return false;
1078
1079 // C++ [temp.arg.nontype]p5:
1080 // The following conversions are performed on each expression used
1081 // as a non-type template-argument. If a non-type
1082 // template-argument cannot be converted to the type of the
1083 // corresponding template-parameter then the program is
1084 // ill-formed.
1085 //
1086 // -- for a non-type template-parameter of integral or
1087 // enumeration type, integral promotions (4.5) and integral
1088 // conversions (4.7) are applied.
1089 QualType ParamType = Param->getType();
Douglas Gregora35284b2009-02-11 00:19:33 +00001090 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001091 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001092 // C++ [temp.arg.nontype]p1:
1093 // A template-argument for a non-type, non-template
1094 // template-parameter shall be one of:
1095 //
1096 // -- an integral constant-expression of integral or enumeration
1097 // type; or
1098 // -- the name of a non-type template-parameter; or
1099 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001100 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001101 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1102 Diag(Arg->getSourceRange().getBegin(),
1103 diag::err_template_arg_not_integral_or_enumeral)
1104 << ArgType << Arg->getSourceRange();
1105 Diag(Param->getLocation(), diag::note_template_param_here);
1106 return true;
1107 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001108 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001109 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1110 << ArgType << Arg->getSourceRange();
1111 return true;
1112 }
1113
1114 // FIXME: We need some way to more easily get the unqualified form
1115 // of the types without going all the way to the
1116 // canonical type.
1117 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1118 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1119 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1120 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1121
1122 // Try to convert the argument to the parameter's type.
1123 if (ParamType == ArgType) {
1124 // Okay: no conversion necessary
1125 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1126 !ParamType->isEnumeralType()) {
1127 // This is an integral promotion or conversion.
1128 ImpCastExprToType(Arg, ParamType);
1129 } else {
1130 // We can't perform this conversion.
1131 Diag(Arg->getSourceRange().getBegin(),
1132 diag::err_template_arg_not_convertible)
1133 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1134 Diag(Param->getLocation(), diag::note_template_param_here);
1135 return true;
1136 }
1137
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001138 // FIXME: Check overflow of template arguments?
1139
1140 if (Converted) {
1141 // Add the value of this argument to the list of converted
1142 // arguments. We use the bitwidth and signedness of the template
1143 // parameter.
1144 QualType IntegerType = Context.getCanonicalType(ParamType);
1145 if (const EnumType *Enum = IntegerType->getAsEnumType())
1146 IntegerType = Enum->getDecl()->getIntegerType();
1147
1148 llvm::APInt CanonicalArg(Context.getTypeSize(IntegerType), 0,
1149 IntegerType->isSignedIntegerType());
1150 CanonicalArg = Value;
1151
1152 Converted->push_back(TemplateArgument(CanonicalArg));
1153 }
1154
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001155 return false;
1156 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001157
Douglas Gregorb86b0572009-02-11 01:18:59 +00001158 // Handle pointer-to-function, reference-to-function, and
1159 // pointer-to-member-function all in (roughly) the same way.
1160 if (// -- For a non-type template-parameter of type pointer to
1161 // function, only the function-to-pointer conversion (4.3) is
1162 // applied. If the template-argument represents a set of
1163 // overloaded functions (or a pointer to such), the matching
1164 // function is selected from the set (13.4).
1165 (ParamType->isPointerType() &&
1166 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1167 // -- For a non-type template-parameter of type reference to
1168 // function, no conversions apply. If the template-argument
1169 // represents a set of overloaded functions, the matching
1170 // function is selected from the set (13.4).
1171 (ParamType->isReferenceType() &&
1172 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1173 // -- For a non-type template-parameter of type pointer to
1174 // member function, no conversions apply. If the
1175 // template-argument represents a set of overloaded member
1176 // functions, the matching member function is selected from
1177 // the set (13.4).
1178 (ParamType->isMemberPointerType() &&
1179 ParamType->getAsMemberPointerType()->getPointeeType()
1180 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001181 if (Context.hasSameUnqualifiedType(ArgType,
1182 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001183 // We don't have to do anything: the types already match.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001184 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001185 ArgType = Context.getPointerType(ArgType);
1186 ImpCastExprToType(Arg, ArgType);
1187 } else if (FunctionDecl *Fn
1188 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001189 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1190 return true;
1191
Douglas Gregora35284b2009-02-11 00:19:33 +00001192 FixOverloadedFunctionReference(Arg, Fn);
1193 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001194 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001195 ArgType = Context.getPointerType(Arg->getType());
1196 ImpCastExprToType(Arg, ArgType);
1197 }
1198 }
1199
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001200 if (!Context.hasSameUnqualifiedType(ArgType,
1201 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001202 // We can't perform this conversion.
1203 Diag(Arg->getSourceRange().getBegin(),
1204 diag::err_template_arg_not_convertible)
1205 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1206 Diag(Param->getLocation(), diag::note_template_param_here);
1207 return true;
1208 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001209
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001210 if (ParamType->isMemberPointerType()) {
1211 NamedDecl *Member = 0;
1212 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1213 return true;
1214
1215 if (Converted)
1216 Converted->push_back(TemplateArgument(Member));
1217
1218 return false;
1219 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001220
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001221 NamedDecl *Entity = 0;
1222 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1223 return true;
1224
1225 if (Converted)
1226 Converted->push_back(TemplateArgument(Entity));
1227 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001228 }
1229
Chris Lattnerfe90de72009-02-20 21:37:53 +00001230 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001231 // -- for a non-type template-parameter of type pointer to
1232 // object, qualification conversions (4.4) and the
1233 // array-to-pointer conversion (4.2) are applied.
Chris Lattnerfe90de72009-02-20 21:37:53 +00001234 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001235 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001236
Douglas Gregorb86b0572009-02-11 01:18:59 +00001237 if (ArgType->isArrayType()) {
1238 ArgType = Context.getArrayDecayedType(ArgType);
1239 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001240 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001241
1242 if (IsQualificationConversion(ArgType, ParamType)) {
1243 ArgType = ParamType;
1244 ImpCastExprToType(Arg, ParamType);
1245 }
1246
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001247 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001248 // We can't perform this conversion.
1249 Diag(Arg->getSourceRange().getBegin(),
1250 diag::err_template_arg_not_convertible)
1251 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1252 Diag(Param->getLocation(), diag::note_template_param_here);
1253 return true;
1254 }
1255
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001256 NamedDecl *Entity = 0;
1257 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1258 return true;
1259
1260 if (Converted)
1261 Converted->push_back(TemplateArgument(Entity));
1262
1263 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001264 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001265
1266 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1267 // -- For a non-type template-parameter of type reference to
1268 // object, no conversions apply. The type referred to by the
1269 // reference may be more cv-qualified than the (otherwise
1270 // identical) type of the template-argument. The
1271 // template-parameter is bound directly to the
1272 // template-argument, which must be an lvalue.
1273 assert(ParamRefType->getPointeeType()->isObjectType() &&
1274 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001275
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001276 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001277 Diag(Arg->getSourceRange().getBegin(),
1278 diag::err_template_arg_no_ref_bind)
1279 << Param->getType() << Arg->getType()
1280 << Arg->getSourceRange();
1281 Diag(Param->getLocation(), diag::note_template_param_here);
1282 return true;
1283 }
1284
1285 unsigned ParamQuals
1286 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1287 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1288
1289 if ((ParamQuals | ArgQuals) != ParamQuals) {
1290 Diag(Arg->getSourceRange().getBegin(),
1291 diag::err_template_arg_ref_bind_ignores_quals)
1292 << Param->getType() << Arg->getType()
1293 << Arg->getSourceRange();
1294 Diag(Param->getLocation(), diag::note_template_param_here);
1295 return true;
1296 }
1297
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001298 NamedDecl *Entity = 0;
1299 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1300 return true;
1301
1302 if (Converted)
1303 Converted->push_back(TemplateArgument(Entity));
1304
1305 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001306 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001307
1308 // -- For a non-type template-parameter of type pointer to data
1309 // member, qualification conversions (4.4) are applied.
1310 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1311
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001312 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001313 // Types match exactly: nothing more to do here.
1314 } else if (IsQualificationConversion(ArgType, ParamType)) {
1315 ImpCastExprToType(Arg, ParamType);
1316 } else {
1317 // We can't perform this conversion.
1318 Diag(Arg->getSourceRange().getBegin(),
1319 diag::err_template_arg_not_convertible)
1320 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1321 Diag(Param->getLocation(), diag::note_template_param_here);
1322 return true;
1323 }
1324
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001325 NamedDecl *Member = 0;
1326 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1327 return true;
1328
1329 if (Converted)
1330 Converted->push_back(TemplateArgument(Member));
1331
1332 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001333}
1334
1335/// \brief Check a template argument against its corresponding
1336/// template template parameter.
1337///
1338/// This routine implements the semantics of C++ [temp.arg.template].
1339/// It returns true if an error occurred, and false otherwise.
1340bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1341 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001342 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1343 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1344
1345 // C++ [temp.arg.template]p1:
1346 // A template-argument for a template template-parameter shall be
1347 // the name of a class template, expressed as id-expression. Only
1348 // primary class templates are considered when matching the
1349 // template template argument with the corresponding parameter;
1350 // partial specializations are not considered even if their
1351 // parameter lists match that of the template template parameter.
1352 if (!isa<ClassTemplateDecl>(Template)) {
1353 assert(isa<FunctionTemplateDecl>(Template) &&
1354 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001355 Diag(Arg->getSourceRange().getBegin(),
1356 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001357 << Template;
1358 }
1359
1360 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1361 Param->getTemplateParameters(),
1362 true, true,
1363 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001364}
1365
Douglas Gregorddc29e12009-02-06 22:42:48 +00001366/// \brief Determine whether the given template parameter lists are
1367/// equivalent.
1368///
1369/// \param New The new template parameter list, typically written in the
1370/// source code as part of a new template declaration.
1371///
1372/// \param Old The old template parameter list, typically found via
1373/// name lookup of the template declared with this template parameter
1374/// list.
1375///
1376/// \param Complain If true, this routine will produce a diagnostic if
1377/// the template parameter lists are not equivalent.
1378///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001379/// \param IsTemplateTemplateParm If true, this routine is being
1380/// called to compare the template parameter lists of a template
1381/// template parameter.
1382///
1383/// \param TemplateArgLoc If this source location is valid, then we
1384/// are actually checking the template parameter list of a template
1385/// argument (New) against the template parameter list of its
1386/// corresponding template template parameter (Old). We produce
1387/// slightly different diagnostics in this scenario.
1388///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001389/// \returns True if the template parameter lists are equal, false
1390/// otherwise.
1391bool
1392Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1393 TemplateParameterList *Old,
1394 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001395 bool IsTemplateTemplateParm,
1396 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001397 if (Old->size() != New->size()) {
1398 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001399 unsigned NextDiag = diag::err_template_param_list_different_arity;
1400 if (TemplateArgLoc.isValid()) {
1401 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1402 NextDiag = diag::note_template_param_list_different_arity;
1403 }
1404 Diag(New->getTemplateLoc(), NextDiag)
1405 << (New->size() > Old->size())
1406 << IsTemplateTemplateParm
1407 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001408 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1409 << IsTemplateTemplateParm
1410 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1411 }
1412
1413 return false;
1414 }
1415
1416 for (TemplateParameterList::iterator OldParm = Old->begin(),
1417 OldParmEnd = Old->end(), NewParm = New->begin();
1418 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1419 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001420 unsigned NextDiag = diag::err_template_param_different_kind;
1421 if (TemplateArgLoc.isValid()) {
1422 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1423 NextDiag = diag::note_template_param_different_kind;
1424 }
1425 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001426 << IsTemplateTemplateParm;
1427 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1428 << IsTemplateTemplateParm;
1429 return false;
1430 }
1431
1432 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1433 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001434 // know we're at the same index).
1435#if 0
1436 // FIXME: Enable this code in debug mode *after* we properly go
1437 // through and "instantiate" the template parameter lists of
1438 // template template parameters. It's only after this
1439 // instantiation that (1) any dependent types within the
1440 // template parameter list of the template template parameter
1441 // can be checked, and (2) the template type parameter depths
1442 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001443 QualType OldParmType
1444 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1445 QualType NewParmType
1446 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1447 assert(Context.getCanonicalType(OldParmType) ==
1448 Context.getCanonicalType(NewParmType) &&
1449 "type parameter mismatch?");
1450#endif
1451 } else if (NonTypeTemplateParmDecl *OldNTTP
1452 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1453 // The types of non-type template parameters must agree.
1454 NonTypeTemplateParmDecl *NewNTTP
1455 = cast<NonTypeTemplateParmDecl>(*NewParm);
1456 if (Context.getCanonicalType(OldNTTP->getType()) !=
1457 Context.getCanonicalType(NewNTTP->getType())) {
1458 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001459 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1460 if (TemplateArgLoc.isValid()) {
1461 Diag(TemplateArgLoc,
1462 diag::err_template_arg_template_params_mismatch);
1463 NextDiag = diag::note_template_nontype_parm_different_type;
1464 }
1465 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001466 << NewNTTP->getType()
1467 << IsTemplateTemplateParm;
1468 Diag(OldNTTP->getLocation(),
1469 diag::note_template_nontype_parm_prev_declaration)
1470 << OldNTTP->getType();
1471 }
1472 return false;
1473 }
1474 } else {
1475 // The template parameter lists of template template
1476 // parameters must agree.
1477 // FIXME: Could we perform a faster "type" comparison here?
1478 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1479 "Only template template parameters handled here");
1480 TemplateTemplateParmDecl *OldTTP
1481 = cast<TemplateTemplateParmDecl>(*OldParm);
1482 TemplateTemplateParmDecl *NewTTP
1483 = cast<TemplateTemplateParmDecl>(*NewParm);
1484 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1485 OldTTP->getTemplateParameters(),
1486 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001487 /*IsTemplateTemplateParm=*/true,
1488 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001489 return false;
1490 }
1491 }
1492
1493 return true;
1494}
1495
1496/// \brief Check whether a template can be declared within this scope.
1497///
1498/// If the template declaration is valid in this scope, returns
1499/// false. Otherwise, issues a diagnostic and returns true.
1500bool
1501Sema::CheckTemplateDeclScope(Scope *S,
1502 MultiTemplateParamsArg &TemplateParameterLists) {
1503 assert(TemplateParameterLists.size() > 0 && "Not a template");
1504
1505 // Find the nearest enclosing declaration scope.
1506 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1507 (S->getFlags() & Scope::TemplateParamScope) != 0)
1508 S = S->getParent();
1509
1510 TemplateParameterList *TemplateParams =
1511 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1512 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1513 SourceRange TemplateRange
1514 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1515
1516 // C++ [temp]p2:
1517 // A template-declaration can appear only as a namespace scope or
1518 // class scope declaration.
1519 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1520 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1521 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1522 return Diag(TemplateLoc, diag::err_template_linkage)
1523 << TemplateRange;
1524
1525 Ctx = Ctx->getParent();
1526 }
1527
1528 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1529 return false;
1530
1531 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1532 << TemplateRange;
1533}
Douglas Gregorcc636682009-02-17 23:15:12 +00001534
Douglas Gregor88b70942009-02-25 22:02:03 +00001535/// \brief Check whether a class template specialization in the
1536/// current context is well-formed.
1537///
1538/// This routine determines whether a class template specialization
1539/// can be declared in the current context (C++ [temp.expl.spec]p2)
1540/// and emits appropriate diagnostics if there was an error. It
1541/// returns true if there was an error that we cannot recover from,
1542/// and false otherwise.
1543bool
1544Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1545 ClassTemplateSpecializationDecl *PrevDecl,
1546 SourceLocation TemplateNameLoc,
1547 SourceRange ScopeSpecifierRange) {
1548 // C++ [temp.expl.spec]p2:
1549 // An explicit specialization shall be declared in the namespace
1550 // of which the template is a member, or, for member templates, in
1551 // the namespace of which the enclosing class or enclosing class
1552 // template is a member. An explicit specialization of a member
1553 // function, member class or static data member of a class
1554 // template shall be declared in the namespace of which the class
1555 // template is a member. Such a declaration may also be a
1556 // definition. If the declaration is not a definition, the
1557 // specialization may be defined later in the name- space in which
1558 // the explicit specialization was declared, or in a namespace
1559 // that encloses the one in which the explicit specialization was
1560 // declared.
1561 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1562 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1563 << ClassTemplate;
1564 return true;
1565 }
1566
1567 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1568 DeclContext *TemplateContext
1569 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1570 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1571 // There is no prior declaration of this entity, so this
1572 // specialization must be in the same context as the template
1573 // itself.
1574 if (DC != TemplateContext) {
1575 if (isa<TranslationUnitDecl>(TemplateContext))
1576 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1577 << ClassTemplate << ScopeSpecifierRange;
1578 else if (isa<NamespaceDecl>(TemplateContext))
1579 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1580 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1581 << ScopeSpecifierRange;
1582
1583 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1584 }
1585
1586 return false;
1587 }
1588
1589 // We have a previous declaration of this entity. Make sure that
1590 // this redeclaration (or definition) occurs in an enclosing namespace.
1591 if (!CurContext->Encloses(TemplateContext)) {
1592 if (isa<TranslationUnitDecl>(TemplateContext))
1593 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1594 << ClassTemplate << ScopeSpecifierRange;
1595 else if (isa<NamespaceDecl>(TemplateContext))
1596 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1597 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1598 << ScopeSpecifierRange;
1599
1600 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1601 }
1602
1603 return false;
1604}
1605
Douglas Gregorcc636682009-02-17 23:15:12 +00001606Sema::DeclTy *
1607Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1608 SourceLocation KWLoc,
1609 const CXXScopeSpec &SS,
1610 DeclTy *TemplateD,
1611 SourceLocation TemplateNameLoc,
1612 SourceLocation LAngleLoc,
1613 ASTTemplateArgsPtr TemplateArgs,
1614 SourceLocation *TemplateArgLocs,
1615 SourceLocation RAngleLoc,
1616 AttributeList *Attr,
1617 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00001618 // Find the class template we're specializing
1619 ClassTemplateDecl *ClassTemplate
1620 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1621 if (!ClassTemplate)
1622 return 0;
1623
Douglas Gregor88b70942009-02-25 22:02:03 +00001624 // Check the validity of the template headers that introduce this
1625 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001626 // FIXME: Once we have member templates, we'll need to check
1627 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1628 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001629 if (TemplateParameterLists.size() == 0)
1630 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00001631 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001632 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00001633 TemplateParameterList *TemplateParams
1634 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1635 if (TemplateParameterLists.size() > 1) {
1636 Diag(TemplateParams->getTemplateLoc(),
1637 diag::err_template_spec_extra_headers);
1638 return 0;
1639 }
1640
1641 if (TemplateParams->size() > 0) {
1642 // FIXME: No support for class template partial specialization.
1643 Diag(TemplateParams->getTemplateLoc(),
1644 diag::unsup_template_partial_spec);
1645 return 0;
1646 }
1647 }
1648
Douglas Gregorcc636682009-02-17 23:15:12 +00001649 // Check that the specialization uses the same tag kind as the
1650 // original template.
1651 TagDecl::TagKind Kind;
1652 switch (TagSpec) {
1653 default: assert(0 && "Unknown tag type!");
1654 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1655 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1656 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1657 }
1658 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1659 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1660 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1661 diag::note_previous_use);
1662 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1663 }
1664
1665 // Check that the template argument list is well-formed for this
1666 // template.
1667 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1668 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
1669 TemplateArgs, TemplateArgLocs, RAngleLoc,
1670 ConvertedTemplateArgs))
1671 return 0;
1672
1673 assert((ConvertedTemplateArgs.size() ==
1674 ClassTemplate->getTemplateParameters()->size()) &&
1675 "Converted template argument list is too short!");
1676
1677 // Find the class template specialization declaration that
1678 // corresponds to these arguments.
1679 llvm::FoldingSetNodeID ID;
1680 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1681 ConvertedTemplateArgs.size());
1682 void *InsertPos = 0;
1683 ClassTemplateSpecializationDecl *PrevDecl
1684 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1685
1686 ClassTemplateSpecializationDecl *Specialization = 0;
1687
Douglas Gregor88b70942009-02-25 22:02:03 +00001688 // Check whether we can declare a class template specialization in
1689 // the current scope.
1690 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1691 TemplateNameLoc,
1692 SS.getRange()))
1693 return 0;
1694
Douglas Gregorcc636682009-02-17 23:15:12 +00001695 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1696 // Since the only prior class template specialization with these
1697 // arguments was referenced but not declared, reuse that
1698 // declaration node as our own, updating its source location to
1699 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00001700 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001701 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00001702 PrevDecl = 0;
1703 } else {
1704 // Create a new class template specialization declaration node for
1705 // this explicit specialization.
1706 Specialization
1707 = ClassTemplateSpecializationDecl::Create(Context,
1708 ClassTemplate->getDeclContext(),
1709 TemplateNameLoc,
1710 ClassTemplate,
1711 &ConvertedTemplateArgs[0],
1712 ConvertedTemplateArgs.size(),
1713 PrevDecl);
1714
1715 if (PrevDecl) {
1716 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1717 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1718 } else {
1719 ClassTemplate->getSpecializations().InsertNode(Specialization,
1720 InsertPos);
1721 }
1722 }
1723
1724 // Note that this is an explicit specialization.
1725 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1726
1727 // Check that this isn't a redefinition of this specialization.
1728 if (TK == TK_Definition) {
1729 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1730 // FIXME: Should also handle explicit specialization after
1731 // implicit instantiation with a special diagnostic.
1732 SourceRange Range(TemplateNameLoc, RAngleLoc);
1733 Diag(TemplateNameLoc, diag::err_redefinition)
1734 << Specialization << Range;
1735 Diag(Def->getLocation(), diag::note_previous_definition);
1736 Specialization->setInvalidDecl();
1737 return 0;
1738 }
1739 }
1740
Douglas Gregorfc705b82009-02-26 22:19:44 +00001741 // Build the fully-sugared type for this class template
1742 // specialization as the user wrote in the specialization
1743 // itself. This means that we'll pretty-print the type retrieved
1744 // from the specialization's declaration the way that the user
1745 // actually wrote the specialization, rather than formatting the
1746 // name based on the "canonical" representation used to store the
1747 // template arguments in the specialization.
1748 Specialization->setTypeAsWritten(
1749 Context.getClassTemplateSpecializationType(ClassTemplate,
1750 TemplateArgs.size(),
1751 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
1752 TemplateArgs.getArgIsType(),
1753 Context.getTypeDeclType(Specialization)));
1754 TemplateArgs.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00001755
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001756 // C++ [temp.expl.spec]p9:
1757 // A template explicit specialization is in the scope of the
1758 // namespace in which the template was defined.
1759 //
1760 // We actually implement this paragraph where we set the semantic
1761 // context (in the creation of the ClassTemplateSpecializationDecl),
1762 // but we also maintain the lexical context where the actual
1763 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00001764 Specialization->setLexicalDeclContext(CurContext);
1765
1766 // We may be starting the definition of this specialization.
1767 if (TK == TK_Definition)
1768 Specialization->startDefinition();
1769
1770 // Add the specialization into its lexical context, so that it can
1771 // be seen when iterating through the list of declarations in that
1772 // context. However, specializations are not found by name lookup.
1773 CurContext->addDecl(Specialization);
1774 return Specialization;
1775}