blob: 69946975cdc04c2364495ea1fd48380a116df6bb [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");
Douglas Gregor55216ac2009-03-26 00:10:35 +000045 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
46 // C++ [temp.local]p1:
47 // Like normal (non-template) classes, class templates have an
48 // injected-class-name (Clause 9). The injected-class-name
49 // can be used with or without a template-argument-list. When
50 // it is used without a template-argument-list, it is
51 // equivalent to the injected-class-name followed by the
52 // template-parameters of the class template enclosed in
53 // <>. When it is used with a template-argument-list, it
54 // refers to the specified class template specialization,
55 // which could be the current specialization or another
56 // specialization.
57 if (Record->isInjectedClassName()) {
58 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
59 if ((Template = Record->getDescribedClassTemplate()))
60 return TNK_Class_template;
61 else if (ClassTemplateSpecializationDecl *Spec
62 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
63 Template = Spec->getSpecializedTemplate();
64 return TNK_Class_template;
65 }
66 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000067 }
Douglas Gregor279272e2009-02-04 19:02:06 +000068
Douglas Gregor8e458f42009-02-09 18:46:07 +000069 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000071 if (FD->getType()->isDependentType()) {
72 Template = FD;
73 return TNK_Function_template;
74 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000075 } else if (OverloadedFunctionDecl *Ovl
76 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
77 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
78 FEnd = Ovl->function_end();
79 F != FEnd; ++F) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000080 if ((*F)->getType()->isDependentType()) {
81 Template = Ovl;
82 return TNK_Function_template;
83 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000084 }
85 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000086 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000087 return TNK_Non_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +000088}
89
Douglas Gregordd861062008-12-05 18:15:24 +000090/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
91/// that the template parameter 'PrevDecl' is being shadowed by a new
92/// declaration at location Loc. Returns true to indicate that this is
93/// an error, and false otherwise.
94bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +000095 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +000096
97 // Microsoft Visual C++ permits template parameters to be shadowed.
98 if (getLangOptions().Microsoft)
99 return false;
100
101 // C++ [temp.local]p4:
102 // A template-parameter shall not be redeclared within its
103 // scope (including nested scopes).
104 Diag(Loc, diag::err_template_param_shadow)
105 << cast<NamedDecl>(PrevDecl)->getDeclName();
106 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
107 return true;
108}
109
Douglas Gregored3a3982009-03-03 04:44:36 +0000110/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregor279272e2009-02-04 19:02:06 +0000111/// the parameter D to reference the templated declaration and return a pointer
112/// to the template declaration. Otherwise, do nothing to D and return null.
113TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
114{
115 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
116 D = Temp->getTemplatedDecl();
117 return Temp;
118 }
119 return 0;
120}
121
Douglas Gregordd861062008-12-05 18:15:24 +0000122/// ActOnTypeParameter - Called when a C++ template type parameter
123/// (e.g., "typename T") has been parsed. Typename specifies whether
124/// the keyword "typename" was used to declare the type parameter
125/// (otherwise, "class" was used), and KeyLoc is the location of the
126/// "class" or "typename" keyword. ParamName is the name of the
127/// parameter (NULL indicates an unnamed template parameter) and
128/// ParamName is the location of the parameter name (if any).
129/// If the type parameter has a default argument, it will be added
130/// later via ActOnTypeParameterDefault.
131Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
132 SourceLocation KeyLoc,
133 IdentifierInfo *ParamName,
Douglas Gregor52473432008-12-24 02:52:09 +0000134 SourceLocation ParamNameLoc,
135 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000136 assert(S->isTemplateParamScope() &&
137 "Template type parameter not in template parameter scope!");
138 bool Invalid = false;
139
140 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000141 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000142 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000143 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
144 PrevDecl);
145 }
146
Douglas Gregord406b032009-02-06 22:42:48 +0000147 SourceLocation Loc = ParamNameLoc;
148 if (!ParamName)
149 Loc = KeyLoc;
150
Douglas Gregordd861062008-12-05 18:15:24 +0000151 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000152 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000153 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000154 if (Invalid)
155 Param->setInvalidDecl();
156
157 if (ParamName) {
158 // Add the template parameter into the current scope.
159 S->AddDecl(Param);
160 IdResolver.AddDecl(Param);
161 }
162
163 return Param;
164}
165
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000166/// ActOnTypeParameterDefault - Adds a default argument (the type
167/// Default) to the given template type parameter (TypeParam).
168void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
169 SourceLocation EqualLoc,
170 SourceLocation DefaultLoc,
171 TypeTy *DefaultT) {
172 TemplateTypeParmDecl *Parm
173 = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
174 QualType Default = QualType::getFromOpaquePtr(DefaultT);
175
176 // C++ [temp.param]p14:
177 // A template-parameter shall not be used in its own default argument.
178 // FIXME: Implement this check! Needs a recursive walk over the types.
179
180 // Check the template argument itself.
181 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
182 Parm->setInvalidDecl();
183 return;
184 }
185
186 Parm->setDefaultArgument(Default, DefaultLoc, false);
187}
188
Douglas Gregored3a3982009-03-03 04:44:36 +0000189/// \brief Check that the type of a non-type template parameter is
190/// well-formed.
191///
192/// \returns the (possibly-promoted) parameter type if valid;
193/// otherwise, produces a diagnostic and returns a NULL type.
194QualType
195Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
196 // C++ [temp.param]p4:
197 //
198 // A non-type template-parameter shall have one of the following
199 // (optionally cv-qualified) types:
200 //
201 // -- integral or enumeration type,
202 if (T->isIntegralType() || T->isEnumeralType() ||
203 // -- pointer to object or pointer to function,
204 (T->isPointerType() &&
205 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
206 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
207 // -- reference to object or reference to function,
208 T->isReferenceType() ||
209 // -- pointer to member.
210 T->isMemberPointerType() ||
211 // If T is a dependent type, we can't do the check now, so we
212 // assume that it is well-formed.
213 T->isDependentType())
214 return T;
215 // C++ [temp.param]p8:
216 //
217 // A non-type template-parameter of type "array of T" or
218 // "function returning T" is adjusted to be of type "pointer to
219 // T" or "pointer to function returning T", respectively.
220 else if (T->isArrayType())
221 // FIXME: Keep the type prior to promotion?
222 return Context.getArrayDecayedType(T);
223 else if (T->isFunctionType())
224 // FIXME: Keep the type prior to promotion?
225 return Context.getPointerType(T);
226
227 Diag(Loc, diag::err_template_nontype_parm_bad_type)
228 << T;
229
230 return QualType();
231}
232
Douglas Gregordd861062008-12-05 18:15:24 +0000233/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
234/// template parameter (e.g., "int Size" in "template<int Size>
235/// class Array") has been parsed. S is the current scope and D is
236/// the parsed declarator.
Douglas Gregor52473432008-12-24 02:52:09 +0000237Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
238 unsigned Depth,
239 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000240 QualType T = GetTypeForDeclarator(D, S);
241
Douglas Gregor279272e2009-02-04 19:02:06 +0000242 assert(S->isTemplateParamScope() &&
243 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000244 bool Invalid = false;
245
246 IdentifierInfo *ParamName = D.getIdentifier();
247 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000248 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000249 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000250 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000251 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000252 }
253
Douglas Gregored3a3982009-03-03 04:44:36 +0000254 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000255 if (T.isNull()) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000256 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregor8b90e8e2009-03-09 16:46:39 +0000257 Invalid = true;
258 }
Douglas Gregor62cdc792009-02-10 17:43:50 +0000259
Douglas Gregordd861062008-12-05 18:15:24 +0000260 NonTypeTemplateParmDecl *Param
261 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000262 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000263 if (Invalid)
264 Param->setInvalidDecl();
265
266 if (D.getIdentifier()) {
267 // Add the template parameter into the current scope.
268 S->AddDecl(Param);
269 IdResolver.AddDecl(Param);
270 }
271 return Param;
272}
Douglas Gregor52473432008-12-24 02:52:09 +0000273
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000274/// \brief Adds a default argument to the given non-type template
275/// parameter.
276void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
277 SourceLocation EqualLoc,
278 ExprArg DefaultE) {
279 NonTypeTemplateParmDecl *TemplateParm
280 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
281 Expr *Default = static_cast<Expr *>(DefaultE.get());
282
283 // C++ [temp.param]p14:
284 // A template-parameter shall not be used in its own default argument.
285 // FIXME: Implement this check! Needs a recursive walk over the types.
286
287 // Check the well-formedness of the default template argument.
Douglas Gregored3a3982009-03-03 04:44:36 +0000288 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000289 TemplateParm->setInvalidDecl();
290 return;
291 }
292
293 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
294}
295
Douglas Gregor279272e2009-02-04 19:02:06 +0000296
297/// ActOnTemplateTemplateParameter - Called when a C++ template template
298/// parameter (e.g. T in template <template <typename> class T> class array)
299/// has been parsed. S is the current scope.
300Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
301 SourceLocation TmpLoc,
302 TemplateParamsTy *Params,
303 IdentifierInfo *Name,
304 SourceLocation NameLoc,
305 unsigned Depth,
306 unsigned Position)
307{
308 assert(S->isTemplateParamScope() &&
309 "Template template parameter not in template parameter scope!");
310
311 // Construct the parameter object.
312 TemplateTemplateParmDecl *Param =
313 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
314 Position, Name,
315 (TemplateParameterList*)Params);
316
317 // Make sure the parameter is valid.
318 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
319 // do anything yet. However, if the template parameter list or (eventual)
320 // default value is ever invalidated, that will propagate here.
321 bool Invalid = false;
322 if (Invalid) {
323 Param->setInvalidDecl();
324 }
325
326 // If the tt-param has a name, then link the identifier into the scope
327 // and lookup mechanisms.
328 if (Name) {
329 S->AddDecl(Param);
330 IdResolver.AddDecl(Param);
331 }
332
333 return Param;
334}
335
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000336/// \brief Adds a default argument to the given template template
337/// parameter.
338void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
339 SourceLocation EqualLoc,
340 ExprArg DefaultE) {
341 TemplateTemplateParmDecl *TemplateParm
342 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
343
344 // Since a template-template parameter's default argument is an
345 // id-expression, it must be a DeclRefExpr.
346 DeclRefExpr *Default
347 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
348
349 // C++ [temp.param]p14:
350 // A template-parameter shall not be used in its own default argument.
351 // FIXME: Implement this check! Needs a recursive walk over the types.
352
353 // Check the well-formedness of the template argument.
354 if (!isa<TemplateDecl>(Default->getDecl())) {
355 Diag(Default->getSourceRange().getBegin(),
356 diag::err_template_arg_must_be_template)
357 << Default->getSourceRange();
358 TemplateParm->setInvalidDecl();
359 return;
360 }
361 if (CheckTemplateArgument(TemplateParm, Default)) {
362 TemplateParm->setInvalidDecl();
363 return;
364 }
365
366 DefaultE.release();
367 TemplateParm->setDefaultArgument(Default);
368}
369
Douglas Gregor52473432008-12-24 02:52:09 +0000370/// ActOnTemplateParameterList - Builds a TemplateParameterList that
371/// contains the template parameters in Params/NumParams.
372Sema::TemplateParamsTy *
373Sema::ActOnTemplateParameterList(unsigned Depth,
374 SourceLocation ExportLoc,
375 SourceLocation TemplateLoc,
376 SourceLocation LAngleLoc,
377 DeclTy **Params, unsigned NumParams,
378 SourceLocation RAngleLoc) {
379 if (ExportLoc.isValid())
380 Diag(ExportLoc, diag::note_template_export_unsupported);
381
Douglas Gregord406b032009-02-06 22:42:48 +0000382 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
383 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000384}
Douglas Gregor279272e2009-02-04 19:02:06 +0000385
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000386Sema::DeclResult
Douglas Gregord406b032009-02-06 22:42:48 +0000387Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
388 SourceLocation KWLoc, const CXXScopeSpec &SS,
389 IdentifierInfo *Name, SourceLocation NameLoc,
390 AttributeList *Attr,
Anders Carlssoned20fb92009-03-26 00:52:18 +0000391 MultiTemplateParamsArg TemplateParameterLists,
392 AccessSpecifier AS) {
Douglas Gregord406b032009-02-06 22:42:48 +0000393 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
394 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000395 bool Invalid = false;
Douglas Gregord406b032009-02-06 22:42:48 +0000396
397 // Check that we can declare a template here.
398 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000399 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000400
401 TagDecl::TagKind Kind;
402 switch (TagSpec) {
403 default: assert(0 && "Unknown tag type!");
404 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
405 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
406 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
407 }
408
409 // There is no such thing as an unnamed class template.
410 if (!Name) {
411 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000412 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000413 }
414
415 // Find any previous declaration with this name.
416 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
417 true);
418 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
419 NamedDecl *PrevDecl = 0;
420 if (Previous.begin() != Previous.end())
421 PrevDecl = *Previous.begin();
422
423 DeclContext *SemanticContext = CurContext;
424 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000425 SemanticContext = computeDeclContext(SS);
Douglas Gregord406b032009-02-06 22:42:48 +0000426
427 // FIXME: need to match up several levels of template parameter
428 // lists here.
429 }
430
431 // FIXME: member templates!
432 TemplateParameterList *TemplateParams
433 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
434
435 // If there is a previous declaration with the same name, check
436 // whether this is a valid redeclaration.
437 ClassTemplateDecl *PrevClassTemplate
438 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
439 if (PrevClassTemplate) {
440 // Ensure that the template parameter lists are compatible.
441 if (!TemplateParameterListsAreEqual(TemplateParams,
442 PrevClassTemplate->getTemplateParameters(),
443 /*Complain=*/true))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000444 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000445
446 // C++ [temp.class]p4:
447 // In a redeclaration, partial specialization, explicit
448 // specialization or explicit instantiation of a class template,
449 // the class-key shall agree in kind with the original class
450 // template declaration (7.1.5.3).
451 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
452 if (PrevRecordDecl->getTagKind() != Kind) {
453 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
454 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000455 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000456 }
457
458
459 // Check for redefinition of this class template.
460 if (TK == TK_Definition) {
461 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
462 Diag(NameLoc, diag::err_redefinition) << Name;
463 Diag(Def->getLocation(), diag::note_previous_definition);
464 // FIXME: Would it make sense to try to "forget" the previous
465 // definition, as part of error recovery?
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000466 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000467 }
468 }
469 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
470 // Maybe we will complain about the shadowed template parameter.
471 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
472 // Just pretend that we didn't see the previous declaration.
473 PrevDecl = 0;
474 } else if (PrevDecl) {
475 // C++ [temp]p5:
476 // A class template shall not have the same name as any other
477 // template, class, function, object, enumeration, enumerator,
478 // namespace, or type in the same scope (3.3), except as specified
479 // in (14.5.4).
480 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
481 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc5d6fa72009-03-25 00:13:59 +0000482 return true;
Douglas Gregord406b032009-02-06 22:42:48 +0000483 }
484
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000485 // Check the template parameter list of this declaration, possibly
486 // merging in the template parameter list from the previous class
487 // template declaration.
488 if (CheckTemplateParameterList(TemplateParams,
489 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
490 Invalid = true;
491
Douglas Gregord406b032009-02-06 22:42:48 +0000492 // If we had a scope specifier, we better have a previous template
493 // declaration!
494
Douglas Gregor55216ac2009-03-26 00:10:35 +0000495 CXXRecordDecl *NewClass =
Douglas Gregord406b032009-02-06 22:42:48 +0000496 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
497 PrevClassTemplate?
498 PrevClassTemplate->getTemplatedDecl() : 0);
499
500 ClassTemplateDecl *NewTemplate
501 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
502 DeclarationName(Name), TemplateParams,
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000503 NewClass, PrevClassTemplate);
Douglas Gregor55216ac2009-03-26 00:10:35 +0000504 NewClass->setDescribedClassTemplate(NewTemplate);
505
Anders Carlsson4ca43492009-03-26 01:24:28 +0000506 // Set the access specifier.
507 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
508
Douglas Gregord406b032009-02-06 22:42:48 +0000509 // Set the lexical context of these templates
510 NewClass->setLexicalDeclContext(CurContext);
511 NewTemplate->setLexicalDeclContext(CurContext);
512
513 if (TK == TK_Definition)
514 NewClass->startDefinition();
515
516 if (Attr)
517 ProcessDeclAttributeList(NewClass, Attr);
518
519 PushOnScopeChains(NewTemplate, S);
520
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000521 if (Invalid) {
522 NewTemplate->setInvalidDecl();
523 NewClass->setInvalidDecl();
524 }
Douglas Gregord406b032009-02-06 22:42:48 +0000525 return NewTemplate;
526}
527
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000528/// \brief Checks the validity of a template parameter list, possibly
529/// considering the template parameter list from a previous
530/// declaration.
531///
532/// If an "old" template parameter list is provided, it must be
533/// equivalent (per TemplateParameterListsAreEqual) to the "new"
534/// template parameter list.
535///
536/// \param NewParams Template parameter list for a new template
537/// declaration. This template parameter list will be updated with any
538/// default arguments that are carried through from the previous
539/// template parameter list.
540///
541/// \param OldParams If provided, template parameter list from a
542/// previous declaration of the same template. Default template
543/// arguments will be merged from the old template parameter list to
544/// the new template parameter list.
545///
546/// \returns true if an error occurred, false otherwise.
547bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
548 TemplateParameterList *OldParams) {
549 bool Invalid = false;
550
551 // C++ [temp.param]p10:
552 // The set of default template-arguments available for use with a
553 // template declaration or definition is obtained by merging the
554 // default arguments from the definition (if in scope) and all
555 // declarations in scope in the same way default function
556 // arguments are (8.3.6).
557 bool SawDefaultArgument = false;
558 SourceLocation PreviousDefaultArgLoc;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000559
Mike Stumpe0b7e032009-02-11 23:03:27 +0000560 // Dummy initialization to avoid warnings.
Douglas Gregorc5363f42009-02-11 20:46:19 +0000561 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000562 if (OldParams)
563 OldParam = OldParams->begin();
564
565 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
566 NewParamEnd = NewParams->end();
567 NewParam != NewParamEnd; ++NewParam) {
568 // Variables used to diagnose redundant default arguments
569 bool RedundantDefaultArg = false;
570 SourceLocation OldDefaultLoc;
571 SourceLocation NewDefaultLoc;
572
573 // Variables used to diagnose missing default arguments
574 bool MissingDefaultArg = false;
575
576 // Merge default arguments for template type parameters.
577 if (TemplateTypeParmDecl *NewTypeParm
578 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
579 TemplateTypeParmDecl *OldTypeParm
580 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
581
582 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
583 NewTypeParm->hasDefaultArgument()) {
584 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
585 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
586 SawDefaultArgument = true;
587 RedundantDefaultArg = true;
588 PreviousDefaultArgLoc = NewDefaultLoc;
589 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
590 // Merge the default argument from the old declaration to the
591 // new declaration.
592 SawDefaultArgument = true;
593 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
594 OldTypeParm->getDefaultArgumentLoc(),
595 true);
596 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
597 } else if (NewTypeParm->hasDefaultArgument()) {
598 SawDefaultArgument = true;
599 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
600 } else if (SawDefaultArgument)
601 MissingDefaultArg = true;
602 }
603 // Merge default arguments for non-type template parameters
604 else if (NonTypeTemplateParmDecl *NewNonTypeParm
605 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
606 NonTypeTemplateParmDecl *OldNonTypeParm
607 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
608 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
609 NewNonTypeParm->hasDefaultArgument()) {
610 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
611 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
612 SawDefaultArgument = true;
613 RedundantDefaultArg = true;
614 PreviousDefaultArgLoc = NewDefaultLoc;
615 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
616 // Merge the default argument from the old declaration to the
617 // new declaration.
618 SawDefaultArgument = true;
619 // FIXME: We need to create a new kind of "default argument"
620 // expression that points to a previous template template
621 // parameter.
622 NewNonTypeParm->setDefaultArgument(
623 OldNonTypeParm->getDefaultArgument());
624 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
625 } else if (NewNonTypeParm->hasDefaultArgument()) {
626 SawDefaultArgument = true;
627 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
628 } else if (SawDefaultArgument)
629 MissingDefaultArg = true;
630 }
631 // Merge default arguments for template template parameters
632 else {
633 TemplateTemplateParmDecl *NewTemplateParm
634 = cast<TemplateTemplateParmDecl>(*NewParam);
635 TemplateTemplateParmDecl *OldTemplateParm
636 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
637 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
638 NewTemplateParm->hasDefaultArgument()) {
639 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
640 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
641 SawDefaultArgument = true;
642 RedundantDefaultArg = true;
643 PreviousDefaultArgLoc = NewDefaultLoc;
644 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
645 // Merge the default argument from the old declaration to the
646 // new declaration.
647 SawDefaultArgument = true;
648 // FIXME: We need to create a new kind of "default argument"
649 // expression that points to a previous template template
650 // parameter.
651 NewTemplateParm->setDefaultArgument(
652 OldTemplateParm->getDefaultArgument());
653 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
654 } else if (NewTemplateParm->hasDefaultArgument()) {
655 SawDefaultArgument = true;
656 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
657 } else if (SawDefaultArgument)
658 MissingDefaultArg = true;
659 }
660
661 if (RedundantDefaultArg) {
662 // C++ [temp.param]p12:
663 // A template-parameter shall not be given default arguments
664 // by two different declarations in the same scope.
665 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
666 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
667 Invalid = true;
668 } else if (MissingDefaultArg) {
669 // C++ [temp.param]p11:
670 // If a template-parameter has a default template-argument,
671 // all subsequent template-parameters shall have a default
672 // template-argument supplied.
673 Diag((*NewParam)->getLocation(),
674 diag::err_template_param_default_arg_missing);
675 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
676 Invalid = true;
677 }
678
679 // If we have an old template parameter list that we're merging
680 // in, move on to the next parameter.
681 if (OldParams)
682 ++OldParam;
683 }
684
685 return Invalid;
686}
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000687
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000688/// \brief Translates template arguments as provided by the parser
689/// into template arguments used by semantic analysis.
690static void
691translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
692 SourceLocation *TemplateArgLocs,
693 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
694 TemplateArgs.reserve(TemplateArgsIn.size());
695
696 void **Args = TemplateArgsIn.getArgs();
697 bool *ArgIsType = TemplateArgsIn.getArgIsType();
698 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
699 TemplateArgs.push_back(
700 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
701 QualType::getFromOpaquePtr(Args[Arg]))
702 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
703 }
704}
705
706QualType Sema::CheckClassTemplateId(ClassTemplateDecl *ClassTemplate,
707 SourceLocation TemplateLoc,
708 SourceLocation LAngleLoc,
709 const TemplateArgument *TemplateArgs,
710 unsigned NumTemplateArgs,
711 SourceLocation RAngleLoc) {
712 // Check that the template argument list is well-formed for this
713 // template.
714 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
715 if (CheckTemplateArgumentList(ClassTemplate, TemplateLoc, LAngleLoc,
716 TemplateArgs, NumTemplateArgs, RAngleLoc,
717 ConvertedTemplateArgs))
718 return QualType();
719
720 assert((ConvertedTemplateArgs.size() ==
721 ClassTemplate->getTemplateParameters()->size()) &&
722 "Converted template argument list is too short!");
723
724 QualType CanonType;
725
726 if (ClassTemplateSpecializationType::anyDependentTemplateArguments(
727 TemplateArgs,
728 NumTemplateArgs)) {
729 // This class template specialization is a dependent
730 // type. Therefore, its canonical type is another class template
731 // specialization type that contains all of the converted
732 // arguments in canonical form. This ensures that, e.g., A<T> and
733 // A<T, T> have identical types when A is declared as:
734 //
735 // template<typename T, typename U = T> struct A;
736
737 CanonType = Context.getClassTemplateSpecializationType(ClassTemplate,
738 &ConvertedTemplateArgs[0],
739 ConvertedTemplateArgs.size());
740 } else {
741 // Find the class template specialization declaration that
742 // corresponds to these arguments.
743 llvm::FoldingSetNodeID ID;
744 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
745 ConvertedTemplateArgs.size());
746 void *InsertPos = 0;
747 ClassTemplateSpecializationDecl *Decl
748 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
749 if (!Decl) {
750 // This is the first time we have referenced this class template
751 // specialization. Create the canonical declaration and add it to
752 // the set of specializations.
753 Decl = ClassTemplateSpecializationDecl::Create(Context,
754 ClassTemplate->getDeclContext(),
755 TemplateLoc,
756 ClassTemplate,
757 &ConvertedTemplateArgs[0],
758 ConvertedTemplateArgs.size(),
759 0);
760 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
761 Decl->setLexicalDeclContext(CurContext);
762 }
763
764 CanonType = Context.getTypeDeclType(Decl);
765 }
766
767 // Build the fully-sugared type for this class template
768 // specialization, which refers back to the class template
769 // specialization we created or found.
770 return Context.getClassTemplateSpecializationType(ClassTemplate,
771 TemplateArgs,
772 NumTemplateArgs,
773 CanonType);
774}
775
Douglas Gregora08b6c72009-02-17 23:15:12 +0000776Action::TypeResult
777Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
778 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000779 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000780 SourceLocation *TemplateArgLocs,
781 SourceLocation RAngleLoc,
782 const CXXScopeSpec *SS) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000783 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregorad964b32009-02-17 01:05:43 +0000784 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000785
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000786 // Translate the parser's template argument list in our AST format.
787 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
788 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000789
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000790 QualType Result = CheckClassTemplateId(ClassTemplate, TemplateLoc,
791 LAngleLoc,
792 &TemplateArgs[0],
793 TemplateArgs.size(),
794 RAngleLoc);
Douglas Gregor8c795a12009-03-19 00:39:20 +0000795
796 if (SS)
797 Result = getQualifiedNameType(*SS, Result);
Douglas Gregorad964b32009-02-17 01:05:43 +0000798
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000799 TemplateArgsIn.release();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000800 return Result.getAsOpaquePtr();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000801}
802
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000803/// \brief Check that the given template argument list is well-formed
804/// for specializing the given template.
805bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
806 SourceLocation TemplateLoc,
807 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000808 const TemplateArgument *TemplateArgs,
809 unsigned NumTemplateArgs,
Douglas Gregorad964b32009-02-17 01:05:43 +0000810 SourceLocation RAngleLoc,
811 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000812 TemplateParameterList *Params = Template->getTemplateParameters();
813 unsigned NumParams = Params->size();
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000814 unsigned NumArgs = NumTemplateArgs;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000815 bool Invalid = false;
816
817 if (NumArgs > NumParams ||
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000818 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000819 // FIXME: point at either the first arg beyond what we can handle,
820 // or the '>', depending on whether we have too many or too few
821 // arguments.
822 SourceRange Range;
823 if (NumArgs > NumParams)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000824 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000825 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
826 << (NumArgs > NumParams)
827 << (isa<ClassTemplateDecl>(Template)? 0 :
828 isa<FunctionTemplateDecl>(Template)? 1 :
829 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
830 << Template << Range;
Douglas Gregorc347d8e2009-02-11 18:16:40 +0000831 Diag(Template->getLocation(), diag::note_template_decl_here)
832 << Params->getSourceRange();
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000833 Invalid = true;
834 }
835
836 // C++ [temp.arg]p1:
837 // [...] The type and form of each template-argument specified in
838 // a template-id shall match the type and form specified for the
839 // corresponding parameter declared by the template in its
840 // template-parameter-list.
841 unsigned ArgIdx = 0;
842 for (TemplateParameterList::iterator Param = Params->begin(),
843 ParamEnd = Params->end();
844 Param != ParamEnd; ++Param, ++ArgIdx) {
845 // Decode the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000846 TemplateArgument Arg;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000847 if (ArgIdx >= NumArgs) {
Douglas Gregorad964b32009-02-17 01:05:43 +0000848 // Retrieve the default template argument from the template
849 // parameter.
850 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
851 if (!TTP->hasDefaultArgument())
852 break;
853
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000854 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor74296542009-02-27 19:31:52 +0000855
856 // If the argument type is dependent, instantiate it now based
857 // on the previously-computed template arguments.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000858 if (ArgType->isDependentType()) {
859 InstantiatingTemplate Inst(*this, TemplateLoc,
860 Template, &Converted[0],
861 Converted.size(),
862 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor74296542009-02-27 19:31:52 +0000863 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
864 TTP->getDefaultArgumentLoc(),
865 TTP->getDeclName());
Douglas Gregor56d25a72009-03-10 20:44:00 +0000866 }
Douglas Gregor74296542009-02-27 19:31:52 +0000867
868 if (ArgType.isNull())
Douglas Gregorf57dcd02009-02-28 00:25:32 +0000869 return true;
Douglas Gregor74296542009-02-27 19:31:52 +0000870
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000871 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregorad964b32009-02-17 01:05:43 +0000872 } else if (NonTypeTemplateParmDecl *NTTP
873 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
874 if (!NTTP->hasDefaultArgument())
875 break;
876
Douglas Gregored3a3982009-03-03 04:44:36 +0000877 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000878 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000879 } else {
880 TemplateTemplateParmDecl *TempParm
881 = cast<TemplateTemplateParmDecl>(*Param);
882
883 if (!TempParm->hasDefaultArgument())
884 break;
885
Douglas Gregored3a3982009-03-03 04:44:36 +0000886 // FIXME: Instantiate default argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000887 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregorad964b32009-02-17 01:05:43 +0000888 }
889 } else {
890 // Retrieve the template argument produced by the user.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000891 Arg = TemplateArgs[ArgIdx];
Douglas Gregorad964b32009-02-17 01:05:43 +0000892 }
893
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000894
895 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
896 // Check template type parameters.
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000897 if (Arg.getKind() == TemplateArgument::Type) {
898 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000899 Invalid = true;
Douglas Gregorad964b32009-02-17 01:05:43 +0000900
901 // Add the converted template type argument.
902 Converted.push_back(
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000903 TemplateArgument(Arg.getLocation(),
904 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000905 continue;
906 }
907
908 // C++ [temp.arg.type]p1:
909 // A template-argument for a template-parameter which is a
910 // type shall be a type-id.
911
912 // We have a template type parameter but the template argument
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000913 // is not a type.
914 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor341ac792009-02-10 00:53:15 +0000915 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000916 Invalid = true;
917 } else if (NonTypeTemplateParmDecl *NTTP
918 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
919 // Check non-type template parameters.
Douglas Gregored3a3982009-03-03 04:44:36 +0000920
921 // Instantiate the type of the non-type template parameter with
922 // the template arguments we've seen thus far.
923 QualType NTTPType = NTTP->getType();
924 if (NTTPType->isDependentType()) {
925 // Instantiate the type of the non-type template parameter.
Douglas Gregor56d25a72009-03-10 20:44:00 +0000926 InstantiatingTemplate Inst(*this, TemplateLoc,
927 Template, &Converted[0],
928 Converted.size(),
929 SourceRange(TemplateLoc, RAngleLoc));
930
Douglas Gregored3a3982009-03-03 04:44:36 +0000931 NTTPType = InstantiateType(NTTPType,
932 &Converted[0], Converted.size(),
933 NTTP->getLocation(),
934 NTTP->getDeclName());
935 // If that worked, check the non-type template parameter type
936 // for validity.
937 if (!NTTPType.isNull())
938 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
939 NTTP->getLocation());
940
941 if (NTTPType.isNull()) {
942 Invalid = true;
943 break;
944 }
945 }
946
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000947 switch (Arg.getKind()) {
948 case TemplateArgument::Expression: {
949 Expr *E = Arg.getAsExpr();
950 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000951 Invalid = true;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000952 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000953 }
954
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000955 case TemplateArgument::Declaration:
956 case TemplateArgument::Integral:
957 // We've already checked this template argument, so just copy
958 // it to the list of converted arguments.
959 Converted.push_back(Arg);
960 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000961
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000962 case TemplateArgument::Type:
963 // We have a non-type template parameter but the template
964 // argument is a type.
965
966 // C++ [temp.arg]p2:
967 // In a template-argument, an ambiguity between a type-id and
968 // an expression is resolved to a type-id, regardless of the
969 // form of the corresponding template-parameter.
970 //
971 // We warn specifically about this case, since it can be rather
972 // confusing for users.
973 if (Arg.getAsType()->isFunctionType())
974 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
975 << Arg.getAsType();
976 else
977 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
978 Diag((*Param)->getLocation(), diag::note_template_param_here);
979 Invalid = true;
980 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000981 } else {
982 // Check template template parameters.
983 TemplateTemplateParmDecl *TempParm
984 = cast<TemplateTemplateParmDecl>(*Param);
985
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000986 switch (Arg.getKind()) {
987 case TemplateArgument::Expression: {
988 Expr *ArgExpr = Arg.getAsExpr();
989 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
990 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
991 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
992 Invalid = true;
993
994 // Add the converted template argument.
995 // FIXME: Need the "canonical" template declaration!
996 Converted.push_back(
997 TemplateArgument(Arg.getLocation(),
998 cast<DeclRefExpr>(ArgExpr)->getDecl()));
999 continue;
1000 }
1001 }
1002 // fall through
1003
1004 case TemplateArgument::Type: {
1005 // We have a template template parameter but the template
1006 // argument does not refer to a template.
1007 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1008 Invalid = true;
1009 break;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001010 }
1011
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001012 case TemplateArgument::Declaration:
1013 // We've already checked this template argument, so just copy
1014 // it to the list of converted arguments.
1015 Converted.push_back(Arg);
1016 break;
1017
1018 case TemplateArgument::Integral:
1019 assert(false && "Integral argument with template template parameter");
1020 break;
1021 }
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001022 }
1023 }
1024
1025 return Invalid;
1026}
1027
1028/// \brief Check a template argument against its corresponding
1029/// template type parameter.
1030///
1031/// This routine implements the semantics of C++ [temp.arg.type]. It
1032/// returns true if an error occurred, and false otherwise.
1033bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1034 QualType Arg, SourceLocation ArgLoc) {
1035 // C++ [temp.arg.type]p2:
1036 // A local type, a type with no linkage, an unnamed type or a type
1037 // compounded from any of these types shall not be used as a
1038 // template-argument for a template type-parameter.
1039 //
1040 // FIXME: Perform the recursive and no-linkage type checks.
1041 const TagType *Tag = 0;
1042 if (const EnumType *EnumT = Arg->getAsEnumType())
1043 Tag = EnumT;
1044 else if (const RecordType *RecordT = Arg->getAsRecordType())
1045 Tag = RecordT;
1046 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1047 return Diag(ArgLoc, diag::err_template_arg_local_type)
1048 << QualType(Tag, 0);
Douglas Gregor04385782009-03-10 18:33:27 +00001049 else if (Tag && !Tag->getDecl()->getDeclName() &&
1050 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001051 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1052 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1053 return true;
1054 }
1055
1056 return false;
1057}
1058
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001059/// \brief Checks whether the given template argument is the address
1060/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001061bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1062 NamedDecl *&Entity) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001063 bool Invalid = false;
1064
1065 // See through any implicit casts we added to fix the type.
1066 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1067 Arg = Cast->getSubExpr();
1068
1069 // C++ [temp.arg.nontype]p1:
1070 //
1071 // A template-argument for a non-type, non-template
1072 // template-parameter shall be one of: [...]
1073 //
1074 // -- the address of an object or function with external
1075 // linkage, including function templates and function
1076 // template-ids but excluding non-static class members,
1077 // expressed as & id-expression where the & is optional if
1078 // the name refers to a function or array, or if the
1079 // corresponding template-parameter is a reference; or
1080 DeclRefExpr *DRE = 0;
1081
1082 // Ignore (and complain about) any excess parentheses.
1083 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1084 if (!Invalid) {
1085 Diag(Arg->getSourceRange().getBegin(),
1086 diag::err_template_arg_extra_parens)
1087 << Arg->getSourceRange();
1088 Invalid = true;
1089 }
1090
1091 Arg = Parens->getSubExpr();
1092 }
1093
1094 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1095 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1096 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1097 } else
1098 DRE = dyn_cast<DeclRefExpr>(Arg);
1099
1100 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1101 return Diag(Arg->getSourceRange().getBegin(),
1102 diag::err_template_arg_not_object_or_func_form)
1103 << Arg->getSourceRange();
1104
1105 // Cannot refer to non-static data members
1106 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1107 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1108 << Field << Arg->getSourceRange();
1109
1110 // Cannot refer to non-static member functions
1111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1112 if (!Method->isStatic())
1113 return Diag(Arg->getSourceRange().getBegin(),
1114 diag::err_template_arg_method)
1115 << Method << Arg->getSourceRange();
1116
1117 // Functions must have external linkage.
1118 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1119 if (Func->getStorageClass() == FunctionDecl::Static) {
1120 Diag(Arg->getSourceRange().getBegin(),
1121 diag::err_template_arg_function_not_extern)
1122 << Func << Arg->getSourceRange();
1123 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1124 << true;
1125 return true;
1126 }
1127
1128 // Okay: we've named a function with external linkage.
Douglas Gregorad964b32009-02-17 01:05:43 +00001129 Entity = Func;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001130 return Invalid;
1131 }
1132
1133 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1134 if (!Var->hasGlobalStorage()) {
1135 Diag(Arg->getSourceRange().getBegin(),
1136 diag::err_template_arg_object_not_extern)
1137 << Var << Arg->getSourceRange();
1138 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1139 << true;
1140 return true;
1141 }
1142
1143 // Okay: we've named an object with external linkage
Douglas Gregorad964b32009-02-17 01:05:43 +00001144 Entity = Var;
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001145 return Invalid;
1146 }
1147
1148 // We found something else, but we don't know specifically what it is.
1149 Diag(Arg->getSourceRange().getBegin(),
1150 diag::err_template_arg_not_object_or_func)
1151 << Arg->getSourceRange();
1152 Diag(DRE->getDecl()->getLocation(),
1153 diag::note_template_arg_refers_here);
1154 return true;
1155}
1156
1157/// \brief Checks whether the given template argument is a pointer to
1158/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorad964b32009-02-17 01:05:43 +00001159bool
1160Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001161 bool Invalid = false;
1162
1163 // See through any implicit casts we added to fix the type.
1164 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1165 Arg = Cast->getSubExpr();
1166
1167 // C++ [temp.arg.nontype]p1:
1168 //
1169 // A template-argument for a non-type, non-template
1170 // template-parameter shall be one of: [...]
1171 //
1172 // -- a pointer to member expressed as described in 5.3.1.
1173 QualifiedDeclRefExpr *DRE = 0;
1174
1175 // Ignore (and complain about) any excess parentheses.
1176 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1177 if (!Invalid) {
1178 Diag(Arg->getSourceRange().getBegin(),
1179 diag::err_template_arg_extra_parens)
1180 << Arg->getSourceRange();
1181 Invalid = true;
1182 }
1183
1184 Arg = Parens->getSubExpr();
1185 }
1186
1187 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1188 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1189 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1190
1191 if (!DRE)
1192 return Diag(Arg->getSourceRange().getBegin(),
1193 diag::err_template_arg_not_pointer_to_member_form)
1194 << Arg->getSourceRange();
1195
1196 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1197 assert((isa<FieldDecl>(DRE->getDecl()) ||
1198 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1199 "Only non-static member pointers can make it here");
1200
1201 // Okay: this is the address of a non-static member, and therefore
1202 // a member pointer constant.
Douglas Gregorad964b32009-02-17 01:05:43 +00001203 Member = DRE->getDecl();
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001204 return Invalid;
1205 }
1206
1207 // We found something else, but we don't know specifically what it is.
1208 Diag(Arg->getSourceRange().getBegin(),
1209 diag::err_template_arg_not_pointer_to_member_form)
1210 << Arg->getSourceRange();
1211 Diag(DRE->getDecl()->getLocation(),
1212 diag::note_template_arg_refers_here);
1213 return true;
1214}
1215
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001216/// \brief Check a template argument against its corresponding
1217/// non-type template parameter.
1218///
Douglas Gregored3a3982009-03-03 04:44:36 +00001219/// This routine implements the semantics of C++ [temp.arg.nontype].
1220/// It returns true if an error occurred, and false otherwise. \p
1221/// InstantiatedParamType is the type of the non-type template
1222/// parameter after it has been instantiated.
Douglas Gregorad964b32009-02-17 01:05:43 +00001223///
1224/// If Converted is non-NULL and no errors occur, the value
1225/// of this argument will be added to the end of the Converted vector.
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001226bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregored3a3982009-03-03 04:44:36 +00001227 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregorad964b32009-02-17 01:05:43 +00001228 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001229 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1230
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001231 // If either the parameter has a dependent type or the argument is
1232 // type-dependent, there's nothing we can check now.
Douglas Gregorad964b32009-02-17 01:05:43 +00001233 // FIXME: Add template argument to Converted!
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001234 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1235 // FIXME: Produce a cloned, canonical expression?
1236 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001237 return false;
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001238 }
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001239
1240 // C++ [temp.arg.nontype]p5:
1241 // The following conversions are performed on each expression used
1242 // as a non-type template-argument. If a non-type
1243 // template-argument cannot be converted to the type of the
1244 // corresponding template-parameter then the program is
1245 // ill-formed.
1246 //
1247 // -- for a non-type template-parameter of integral or
1248 // enumeration type, integral promotions (4.5) and integral
1249 // conversions (4.7) are applied.
Douglas Gregored3a3982009-03-03 04:44:36 +00001250 QualType ParamType = InstantiatedParamType;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001251 QualType ArgType = Arg->getType();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001252 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001253 // C++ [temp.arg.nontype]p1:
1254 // A template-argument for a non-type, non-template
1255 // template-parameter shall be one of:
1256 //
1257 // -- an integral constant-expression of integral or enumeration
1258 // type; or
1259 // -- the name of a non-type template-parameter; or
1260 SourceLocation NonConstantLoc;
Douglas Gregorad964b32009-02-17 01:05:43 +00001261 llvm::APSInt Value;
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001262 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1263 Diag(Arg->getSourceRange().getBegin(),
1264 diag::err_template_arg_not_integral_or_enumeral)
1265 << ArgType << Arg->getSourceRange();
1266 Diag(Param->getLocation(), diag::note_template_param_here);
1267 return true;
1268 } else if (!Arg->isValueDependent() &&
Douglas Gregorad964b32009-02-17 01:05:43 +00001269 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001270 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1271 << ArgType << Arg->getSourceRange();
1272 return true;
1273 }
1274
1275 // FIXME: We need some way to more easily get the unqualified form
1276 // of the types without going all the way to the
1277 // canonical type.
1278 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1279 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1280 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1281 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1282
1283 // Try to convert the argument to the parameter's type.
1284 if (ParamType == ArgType) {
1285 // Okay: no conversion necessary
1286 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1287 !ParamType->isEnumeralType()) {
1288 // This is an integral promotion or conversion.
1289 ImpCastExprToType(Arg, ParamType);
1290 } else {
1291 // We can't perform this conversion.
1292 Diag(Arg->getSourceRange().getBegin(),
1293 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001294 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001295 Diag(Param->getLocation(), diag::note_template_param_here);
1296 return true;
1297 }
1298
Douglas Gregorafc86942009-03-14 00:20:21 +00001299 QualType IntegerType = Context.getCanonicalType(ParamType);
1300 if (const EnumType *Enum = IntegerType->getAsEnumType())
1301 IntegerType = Enum->getDecl()->getIntegerType();
1302
1303 if (!Arg->isValueDependent()) {
1304 // Check that an unsigned parameter does not receive a negative
1305 // value.
1306 if (IntegerType->isUnsignedIntegerType()
1307 && (Value.isSigned() && Value.isNegative())) {
1308 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1309 << Value.toString(10) << Param->getType()
1310 << Arg->getSourceRange();
1311 Diag(Param->getLocation(), diag::note_template_param_here);
1312 return true;
1313 }
1314
1315 // Check that we don't overflow the template parameter type.
1316 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1317 if (Value.getActiveBits() > AllowedBits) {
1318 Diag(Arg->getSourceRange().getBegin(),
1319 diag::err_template_arg_too_large)
1320 << Value.toString(10) << Param->getType()
1321 << Arg->getSourceRange();
1322 Diag(Param->getLocation(), diag::note_template_param_here);
1323 return true;
1324 }
1325
1326 if (Value.getBitWidth() != AllowedBits)
1327 Value.extOrTrunc(AllowedBits);
1328 Value.setIsSigned(IntegerType->isSignedIntegerType());
1329 }
Douglas Gregorad964b32009-02-17 01:05:43 +00001330
1331 if (Converted) {
1332 // Add the value of this argument to the list of converted
1333 // arguments. We use the bitwidth and signedness of the template
1334 // parameter.
Douglas Gregor396f1142009-03-13 21:01:28 +00001335 if (Arg->isValueDependent()) {
1336 // The argument is value-dependent. Create a new
1337 // TemplateArgument with the converted expression.
1338 Converted->push_back(TemplateArgument(Arg));
1339 return false;
1340 }
1341
Douglas Gregor544cda62009-03-14 00:03:48 +00001342 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregor63f5d602009-03-12 22:20:26 +00001343 Context.getCanonicalType(IntegerType)));
Douglas Gregorad964b32009-02-17 01:05:43 +00001344 }
1345
Douglas Gregor79e5c9c2009-02-10 23:36:10 +00001346 return false;
1347 }
Douglas Gregor2eedd992009-02-11 00:19:33 +00001348
Douglas Gregor3f411962009-02-11 01:18:59 +00001349 // Handle pointer-to-function, reference-to-function, and
1350 // pointer-to-member-function all in (roughly) the same way.
1351 if (// -- For a non-type template-parameter of type pointer to
1352 // function, only the function-to-pointer conversion (4.3) is
1353 // applied. If the template-argument represents a set of
1354 // overloaded functions (or a pointer to such), the matching
1355 // function is selected from the set (13.4).
1356 (ParamType->isPointerType() &&
1357 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1358 // -- For a non-type template-parameter of type reference to
1359 // function, no conversions apply. If the template-argument
1360 // represents a set of overloaded functions, the matching
1361 // function is selected from the set (13.4).
1362 (ParamType->isReferenceType() &&
1363 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1364 // -- For a non-type template-parameter of type pointer to
1365 // member function, no conversions apply. If the
1366 // template-argument represents a set of overloaded member
1367 // functions, the matching member function is selected from
1368 // the set (13.4).
1369 (ParamType->isMemberPointerType() &&
1370 ParamType->getAsMemberPointerType()->getPointeeType()
1371 ->isFunctionType())) {
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001372 if (Context.hasSameUnqualifiedType(ArgType,
1373 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001374 // We don't have to do anything: the types already match.
Douglas Gregor3f411962009-02-11 01:18:59 +00001375 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001376 ArgType = Context.getPointerType(ArgType);
1377 ImpCastExprToType(Arg, ArgType);
1378 } else if (FunctionDecl *Fn
1379 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001380 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1381 return true;
1382
Douglas Gregor2eedd992009-02-11 00:19:33 +00001383 FixOverloadedFunctionReference(Arg, Fn);
1384 ArgType = Arg->getType();
Douglas Gregor3f411962009-02-11 01:18:59 +00001385 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001386 ArgType = Context.getPointerType(Arg->getType());
1387 ImpCastExprToType(Arg, ArgType);
1388 }
1389 }
1390
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001391 if (!Context.hasSameUnqualifiedType(ArgType,
1392 ParamType.getNonReferenceType())) {
Douglas Gregor2eedd992009-02-11 00:19:33 +00001393 // We can't perform this conversion.
1394 Diag(Arg->getSourceRange().getBegin(),
1395 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001396 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor2eedd992009-02-11 00:19:33 +00001397 Diag(Param->getLocation(), diag::note_template_param_here);
1398 return true;
1399 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001400
Douglas Gregorad964b32009-02-17 01:05:43 +00001401 if (ParamType->isMemberPointerType()) {
1402 NamedDecl *Member = 0;
1403 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1404 return true;
1405
1406 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001407 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001408
1409 return false;
1410 }
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001411
Douglas Gregorad964b32009-02-17 01:05:43 +00001412 NamedDecl *Entity = 0;
1413 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1414 return true;
1415
1416 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001417 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001418 return false;
Douglas Gregor2eedd992009-02-11 00:19:33 +00001419 }
1420
Chris Lattner320dff22009-02-20 21:37:53 +00001421 if (ParamType->isPointerType()) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001422 // -- for a non-type template-parameter of type pointer to
1423 // object, qualification conversions (4.4) and the
1424 // array-to-pointer conversion (4.2) are applied.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001425 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001426 "Only object pointers allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001427
Douglas Gregor3f411962009-02-11 01:18:59 +00001428 if (ArgType->isArrayType()) {
1429 ArgType = Context.getArrayDecayedType(ArgType);
1430 ImpCastExprToType(Arg, ArgType);
Douglas Gregord8c8c092009-02-11 00:44:29 +00001431 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001432
1433 if (IsQualificationConversion(ArgType, ParamType)) {
1434 ArgType = ParamType;
1435 ImpCastExprToType(Arg, ParamType);
1436 }
1437
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001438 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001439 // We can't perform this conversion.
1440 Diag(Arg->getSourceRange().getBegin(),
1441 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001442 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3f411962009-02-11 01:18:59 +00001443 Diag(Param->getLocation(), diag::note_template_param_here);
1444 return true;
1445 }
1446
Douglas Gregorad964b32009-02-17 01:05:43 +00001447 NamedDecl *Entity = 0;
1448 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1449 return true;
1450
1451 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001452 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001453
1454 return false;
Douglas Gregord8c8c092009-02-11 00:44:29 +00001455 }
Douglas Gregor3f411962009-02-11 01:18:59 +00001456
1457 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1458 // -- For a non-type template-parameter of type reference to
1459 // object, no conversions apply. The type referred to by the
1460 // reference may be more cv-qualified than the (otherwise
1461 // identical) type of the template-argument. The
1462 // template-parameter is bound directly to the
1463 // template-argument, which must be an lvalue.
Douglas Gregor26ea1222009-03-24 20:32:41 +00001464 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor3f411962009-02-11 01:18:59 +00001465 "Only object references allowed here");
Douglas Gregord8c8c092009-02-11 00:44:29 +00001466
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001467 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregor3f411962009-02-11 01:18:59 +00001468 Diag(Arg->getSourceRange().getBegin(),
1469 diag::err_template_arg_no_ref_bind)
Douglas Gregored3a3982009-03-03 04:44:36 +00001470 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001471 << Arg->getSourceRange();
1472 Diag(Param->getLocation(), diag::note_template_param_here);
1473 return true;
1474 }
1475
1476 unsigned ParamQuals
1477 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1478 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1479
1480 if ((ParamQuals | ArgQuals) != ParamQuals) {
1481 Diag(Arg->getSourceRange().getBegin(),
1482 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregored3a3982009-03-03 04:44:36 +00001483 << InstantiatedParamType << Arg->getType()
Douglas Gregor3f411962009-02-11 01:18:59 +00001484 << Arg->getSourceRange();
1485 Diag(Param->getLocation(), diag::note_template_param_here);
1486 return true;
1487 }
1488
Douglas Gregorad964b32009-02-17 01:05:43 +00001489 NamedDecl *Entity = 0;
1490 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1491 return true;
1492
1493 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001494 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregorad964b32009-02-17 01:05:43 +00001495
1496 return false;
Douglas Gregor3f411962009-02-11 01:18:59 +00001497 }
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001498
1499 // -- For a non-type template-parameter of type pointer to data
1500 // member, qualification conversions (4.4) are applied.
1501 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1502
Douglas Gregor0ea4e302009-02-11 18:22:40 +00001503 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001504 // Types match exactly: nothing more to do here.
1505 } else if (IsQualificationConversion(ArgType, ParamType)) {
1506 ImpCastExprToType(Arg, ParamType);
1507 } else {
1508 // We can't perform this conversion.
1509 Diag(Arg->getSourceRange().getBegin(),
1510 diag::err_template_arg_not_convertible)
Douglas Gregored3a3982009-03-03 04:44:36 +00001511 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3628e1b2009-02-11 16:16:59 +00001512 Diag(Param->getLocation(), diag::note_template_param_here);
1513 return true;
1514 }
1515
Douglas Gregorad964b32009-02-17 01:05:43 +00001516 NamedDecl *Member = 0;
1517 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1518 return true;
1519
1520 if (Converted)
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001521 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregorad964b32009-02-17 01:05:43 +00001522
1523 return false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001524}
1525
1526/// \brief Check a template argument against its corresponding
1527/// template template parameter.
1528///
1529/// This routine implements the semantics of C++ [temp.arg.template].
1530/// It returns true if an error occurred, and false otherwise.
1531bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1532 DeclRefExpr *Arg) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001533 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1534 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1535
1536 // C++ [temp.arg.template]p1:
1537 // A template-argument for a template template-parameter shall be
1538 // the name of a class template, expressed as id-expression. Only
1539 // primary class templates are considered when matching the
1540 // template template argument with the corresponding parameter;
1541 // partial specializations are not considered even if their
1542 // parameter lists match that of the template template parameter.
1543 if (!isa<ClassTemplateDecl>(Template)) {
1544 assert(isa<FunctionTemplateDecl>(Template) &&
1545 "Only function templates are possible here");
Douglas Gregor6b3a0ba2009-02-11 19:52:55 +00001546 Diag(Arg->getSourceRange().getBegin(),
1547 diag::note_template_arg_refers_here_func)
Douglas Gregore8e367f2009-02-10 00:24:35 +00001548 << Template;
1549 }
1550
1551 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1552 Param->getTemplateParameters(),
1553 true, true,
1554 Arg->getSourceRange().getBegin());
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001555}
1556
Douglas Gregord406b032009-02-06 22:42:48 +00001557/// \brief Determine whether the given template parameter lists are
1558/// equivalent.
1559///
1560/// \param New The new template parameter list, typically written in the
1561/// source code as part of a new template declaration.
1562///
1563/// \param Old The old template parameter list, typically found via
1564/// name lookup of the template declared with this template parameter
1565/// list.
1566///
1567/// \param Complain If true, this routine will produce a diagnostic if
1568/// the template parameter lists are not equivalent.
1569///
Douglas Gregore8e367f2009-02-10 00:24:35 +00001570/// \param IsTemplateTemplateParm If true, this routine is being
1571/// called to compare the template parameter lists of a template
1572/// template parameter.
1573///
1574/// \param TemplateArgLoc If this source location is valid, then we
1575/// are actually checking the template parameter list of a template
1576/// argument (New) against the template parameter list of its
1577/// corresponding template template parameter (Old). We produce
1578/// slightly different diagnostics in this scenario.
1579///
Douglas Gregord406b032009-02-06 22:42:48 +00001580/// \returns True if the template parameter lists are equal, false
1581/// otherwise.
1582bool
1583Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1584 TemplateParameterList *Old,
1585 bool Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001586 bool IsTemplateTemplateParm,
1587 SourceLocation TemplateArgLoc) {
Douglas Gregord406b032009-02-06 22:42:48 +00001588 if (Old->size() != New->size()) {
1589 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001590 unsigned NextDiag = diag::err_template_param_list_different_arity;
1591 if (TemplateArgLoc.isValid()) {
1592 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1593 NextDiag = diag::note_template_param_list_different_arity;
1594 }
1595 Diag(New->getTemplateLoc(), NextDiag)
1596 << (New->size() > Old->size())
1597 << IsTemplateTemplateParm
1598 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregord406b032009-02-06 22:42:48 +00001599 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1600 << IsTemplateTemplateParm
1601 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1602 }
1603
1604 return false;
1605 }
1606
1607 for (TemplateParameterList::iterator OldParm = Old->begin(),
1608 OldParmEnd = Old->end(), NewParm = New->begin();
1609 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1610 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001611 unsigned NextDiag = diag::err_template_param_different_kind;
1612 if (TemplateArgLoc.isValid()) {
1613 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1614 NextDiag = diag::note_template_param_different_kind;
1615 }
1616 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001617 << IsTemplateTemplateParm;
1618 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1619 << IsTemplateTemplateParm;
1620 return false;
1621 }
1622
1623 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1624 // Okay; all template type parameters are equivalent (since we
Douglas Gregore8e367f2009-02-10 00:24:35 +00001625 // know we're at the same index).
1626#if 0
1627 // FIXME: Enable this code in debug mode *after* we properly go
1628 // through and "instantiate" the template parameter lists of
1629 // template template parameters. It's only after this
1630 // instantiation that (1) any dependent types within the
1631 // template parameter list of the template template parameter
1632 // can be checked, and (2) the template type parameter depths
1633 // will match up.
Douglas Gregord406b032009-02-06 22:42:48 +00001634 QualType OldParmType
1635 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1636 QualType NewParmType
1637 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1638 assert(Context.getCanonicalType(OldParmType) ==
1639 Context.getCanonicalType(NewParmType) &&
1640 "type parameter mismatch?");
1641#endif
1642 } else if (NonTypeTemplateParmDecl *OldNTTP
1643 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1644 // The types of non-type template parameters must agree.
1645 NonTypeTemplateParmDecl *NewNTTP
1646 = cast<NonTypeTemplateParmDecl>(*NewParm);
1647 if (Context.getCanonicalType(OldNTTP->getType()) !=
1648 Context.getCanonicalType(NewNTTP->getType())) {
1649 if (Complain) {
Douglas Gregore8e367f2009-02-10 00:24:35 +00001650 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1651 if (TemplateArgLoc.isValid()) {
1652 Diag(TemplateArgLoc,
1653 diag::err_template_arg_template_params_mismatch);
1654 NextDiag = diag::note_template_nontype_parm_different_type;
1655 }
1656 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregord406b032009-02-06 22:42:48 +00001657 << NewNTTP->getType()
1658 << IsTemplateTemplateParm;
1659 Diag(OldNTTP->getLocation(),
1660 diag::note_template_nontype_parm_prev_declaration)
1661 << OldNTTP->getType();
1662 }
1663 return false;
1664 }
1665 } else {
1666 // The template parameter lists of template template
1667 // parameters must agree.
1668 // FIXME: Could we perform a faster "type" comparison here?
1669 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1670 "Only template template parameters handled here");
1671 TemplateTemplateParmDecl *OldTTP
1672 = cast<TemplateTemplateParmDecl>(*OldParm);
1673 TemplateTemplateParmDecl *NewTTP
1674 = cast<TemplateTemplateParmDecl>(*NewParm);
1675 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1676 OldTTP->getTemplateParameters(),
1677 Complain,
Douglas Gregore8e367f2009-02-10 00:24:35 +00001678 /*IsTemplateTemplateParm=*/true,
1679 TemplateArgLoc))
Douglas Gregord406b032009-02-06 22:42:48 +00001680 return false;
1681 }
1682 }
1683
1684 return true;
1685}
1686
1687/// \brief Check whether a template can be declared within this scope.
1688///
1689/// If the template declaration is valid in this scope, returns
1690/// false. Otherwise, issues a diagnostic and returns true.
1691bool
1692Sema::CheckTemplateDeclScope(Scope *S,
1693 MultiTemplateParamsArg &TemplateParameterLists) {
1694 assert(TemplateParameterLists.size() > 0 && "Not a template");
1695
1696 // Find the nearest enclosing declaration scope.
1697 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1698 (S->getFlags() & Scope::TemplateParamScope) != 0)
1699 S = S->getParent();
1700
1701 TemplateParameterList *TemplateParams =
1702 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1703 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1704 SourceRange TemplateRange
1705 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1706
1707 // C++ [temp]p2:
1708 // A template-declaration can appear only as a namespace scope or
1709 // class scope declaration.
1710 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1711 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1712 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1713 return Diag(TemplateLoc, diag::err_template_linkage)
1714 << TemplateRange;
1715
1716 Ctx = Ctx->getParent();
1717 }
1718
1719 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1720 return false;
1721
1722 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1723 << TemplateRange;
1724}
Douglas Gregora08b6c72009-02-17 23:15:12 +00001725
Douglas Gregor0d93f692009-02-25 22:02:03 +00001726/// \brief Check whether a class template specialization in the
1727/// current context is well-formed.
1728///
1729/// This routine determines whether a class template specialization
1730/// can be declared in the current context (C++ [temp.expl.spec]p2)
1731/// and emits appropriate diagnostics if there was an error. It
1732/// returns true if there was an error that we cannot recover from,
1733/// and false otherwise.
1734bool
1735Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1736 ClassTemplateSpecializationDecl *PrevDecl,
1737 SourceLocation TemplateNameLoc,
1738 SourceRange ScopeSpecifierRange) {
1739 // C++ [temp.expl.spec]p2:
1740 // An explicit specialization shall be declared in the namespace
1741 // of which the template is a member, or, for member templates, in
1742 // the namespace of which the enclosing class or enclosing class
1743 // template is a member. An explicit specialization of a member
1744 // function, member class or static data member of a class
1745 // template shall be declared in the namespace of which the class
1746 // template is a member. Such a declaration may also be a
1747 // definition. If the declaration is not a definition, the
1748 // specialization may be defined later in the name- space in which
1749 // the explicit specialization was declared, or in a namespace
1750 // that encloses the one in which the explicit specialization was
1751 // declared.
1752 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1753 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1754 << ClassTemplate;
1755 return true;
1756 }
1757
1758 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1759 DeclContext *TemplateContext
1760 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1761 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1762 // There is no prior declaration of this entity, so this
1763 // specialization must be in the same context as the template
1764 // itself.
1765 if (DC != TemplateContext) {
1766 if (isa<TranslationUnitDecl>(TemplateContext))
1767 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1768 << ClassTemplate << ScopeSpecifierRange;
1769 else if (isa<NamespaceDecl>(TemplateContext))
1770 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1771 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1772 << ScopeSpecifierRange;
1773
1774 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1775 }
1776
1777 return false;
1778 }
1779
1780 // We have a previous declaration of this entity. Make sure that
1781 // this redeclaration (or definition) occurs in an enclosing namespace.
1782 if (!CurContext->Encloses(TemplateContext)) {
1783 if (isa<TranslationUnitDecl>(TemplateContext))
1784 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1785 << ClassTemplate << ScopeSpecifierRange;
1786 else if (isa<NamespaceDecl>(TemplateContext))
1787 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1788 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1789 << ScopeSpecifierRange;
1790
1791 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1792 }
1793
1794 return false;
1795}
1796
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001797Sema::DeclResult
Douglas Gregora08b6c72009-02-17 23:15:12 +00001798Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1799 SourceLocation KWLoc,
1800 const CXXScopeSpec &SS,
1801 DeclTy *TemplateD,
1802 SourceLocation TemplateNameLoc,
1803 SourceLocation LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001804 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora08b6c72009-02-17 23:15:12 +00001805 SourceLocation *TemplateArgLocs,
1806 SourceLocation RAngleLoc,
1807 AttributeList *Attr,
1808 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregora08b6c72009-02-17 23:15:12 +00001809 // Find the class template we're specializing
1810 ClassTemplateDecl *ClassTemplate
1811 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1812 if (!ClassTemplate)
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001813 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001814
Douglas Gregor0d93f692009-02-25 22:02:03 +00001815 // Check the validity of the template headers that introduce this
1816 // template.
Douglas Gregor50113ca2009-02-25 22:18:32 +00001817 // FIXME: Once we have member templates, we'll need to check
1818 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1819 // template<> headers.
Douglas Gregor3bb30002009-02-26 21:00:50 +00001820 if (TemplateParameterLists.size() == 0)
1821 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor61be3602009-02-27 17:53:17 +00001822 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor3bb30002009-02-26 21:00:50 +00001823 else {
Douglas Gregor0d93f692009-02-25 22:02:03 +00001824 TemplateParameterList *TemplateParams
1825 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001826 if (TemplateParameterLists.size() > 1)
1827 return Diag(TemplateParams->getTemplateLoc(),
1828 diag::err_template_spec_extra_headers);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001829
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001830 if (TemplateParams->size() > 0)
Douglas Gregor0d93f692009-02-25 22:02:03 +00001831 // FIXME: No support for class template partial specialization.
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001832 return Diag(TemplateParams->getTemplateLoc(),
1833 diag::unsup_template_partial_spec);
Douglas Gregor0d93f692009-02-25 22:02:03 +00001834 }
1835
Douglas Gregora08b6c72009-02-17 23:15:12 +00001836 // Check that the specialization uses the same tag kind as the
1837 // original template.
1838 TagDecl::TagKind Kind;
1839 switch (TagSpec) {
1840 default: assert(0 && "Unknown tag type!");
1841 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1842 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1843 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1844 }
1845 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1846 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1847 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1848 diag::note_previous_use);
1849 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1850 }
1851
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001852 // Translate the parser's template argument list in our AST format.
1853 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1854 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1855
Douglas Gregora08b6c72009-02-17 23:15:12 +00001856 // Check that the template argument list is well-formed for this
1857 // template.
1858 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1859 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001860 &TemplateArgs[0], TemplateArgs.size(),
1861 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001862 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001863
1864 assert((ConvertedTemplateArgs.size() ==
1865 ClassTemplate->getTemplateParameters()->size()) &&
1866 "Converted template argument list is too short!");
1867
1868 // Find the class template specialization declaration that
1869 // corresponds to these arguments.
1870 llvm::FoldingSetNodeID ID;
1871 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1872 ConvertedTemplateArgs.size());
1873 void *InsertPos = 0;
1874 ClassTemplateSpecializationDecl *PrevDecl
1875 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1876
1877 ClassTemplateSpecializationDecl *Specialization = 0;
1878
Douglas Gregor0d93f692009-02-25 22:02:03 +00001879 // Check whether we can declare a class template specialization in
1880 // the current scope.
1881 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1882 TemplateNameLoc,
1883 SS.getRange()))
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001884 return true;
Douglas Gregor0d93f692009-02-25 22:02:03 +00001885
Douglas Gregora08b6c72009-02-17 23:15:12 +00001886 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1887 // Since the only prior class template specialization with these
1888 // arguments was referenced but not declared, reuse that
1889 // declaration node as our own, updating its source location to
1890 // reflect our new declaration.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001891 Specialization = PrevDecl;
Douglas Gregor50113ca2009-02-25 22:18:32 +00001892 Specialization->setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +00001893 PrevDecl = 0;
1894 } else {
1895 // Create a new class template specialization declaration node for
1896 // this explicit specialization.
1897 Specialization
1898 = ClassTemplateSpecializationDecl::Create(Context,
1899 ClassTemplate->getDeclContext(),
1900 TemplateNameLoc,
1901 ClassTemplate,
1902 &ConvertedTemplateArgs[0],
1903 ConvertedTemplateArgs.size(),
1904 PrevDecl);
1905
1906 if (PrevDecl) {
1907 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1908 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1909 } else {
1910 ClassTemplate->getSpecializations().InsertNode(Specialization,
1911 InsertPos);
1912 }
1913 }
1914
1915 // Note that this is an explicit specialization.
1916 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1917
1918 // Check that this isn't a redefinition of this specialization.
1919 if (TK == TK_Definition) {
1920 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1921 // FIXME: Should also handle explicit specialization after
1922 // implicit instantiation with a special diagnostic.
1923 SourceRange Range(TemplateNameLoc, RAngleLoc);
1924 Diag(TemplateNameLoc, diag::err_redefinition)
1925 << Specialization << Range;
1926 Diag(Def->getLocation(), diag::note_previous_definition);
1927 Specialization->setInvalidDecl();
Douglas Gregorc5d6fa72009-03-25 00:13:59 +00001928 return true;
Douglas Gregora08b6c72009-02-17 23:15:12 +00001929 }
1930 }
1931
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001932 // Build the fully-sugared type for this class template
1933 // specialization as the user wrote in the specialization
1934 // itself. This means that we'll pretty-print the type retrieved
1935 // from the specialization's declaration the way that the user
1936 // actually wrote the specialization, rather than formatting the
1937 // name based on the "canonical" representation used to store the
1938 // template arguments in the specialization.
Douglas Gregor8c795a12009-03-19 00:39:20 +00001939 QualType WrittenTy
1940 = Context.getClassTemplateSpecializationType(ClassTemplate,
1941 &TemplateArgs[0],
1942 TemplateArgs.size(),
1943 Context.getTypeDeclType(Specialization));
1944 Specialization->setTypeAsWritten(getQualifiedNameType(SS, WrittenTy));
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001945 TemplateArgsIn.release();
Douglas Gregora08b6c72009-02-17 23:15:12 +00001946
Douglas Gregor50113ca2009-02-25 22:18:32 +00001947 // C++ [temp.expl.spec]p9:
1948 // A template explicit specialization is in the scope of the
1949 // namespace in which the template was defined.
1950 //
1951 // We actually implement this paragraph where we set the semantic
1952 // context (in the creation of the ClassTemplateSpecializationDecl),
1953 // but we also maintain the lexical context where the actual
1954 // definition occurs.
Douglas Gregora08b6c72009-02-17 23:15:12 +00001955 Specialization->setLexicalDeclContext(CurContext);
1956
1957 // We may be starting the definition of this specialization.
1958 if (TK == TK_Definition)
1959 Specialization->startDefinition();
1960
1961 // Add the specialization into its lexical context, so that it can
1962 // be seen when iterating through the list of declarations in that
1963 // context. However, specializations are not found by name lookup.
1964 CurContext->addDecl(Specialization);
1965 return Specialization;
1966}
Douglas Gregord3022602009-03-27 23:10:48 +00001967
1968Sema::TypeResult
1969Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
1970 const IdentifierInfo &II, SourceLocation IdLoc) {
1971 NestedNameSpecifier *NNS
1972 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1973 if (!NNS)
1974 return true;
1975
1976 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
1977 if (T.isNull())
1978 return 0;
1979
1980 return T.getAsOpaquePtr();
1981}
1982
1983/// \brief Build the type that describes a C++ typename specifier,
1984/// e.g., "typename T::type".
1985QualType
1986Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
1987 SourceRange Range) {
1988 if (NNS->isDependent()) // FIXME: member of the current instantiation!
1989 return Context.getTypenameType(NNS, &II);
1990
1991 CXXScopeSpec SS;
1992 SS.setScopeRep(NNS);
1993 SS.setRange(Range);
1994 if (RequireCompleteDeclContext(SS))
1995 return QualType();
1996
1997 DeclContext *Ctx = computeDeclContext(SS);
1998 assert(Ctx && "No declaration context?");
1999
2000 DeclarationName Name(&II);
2001 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2002 false);
2003 unsigned DiagID = 0;
2004 Decl *Referenced = 0;
2005 switch (Result.getKind()) {
2006 case LookupResult::NotFound:
2007 if (Ctx->isTranslationUnit())
2008 DiagID = diag::err_typename_nested_not_found_global;
2009 else
2010 DiagID = diag::err_typename_nested_not_found;
2011 break;
2012
2013 case LookupResult::Found:
2014 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2015 // We found a type. Build a QualifiedNameType, since the
2016 // typename-specifier was just sugar. FIXME: Tell
2017 // QualifiedNameType that it has a "typename" prefix.
2018 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2019 }
2020
2021 DiagID = diag::err_typename_nested_not_type;
2022 Referenced = Result.getAsDecl();
2023 break;
2024
2025 case LookupResult::FoundOverloaded:
2026 DiagID = diag::err_typename_nested_not_type;
2027 Referenced = *Result.begin();
2028 break;
2029
2030 case LookupResult::AmbiguousBaseSubobjectTypes:
2031 case LookupResult::AmbiguousBaseSubobjects:
2032 case LookupResult::AmbiguousReference:
2033 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2034 return QualType();
2035 }
2036
2037 // If we get here, it's because name lookup did not find a
2038 // type. Emit an appropriate diagnostic and return an error.
2039 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2040 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2041 else
2042 Diag(Range.getEnd(), DiagID) << Range << Name;
2043 if (Referenced)
2044 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2045 << Name;
2046 return QualType();
2047}