blob: a55e3a5184578efeb8602c6c6181925415410f78 [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.
Douglas Gregor74296542009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor74296542009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregordd861062008-12-05 18:15:24 +000013
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 Gregor0c281a82009-02-25 19:37:18 +000029TemplateNameKind 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 Gregored3a3982009-03-03 04:44:36 +000088/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +000089/// 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 Gregored3a3982009-03-03 04:44:36 +0000167/// \brief Check that the type of a non-type template parameter is
168/// well-formed.
169///
170/// \returns the (possibly-promoted) parameter type if valid;
171/// otherwise, produces a diagnostic and returns a NULL type.
172QualType
173Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
174 // C++ [temp.param]p4:
175 //
176 // A non-type template-parameter shall have one of the following
177 // (optionally cv-qualified) types:
178 //
179 // -- integral or enumeration type,
180 if (T->isIntegralType() || T->isEnumeralType() ||
181 // -- pointer to object or pointer to function,
182 (T->isPointerType() &&
183 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
184 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
185 // -- reference to object or reference to function,
186 T->isReferenceType() ||
187 // -- pointer to member.
188 T->isMemberPointerType() ||
189 // If T is a dependent type, we can't do the check now, so we
190 // assume that it is well-formed.
191 T->isDependentType())
192 return T;
193 // C++ [temp.param]p8:
194 //
195 // A non-type template-parameter of type "array of T" or
196 // "function returning T" is adjusted to be of type "pointer to
197 // T" or "pointer to function returning T", respectively.
198 else if (T->isArrayType())
199 // FIXME: Keep the type prior to promotion?
200 return Context.getArrayDecayedType(T);
201 else if (T->isFunctionType())
202 // FIXME: Keep the type prior to promotion?
203 return Context.getPointerType(T);
204
205 Diag(Loc, diag::err_template_nontype_parm_bad_type)
206 << T;
207
208 return QualType();
209}
210
Douglas Gregordd861062008-12-05 18:15:24 +0000211/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
212/// template parameter (e.g., "int Size" in "template<int Size>
213/// class Array") has been parsed. S is the current scope and D is
214/// the parsed declarator.
Douglas Gregor52473432008-12-24 02:52:09 +0000215Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
216 unsigned Depth,
217 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000218 QualType T = GetTypeForDeclarator(D, S);
219
Douglas Gregor279272e2009-02-04 19:02:06 +0000220 assert(S->isTemplateParamScope() &&
221 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000222 bool Invalid = false;
223
224 IdentifierInfo *ParamName = D.getIdentifier();
225 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000226 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000227 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000228 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000229 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000230 }
231
Douglas Gregored3a3982009-03-03 04:44:36 +0000232 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000233 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000234 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000235 Invalid = true;
236 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000237
Douglas Gregordd861062008-12-05 18:15:24 +0000238 NonTypeTemplateParmDecl *Param
239 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000240 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000241 if (Invalid)
242 Param->setInvalidDecl();
243
244 if (D.getIdentifier()) {
245 // Add the template parameter into the current scope.
246 S->AddDecl(Param);
247 IdResolver.AddDecl(Param);
248 }
249 return Param;
250}
Douglas Gregor52473432008-12-24 02:52:09 +0000251
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000252/// \brief Adds a default argument to the given non-type template
253/// parameter.
254void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
255 SourceLocation EqualLoc,
256 ExprArg DefaultE) {
257 NonTypeTemplateParmDecl *TemplateParm
258 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
259 Expr *Default = static_cast<Expr *>(DefaultE.get());
260
261 // C++ [temp.param]p14:
262 // A template-parameter shall not be used in its own default argument.
263 // FIXME: Implement this check! Needs a recursive walk over the types.
264
265 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000266 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000267 TemplateParm->setInvalidDecl();
268 return;
269 }
270
271 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
272}
273
Douglas Gregor279272e2009-02-04 19:02:06 +0000274
275/// ActOnTemplateTemplateParameter - Called when a C++ template template
276/// parameter (e.g. T in template <template <typename> class T> class array)
277/// has been parsed. S is the current scope.
278Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
279 SourceLocation TmpLoc,
280 TemplateParamsTy *Params,
281 IdentifierInfo *Name,
282 SourceLocation NameLoc,
283 unsigned Depth,
284 unsigned Position)
285{
286 assert(S->isTemplateParamScope() &&
287 "Template template parameter not in template parameter scope!");
288
289 // Construct the parameter object.
290 TemplateTemplateParmDecl *Param =
291 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
292 Position, Name,
293 (TemplateParameterList*)Params);
294
295 // Make sure the parameter is valid.
296 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
297 // do anything yet. However, if the template parameter list or (eventual)
298 // default value is ever invalidated, that will propagate here.
299 bool Invalid = false;
300 if (Invalid) {
301 Param->setInvalidDecl();
302 }
303
304 // If the tt-param has a name, then link the identifier into the scope
305 // and lookup mechanisms.
306 if (Name) {
307 S->AddDecl(Param);
308 IdResolver.AddDecl(Param);
309 }
310
311 return Param;
312}
313
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000314/// \brief Adds a default argument to the given template template
315/// parameter.
316void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
317 SourceLocation EqualLoc,
318 ExprArg DefaultE) {
319 TemplateTemplateParmDecl *TemplateParm
320 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
321
322 // Since a template-template parameter's default argument is an
323 // id-expression, it must be a DeclRefExpr.
324 DeclRefExpr *Default
325 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
326
327 // C++ [temp.param]p14:
328 // A template-parameter shall not be used in its own default argument.
329 // FIXME: Implement this check! Needs a recursive walk over the types.
330
331 // Check the well-formedness of the template argument.
332 if (!isa<TemplateDecl>(Default->getDecl())) {
333 Diag(Default->getSourceRange().getBegin(),
334 diag::err_template_arg_must_be_template)
335 << Default->getSourceRange();
336 TemplateParm->setInvalidDecl();
337 return;
338 }
339 if (CheckTemplateArgument(TemplateParm, Default)) {
340 TemplateParm->setInvalidDecl();
341 return;
342 }
343
344 DefaultE.release();
345 TemplateParm->setDefaultArgument(Default);
346}
347
Douglas Gregor52473432008-12-24 02:52:09 +0000348/// ActOnTemplateParameterList - Builds a TemplateParameterList that
349/// contains the template parameters in Params/NumParams.
350Sema::TemplateParamsTy *
351Sema::ActOnTemplateParameterList(unsigned Depth,
352 SourceLocation ExportLoc,
353 SourceLocation TemplateLoc,
354 SourceLocation LAngleLoc,
355 DeclTy **Params, unsigned NumParams,
356 SourceLocation RAngleLoc) {
357 if (ExportLoc.isValid())
358 Diag(ExportLoc, diag::note_template_export_unsupported);
359
Douglas Gregord406b032009-02-06 22:42:48 +0000360 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
361 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000362}
Douglas Gregor279272e2009-02-04 19:02:06 +0000363
Douglas Gregord406b032009-02-06 22:42:48 +0000364Sema::DeclTy *
365Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
366 SourceLocation KWLoc, const CXXScopeSpec &SS,
367 IdentifierInfo *Name, SourceLocation NameLoc,
368 AttributeList *Attr,
369 MultiTemplateParamsArg TemplateParameterLists) {
370 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
371 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000372 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000373
374 // Check that we can declare a template here.
375 if (CheckTemplateDeclScope(S, TemplateParameterLists))
376 return 0;
377
378 TagDecl::TagKind Kind;
379 switch (TagSpec) {
380 default: assert(0 && "Unknown tag type!");
381 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
382 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
383 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
384 }
385
386 // There is no such thing as an unnamed class template.
387 if (!Name) {
388 Diag(KWLoc, diag::err_template_unnamed_class);
389 return 0;
390 }
391
392 // Find any previous declaration with this name.
393 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
394 true);
395 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
396 NamedDecl *PrevDecl = 0;
397 if (Previous.begin() != Previous.end())
398 PrevDecl = *Previous.begin();
399
400 DeclContext *SemanticContext = CurContext;
401 if (SS.isNotEmpty() && !SS.isInvalid()) {
402 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
403
404 // FIXME: need to match up several levels of template parameter
405 // lists here.
406 }
407
408 // FIXME: member templates!
409 TemplateParameterList *TemplateParams
410 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
411
412 // If there is a previous declaration with the same name, check
413 // whether this is a valid redeclaration.
414 ClassTemplateDecl *PrevClassTemplate
415 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
416 if (PrevClassTemplate) {
417 // Ensure that the template parameter lists are compatible.
418 if (!TemplateParameterListsAreEqual(TemplateParams,
419 PrevClassTemplate->getTemplateParameters(),
420 /*Complain=*/true))
421 return 0;
422
423 // C++ [temp.class]p4:
424 // In a redeclaration, partial specialization, explicit
425 // specialization or explicit instantiation of a class template,
426 // the class-key shall agree in kind with the original class
427 // template declaration (7.1.5.3).
428 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
429 if (PrevRecordDecl->getTagKind() != Kind) {
430 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
431 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
432 return 0;
433 }
434
435
436 // Check for redefinition of this class template.
437 if (TK == TK_Definition) {
438 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
439 Diag(NameLoc, diag::err_redefinition) << Name;
440 Diag(Def->getLocation(), diag::note_previous_definition);
441 // FIXME: Would it make sense to try to "forget" the previous
442 // definition, as part of error recovery?
443 return 0;
444 }
445 }
446 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
447 // Maybe we will complain about the shadowed template parameter.
448 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
449 // Just pretend that we didn't see the previous declaration.
450 PrevDecl = 0;
451 } else if (PrevDecl) {
452 // C++ [temp]p5:
453 // A class template shall not have the same name as any other
454 // template, class, function, object, enumeration, enumerator,
455 // namespace, or type in the same scope (3.3), except as specified
456 // in (14.5.4).
457 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
458 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
459 return 0;
460 }
461
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000462 // Check the template parameter list of this declaration, possibly
463 // merging in the template parameter list from the previous class
464 // template declaration.
465 if (CheckTemplateParameterList(TemplateParams,
466 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
467 Invalid = true;
468
Douglas Gregord406b032009-02-06 22:42:48 +0000469 // If we had a scope specifier, we better have a previous template
470 // declaration!
471
472 TagDecl *NewClass =
473 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
474 PrevClassTemplate?
475 PrevClassTemplate->getTemplatedDecl() : 0);
476
477 ClassTemplateDecl *NewTemplate
478 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
479 DeclarationName(Name), TemplateParams,
480 NewClass);
481
482 // Set the lexical context of these templates
483 NewClass->setLexicalDeclContext(CurContext);
484 NewTemplate->setLexicalDeclContext(CurContext);
485
486 if (TK == TK_Definition)
487 NewClass->startDefinition();
488
489 if (Attr)
490 ProcessDeclAttributeList(NewClass, Attr);
491
492 PushOnScopeChains(NewTemplate, S);
493
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000494 if (Invalid) {
495 NewTemplate->setInvalidDecl();
496 NewClass->setInvalidDecl();
497 }
Douglas Gregord406b032009-02-06 22:42:48 +0000498 return NewTemplate;
499}
500
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000501/// \brief Checks the validity of a template parameter list, possibly
502/// considering the template parameter list from a previous
503/// declaration.
504///
505/// If an "old" template parameter list is provided, it must be
506/// equivalent (per TemplateParameterListsAreEqual) to the "new"
507/// template parameter list.
508///
509/// \param NewParams Template parameter list for a new template
510/// declaration. This template parameter list will be updated with any
511/// default arguments that are carried through from the previous
512/// template parameter list.
513///
514/// \param OldParams If provided, template parameter list from a
515/// previous declaration of the same template. Default template
516/// arguments will be merged from the old template parameter list to
517/// the new template parameter list.
518///
519/// \returns true if an error occurred, false otherwise.
520bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
521 TemplateParameterList *OldParams) {
522 bool Invalid = false;
523
524 // C++ [temp.param]p10:
525 // The set of default template-arguments available for use with a
526 // template declaration or definition is obtained by merging the
527 // default arguments from the definition (if in scope) and all
528 // declarations in scope in the same way default function
529 // arguments are (8.3.6).
530 bool SawDefaultArgument = false;
531 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000532
Mike Stumpe0b7e032009-02-11 23:03:27 +0000533 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000534 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000535 if (OldParams)
536 OldParam = OldParams->begin();
537
538 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
539 NewParamEnd = NewParams->end();
540 NewParam != NewParamEnd; ++NewParam) {
541 // Variables used to diagnose redundant default arguments
542 bool RedundantDefaultArg = false;
543 SourceLocation OldDefaultLoc;
544 SourceLocation NewDefaultLoc;
545
546 // Variables used to diagnose missing default arguments
547 bool MissingDefaultArg = false;
548
549 // Merge default arguments for template type parameters.
550 if (TemplateTypeParmDecl *NewTypeParm
551 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
552 TemplateTypeParmDecl *OldTypeParm
553 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
554
555 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
556 NewTypeParm->hasDefaultArgument()) {
557 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
558 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
559 SawDefaultArgument = true;
560 RedundantDefaultArg = true;
561 PreviousDefaultArgLoc = NewDefaultLoc;
562 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
563 // Merge the default argument from the old declaration to the
564 // new declaration.
565 SawDefaultArgument = true;
566 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
567 OldTypeParm->getDefaultArgumentLoc(),
568 true);
569 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
570 } else if (NewTypeParm->hasDefaultArgument()) {
571 SawDefaultArgument = true;
572 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
573 } else if (SawDefaultArgument)
574 MissingDefaultArg = true;
575 }
576 // Merge default arguments for non-type template parameters
577 else if (NonTypeTemplateParmDecl *NewNonTypeParm
578 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
579 NonTypeTemplateParmDecl *OldNonTypeParm
580 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
581 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
582 NewNonTypeParm->hasDefaultArgument()) {
583 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
584 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
585 SawDefaultArgument = true;
586 RedundantDefaultArg = true;
587 PreviousDefaultArgLoc = NewDefaultLoc;
588 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
589 // Merge the default argument from the old declaration to the
590 // new declaration.
591 SawDefaultArgument = true;
592 // FIXME: We need to create a new kind of "default argument"
593 // expression that points to a previous template template
594 // parameter.
595 NewNonTypeParm->setDefaultArgument(
596 OldNonTypeParm->getDefaultArgument());
597 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
598 } else if (NewNonTypeParm->hasDefaultArgument()) {
599 SawDefaultArgument = true;
600 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
601 } else if (SawDefaultArgument)
602 MissingDefaultArg = true;
603 }
604 // Merge default arguments for template template parameters
605 else {
606 TemplateTemplateParmDecl *NewTemplateParm
607 = cast<TemplateTemplateParmDecl>(*NewParam);
608 TemplateTemplateParmDecl *OldTemplateParm
609 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
610 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
611 NewTemplateParm->hasDefaultArgument()) {
612 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
613 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
614 SawDefaultArgument = true;
615 RedundantDefaultArg = true;
616 PreviousDefaultArgLoc = NewDefaultLoc;
617 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
618 // Merge the default argument from the old declaration to the
619 // new declaration.
620 SawDefaultArgument = true;
621 // FIXME: We need to create a new kind of "default argument"
622 // expression that points to a previous template template
623 // parameter.
624 NewTemplateParm->setDefaultArgument(
625 OldTemplateParm->getDefaultArgument());
626 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
627 } else if (NewTemplateParm->hasDefaultArgument()) {
628 SawDefaultArgument = true;
629 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
630 } else if (SawDefaultArgument)
631 MissingDefaultArg = true;
632 }
633
634 if (RedundantDefaultArg) {
635 // C++ [temp.param]p12:
636 // A template-parameter shall not be given default arguments
637 // by two different declarations in the same scope.
638 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
639 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
640 Invalid = true;
641 } else if (MissingDefaultArg) {
642 // C++ [temp.param]p11:
643 // If a template-parameter has a default template-argument,
644 // all subsequent template-parameters shall have a default
645 // template-argument supplied.
646 Diag((*NewParam)->getLocation(),
647 diag::err_template_param_default_arg_missing);
648 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
649 Invalid = true;
650 }
651
652 // If we have an old template parameter list that we're merging
653 // in, move on to the next parameter.
654 if (OldParams)
655 ++OldParam;
656 }
657
658 return Invalid;
659}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000660
Douglas Gregora08b6c72009-02-17 23:15:12 +0000661Action::TypeResult
662Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
663 SourceLocation LAngleLoc,
664 ASTTemplateArgsPtr TemplateArgs,
665 SourceLocation *TemplateArgLocs,
666 SourceLocation RAngleLoc,
667 const CXXScopeSpec *SS) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000668 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregorad964b32009-02-17 01:05:43 +0000669 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000670
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000671 // Check that the template argument list is well-formed for this
672 // template.
Douglas Gregorad964b32009-02-17 01:05:43 +0000673 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000674 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorad964b32009-02-17 01:05:43 +0000675 TemplateArgs, TemplateArgLocs, RAngleLoc,
676 ConvertedTemplateArgs))
Douglas Gregora08b6c72009-02-17 23:15:12 +0000677 return true;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000678
Douglas Gregorad964b32009-02-17 01:05:43 +0000679 assert((ConvertedTemplateArgs.size() ==
680 Template->getTemplateParameters()->size()) &&
681 "Converted template argument list is too short!");
682
683 // Find the class template specialization declaration that
684 // corresponds to these arguments.
685 llvm::FoldingSetNodeID ID;
686 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
687 ConvertedTemplateArgs.size());
688 void *InsertPos = 0;
689 ClassTemplateSpecializationDecl *Decl
690 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
691 if (!Decl) {
692 // This is the first time we have referenced this class template
Douglas Gregora08b6c72009-02-17 23:15:12 +0000693 // specialization. Create the canonical declaration and add it to
694 // the set of specializations.
Douglas Gregorad964b32009-02-17 01:05:43 +0000695 Decl = ClassTemplateSpecializationDecl::Create(Context,
696 ClassTemplate->getDeclContext(),
697 TemplateLoc,
698 ClassTemplate,
699 &ConvertedTemplateArgs[0],
Douglas Gregora08b6c72009-02-17 23:15:12 +0000700 ConvertedTemplateArgs.size(),
701 0);
Douglas Gregorad964b32009-02-17 01:05:43 +0000702 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
Douglas Gregor50113ca2009-02-25 22:18:32 +0000703 Decl->setLexicalDeclContext(CurContext);
Douglas Gregorad964b32009-02-17 01:05:43 +0000704 }
Douglas Gregor50113ca2009-02-25 22:18:32 +0000705
Douglas Gregorad964b32009-02-17 01:05:43 +0000706 // Build the fully-sugared type for this class template
707 // specialization, which refers back to the class template
708 // specialization we created or found.
Douglas Gregor6f37b582009-02-09 19:34:22 +0000709 QualType Result
710 = Context.getClassTemplateSpecializationType(Template,
711 TemplateArgs.size(),
712 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
713 TemplateArgs.getArgIsType(),
Douglas Gregorad964b32009-02-17 01:05:43 +0000714 Context.getTypeDeclType(Decl));
Douglas Gregor6f37b582009-02-09 19:34:22 +0000715 TemplateArgs.release();
716 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000717}
718
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000719/// \brief Check that the given template argument list is well-formed
720/// for specializing the given template.
721bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
722 SourceLocation TemplateLoc,
723 SourceLocation LAngleLoc,
724 ASTTemplateArgsPtr& Args,
725 SourceLocation *TemplateArgLocs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000726 SourceLocation RAngleLoc,
727 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000728 TemplateParameterList *Params = Template->getTemplateParameters();
729 unsigned NumParams = Params->size();
730 unsigned NumArgs = Args.size();
731 bool Invalid = false;
732
733 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000734 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000735 // FIXME: point at either the first arg beyond what we can handle,
736 // or the '>', depending on whether we have too many or too few
737 // arguments.
738 SourceRange Range;
739 if (NumArgs > NumParams)
740 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
741 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
742 << (NumArgs > NumParams)
743 << (isa<ClassTemplateDecl>(Template)? 0 :
744 isa<FunctionTemplateDecl>(Template)? 1 :
745 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
746 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000747 Diag(Template->getLocation(), diag::note_template_decl_here)
748 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000749 Invalid = true;
750 }
751
752 // C++ [temp.arg]p1:
753 // [...] The type and form of each template-argument specified in
754 // a template-id shall match the type and form specified for the
755 // corresponding parameter declared by the template in its
756 // template-parameter-list.
757 unsigned ArgIdx = 0;
758 for (TemplateParameterList::iterator Param = Params->begin(),
759 ParamEnd = Params->end();
760 Param != ParamEnd; ++Param, ++ArgIdx) {
761 // Decode the template argument
762 QualType ArgType;
763 Expr *ArgExpr = 0;
764 SourceLocation ArgLoc;
765 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000766 // Retrieve the default template argument from the template
767 // parameter.
768 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
769 if (!TTP->hasDefaultArgument())
770 break;
771
772 ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000773
774 // If the argument type is dependent, instantiate it now based
775 // on the previously-computed template arguments.
776 if (ArgType->isDependentType())
777 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
778 TTP->getDefaultArgumentLoc(),
779 TTP->getDeclName());
780
781 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000782 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000783
Douglas Gregorad964b32009-02-17 01:05:43 +0000784 ArgLoc = TTP->getDefaultArgumentLoc();
785 } else if (NonTypeTemplateParmDecl *NTTP
786 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
787 if (!NTTP->hasDefaultArgument())
788 break;
789
Douglas Gregored3a3982009-03-03 04:44:36 +0000790 // FIXME: Instantiate default argument
Douglas Gregorad964b32009-02-17 01:05:43 +0000791 ArgExpr = NTTP->getDefaultArgument();
792 ArgLoc = NTTP->getDefaultArgumentLoc();
793 } else {
794 TemplateTemplateParmDecl *TempParm
795 = cast<TemplateTemplateParmDecl>(*Param);
796
797 if (!TempParm->hasDefaultArgument())
798 break;
799
Douglas Gregored3a3982009-03-03 04:44:36 +0000800 // FIXME: Instantiate default argument
Douglas Gregorad964b32009-02-17 01:05:43 +0000801 ArgExpr = TempParm->getDefaultArgument();
802 ArgLoc = TempParm->getDefaultArgumentLoc();
803 }
804 } else {
805 // Retrieve the template argument produced by the user.
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000806 ArgLoc = TemplateArgLocs[ArgIdx];
807
Douglas Gregorad964b32009-02-17 01:05:43 +0000808 if (Args.getArgIsType()[ArgIdx])
809 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
810 else
811 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
812 }
813
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000814
815 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
816 // Check template type parameters.
817 if (!ArgType.isNull()) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000818 if (CheckTemplateArgument(TTP, ArgType, ArgLoc))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000819 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000820
821 // Add the converted template type argument.
822 Converted.push_back(
823 TemplateArgument(Context.getCanonicalType(ArgType)));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000824 continue;
825 }
826
827 // C++ [temp.arg.type]p1:
828 // A template-argument for a template-parameter which is a
829 // type shall be a type-id.
830
831 // We have a template type parameter but the template argument
832 // is an expression.
833 Diag(ArgExpr->getSourceRange().getBegin(),
834 diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000835 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000836 Invalid = true;
837 } else if (NonTypeTemplateParmDecl *NTTP
838 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
839 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +0000840
841 // Instantiate the type of the non-type template parameter with
842 // the template arguments we've seen thus far.
843 QualType NTTPType = NTTP->getType();
844 if (NTTPType->isDependentType()) {
845 // Instantiate the type of the non-type template parameter.
846 NTTPType = InstantiateType(NTTPType,
847 &Converted[0], Converted.size(),
848 NTTP->getLocation(),
849 NTTP->getDeclName());
850 // If that worked, check the non-type template parameter type
851 // for validity.
852 if (!NTTPType.isNull())
853 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
854 NTTP->getLocation());
855
856 if (NTTPType.isNull()) {
857 Invalid = true;
858 break;
859 }
860 }
861
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000862 if (ArgExpr) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000863 if (CheckTemplateArgument(NTTP, NTTPType, ArgExpr, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000864 Invalid = true;
865 continue;
866 }
867
868 // We have a non-type template parameter but the template
869 // argument is a type.
870
871 // C++ [temp.arg]p2:
872 // In a template-argument, an ambiguity between a type-id and
873 // an expression is resolved to a type-id, regardless of the
874 // form of the corresponding template-parameter.
875 //
876 // We warn specifically about this case, since it can be rather
877 // confusing for users.
878 if (ArgType->isFunctionType())
879 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
880 << ArgType;
881 else
882 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor341ac792009-02-10 00:53:15 +0000883 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000884 Invalid = true;
885 } else {
886 // Check template template parameters.
887 TemplateTemplateParmDecl *TempParm
888 = cast<TemplateTemplateParmDecl>(*Param);
889
890 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
891 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +0000892 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000893 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000894
895 // Add the converted template argument.
896 // FIXME: Need the "canonical" template declaration!
897 Converted.push_back(
898 TemplateArgument(cast<DeclRefExpr>(ArgExpr)->getDecl()));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000899 continue;
900 }
901
902 // We have a template template parameter but the template
903 // argument does not refer to a template.
904 Diag(ArgLoc, diag::err_template_arg_must_be_template);
905 Invalid = true;
906 }
907 }
908
909 return Invalid;
910}
911
912/// \brief Check a template argument against its corresponding
913/// template type parameter.
914///
915/// This routine implements the semantics of C++ [temp.arg.type]. It
916/// returns true if an error occurred, and false otherwise.
917bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
918 QualType Arg, SourceLocation ArgLoc) {
919 // C++ [temp.arg.type]p2:
920 // A local type, a type with no linkage, an unnamed type or a type
921 // compounded from any of these types shall not be used as a
922 // template-argument for a template type-parameter.
923 //
924 // FIXME: Perform the recursive and no-linkage type checks.
925 const TagType *Tag = 0;
926 if (const EnumType *EnumT = Arg->getAsEnumType())
927 Tag = EnumT;
928 else if (const RecordType *RecordT = Arg->getAsRecordType())
929 Tag = RecordT;
930 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
931 return Diag(ArgLoc, diag::err_template_arg_local_type)
932 << QualType(Tag, 0);
933 else if (Tag && !Tag->getDecl()->getDeclName()) {
934 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
935 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
936 return true;
937 }
938
939 return false;
940}
941
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +0000942/// \brief Checks whether the given template argument is the address
943/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +0000944bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
945 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +0000946 bool Invalid = false;
947
948 // See through any implicit casts we added to fix the type.
949 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
950 Arg = Cast->getSubExpr();
951
952 // C++ [temp.arg.nontype]p1:
953 //
954 // A template-argument for a non-type, non-template
955 // template-parameter shall be one of: [...]
956 //
957 // -- the address of an object or function with external
958 // linkage, including function templates and function
959 // template-ids but excluding non-static class members,
960 // expressed as & id-expression where the & is optional if
961 // the name refers to a function or array, or if the
962 // corresponding template-parameter is a reference; or
963 DeclRefExpr *DRE = 0;
964
965 // Ignore (and complain about) any excess parentheses.
966 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
967 if (!Invalid) {
968 Diag(Arg->getSourceRange().getBegin(),
969 diag::err_template_arg_extra_parens)
970 << Arg->getSourceRange();
971 Invalid = true;
972 }
973
974 Arg = Parens->getSubExpr();
975 }
976
977 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
978 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
979 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
980 } else
981 DRE = dyn_cast<DeclRefExpr>(Arg);
982
983 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
984 return Diag(Arg->getSourceRange().getBegin(),
985 diag::err_template_arg_not_object_or_func_form)
986 << Arg->getSourceRange();
987
988 // Cannot refer to non-static data members
989 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
990 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
991 << Field << Arg->getSourceRange();
992
993 // Cannot refer to non-static member functions
994 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
995 if (!Method->isStatic())
996 return Diag(Arg->getSourceRange().getBegin(),
997 diag::err_template_arg_method)
998 << Method << Arg->getSourceRange();
999
1000 // Functions must have external linkage.
1001 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1002 if (Func->getStorageClass() == FunctionDecl::Static) {
1003 Diag(Arg->getSourceRange().getBegin(),
1004 diag::err_template_arg_function_not_extern)
1005 << Func << Arg->getSourceRange();
1006 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1007 << true;
1008 return true;
1009 }
1010
1011 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001012 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001013 return Invalid;
1014 }
1015
1016 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1017 if (!Var->hasGlobalStorage()) {
1018 Diag(Arg->getSourceRange().getBegin(),
1019 diag::err_template_arg_object_not_extern)
1020 << Var << Arg->getSourceRange();
1021 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1022 << true;
1023 return true;
1024 }
1025
1026 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001027 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001028 return Invalid;
1029 }
1030
1031 // We found something else, but we don't know specifically what it is.
1032 Diag(Arg->getSourceRange().getBegin(),
1033 diag::err_template_arg_not_object_or_func)
1034 << Arg->getSourceRange();
1035 Diag(DRE->getDecl()->getLocation(),
1036 diag::note_template_arg_refers_here);
1037 return true;
1038}
1039
1040/// \brief Checks whether the given template argument is a pointer to
1041/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001042bool
1043Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001044 bool Invalid = false;
1045
1046 // See through any implicit casts we added to fix the type.
1047 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1048 Arg = Cast->getSubExpr();
1049
1050 // C++ [temp.arg.nontype]p1:
1051 //
1052 // A template-argument for a non-type, non-template
1053 // template-parameter shall be one of: [...]
1054 //
1055 // -- a pointer to member expressed as described in 5.3.1.
1056 QualifiedDeclRefExpr *DRE = 0;
1057
1058 // Ignore (and complain about) any excess parentheses.
1059 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1060 if (!Invalid) {
1061 Diag(Arg->getSourceRange().getBegin(),
1062 diag::err_template_arg_extra_parens)
1063 << Arg->getSourceRange();
1064 Invalid = true;
1065 }
1066
1067 Arg = Parens->getSubExpr();
1068 }
1069
1070 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1071 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1072 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1073
1074 if (!DRE)
1075 return Diag(Arg->getSourceRange().getBegin(),
1076 diag::err_template_arg_not_pointer_to_member_form)
1077 << Arg->getSourceRange();
1078
1079 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1080 assert((isa<FieldDecl>(DRE->getDecl()) ||
1081 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1082 "Only non-static member pointers can make it here");
1083
1084 // Okay: this is the address of a non-static member, and therefore
1085 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001086 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001087 return Invalid;
1088 }
1089
1090 // We found something else, but we don't know specifically what it is.
1091 Diag(Arg->getSourceRange().getBegin(),
1092 diag::err_template_arg_not_pointer_to_member_form)
1093 << Arg->getSourceRange();
1094 Diag(DRE->getDecl()->getLocation(),
1095 diag::note_template_arg_refers_here);
1096 return true;
1097}
1098
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001099/// \brief Check a template argument against its corresponding
1100/// non-type template parameter.
1101///
Douglas Gregored3a3982009-03-03 04:44:36 +00001102/// This routine implements the semantics of C++ [temp.arg.nontype].
1103/// It returns true if an error occurred, and false otherwise. \p
1104/// InstantiatedParamType is the type of the non-type template
1105/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001106///
1107/// If Converted is non-NULL and no errors occur, the value
1108/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001109bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001110 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001111 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001112 // If either the parameter has a dependent type or the argument is
1113 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001114 // FIXME: Add template argument to Converted!
Douglas Gregored3a3982009-03-03 04:44:36 +00001115 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent())
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001116 return false;
1117
1118 // C++ [temp.arg.nontype]p5:
1119 // The following conversions are performed on each expression used
1120 // as a non-type template-argument. If a non-type
1121 // template-argument cannot be converted to the type of the
1122 // corresponding template-parameter then the program is
1123 // ill-formed.
1124 //
1125 // -- for a non-type template-parameter of integral or
1126 // enumeration type, integral promotions (4.5) and integral
1127 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001128 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001129 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001130 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001131 // C++ [temp.arg.nontype]p1:
1132 // A template-argument for a non-type, non-template
1133 // template-parameter shall be one of:
1134 //
1135 // -- an integral constant-expression of integral or enumeration
1136 // type; or
1137 // -- the name of a non-type template-parameter; or
1138 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001139 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001140 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1141 Diag(Arg->getSourceRange().getBegin(),
1142 diag::err_template_arg_not_integral_or_enumeral)
1143 << ArgType << Arg->getSourceRange();
1144 Diag(Param->getLocation(), diag::note_template_param_here);
1145 return true;
1146 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001147 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001148 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1149 << ArgType << Arg->getSourceRange();
1150 return true;
1151 }
1152
1153 // FIXME: We need some way to more easily get the unqualified form
1154 // of the types without going all the way to the
1155 // canonical type.
1156 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1157 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1158 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1159 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1160
1161 // Try to convert the argument to the parameter's type.
1162 if (ParamType == ArgType) {
1163 // Okay: no conversion necessary
1164 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1165 !ParamType->isEnumeralType()) {
1166 // This is an integral promotion or conversion.
1167 ImpCastExprToType(Arg, ParamType);
1168 } else {
1169 // We can't perform this conversion.
1170 Diag(Arg->getSourceRange().getBegin(),
1171 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001172 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001173 Diag(Param->getLocation(), diag::note_template_param_here);
1174 return true;
1175 }
1176
Douglas Gregorad964b32009-02-17 01:05:43 +00001177 // FIXME: Check overflow of template arguments?
1178
1179 if (Converted) {
1180 // Add the value of this argument to the list of converted
1181 // arguments. We use the bitwidth and signedness of the template
1182 // parameter.
1183 QualType IntegerType = Context.getCanonicalType(ParamType);
1184 if (const EnumType *Enum = IntegerType->getAsEnumType())
1185 IntegerType = Enum->getDecl()->getIntegerType();
1186
1187 llvm::APInt CanonicalArg(Context.getTypeSize(IntegerType), 0,
1188 IntegerType->isSignedIntegerType());
1189 CanonicalArg = Value;
1190
1191 Converted->push_back(TemplateArgument(CanonicalArg));
1192 }
1193
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001194 return false;
1195 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001196
Douglas Gregor3f411962009-02-11 01:18:59 +00001197 // Handle pointer-to-function, reference-to-function, and
1198 // pointer-to-member-function all in (roughly) the same way.
1199 if (// -- For a non-type template-parameter of type pointer to
1200 // function, only the function-to-pointer conversion (4.3) is
1201 // applied. If the template-argument represents a set of
1202 // overloaded functions (or a pointer to such), the matching
1203 // function is selected from the set (13.4).
1204 (ParamType->isPointerType() &&
1205 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1206 // -- For a non-type template-parameter of type reference to
1207 // function, no conversions apply. If the template-argument
1208 // represents a set of overloaded functions, the matching
1209 // function is selected from the set (13.4).
1210 (ParamType->isReferenceType() &&
1211 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1212 // -- For a non-type template-parameter of type pointer to
1213 // member function, no conversions apply. If the
1214 // template-argument represents a set of overloaded member
1215 // functions, the matching member function is selected from
1216 // the set (13.4).
1217 (ParamType->isMemberPointerType() &&
1218 ParamType->getAsMemberPointerType()->getPointeeType()
1219 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001220 if (Context.hasSameUnqualifiedType(ArgType,
1221 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001222 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001223 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001224 ArgType = Context.getPointerType(ArgType);
1225 ImpCastExprToType(Arg, ArgType);
1226 } else if (FunctionDecl *Fn
1227 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001228 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1229 return true;
1230
Douglas Gregor2eedd992009-02-11 00:19:33 +00001231 FixOverloadedFunctionReference(Arg, Fn);
1232 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001233 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001234 ArgType = Context.getPointerType(Arg->getType());
1235 ImpCastExprToType(Arg, ArgType);
1236 }
1237 }
1238
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001239 if (!Context.hasSameUnqualifiedType(ArgType,
1240 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001241 // We can't perform this conversion.
1242 Diag(Arg->getSourceRange().getBegin(),
1243 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001244 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001245 Diag(Param->getLocation(), diag::note_template_param_here);
1246 return true;
1247 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001248
Douglas Gregorad964b32009-02-17 01:05:43 +00001249 if (ParamType->isMemberPointerType()) {
1250 NamedDecl *Member = 0;
1251 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1252 return true;
1253
1254 if (Converted)
1255 Converted->push_back(TemplateArgument(Member));
1256
1257 return false;
1258 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001259
Douglas Gregorad964b32009-02-17 01:05:43 +00001260 NamedDecl *Entity = 0;
1261 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1262 return true;
1263
1264 if (Converted)
1265 Converted->push_back(TemplateArgument(Entity));
1266 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001267 }
1268
Chris Lattner320dff22009-02-20 21:37:53 +00001269 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001270 // -- for a non-type template-parameter of type pointer to
1271 // object, qualification conversions (4.4) and the
1272 // array-to-pointer conversion (4.2) are applied.
Chris Lattner320dff22009-02-20 21:37:53 +00001273 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001274 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001275
Douglas Gregor3f411962009-02-11 01:18:59 +00001276 if (ArgType->isArrayType()) {
1277 ArgType = Context.getArrayDecayedType(ArgType);
1278 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001279 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001280
1281 if (IsQualificationConversion(ArgType, ParamType)) {
1282 ArgType = ParamType;
1283 ImpCastExprToType(Arg, ParamType);
1284 }
1285
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001286 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001287 // We can't perform this conversion.
1288 Diag(Arg->getSourceRange().getBegin(),
1289 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001290 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001291 Diag(Param->getLocation(), diag::note_template_param_here);
1292 return true;
1293 }
1294
Douglas Gregorad964b32009-02-17 01:05:43 +00001295 NamedDecl *Entity = 0;
1296 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1297 return true;
1298
1299 if (Converted)
1300 Converted->push_back(TemplateArgument(Entity));
1301
1302 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001303 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001304
1305 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1306 // -- For a non-type template-parameter of type reference to
1307 // object, no conversions apply. The type referred to by the
1308 // reference may be more cv-qualified than the (otherwise
1309 // identical) type of the template-argument. The
1310 // template-parameter is bound directly to the
1311 // template-argument, which must be an lvalue.
1312 assert(ParamRefType->getPointeeType()->isObjectType() &&
1313 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001314
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001315 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001316 Diag(Arg->getSourceRange().getBegin(),
1317 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001318 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001319 << Arg->getSourceRange();
1320 Diag(Param->getLocation(), diag::note_template_param_here);
1321 return true;
1322 }
1323
1324 unsigned ParamQuals
1325 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1326 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1327
1328 if ((ParamQuals | ArgQuals) != ParamQuals) {
1329 Diag(Arg->getSourceRange().getBegin(),
1330 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001331 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001332 << Arg->getSourceRange();
1333 Diag(Param->getLocation(), diag::note_template_param_here);
1334 return true;
1335 }
1336
Douglas Gregorad964b32009-02-17 01:05:43 +00001337 NamedDecl *Entity = 0;
1338 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1339 return true;
1340
1341 if (Converted)
1342 Converted->push_back(TemplateArgument(Entity));
1343
1344 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001345 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001346
1347 // -- For a non-type template-parameter of type pointer to data
1348 // member, qualification conversions (4.4) are applied.
1349 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1350
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001351 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001352 // Types match exactly: nothing more to do here.
1353 } else if (IsQualificationConversion(ArgType, ParamType)) {
1354 ImpCastExprToType(Arg, ParamType);
1355 } else {
1356 // We can't perform this conversion.
1357 Diag(Arg->getSourceRange().getBegin(),
1358 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001359 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001360 Diag(Param->getLocation(), diag::note_template_param_here);
1361 return true;
1362 }
1363
Douglas Gregorad964b32009-02-17 01:05:43 +00001364 NamedDecl *Member = 0;
1365 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1366 return true;
1367
1368 if (Converted)
1369 Converted->push_back(TemplateArgument(Member));
1370
1371 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001372}
1373
1374/// \brief Check a template argument against its corresponding
1375/// template template parameter.
1376///
1377/// This routine implements the semantics of C++ [temp.arg.template].
1378/// It returns true if an error occurred, and false otherwise.
1379bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1380 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001381 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1382 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1383
1384 // C++ [temp.arg.template]p1:
1385 // A template-argument for a template template-parameter shall be
1386 // the name of a class template, expressed as id-expression. Only
1387 // primary class templates are considered when matching the
1388 // template template argument with the corresponding parameter;
1389 // partial specializations are not considered even if their
1390 // parameter lists match that of the template template parameter.
1391 if (!isa<ClassTemplateDecl>(Template)) {
1392 assert(isa<FunctionTemplateDecl>(Template) &&
1393 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001394 Diag(Arg->getSourceRange().getBegin(),
1395 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001396 << Template;
1397 }
1398
1399 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1400 Param->getTemplateParameters(),
1401 true, true,
1402 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001403}
1404
Douglas Gregord406b032009-02-06 22:42:48 +00001405/// \brief Determine whether the given template parameter lists are
1406/// equivalent.
1407///
1408/// \param New The new template parameter list, typically written in the
1409/// source code as part of a new template declaration.
1410///
1411/// \param Old The old template parameter list, typically found via
1412/// name lookup of the template declared with this template parameter
1413/// list.
1414///
1415/// \param Complain If true, this routine will produce a diagnostic if
1416/// the template parameter lists are not equivalent.
1417///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001418/// \param IsTemplateTemplateParm If true, this routine is being
1419/// called to compare the template parameter lists of a template
1420/// template parameter.
1421///
1422/// \param TemplateArgLoc If this source location is valid, then we
1423/// are actually checking the template parameter list of a template
1424/// argument (New) against the template parameter list of its
1425/// corresponding template template parameter (Old). We produce
1426/// slightly different diagnostics in this scenario.
1427///
Douglas Gregord406b032009-02-06 22:42:48 +00001428/// \returns True if the template parameter lists are equal, false
1429/// otherwise.
1430bool
1431Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1432 TemplateParameterList *Old,
1433 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001434 bool IsTemplateTemplateParm,
1435 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001436 if (Old->size() != New->size()) {
1437 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001438 unsigned NextDiag = diag::err_template_param_list_different_arity;
1439 if (TemplateArgLoc.isValid()) {
1440 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1441 NextDiag = diag::note_template_param_list_different_arity;
1442 }
1443 Diag(New->getTemplateLoc(), NextDiag)
1444 << (New->size() > Old->size())
1445 << IsTemplateTemplateParm
1446 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001447 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1448 << IsTemplateTemplateParm
1449 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1450 }
1451
1452 return false;
1453 }
1454
1455 for (TemplateParameterList::iterator OldParm = Old->begin(),
1456 OldParmEnd = Old->end(), NewParm = New->begin();
1457 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1458 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001459 unsigned NextDiag = diag::err_template_param_different_kind;
1460 if (TemplateArgLoc.isValid()) {
1461 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1462 NextDiag = diag::note_template_param_different_kind;
1463 }
1464 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001465 << IsTemplateTemplateParm;
1466 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1467 << IsTemplateTemplateParm;
1468 return false;
1469 }
1470
1471 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1472 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001473 // know we're at the same index).
1474#if 0
1475 // FIXME: Enable this code in debug mode *after* we properly go
1476 // through and "instantiate" the template parameter lists of
1477 // template template parameters. It's only after this
1478 // instantiation that (1) any dependent types within the
1479 // template parameter list of the template template parameter
1480 // can be checked, and (2) the template type parameter depths
1481 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001482 QualType OldParmType
1483 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1484 QualType NewParmType
1485 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1486 assert(Context.getCanonicalType(OldParmType) ==
1487 Context.getCanonicalType(NewParmType) &&
1488 "type parameter mismatch?");
1489#endif
1490 } else if (NonTypeTemplateParmDecl *OldNTTP
1491 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1492 // The types of non-type template parameters must agree.
1493 NonTypeTemplateParmDecl *NewNTTP
1494 = cast<NonTypeTemplateParmDecl>(*NewParm);
1495 if (Context.getCanonicalType(OldNTTP->getType()) !=
1496 Context.getCanonicalType(NewNTTP->getType())) {
1497 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001498 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1499 if (TemplateArgLoc.isValid()) {
1500 Diag(TemplateArgLoc,
1501 diag::err_template_arg_template_params_mismatch);
1502 NextDiag = diag::note_template_nontype_parm_different_type;
1503 }
1504 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001505 << NewNTTP->getType()
1506 << IsTemplateTemplateParm;
1507 Diag(OldNTTP->getLocation(),
1508 diag::note_template_nontype_parm_prev_declaration)
1509 << OldNTTP->getType();
1510 }
1511 return false;
1512 }
1513 } else {
1514 // The template parameter lists of template template
1515 // parameters must agree.
1516 // FIXME: Could we perform a faster "type" comparison here?
1517 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1518 "Only template template parameters handled here");
1519 TemplateTemplateParmDecl *OldTTP
1520 = cast<TemplateTemplateParmDecl>(*OldParm);
1521 TemplateTemplateParmDecl *NewTTP
1522 = cast<TemplateTemplateParmDecl>(*NewParm);
1523 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1524 OldTTP->getTemplateParameters(),
1525 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001526 /*IsTemplateTemplateParm=*/true,
1527 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001528 return false;
1529 }
1530 }
1531
1532 return true;
1533}
1534
1535/// \brief Check whether a template can be declared within this scope.
1536///
1537/// If the template declaration is valid in this scope, returns
1538/// false. Otherwise, issues a diagnostic and returns true.
1539bool
1540Sema::CheckTemplateDeclScope(Scope *S,
1541 MultiTemplateParamsArg &TemplateParameterLists) {
1542 assert(TemplateParameterLists.size() > 0 && "Not a template");
1543
1544 // Find the nearest enclosing declaration scope.
1545 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1546 (S->getFlags() & Scope::TemplateParamScope) != 0)
1547 S = S->getParent();
1548
1549 TemplateParameterList *TemplateParams =
1550 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1551 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1552 SourceRange TemplateRange
1553 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1554
1555 // C++ [temp]p2:
1556 // A template-declaration can appear only as a namespace scope or
1557 // class scope declaration.
1558 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1559 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1560 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1561 return Diag(TemplateLoc, diag::err_template_linkage)
1562 << TemplateRange;
1563
1564 Ctx = Ctx->getParent();
1565 }
1566
1567 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1568 return false;
1569
1570 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1571 << TemplateRange;
1572}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001573
Douglas Gregor0d93f692009-02-25 22:02:03 +00001574/// \brief Check whether a class template specialization in the
1575/// current context is well-formed.
1576///
1577/// This routine determines whether a class template specialization
1578/// can be declared in the current context (C++ [temp.expl.spec]p2)
1579/// and emits appropriate diagnostics if there was an error. It
1580/// returns true if there was an error that we cannot recover from,
1581/// and false otherwise.
1582bool
1583Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1584 ClassTemplateSpecializationDecl *PrevDecl,
1585 SourceLocation TemplateNameLoc,
1586 SourceRange ScopeSpecifierRange) {
1587 // C++ [temp.expl.spec]p2:
1588 // An explicit specialization shall be declared in the namespace
1589 // of which the template is a member, or, for member templates, in
1590 // the namespace of which the enclosing class or enclosing class
1591 // template is a member. An explicit specialization of a member
1592 // function, member class or static data member of a class
1593 // template shall be declared in the namespace of which the class
1594 // template is a member. Such a declaration may also be a
1595 // definition. If the declaration is not a definition, the
1596 // specialization may be defined later in the name- space in which
1597 // the explicit specialization was declared, or in a namespace
1598 // that encloses the one in which the explicit specialization was
1599 // declared.
1600 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1601 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1602 << ClassTemplate;
1603 return true;
1604 }
1605
1606 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1607 DeclContext *TemplateContext
1608 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1609 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1610 // There is no prior declaration of this entity, so this
1611 // specialization must be in the same context as the template
1612 // itself.
1613 if (DC != TemplateContext) {
1614 if (isa<TranslationUnitDecl>(TemplateContext))
1615 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1616 << ClassTemplate << ScopeSpecifierRange;
1617 else if (isa<NamespaceDecl>(TemplateContext))
1618 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1619 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1620 << ScopeSpecifierRange;
1621
1622 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1623 }
1624
1625 return false;
1626 }
1627
1628 // We have a previous declaration of this entity. Make sure that
1629 // this redeclaration (or definition) occurs in an enclosing namespace.
1630 if (!CurContext->Encloses(TemplateContext)) {
1631 if (isa<TranslationUnitDecl>(TemplateContext))
1632 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1633 << ClassTemplate << ScopeSpecifierRange;
1634 else if (isa<NamespaceDecl>(TemplateContext))
1635 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1636 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1637 << ScopeSpecifierRange;
1638
1639 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1640 }
1641
1642 return false;
1643}
1644
Douglas Gregora08b6c72009-02-17 23:15:12 +00001645Sema::DeclTy *
1646Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1647 SourceLocation KWLoc,
1648 const CXXScopeSpec &SS,
1649 DeclTy *TemplateD,
1650 SourceLocation TemplateNameLoc,
1651 SourceLocation LAngleLoc,
1652 ASTTemplateArgsPtr TemplateArgs,
1653 SourceLocation *TemplateArgLocs,
1654 SourceLocation RAngleLoc,
1655 AttributeList *Attr,
1656 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001657 // Find the class template we're specializing
1658 ClassTemplateDecl *ClassTemplate
1659 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1660 if (!ClassTemplate)
1661 return 0;
1662
Douglas Gregor0d93f692009-02-25 22:02:03 +00001663 // Check the validity of the template headers that introduce this
1664 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001665 // FIXME: Once we have member templates, we'll need to check
1666 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1667 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001668 if (TemplateParameterLists.size() == 0)
1669 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001670 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001671 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001672 TemplateParameterList *TemplateParams
1673 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1674 if (TemplateParameterLists.size() > 1) {
1675 Diag(TemplateParams->getTemplateLoc(),
1676 diag::err_template_spec_extra_headers);
1677 return 0;
1678 }
1679
1680 if (TemplateParams->size() > 0) {
1681 // FIXME: No support for class template partial specialization.
1682 Diag(TemplateParams->getTemplateLoc(),
1683 diag::unsup_template_partial_spec);
1684 return 0;
1685 }
1686 }
1687
Douglas Gregora08b6c72009-02-17 23:15:12 +00001688 // Check that the specialization uses the same tag kind as the
1689 // original template.
1690 TagDecl::TagKind Kind;
1691 switch (TagSpec) {
1692 default: assert(0 && "Unknown tag type!");
1693 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1694 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1695 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1696 }
1697 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1698 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1699 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1700 diag::note_previous_use);
1701 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1702 }
1703
1704 // Check that the template argument list is well-formed for this
1705 // template.
1706 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1707 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
1708 TemplateArgs, TemplateArgLocs, RAngleLoc,
1709 ConvertedTemplateArgs))
1710 return 0;
1711
1712 assert((ConvertedTemplateArgs.size() ==
1713 ClassTemplate->getTemplateParameters()->size()) &&
1714 "Converted template argument list is too short!");
1715
1716 // Find the class template specialization declaration that
1717 // corresponds to these arguments.
1718 llvm::FoldingSetNodeID ID;
1719 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1720 ConvertedTemplateArgs.size());
1721 void *InsertPos = 0;
1722 ClassTemplateSpecializationDecl *PrevDecl
1723 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1724
1725 ClassTemplateSpecializationDecl *Specialization = 0;
1726
Douglas Gregor0d93f692009-02-25 22:02:03 +00001727 // Check whether we can declare a class template specialization in
1728 // the current scope.
1729 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1730 TemplateNameLoc,
1731 SS.getRange()))
1732 return 0;
1733
Douglas Gregora08b6c72009-02-17 23:15:12 +00001734 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1735 // Since the only prior class template specialization with these
1736 // arguments was referenced but not declared, reuse that
1737 // declaration node as our own, updating its source location to
1738 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001739 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00001740 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001741 PrevDecl = 0;
1742 } else {
1743 // Create a new class template specialization declaration node for
1744 // this explicit specialization.
1745 Specialization
1746 = ClassTemplateSpecializationDecl::Create(Context,
1747 ClassTemplate->getDeclContext(),
1748 TemplateNameLoc,
1749 ClassTemplate,
1750 &ConvertedTemplateArgs[0],
1751 ConvertedTemplateArgs.size(),
1752 PrevDecl);
1753
1754 if (PrevDecl) {
1755 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1756 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1757 } else {
1758 ClassTemplate->getSpecializations().InsertNode(Specialization,
1759 InsertPos);
1760 }
1761 }
1762
1763 // Note that this is an explicit specialization.
1764 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1765
1766 // Check that this isn't a redefinition of this specialization.
1767 if (TK == TK_Definition) {
1768 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1769 // FIXME: Should also handle explicit specialization after
1770 // implicit instantiation with a special diagnostic.
1771 SourceRange Range(TemplateNameLoc, RAngleLoc);
1772 Diag(TemplateNameLoc, diag::err_redefinition)
1773 << Specialization << Range;
1774 Diag(Def->getLocation(), diag::note_previous_definition);
1775 Specialization->setInvalidDecl();
1776 return 0;
1777 }
1778 }
1779
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001780 // Build the fully-sugared type for this class template
1781 // specialization as the user wrote in the specialization
1782 // itself. This means that we'll pretty-print the type retrieved
1783 // from the specialization's declaration the way that the user
1784 // actually wrote the specialization, rather than formatting the
1785 // name based on the "canonical" representation used to store the
1786 // template arguments in the specialization.
1787 Specialization->setTypeAsWritten(
1788 Context.getClassTemplateSpecializationType(ClassTemplate,
1789 TemplateArgs.size(),
1790 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
1791 TemplateArgs.getArgIsType(),
1792 Context.getTypeDeclType(Specialization)));
1793 TemplateArgs.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001794
Douglas Gregor50113ca2009-02-25 22:18:32 +00001795 // C++ [temp.expl.spec]p9:
1796 // A template explicit specialization is in the scope of the
1797 // namespace in which the template was defined.
1798 //
1799 // We actually implement this paragraph where we set the semantic
1800 // context (in the creation of the ClassTemplateSpecializationDecl),
1801 // but we also maintain the lexical context where the actual
1802 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001803 Specialization->setLexicalDeclContext(CurContext);
1804
1805 // We may be starting the definition of this specialization.
1806 if (TK == TK_Definition)
1807 Specialization->startDefinition();
1808
1809 // Add the specialization into its lexical context, so that it can
1810 // be seen when iterating through the list of declarations in that
1811 // context. However, specializations are not found by name lookup.
1812 CurContext->addDecl(Specialization);
1813 return Specialization;
1814}