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