blob: b339a7ba38a9f5e6e3c1f72a55b13dd323aea780 [file] [log] [blame]
Douglas Gregordd861062008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//+//===----------------------------------------------------------------------===/
9
10//
11// This file implements semantic analysis for C++ templates.
12//+//===----------------------------------------------------------------------===/
13
14#include "Sema.h"
Douglas Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregor2fa10442008-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 Gregor8e458f42009-02-09 18:46:07 +000029Sema::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
30 DeclTy *&Template,
31 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000033
34 if (IIDecl) {
Douglas Gregor8e458f42009-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 Gregor279272e2009-02-04 19:02:06 +000046
Douglas Gregor8e458f42009-02-09 18:46:07 +000047 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000049 if (FD->getType()->isDependentType()) {
50 Template = FD;
51 return TNK_Function_template;
52 }
Douglas Gregor2fa10442008-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 Gregor8e458f42009-02-09 18:46:07 +000058 if ((*F)->getType()->isDependentType()) {
59 Template = Ovl;
60 return TNK_Function_template;
61 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000062 }
63 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000064 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000065 return TNK_Non_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +000066}
67
Douglas Gregordd861062008-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 Gregor2715a1f2008-12-08 18:40:42 +000073 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-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 Gregor279272e2009-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 Gregordd861062008-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 Gregor52473432008-12-24 02:52:09 +0000112 SourceLocation ParamNameLoc,
113 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-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 Gregor09be81b2009-02-04 17:27:36 +0000119 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000120 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000121 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
122 PrevDecl);
123 }
124
Douglas Gregord406b032009-02-06 22:42:48 +0000125 SourceLocation Loc = ParamNameLoc;
126 if (!ParamName)
127 Loc = KeyLoc;
128
Douglas Gregordd861062008-12-05 18:15:24 +0000129 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000130 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000131 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-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 Gregor9225a7e2009-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 Gregordd861062008-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 Gregor52473432008-12-24 02:52:09 +0000171Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
172 unsigned Depth,
173 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000174 QualType T = GetTypeForDeclarator(D, S);
175
Douglas Gregor279272e2009-02-04 19:02:06 +0000176 assert(S->isTemplateParamScope() &&
177 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000178 bool Invalid = false;
179
180 IdentifierInfo *ParamName = D.getIdentifier();
181 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000182 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000183 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000184 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000185 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000186 }
187
Douglas Gregor62cdc792009-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 Gregor2eedd992009-02-11 00:19:33 +0000196 (T->isPointerType() &&
197 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
198 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
Douglas Gregor62cdc792009-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 Gregordd861062008-12-05 18:15:24 +0000225 NonTypeTemplateParmDecl *Param
226 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000227 Depth, Position, ParamName, T);
Douglas Gregordd861062008-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 Gregor52473432008-12-24 02:52:09 +0000238
Douglas Gregor9225a7e2009-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 Gregor279272e2009-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 Gregor9225a7e2009-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 Gregor52473432008-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 Gregord406b032009-02-06 22:42:48 +0000347 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
348 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000349}
Douglas Gregor279272e2009-02-04 19:02:06 +0000350
Douglas Gregord406b032009-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 Gregor9225a7e2009-02-10 19:49:53 +0000359 bool Invalid = false;
Douglas Gregord406b032009-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 Gregor9225a7e2009-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 Gregord406b032009-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 Gregor9225a7e2009-02-10 19:49:53 +0000481 if (Invalid) {
482 NewTemplate->setInvalidDecl();
483 NewClass->setInvalidDecl();
484 }
Douglas Gregord406b032009-02-06 22:42:48 +0000485 return NewTemplate;
486}
487
Douglas Gregor9225a7e2009-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 Gregor35d81bb2009-02-09 23:23:08 +0000519
Mike Stumpe0b7e032009-02-11 23:03:27 +0000520 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000521 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-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 Gregor35d81bb2009-02-09 23:23:08 +0000647
Douglas Gregor8e458f42009-02-09 18:46:07 +0000648Action::TypeTy *
649Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000650 SourceLocation TemplateLoc,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000651 SourceLocation LAngleLoc,
Douglas Gregor6f37b582009-02-09 19:34:22 +0000652 ASTTemplateArgsPtr TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000653 SourceLocation *TemplateArgLocs,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000654 SourceLocation RAngleLoc,
655 const CXXScopeSpec *SS) {
656 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
657
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000658 // Check that the template argument list is well-formed for this
659 // template.
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000660 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
661 TemplateArgs, TemplateArgLocs, RAngleLoc))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000662 return 0;
663
Douglas Gregor8e458f42009-02-09 18:46:07 +0000664 // Yes, all class template specializations are just silly sugar for
665 // 'int'. Gotta problem wit dat?
Douglas Gregor6f37b582009-02-09 19:34:22 +0000666 QualType Result
667 = Context.getClassTemplateSpecializationType(Template,
668 TemplateArgs.size(),
669 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
670 TemplateArgs.getArgIsType(),
671 Context.IntTy);
672 TemplateArgs.release();
673 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000674}
675
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000676/// \brief Check that the given template argument list is well-formed
677/// for specializing the given template.
678bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
679 SourceLocation TemplateLoc,
680 SourceLocation LAngleLoc,
681 ASTTemplateArgsPtr& Args,
682 SourceLocation *TemplateArgLocs,
683 SourceLocation RAngleLoc) {
684 TemplateParameterList *Params = Template->getTemplateParameters();
685 unsigned NumParams = Params->size();
686 unsigned NumArgs = Args.size();
687 bool Invalid = false;
688
689 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000690 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000691 // FIXME: point at either the first arg beyond what we can handle,
692 // or the '>', depending on whether we have too many or too few
693 // arguments.
694 SourceRange Range;
695 if (NumArgs > NumParams)
696 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
697 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
698 << (NumArgs > NumParams)
699 << (isa<ClassTemplateDecl>(Template)? 0 :
700 isa<FunctionTemplateDecl>(Template)? 1 :
701 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
702 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000703 Diag(Template->getLocation(), diag::note_template_decl_here)
704 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000705 Invalid = true;
706 }
707
708 // C++ [temp.arg]p1:
709 // [...] The type and form of each template-argument specified in
710 // a template-id shall match the type and form specified for the
711 // corresponding parameter declared by the template in its
712 // template-parameter-list.
713 unsigned ArgIdx = 0;
714 for (TemplateParameterList::iterator Param = Params->begin(),
715 ParamEnd = Params->end();
716 Param != ParamEnd; ++Param, ++ArgIdx) {
717 // Decode the template argument
718 QualType ArgType;
719 Expr *ArgExpr = 0;
720 SourceLocation ArgLoc;
721 if (ArgIdx >= NumArgs) {
722 // FIXME: Get the default argument here, which might
723 // (eventually) require instantiation.
724 break;
725 } else
726 ArgLoc = TemplateArgLocs[ArgIdx];
727
728 if (Args.getArgIsType()[ArgIdx])
729 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
730 else
731 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
732
733 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
734 // Check template type parameters.
735 if (!ArgType.isNull()) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000736 if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000737 Invalid = true;
738 continue;
739 }
740
741 // C++ [temp.arg.type]p1:
742 // A template-argument for a template-parameter which is a
743 // type shall be a type-id.
744
745 // We have a template type parameter but the template argument
746 // is an expression.
747 Diag(ArgExpr->getSourceRange().getBegin(),
748 diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000749 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000750 Invalid = true;
751 } else if (NonTypeTemplateParmDecl *NTTP
752 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
753 // Check non-type template parameters.
754 if (ArgExpr) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000755 if (CheckTemplateArgument(NTTP, ArgExpr))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000756 Invalid = true;
757 continue;
758 }
759
760 // We have a non-type template parameter but the template
761 // argument is a type.
762
763 // C++ [temp.arg]p2:
764 // In a template-argument, an ambiguity between a type-id and
765 // an expression is resolved to a type-id, regardless of the
766 // form of the corresponding template-parameter.
767 //
768 // We warn specifically about this case, since it can be rather
769 // confusing for users.
770 if (ArgType->isFunctionType())
771 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
772 << ArgType;
773 else
774 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor341ac792009-02-10 00:53:15 +0000775 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000776 Invalid = true;
777 } else {
778 // Check template template parameters.
779 TemplateTemplateParmDecl *TempParm
780 = cast<TemplateTemplateParmDecl>(*Param);
781
782 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
783 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000784 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000785 Invalid = true;
786 continue;
787 }
788
789 // We have a template template parameter but the template
790 // argument does not refer to a template.
791 Diag(ArgLoc, diag::err_template_arg_must_be_template);
792 Invalid = true;
793 }
794 }
795
796 return Invalid;
797}
798
799/// \brief Check a template argument against its corresponding
800/// template type parameter.
801///
802/// This routine implements the semantics of C++ [temp.arg.type]. It
803/// returns true if an error occurred, and false otherwise.
804bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
805 QualType Arg, SourceLocation ArgLoc) {
806 // C++ [temp.arg.type]p2:
807 // A local type, a type with no linkage, an unnamed type or a type
808 // compounded from any of these types shall not be used as a
809 // template-argument for a template type-parameter.
810 //
811 // FIXME: Perform the recursive and no-linkage type checks.
812 const TagType *Tag = 0;
813 if (const EnumType *EnumT = Arg->getAsEnumType())
814 Tag = EnumT;
815 else if (const RecordType *RecordT = Arg->getAsRecordType())
816 Tag = RecordT;
817 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
818 return Diag(ArgLoc, diag::err_template_arg_local_type)
819 << QualType(Tag, 0);
820 else if (Tag && !Tag->getDecl()->getDeclName()) {
821 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
822 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
823 return true;
824 }
825
826 return false;
827}
828
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +0000829/// \brief Checks whether the given template argument is the address
830/// of an object or function according to C++ [temp.arg.nontype]p1.
831bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg) {
832 bool Invalid = false;
833
834 // See through any implicit casts we added to fix the type.
835 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
836 Arg = Cast->getSubExpr();
837
838 // C++ [temp.arg.nontype]p1:
839 //
840 // A template-argument for a non-type, non-template
841 // template-parameter shall be one of: [...]
842 //
843 // -- the address of an object or function with external
844 // linkage, including function templates and function
845 // template-ids but excluding non-static class members,
846 // expressed as & id-expression where the & is optional if
847 // the name refers to a function or array, or if the
848 // corresponding template-parameter is a reference; or
849 DeclRefExpr *DRE = 0;
850
851 // Ignore (and complain about) any excess parentheses.
852 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
853 if (!Invalid) {
854 Diag(Arg->getSourceRange().getBegin(),
855 diag::err_template_arg_extra_parens)
856 << Arg->getSourceRange();
857 Invalid = true;
858 }
859
860 Arg = Parens->getSubExpr();
861 }
862
863 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
864 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
865 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
866 } else
867 DRE = dyn_cast<DeclRefExpr>(Arg);
868
869 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
870 return Diag(Arg->getSourceRange().getBegin(),
871 diag::err_template_arg_not_object_or_func_form)
872 << Arg->getSourceRange();
873
874 // Cannot refer to non-static data members
875 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
876 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
877 << Field << Arg->getSourceRange();
878
879 // Cannot refer to non-static member functions
880 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
881 if (!Method->isStatic())
882 return Diag(Arg->getSourceRange().getBegin(),
883 diag::err_template_arg_method)
884 << Method << Arg->getSourceRange();
885
886 // Functions must have external linkage.
887 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
888 if (Func->getStorageClass() == FunctionDecl::Static) {
889 Diag(Arg->getSourceRange().getBegin(),
890 diag::err_template_arg_function_not_extern)
891 << Func << Arg->getSourceRange();
892 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
893 << true;
894 return true;
895 }
896
897 // Okay: we've named a function with external linkage.
898 return Invalid;
899 }
900
901 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
902 if (!Var->hasGlobalStorage()) {
903 Diag(Arg->getSourceRange().getBegin(),
904 diag::err_template_arg_object_not_extern)
905 << Var << Arg->getSourceRange();
906 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
907 << true;
908 return true;
909 }
910
911 // Okay: we've named an object with external linkage
912 return Invalid;
913 }
914
915 // We found something else, but we don't know specifically what it is.
916 Diag(Arg->getSourceRange().getBegin(),
917 diag::err_template_arg_not_object_or_func)
918 << Arg->getSourceRange();
919 Diag(DRE->getDecl()->getLocation(),
920 diag::note_template_arg_refers_here);
921 return true;
922}
923
924/// \brief Checks whether the given template argument is a pointer to
925/// member constant according to C++ [temp.arg.nontype]p1.
926bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg) {
927 bool Invalid = false;
928
929 // See through any implicit casts we added to fix the type.
930 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
931 Arg = Cast->getSubExpr();
932
933 // C++ [temp.arg.nontype]p1:
934 //
935 // A template-argument for a non-type, non-template
936 // template-parameter shall be one of: [...]
937 //
938 // -- a pointer to member expressed as described in 5.3.1.
939 QualifiedDeclRefExpr *DRE = 0;
940
941 // Ignore (and complain about) any excess parentheses.
942 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
943 if (!Invalid) {
944 Diag(Arg->getSourceRange().getBegin(),
945 diag::err_template_arg_extra_parens)
946 << Arg->getSourceRange();
947 Invalid = true;
948 }
949
950 Arg = Parens->getSubExpr();
951 }
952
953 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
954 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
955 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
956
957 if (!DRE)
958 return Diag(Arg->getSourceRange().getBegin(),
959 diag::err_template_arg_not_pointer_to_member_form)
960 << Arg->getSourceRange();
961
962 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
963 assert((isa<FieldDecl>(DRE->getDecl()) ||
964 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
965 "Only non-static member pointers can make it here");
966
967 // Okay: this is the address of a non-static member, and therefore
968 // a member pointer constant.
969 return Invalid;
970 }
971
972 // We found something else, but we don't know specifically what it is.
973 Diag(Arg->getSourceRange().getBegin(),
974 diag::err_template_arg_not_pointer_to_member_form)
975 << Arg->getSourceRange();
976 Diag(DRE->getDecl()->getLocation(),
977 diag::note_template_arg_refers_here);
978 return true;
979}
980
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000981/// \brief Check a template argument against its corresponding
982/// non-type template parameter.
983///
984/// This routine implements the semantics of C++ [temp.arg.nontype].
985/// It returns true if an error occurred, and false otherwise.
986bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor79e5c9c2009-02-10 23:36:10 +0000987 Expr *&Arg) {
988 // If either the parameter has a dependent type or the argument is
989 // type-dependent, there's nothing we can check now.
990 if (Param->getType()->isDependentType() || Arg->isTypeDependent())
991 return false;
992
993 // C++ [temp.arg.nontype]p5:
994 // The following conversions are performed on each expression used
995 // as a non-type template-argument. If a non-type
996 // template-argument cannot be converted to the type of the
997 // corresponding template-parameter then the program is
998 // ill-formed.
999 //
1000 // -- for a non-type template-parameter of integral or
1001 // enumeration type, integral promotions (4.5) and integral
1002 // conversions (4.7) are applied.
1003 QualType ParamType = Param->getType();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001004 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001005 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001006 // C++ [temp.arg.nontype]p1:
1007 // A template-argument for a non-type, non-template
1008 // template-parameter shall be one of:
1009 //
1010 // -- an integral constant-expression of integral or enumeration
1011 // type; or
1012 // -- the name of a non-type template-parameter; or
1013 SourceLocation NonConstantLoc;
1014 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1015 Diag(Arg->getSourceRange().getBegin(),
1016 diag::err_template_arg_not_integral_or_enumeral)
1017 << ArgType << Arg->getSourceRange();
1018 Diag(Param->getLocation(), diag::note_template_param_here);
1019 return true;
1020 } else if (!Arg->isValueDependent() &&
1021 !Arg->isIntegerConstantExpr(Context, &NonConstantLoc)) {
1022 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1023 << ArgType << Arg->getSourceRange();
1024 return true;
1025 }
1026
1027 // FIXME: We need some way to more easily get the unqualified form
1028 // of the types without going all the way to the
1029 // canonical type.
1030 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1031 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1032 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1033 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1034
1035 // Try to convert the argument to the parameter's type.
1036 if (ParamType == ArgType) {
1037 // Okay: no conversion necessary
1038 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1039 !ParamType->isEnumeralType()) {
1040 // This is an integral promotion or conversion.
1041 ImpCastExprToType(Arg, ParamType);
1042 } else {
1043 // We can't perform this conversion.
1044 Diag(Arg->getSourceRange().getBegin(),
1045 diag::err_template_arg_not_convertible)
1046 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1047 Diag(Param->getLocation(), diag::note_template_param_here);
1048 return true;
1049 }
1050
1051 return false;
1052 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001053
Douglas Gregor3f411962009-02-11 01:18:59 +00001054 // Handle pointer-to-function, reference-to-function, and
1055 // pointer-to-member-function all in (roughly) the same way.
1056 if (// -- For a non-type template-parameter of type pointer to
1057 // function, only the function-to-pointer conversion (4.3) is
1058 // applied. If the template-argument represents a set of
1059 // overloaded functions (or a pointer to such), the matching
1060 // function is selected from the set (13.4).
1061 (ParamType->isPointerType() &&
1062 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1063 // -- For a non-type template-parameter of type reference to
1064 // function, no conversions apply. If the template-argument
1065 // represents a set of overloaded functions, the matching
1066 // function is selected from the set (13.4).
1067 (ParamType->isReferenceType() &&
1068 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1069 // -- For a non-type template-parameter of type pointer to
1070 // member function, no conversions apply. If the
1071 // template-argument represents a set of overloaded member
1072 // functions, the matching member function is selected from
1073 // the set (13.4).
1074 (ParamType->isMemberPointerType() &&
1075 ParamType->getAsMemberPointerType()->getPointeeType()
1076 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001077 if (Context.hasSameUnqualifiedType(ArgType,
1078 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001079 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001080 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001081 ArgType = Context.getPointerType(ArgType);
1082 ImpCastExprToType(Arg, ArgType);
1083 } else if (FunctionDecl *Fn
1084 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
1085 FixOverloadedFunctionReference(Arg, Fn);
1086 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001087 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001088 ArgType = Context.getPointerType(Arg->getType());
1089 ImpCastExprToType(Arg, ArgType);
1090 }
1091 }
1092
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001093 if (!Context.hasSameUnqualifiedType(ArgType,
1094 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001095 // We can't perform this conversion.
1096 Diag(Arg->getSourceRange().getBegin(),
1097 diag::err_template_arg_not_convertible)
1098 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1099 Diag(Param->getLocation(), diag::note_template_param_here);
1100 return true;
1101 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001102
1103 if (ParamType->isMemberPointerType())
1104 return CheckTemplateArgumentPointerToMember(Arg);
1105
1106 return CheckTemplateArgumentAddressOfObjectOrFunction(Arg);
Douglas Gregor2eedd992009-02-11 00:19:33 +00001107 }
1108
Douglas Gregor3f411962009-02-11 01:18:59 +00001109 if (const PointerType *ParamPtrType = ParamType->getAsPointerType()) {
1110 // -- for a non-type template-parameter of type pointer to
1111 // object, qualification conversions (4.4) and the
1112 // array-to-pointer conversion (4.2) are applied.
1113 assert(ParamPtrType->getPointeeType()->isObjectType() &&
1114 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001115
Douglas Gregor3f411962009-02-11 01:18:59 +00001116 if (ArgType->isArrayType()) {
1117 ArgType = Context.getArrayDecayedType(ArgType);
1118 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001119 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001120
1121 if (IsQualificationConversion(ArgType, ParamType)) {
1122 ArgType = ParamType;
1123 ImpCastExprToType(Arg, ParamType);
1124 }
1125
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001126 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001127 // We can't perform this conversion.
1128 Diag(Arg->getSourceRange().getBegin(),
1129 diag::err_template_arg_not_convertible)
1130 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1131 Diag(Param->getLocation(), diag::note_template_param_here);
1132 return true;
1133 }
1134
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001135 return CheckTemplateArgumentAddressOfObjectOrFunction(Arg);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001136 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001137
1138 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1139 // -- For a non-type template-parameter of type reference to
1140 // object, no conversions apply. The type referred to by the
1141 // reference may be more cv-qualified than the (otherwise
1142 // identical) type of the template-argument. The
1143 // template-parameter is bound directly to the
1144 // template-argument, which must be an lvalue.
1145 assert(ParamRefType->getPointeeType()->isObjectType() &&
1146 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001147
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001148 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001149 Diag(Arg->getSourceRange().getBegin(),
1150 diag::err_template_arg_no_ref_bind)
1151 << Param->getType() << Arg->getType()
1152 << Arg->getSourceRange();
1153 Diag(Param->getLocation(), diag::note_template_param_here);
1154 return true;
1155 }
1156
1157 unsigned ParamQuals
1158 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1159 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1160
1161 if ((ParamQuals | ArgQuals) != ParamQuals) {
1162 Diag(Arg->getSourceRange().getBegin(),
1163 diag::err_template_arg_ref_bind_ignores_quals)
1164 << Param->getType() << Arg->getType()
1165 << Arg->getSourceRange();
1166 Diag(Param->getLocation(), diag::note_template_param_here);
1167 return true;
1168 }
1169
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001170 return CheckTemplateArgumentAddressOfObjectOrFunction(Arg);
Douglas Gregor3f411962009-02-11 01:18:59 +00001171 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001172
1173 // -- For a non-type template-parameter of type pointer to data
1174 // member, qualification conversions (4.4) are applied.
1175 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1176
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001177 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001178 // Types match exactly: nothing more to do here.
1179 } else if (IsQualificationConversion(ArgType, ParamType)) {
1180 ImpCastExprToType(Arg, ParamType);
1181 } else {
1182 // We can't perform this conversion.
1183 Diag(Arg->getSourceRange().getBegin(),
1184 diag::err_template_arg_not_convertible)
1185 << Arg->getType() << Param->getType() << Arg->getSourceRange();
1186 Diag(Param->getLocation(), diag::note_template_param_here);
1187 return true;
1188 }
1189
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001190 return CheckTemplateArgumentPointerToMember(Arg);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001191}
1192
1193/// \brief Check a template argument against its corresponding
1194/// template template parameter.
1195///
1196/// This routine implements the semantics of C++ [temp.arg.template].
1197/// It returns true if an error occurred, and false otherwise.
1198bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1199 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001200 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1201 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1202
1203 // C++ [temp.arg.template]p1:
1204 // A template-argument for a template template-parameter shall be
1205 // the name of a class template, expressed as id-expression. Only
1206 // primary class templates are considered when matching the
1207 // template template argument with the corresponding parameter;
1208 // partial specializations are not considered even if their
1209 // parameter lists match that of the template template parameter.
1210 if (!isa<ClassTemplateDecl>(Template)) {
1211 assert(isa<FunctionTemplateDecl>(Template) &&
1212 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001213 Diag(Arg->getSourceRange().getBegin(),
1214 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001215 << Template;
1216 }
1217
1218 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1219 Param->getTemplateParameters(),
1220 true, true,
1221 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001222}
1223
Douglas Gregord406b032009-02-06 22:42:48 +00001224/// \brief Determine whether the given template parameter lists are
1225/// equivalent.
1226///
1227/// \param New The new template parameter list, typically written in the
1228/// source code as part of a new template declaration.
1229///
1230/// \param Old The old template parameter list, typically found via
1231/// name lookup of the template declared with this template parameter
1232/// list.
1233///
1234/// \param Complain If true, this routine will produce a diagnostic if
1235/// the template parameter lists are not equivalent.
1236///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001237/// \param IsTemplateTemplateParm If true, this routine is being
1238/// called to compare the template parameter lists of a template
1239/// template parameter.
1240///
1241/// \param TemplateArgLoc If this source location is valid, then we
1242/// are actually checking the template parameter list of a template
1243/// argument (New) against the template parameter list of its
1244/// corresponding template template parameter (Old). We produce
1245/// slightly different diagnostics in this scenario.
1246///
Douglas Gregord406b032009-02-06 22:42:48 +00001247/// \returns True if the template parameter lists are equal, false
1248/// otherwise.
1249bool
1250Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1251 TemplateParameterList *Old,
1252 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001253 bool IsTemplateTemplateParm,
1254 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001255 if (Old->size() != New->size()) {
1256 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001257 unsigned NextDiag = diag::err_template_param_list_different_arity;
1258 if (TemplateArgLoc.isValid()) {
1259 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1260 NextDiag = diag::note_template_param_list_different_arity;
1261 }
1262 Diag(New->getTemplateLoc(), NextDiag)
1263 << (New->size() > Old->size())
1264 << IsTemplateTemplateParm
1265 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001266 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1267 << IsTemplateTemplateParm
1268 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1269 }
1270
1271 return false;
1272 }
1273
1274 for (TemplateParameterList::iterator OldParm = Old->begin(),
1275 OldParmEnd = Old->end(), NewParm = New->begin();
1276 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1277 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001278 unsigned NextDiag = diag::err_template_param_different_kind;
1279 if (TemplateArgLoc.isValid()) {
1280 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1281 NextDiag = diag::note_template_param_different_kind;
1282 }
1283 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001284 << IsTemplateTemplateParm;
1285 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1286 << IsTemplateTemplateParm;
1287 return false;
1288 }
1289
1290 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1291 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001292 // know we're at the same index).
1293#if 0
1294 // FIXME: Enable this code in debug mode *after* we properly go
1295 // through and "instantiate" the template parameter lists of
1296 // template template parameters. It's only after this
1297 // instantiation that (1) any dependent types within the
1298 // template parameter list of the template template parameter
1299 // can be checked, and (2) the template type parameter depths
1300 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001301 QualType OldParmType
1302 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1303 QualType NewParmType
1304 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1305 assert(Context.getCanonicalType(OldParmType) ==
1306 Context.getCanonicalType(NewParmType) &&
1307 "type parameter mismatch?");
1308#endif
1309 } else if (NonTypeTemplateParmDecl *OldNTTP
1310 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1311 // The types of non-type template parameters must agree.
1312 NonTypeTemplateParmDecl *NewNTTP
1313 = cast<NonTypeTemplateParmDecl>(*NewParm);
1314 if (Context.getCanonicalType(OldNTTP->getType()) !=
1315 Context.getCanonicalType(NewNTTP->getType())) {
1316 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001317 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1318 if (TemplateArgLoc.isValid()) {
1319 Diag(TemplateArgLoc,
1320 diag::err_template_arg_template_params_mismatch);
1321 NextDiag = diag::note_template_nontype_parm_different_type;
1322 }
1323 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001324 << NewNTTP->getType()
1325 << IsTemplateTemplateParm;
1326 Diag(OldNTTP->getLocation(),
1327 diag::note_template_nontype_parm_prev_declaration)
1328 << OldNTTP->getType();
1329 }
1330 return false;
1331 }
1332 } else {
1333 // The template parameter lists of template template
1334 // parameters must agree.
1335 // FIXME: Could we perform a faster "type" comparison here?
1336 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1337 "Only template template parameters handled here");
1338 TemplateTemplateParmDecl *OldTTP
1339 = cast<TemplateTemplateParmDecl>(*OldParm);
1340 TemplateTemplateParmDecl *NewTTP
1341 = cast<TemplateTemplateParmDecl>(*NewParm);
1342 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1343 OldTTP->getTemplateParameters(),
1344 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001345 /*IsTemplateTemplateParm=*/true,
1346 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001347 return false;
1348 }
1349 }
1350
1351 return true;
1352}
1353
1354/// \brief Check whether a template can be declared within this scope.
1355///
1356/// If the template declaration is valid in this scope, returns
1357/// false. Otherwise, issues a diagnostic and returns true.
1358bool
1359Sema::CheckTemplateDeclScope(Scope *S,
1360 MultiTemplateParamsArg &TemplateParameterLists) {
1361 assert(TemplateParameterLists.size() > 0 && "Not a template");
1362
1363 // Find the nearest enclosing declaration scope.
1364 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1365 (S->getFlags() & Scope::TemplateParamScope) != 0)
1366 S = S->getParent();
1367
1368 TemplateParameterList *TemplateParams =
1369 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1370 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1371 SourceRange TemplateRange
1372 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1373
1374 // C++ [temp]p2:
1375 // A template-declaration can appear only as a namespace scope or
1376 // class scope declaration.
1377 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1378 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1379 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1380 return Diag(TemplateLoc, diag::err_template_linkage)
1381 << TemplateRange;
1382
1383 Ctx = Ctx->getParent();
1384 }
1385
1386 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1387 return false;
1388
1389 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1390 << TemplateRange;
1391}