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