blob: b4e505e7c2fe99d214800463759047cef4325fbf [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00008//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00009
10//
11// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000012//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000013
14#include "Sema.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21
22using namespace clang;
23
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000024/// isTemplateName - Determines whether the identifier II is a
25/// template name in the current scope, and returns the template
26/// declaration if II names a template. An optional CXXScope can be
27/// passed to indicate the C++ scope in which the identifier will be
28/// found.
Douglas Gregor39a8de12009-02-25 19:37:18 +000029TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
30 DeclTy *&Template,
31 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000032 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000033
34 if (IIDecl) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000035 if (isa<TemplateDecl>(IIDecl)) {
36 Template = IIDecl;
37 if (isa<FunctionTemplateDecl>(IIDecl))
38 return TNK_Function_template;
39 else if (isa<ClassTemplateDecl>(IIDecl))
40 return TNK_Class_template;
41 else if (isa<TemplateTemplateParmDecl>(IIDecl))
42 return TNK_Template_template_parm;
43 else
44 assert(false && "Unknown TemplateDecl");
45 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000046
Douglas Gregor55f6b142009-02-09 18:46:07 +000047 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000049 if (FD->getType()->isDependentType()) {
50 Template = FD;
51 return TNK_Function_template;
52 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000053 } else if (OverloadedFunctionDecl *Ovl
54 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
55 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
56 FEnd = Ovl->function_end();
57 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000058 if ((*F)->getType()->isDependentType()) {
59 Template = Ovl;
60 return TNK_Function_template;
61 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000062 }
63 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000064 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000065 return TNK_Non_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000066}
67
Douglas Gregor72c3f312008-12-05 18:15:24 +000068/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
69/// that the template parameter 'PrevDecl' is being shadowed by a new
70/// declaration at location Loc. Returns true to indicate that this is
71/// an error, and false otherwise.
72bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +000073 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +000074
75 // Microsoft Visual C++ permits template parameters to be shadowed.
76 if (getLangOptions().Microsoft)
77 return false;
78
79 // C++ [temp.local]p4:
80 // A template-parameter shall not be redeclared within its
81 // scope (including nested scopes).
82 Diag(Loc, diag::err_template_param_shadow)
83 << cast<NamedDecl>(PrevDecl)->getDeclName();
84 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
85 return true;
86}
87
Douglas Gregor2943aed2009-03-03 04:44:36 +000088/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +000089/// the parameter D to reference the templated declaration and return a pointer
90/// to the template declaration. Otherwise, do nothing to D and return null.
91TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
92{
93 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
94 D = Temp->getTemplatedDecl();
95 return Temp;
96 }
97 return 0;
98}
99
Douglas Gregor72c3f312008-12-05 18:15:24 +0000100/// ActOnTypeParameter - Called when a C++ template type parameter
101/// (e.g., "typename T") has been parsed. Typename specifies whether
102/// the keyword "typename" was used to declare the type parameter
103/// (otherwise, "class" was used), and KeyLoc is the location of the
104/// "class" or "typename" keyword. ParamName is the name of the
105/// parameter (NULL indicates an unnamed template parameter) and
106/// ParamName is the location of the parameter name (if any).
107/// If the type parameter has a default argument, it will be added
108/// later via ActOnTypeParameterDefault.
109Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
110 SourceLocation KeyLoc,
111 IdentifierInfo *ParamName,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000112 SourceLocation ParamNameLoc,
113 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000114 assert(S->isTemplateParamScope() &&
115 "Template type parameter not in template parameter scope!");
116 bool Invalid = false;
117
118 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000119 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000120 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000121 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
122 PrevDecl);
123 }
124
Douglas Gregorddc29e12009-02-06 22:42:48 +0000125 SourceLocation Loc = ParamNameLoc;
126 if (!ParamName)
127 Loc = KeyLoc;
128
Douglas Gregor72c3f312008-12-05 18:15:24 +0000129 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000130 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000131 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000132 if (Invalid)
133 Param->setInvalidDecl();
134
135 if (ParamName) {
136 // Add the template parameter into the current scope.
137 S->AddDecl(Param);
138 IdResolver.AddDecl(Param);
139 }
140
141 return Param;
142}
143
Douglas Gregord684b002009-02-10 19:49:53 +0000144/// ActOnTypeParameterDefault - Adds a default argument (the type
145/// Default) to the given template type parameter (TypeParam).
146void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
147 SourceLocation EqualLoc,
148 SourceLocation DefaultLoc,
149 TypeTy *DefaultT) {
150 TemplateTypeParmDecl *Parm
151 = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
152 QualType Default = QualType::getFromOpaquePtr(DefaultT);
153
154 // C++ [temp.param]p14:
155 // A template-parameter shall not be used in its own default argument.
156 // FIXME: Implement this check! Needs a recursive walk over the types.
157
158 // Check the template argument itself.
159 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
160 Parm->setInvalidDecl();
161 return;
162 }
163
164 Parm->setDefaultArgument(Default, DefaultLoc, false);
165}
166
Douglas Gregor2943aed2009-03-03 04:44:36 +0000167/// \brief Check that the type of a non-type template parameter is
168/// well-formed.
169///
170/// \returns the (possibly-promoted) parameter type if valid;
171/// otherwise, produces a diagnostic and returns a NULL type.
172QualType
173Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
174 // C++ [temp.param]p4:
175 //
176 // A non-type template-parameter shall have one of the following
177 // (optionally cv-qualified) types:
178 //
179 // -- integral or enumeration type,
180 if (T->isIntegralType() || T->isEnumeralType() ||
181 // -- pointer to object or pointer to function,
182 (T->isPointerType() &&
183 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
184 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
185 // -- reference to object or reference to function,
186 T->isReferenceType() ||
187 // -- pointer to member.
188 T->isMemberPointerType() ||
189 // If T is a dependent type, we can't do the check now, so we
190 // assume that it is well-formed.
191 T->isDependentType())
192 return T;
193 // C++ [temp.param]p8:
194 //
195 // A non-type template-parameter of type "array of T" or
196 // "function returning T" is adjusted to be of type "pointer to
197 // T" or "pointer to function returning T", respectively.
198 else if (T->isArrayType())
199 // FIXME: Keep the type prior to promotion?
200 return Context.getArrayDecayedType(T);
201 else if (T->isFunctionType())
202 // FIXME: Keep the type prior to promotion?
203 return Context.getPointerType(T);
204
205 Diag(Loc, diag::err_template_nontype_parm_bad_type)
206 << T;
207
208 return QualType();
209}
210
Douglas Gregor72c3f312008-12-05 18:15:24 +0000211/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
212/// template parameter (e.g., "int Size" in "template<int Size>
213/// class Array") has been parsed. S is the current scope and D is
214/// the parsed declarator.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000215Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
216 unsigned Depth,
217 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000218 QualType T = GetTypeForDeclarator(D, S);
219
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000220 assert(S->isTemplateParamScope() &&
221 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000222 bool Invalid = false;
223
224 IdentifierInfo *ParamName = D.getIdentifier();
225 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000226 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000227 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000228 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000229 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000230 }
231
Douglas Gregor2943aed2009-03-03 04:44:36 +0000232 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000233 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000234 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000235 Invalid = true;
236 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000237
Douglas Gregor72c3f312008-12-05 18:15:24 +0000238 NonTypeTemplateParmDecl *Param
239 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000240 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000241 if (Invalid)
242 Param->setInvalidDecl();
243
244 if (D.getIdentifier()) {
245 // Add the template parameter into the current scope.
246 S->AddDecl(Param);
247 IdResolver.AddDecl(Param);
248 }
249 return Param;
250}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000251
Douglas Gregord684b002009-02-10 19:49:53 +0000252/// \brief Adds a default argument to the given non-type template
253/// parameter.
254void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
255 SourceLocation EqualLoc,
256 ExprArg DefaultE) {
257 NonTypeTemplateParmDecl *TemplateParm
258 = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
259 Expr *Default = static_cast<Expr *>(DefaultE.get());
260
261 // C++ [temp.param]p14:
262 // A template-parameter shall not be used in its own default argument.
263 // FIXME: Implement this check! Needs a recursive walk over the types.
264
265 // Check the well-formedness of the default template argument.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000266 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000267 TemplateParm->setInvalidDecl();
268 return;
269 }
270
271 TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
272}
273
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000274
275/// ActOnTemplateTemplateParameter - Called when a C++ template template
276/// parameter (e.g. T in template <template <typename> class T> class array)
277/// has been parsed. S is the current scope.
278Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
279 SourceLocation TmpLoc,
280 TemplateParamsTy *Params,
281 IdentifierInfo *Name,
282 SourceLocation NameLoc,
283 unsigned Depth,
284 unsigned Position)
285{
286 assert(S->isTemplateParamScope() &&
287 "Template template parameter not in template parameter scope!");
288
289 // Construct the parameter object.
290 TemplateTemplateParmDecl *Param =
291 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
292 Position, Name,
293 (TemplateParameterList*)Params);
294
295 // Make sure the parameter is valid.
296 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
297 // do anything yet. However, if the template parameter list or (eventual)
298 // default value is ever invalidated, that will propagate here.
299 bool Invalid = false;
300 if (Invalid) {
301 Param->setInvalidDecl();
302 }
303
304 // If the tt-param has a name, then link the identifier into the scope
305 // and lookup mechanisms.
306 if (Name) {
307 S->AddDecl(Param);
308 IdResolver.AddDecl(Param);
309 }
310
311 return Param;
312}
313
Douglas Gregord684b002009-02-10 19:49:53 +0000314/// \brief Adds a default argument to the given template template
315/// parameter.
316void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
317 SourceLocation EqualLoc,
318 ExprArg DefaultE) {
319 TemplateTemplateParmDecl *TemplateParm
320 = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
321
322 // Since a template-template parameter's default argument is an
323 // id-expression, it must be a DeclRefExpr.
324 DeclRefExpr *Default
325 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
326
327 // C++ [temp.param]p14:
328 // A template-parameter shall not be used in its own default argument.
329 // FIXME: Implement this check! Needs a recursive walk over the types.
330
331 // Check the well-formedness of the template argument.
332 if (!isa<TemplateDecl>(Default->getDecl())) {
333 Diag(Default->getSourceRange().getBegin(),
334 diag::err_template_arg_must_be_template)
335 << Default->getSourceRange();
336 TemplateParm->setInvalidDecl();
337 return;
338 }
339 if (CheckTemplateArgument(TemplateParm, Default)) {
340 TemplateParm->setInvalidDecl();
341 return;
342 }
343
344 DefaultE.release();
345 TemplateParm->setDefaultArgument(Default);
346}
347
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000348/// ActOnTemplateParameterList - Builds a TemplateParameterList that
349/// contains the template parameters in Params/NumParams.
350Sema::TemplateParamsTy *
351Sema::ActOnTemplateParameterList(unsigned Depth,
352 SourceLocation ExportLoc,
353 SourceLocation TemplateLoc,
354 SourceLocation LAngleLoc,
355 DeclTy **Params, unsigned NumParams,
356 SourceLocation RAngleLoc) {
357 if (ExportLoc.isValid())
358 Diag(ExportLoc, diag::note_template_export_unsupported);
359
Douglas Gregorddc29e12009-02-06 22:42:48 +0000360 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
361 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000362}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000363
Douglas Gregorddc29e12009-02-06 22:42:48 +0000364Sema::DeclTy *
365Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
366 SourceLocation KWLoc, const CXXScopeSpec &SS,
367 IdentifierInfo *Name, SourceLocation NameLoc,
368 AttributeList *Attr,
369 MultiTemplateParamsArg TemplateParameterLists) {
370 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
371 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000372 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000373
374 // Check that we can declare a template here.
375 if (CheckTemplateDeclScope(S, TemplateParameterLists))
376 return 0;
377
378 TagDecl::TagKind Kind;
379 switch (TagSpec) {
380 default: assert(0 && "Unknown tag type!");
381 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
382 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
383 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
384 }
385
386 // There is no such thing as an unnamed class template.
387 if (!Name) {
388 Diag(KWLoc, diag::err_template_unnamed_class);
389 return 0;
390 }
391
392 // Find any previous declaration with this name.
393 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
394 true);
395 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
396 NamedDecl *PrevDecl = 0;
397 if (Previous.begin() != Previous.end())
398 PrevDecl = *Previous.begin();
399
400 DeclContext *SemanticContext = CurContext;
401 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000402 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000403
404 // FIXME: need to match up several levels of template parameter
405 // lists here.
406 }
407
408 // FIXME: member templates!
409 TemplateParameterList *TemplateParams
410 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
411
412 // If there is a previous declaration with the same name, check
413 // whether this is a valid redeclaration.
414 ClassTemplateDecl *PrevClassTemplate
415 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
416 if (PrevClassTemplate) {
417 // Ensure that the template parameter lists are compatible.
418 if (!TemplateParameterListsAreEqual(TemplateParams,
419 PrevClassTemplate->getTemplateParameters(),
420 /*Complain=*/true))
421 return 0;
422
423 // C++ [temp.class]p4:
424 // In a redeclaration, partial specialization, explicit
425 // specialization or explicit instantiation of a class template,
426 // the class-key shall agree in kind with the original class
427 // template declaration (7.1.5.3).
428 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
429 if (PrevRecordDecl->getTagKind() != Kind) {
430 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
431 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
432 return 0;
433 }
434
435
436 // Check for redefinition of this class template.
437 if (TK == TK_Definition) {
438 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
439 Diag(NameLoc, diag::err_redefinition) << Name;
440 Diag(Def->getLocation(), diag::note_previous_definition);
441 // FIXME: Would it make sense to try to "forget" the previous
442 // definition, as part of error recovery?
443 return 0;
444 }
445 }
446 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
447 // Maybe we will complain about the shadowed template parameter.
448 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
449 // Just pretend that we didn't see the previous declaration.
450 PrevDecl = 0;
451 } else if (PrevDecl) {
452 // C++ [temp]p5:
453 // A class template shall not have the same name as any other
454 // template, class, function, object, enumeration, enumerator,
455 // namespace, or type in the same scope (3.3), except as specified
456 // in (14.5.4).
457 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
458 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
459 return 0;
460 }
461
Douglas Gregord684b002009-02-10 19:49:53 +0000462 // Check the template parameter list of this declaration, possibly
463 // merging in the template parameter list from the previous class
464 // template declaration.
465 if (CheckTemplateParameterList(TemplateParams,
466 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
467 Invalid = true;
468
Douglas Gregorddc29e12009-02-06 22:42:48 +0000469 // If we had a scope specifier, we better have a previous template
470 // declaration!
471
472 TagDecl *NewClass =
473 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
474 PrevClassTemplate?
475 PrevClassTemplate->getTemplatedDecl() : 0);
476
477 ClassTemplateDecl *NewTemplate
478 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
479 DeclarationName(Name), TemplateParams,
480 NewClass);
481
482 // Set the lexical context of these templates
483 NewClass->setLexicalDeclContext(CurContext);
484 NewTemplate->setLexicalDeclContext(CurContext);
485
486 if (TK == TK_Definition)
487 NewClass->startDefinition();
488
489 if (Attr)
490 ProcessDeclAttributeList(NewClass, Attr);
491
492 PushOnScopeChains(NewTemplate, S);
493
Douglas Gregord684b002009-02-10 19:49:53 +0000494 if (Invalid) {
495 NewTemplate->setInvalidDecl();
496 NewClass->setInvalidDecl();
497 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000498 return NewTemplate;
499}
500
Douglas Gregord684b002009-02-10 19:49:53 +0000501/// \brief Checks the validity of a template parameter list, possibly
502/// considering the template parameter list from a previous
503/// declaration.
504///
505/// If an "old" template parameter list is provided, it must be
506/// equivalent (per TemplateParameterListsAreEqual) to the "new"
507/// template parameter list.
508///
509/// \param NewParams Template parameter list for a new template
510/// declaration. This template parameter list will be updated with any
511/// default arguments that are carried through from the previous
512/// template parameter list.
513///
514/// \param OldParams If provided, template parameter list from a
515/// previous declaration of the same template. Default template
516/// arguments will be merged from the old template parameter list to
517/// the new template parameter list.
518///
519/// \returns true if an error occurred, false otherwise.
520bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
521 TemplateParameterList *OldParams) {
522 bool Invalid = false;
523
524 // C++ [temp.param]p10:
525 // The set of default template-arguments available for use with a
526 // template declaration or definition is obtained by merging the
527 // default arguments from the definition (if in scope) and all
528 // declarations in scope in the same way default function
529 // arguments are (8.3.6).
530 bool SawDefaultArgument = false;
531 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000532
Mike Stump1a35fde2009-02-11 23:03:27 +0000533 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000534 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000535 if (OldParams)
536 OldParam = OldParams->begin();
537
538 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
539 NewParamEnd = NewParams->end();
540 NewParam != NewParamEnd; ++NewParam) {
541 // Variables used to diagnose redundant default arguments
542 bool RedundantDefaultArg = false;
543 SourceLocation OldDefaultLoc;
544 SourceLocation NewDefaultLoc;
545
546 // Variables used to diagnose missing default arguments
547 bool MissingDefaultArg = false;
548
549 // Merge default arguments for template type parameters.
550 if (TemplateTypeParmDecl *NewTypeParm
551 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
552 TemplateTypeParmDecl *OldTypeParm
553 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
554
555 if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
556 NewTypeParm->hasDefaultArgument()) {
557 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
558 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
559 SawDefaultArgument = true;
560 RedundantDefaultArg = true;
561 PreviousDefaultArgLoc = NewDefaultLoc;
562 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
563 // Merge the default argument from the old declaration to the
564 // new declaration.
565 SawDefaultArgument = true;
566 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
567 OldTypeParm->getDefaultArgumentLoc(),
568 true);
569 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
570 } else if (NewTypeParm->hasDefaultArgument()) {
571 SawDefaultArgument = true;
572 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
573 } else if (SawDefaultArgument)
574 MissingDefaultArg = true;
575 }
576 // Merge default arguments for non-type template parameters
577 else if (NonTypeTemplateParmDecl *NewNonTypeParm
578 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
579 NonTypeTemplateParmDecl *OldNonTypeParm
580 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
581 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
582 NewNonTypeParm->hasDefaultArgument()) {
583 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
584 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
585 SawDefaultArgument = true;
586 RedundantDefaultArg = true;
587 PreviousDefaultArgLoc = NewDefaultLoc;
588 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
589 // Merge the default argument from the old declaration to the
590 // new declaration.
591 SawDefaultArgument = true;
592 // FIXME: We need to create a new kind of "default argument"
593 // expression that points to a previous template template
594 // parameter.
595 NewNonTypeParm->setDefaultArgument(
596 OldNonTypeParm->getDefaultArgument());
597 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
598 } else if (NewNonTypeParm->hasDefaultArgument()) {
599 SawDefaultArgument = true;
600 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
601 } else if (SawDefaultArgument)
602 MissingDefaultArg = true;
603 }
604 // Merge default arguments for template template parameters
605 else {
606 TemplateTemplateParmDecl *NewTemplateParm
607 = cast<TemplateTemplateParmDecl>(*NewParam);
608 TemplateTemplateParmDecl *OldTemplateParm
609 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
610 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
611 NewTemplateParm->hasDefaultArgument()) {
612 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
613 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
614 SawDefaultArgument = true;
615 RedundantDefaultArg = true;
616 PreviousDefaultArgLoc = NewDefaultLoc;
617 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
618 // Merge the default argument from the old declaration to the
619 // new declaration.
620 SawDefaultArgument = true;
621 // FIXME: We need to create a new kind of "default argument"
622 // expression that points to a previous template template
623 // parameter.
624 NewTemplateParm->setDefaultArgument(
625 OldTemplateParm->getDefaultArgument());
626 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
627 } else if (NewTemplateParm->hasDefaultArgument()) {
628 SawDefaultArgument = true;
629 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
630 } else if (SawDefaultArgument)
631 MissingDefaultArg = true;
632 }
633
634 if (RedundantDefaultArg) {
635 // C++ [temp.param]p12:
636 // A template-parameter shall not be given default arguments
637 // by two different declarations in the same scope.
638 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
639 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
640 Invalid = true;
641 } else if (MissingDefaultArg) {
642 // C++ [temp.param]p11:
643 // If a template-parameter has a default template-argument,
644 // all subsequent template-parameters shall have a default
645 // template-argument supplied.
646 Diag((*NewParam)->getLocation(),
647 diag::err_template_param_default_arg_missing);
648 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
649 Invalid = true;
650 }
651
652 // If we have an old template parameter list that we're merging
653 // in, move on to the next parameter.
654 if (OldParams)
655 ++OldParam;
656 }
657
658 return Invalid;
659}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000660
Douglas Gregor40808ce2009-03-09 23:48:35 +0000661/// \brief Translates template arguments as provided by the parser
662/// into template arguments used by semantic analysis.
663static void
664translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
665 SourceLocation *TemplateArgLocs,
666 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
667 TemplateArgs.reserve(TemplateArgsIn.size());
668
669 void **Args = TemplateArgsIn.getArgs();
670 bool *ArgIsType = TemplateArgsIn.getArgIsType();
671 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
672 TemplateArgs.push_back(
673 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
674 QualType::getFromOpaquePtr(Args[Arg]))
675 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
676 }
677}
678
679QualType Sema::CheckClassTemplateId(ClassTemplateDecl *ClassTemplate,
680 SourceLocation TemplateLoc,
681 SourceLocation LAngleLoc,
682 const TemplateArgument *TemplateArgs,
683 unsigned NumTemplateArgs,
684 SourceLocation RAngleLoc) {
685 // Check that the template argument list is well-formed for this
686 // template.
687 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
688 if (CheckTemplateArgumentList(ClassTemplate, TemplateLoc, LAngleLoc,
689 TemplateArgs, NumTemplateArgs, RAngleLoc,
690 ConvertedTemplateArgs))
691 return QualType();
692
693 assert((ConvertedTemplateArgs.size() ==
694 ClassTemplate->getTemplateParameters()->size()) &&
695 "Converted template argument list is too short!");
696
697 QualType CanonType;
698
699 if (ClassTemplateSpecializationType::anyDependentTemplateArguments(
700 TemplateArgs,
701 NumTemplateArgs)) {
702 // This class template specialization is a dependent
703 // type. Therefore, its canonical type is another class template
704 // specialization type that contains all of the converted
705 // arguments in canonical form. This ensures that, e.g., A<T> and
706 // A<T, T> have identical types when A is declared as:
707 //
708 // template<typename T, typename U = T> struct A;
709
710 CanonType = Context.getClassTemplateSpecializationType(ClassTemplate,
711 &ConvertedTemplateArgs[0],
712 ConvertedTemplateArgs.size());
713 } else {
714 // Find the class template specialization declaration that
715 // corresponds to these arguments.
716 llvm::FoldingSetNodeID ID;
717 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
718 ConvertedTemplateArgs.size());
719 void *InsertPos = 0;
720 ClassTemplateSpecializationDecl *Decl
721 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
722 if (!Decl) {
723 // This is the first time we have referenced this class template
724 // specialization. Create the canonical declaration and add it to
725 // the set of specializations.
726 Decl = ClassTemplateSpecializationDecl::Create(Context,
727 ClassTemplate->getDeclContext(),
728 TemplateLoc,
729 ClassTemplate,
730 &ConvertedTemplateArgs[0],
731 ConvertedTemplateArgs.size(),
732 0);
733 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
734 Decl->setLexicalDeclContext(CurContext);
735 }
736
737 CanonType = Context.getTypeDeclType(Decl);
738 }
739
740 // Build the fully-sugared type for this class template
741 // specialization, which refers back to the class template
742 // specialization we created or found.
743 return Context.getClassTemplateSpecializationType(ClassTemplate,
744 TemplateArgs,
745 NumTemplateArgs,
746 CanonType);
747}
748
Douglas Gregorcc636682009-02-17 23:15:12 +0000749Action::TypeResult
750Sema::ActOnClassTemplateId(DeclTy *TemplateD, SourceLocation TemplateLoc,
751 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000752 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +0000753 SourceLocation *TemplateArgLocs,
754 SourceLocation RAngleLoc,
755 const CXXScopeSpec *SS) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000756 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000757 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(Template);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000758
Douglas Gregor40808ce2009-03-09 23:48:35 +0000759 // Translate the parser's template argument list in our AST format.
760 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
761 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000762
Douglas Gregor40808ce2009-03-09 23:48:35 +0000763 QualType Result = CheckClassTemplateId(ClassTemplate, TemplateLoc,
764 LAngleLoc,
765 &TemplateArgs[0],
766 TemplateArgs.size(),
767 RAngleLoc);
Douglas Gregore6258932009-03-19 00:39:20 +0000768
769 if (SS)
770 Result = getQualifiedNameType(*SS, Result);
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000771
Douglas Gregor40808ce2009-03-09 23:48:35 +0000772 TemplateArgsIn.release();
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000773 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000774}
775
Douglas Gregorc15cb382009-02-09 23:23:08 +0000776/// \brief Check that the given template argument list is well-formed
777/// for specializing the given template.
778bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
779 SourceLocation TemplateLoc,
780 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000781 const TemplateArgument *TemplateArgs,
782 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000783 SourceLocation RAngleLoc,
784 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000785 TemplateParameterList *Params = Template->getTemplateParameters();
786 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +0000787 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000788 bool Invalid = false;
789
790 if (NumArgs > NumParams ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000791 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +0000792 // FIXME: point at either the first arg beyond what we can handle,
793 // or the '>', depending on whether we have too many or too few
794 // arguments.
795 SourceRange Range;
796 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +0000797 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000798 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
799 << (NumArgs > NumParams)
800 << (isa<ClassTemplateDecl>(Template)? 0 :
801 isa<FunctionTemplateDecl>(Template)? 1 :
802 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
803 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +0000804 Diag(Template->getLocation(), diag::note_template_decl_here)
805 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +0000806 Invalid = true;
807 }
808
809 // C++ [temp.arg]p1:
810 // [...] The type and form of each template-argument specified in
811 // a template-id shall match the type and form specified for the
812 // corresponding parameter declared by the template in its
813 // template-parameter-list.
814 unsigned ArgIdx = 0;
815 for (TemplateParameterList::iterator Param = Params->begin(),
816 ParamEnd = Params->end();
817 Param != ParamEnd; ++Param, ++ArgIdx) {
818 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000819 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000820 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000821 // Retrieve the default template argument from the template
822 // parameter.
823 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
824 if (!TTP->hasDefaultArgument())
825 break;
826
Douglas Gregor40808ce2009-03-09 23:48:35 +0000827 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +0000828
829 // If the argument type is dependent, instantiate it now based
830 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +0000831 if (ArgType->isDependentType()) {
832 InstantiatingTemplate Inst(*this, TemplateLoc,
833 Template, &Converted[0],
834 Converted.size(),
835 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor99ebf652009-02-27 19:31:52 +0000836 ArgType = InstantiateType(ArgType, &Converted[0], Converted.size(),
837 TTP->getDefaultArgumentLoc(),
838 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +0000839 }
Douglas Gregor99ebf652009-02-27 19:31:52 +0000840
841 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +0000842 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000843
Douglas Gregor40808ce2009-03-09 23:48:35 +0000844 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000845 } else if (NonTypeTemplateParmDecl *NTTP
846 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
847 if (!NTTP->hasDefaultArgument())
848 break;
849
Douglas Gregor2943aed2009-03-03 04:44:36 +0000850 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000851 Arg = TemplateArgument(NTTP->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000852 } else {
853 TemplateTemplateParmDecl *TempParm
854 = cast<TemplateTemplateParmDecl>(*Param);
855
856 if (!TempParm->hasDefaultArgument())
857 break;
858
Douglas Gregor2943aed2009-03-03 04:44:36 +0000859 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000860 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000861 }
862 } else {
863 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +0000864 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000865 }
866
Douglas Gregorc15cb382009-02-09 23:23:08 +0000867
868 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
869 // Check template type parameters.
Douglas Gregor40808ce2009-03-09 23:48:35 +0000870 if (Arg.getKind() == TemplateArgument::Type) {
871 if (CheckTemplateArgument(TTP, Arg.getAsType(), Arg.getLocation()))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000872 Invalid = true;
Douglas Gregor3e00bad2009-02-17 01:05:43 +0000873
874 // Add the converted template type argument.
875 Converted.push_back(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000876 TemplateArgument(Arg.getLocation(),
877 Context.getCanonicalType(Arg.getAsType())));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000878 continue;
879 }
880
881 // C++ [temp.arg.type]p1:
882 // A template-argument for a template-parameter which is a
883 // type shall be a type-id.
884
885 // We have a template type parameter but the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +0000886 // is not a type.
887 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +0000888 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000889 Invalid = true;
890 } else if (NonTypeTemplateParmDecl *NTTP
891 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
892 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000893
894 // Instantiate the type of the non-type template parameter with
895 // the template arguments we've seen thus far.
896 QualType NTTPType = NTTP->getType();
897 if (NTTPType->isDependentType()) {
898 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +0000899 InstantiatingTemplate Inst(*this, TemplateLoc,
900 Template, &Converted[0],
901 Converted.size(),
902 SourceRange(TemplateLoc, RAngleLoc));
903
Douglas Gregor2943aed2009-03-03 04:44:36 +0000904 NTTPType = InstantiateType(NTTPType,
905 &Converted[0], Converted.size(),
906 NTTP->getLocation(),
907 NTTP->getDeclName());
908 // If that worked, check the non-type template parameter type
909 // for validity.
910 if (!NTTPType.isNull())
911 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
912 NTTP->getLocation());
913
914 if (NTTPType.isNull()) {
915 Invalid = true;
916 break;
917 }
918 }
919
Douglas Gregor40808ce2009-03-09 23:48:35 +0000920 switch (Arg.getKind()) {
921 case TemplateArgument::Expression: {
922 Expr *E = Arg.getAsExpr();
923 if (CheckTemplateArgument(NTTP, NTTPType, E, &Converted))
Douglas Gregorc15cb382009-02-09 23:23:08 +0000924 Invalid = true;
Douglas Gregor40808ce2009-03-09 23:48:35 +0000925 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000926 }
927
Douglas Gregor40808ce2009-03-09 23:48:35 +0000928 case TemplateArgument::Declaration:
929 case TemplateArgument::Integral:
930 // We've already checked this template argument, so just copy
931 // it to the list of converted arguments.
932 Converted.push_back(Arg);
933 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000934
Douglas Gregor40808ce2009-03-09 23:48:35 +0000935 case TemplateArgument::Type:
936 // We have a non-type template parameter but the template
937 // argument is a type.
938
939 // C++ [temp.arg]p2:
940 // In a template-argument, an ambiguity between a type-id and
941 // an expression is resolved to a type-id, regardless of the
942 // form of the corresponding template-parameter.
943 //
944 // We warn specifically about this case, since it can be rather
945 // confusing for users.
946 if (Arg.getAsType()->isFunctionType())
947 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
948 << Arg.getAsType();
949 else
950 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
951 Diag((*Param)->getLocation(), diag::note_template_param_here);
952 Invalid = true;
953 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000954 } else {
955 // Check template template parameters.
956 TemplateTemplateParmDecl *TempParm
957 = cast<TemplateTemplateParmDecl>(*Param);
958
Douglas Gregor40808ce2009-03-09 23:48:35 +0000959 switch (Arg.getKind()) {
960 case TemplateArgument::Expression: {
961 Expr *ArgExpr = Arg.getAsExpr();
962 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
963 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
964 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
965 Invalid = true;
966
967 // Add the converted template argument.
968 // FIXME: Need the "canonical" template declaration!
969 Converted.push_back(
970 TemplateArgument(Arg.getLocation(),
971 cast<DeclRefExpr>(ArgExpr)->getDecl()));
972 continue;
973 }
974 }
975 // fall through
976
977 case TemplateArgument::Type: {
978 // We have a template template parameter but the template
979 // argument does not refer to a template.
980 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
981 Invalid = true;
982 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000983 }
984
Douglas Gregor40808ce2009-03-09 23:48:35 +0000985 case TemplateArgument::Declaration:
986 // We've already checked this template argument, so just copy
987 // it to the list of converted arguments.
988 Converted.push_back(Arg);
989 break;
990
991 case TemplateArgument::Integral:
992 assert(false && "Integral argument with template template parameter");
993 break;
994 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000995 }
996 }
997
998 return Invalid;
999}
1000
1001/// \brief Check a template argument against its corresponding
1002/// template type parameter.
1003///
1004/// This routine implements the semantics of C++ [temp.arg.type]. It
1005/// returns true if an error occurred, and false otherwise.
1006bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1007 QualType Arg, SourceLocation ArgLoc) {
1008 // C++ [temp.arg.type]p2:
1009 // A local type, a type with no linkage, an unnamed type or a type
1010 // compounded from any of these types shall not be used as a
1011 // template-argument for a template type-parameter.
1012 //
1013 // FIXME: Perform the recursive and no-linkage type checks.
1014 const TagType *Tag = 0;
1015 if (const EnumType *EnumT = Arg->getAsEnumType())
1016 Tag = EnumT;
1017 else if (const RecordType *RecordT = Arg->getAsRecordType())
1018 Tag = RecordT;
1019 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1020 return Diag(ArgLoc, diag::err_template_arg_local_type)
1021 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001022 else if (Tag && !Tag->getDecl()->getDeclName() &&
1023 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001024 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1025 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1026 return true;
1027 }
1028
1029 return false;
1030}
1031
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001032/// \brief Checks whether the given template argument is the address
1033/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001034bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1035 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001036 bool Invalid = false;
1037
1038 // See through any implicit casts we added to fix the type.
1039 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1040 Arg = Cast->getSubExpr();
1041
1042 // C++ [temp.arg.nontype]p1:
1043 //
1044 // A template-argument for a non-type, non-template
1045 // template-parameter shall be one of: [...]
1046 //
1047 // -- the address of an object or function with external
1048 // linkage, including function templates and function
1049 // template-ids but excluding non-static class members,
1050 // expressed as & id-expression where the & is optional if
1051 // the name refers to a function or array, or if the
1052 // corresponding template-parameter is a reference; or
1053 DeclRefExpr *DRE = 0;
1054
1055 // Ignore (and complain about) any excess parentheses.
1056 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1057 if (!Invalid) {
1058 Diag(Arg->getSourceRange().getBegin(),
1059 diag::err_template_arg_extra_parens)
1060 << Arg->getSourceRange();
1061 Invalid = true;
1062 }
1063
1064 Arg = Parens->getSubExpr();
1065 }
1066
1067 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1068 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1069 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1070 } else
1071 DRE = dyn_cast<DeclRefExpr>(Arg);
1072
1073 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1074 return Diag(Arg->getSourceRange().getBegin(),
1075 diag::err_template_arg_not_object_or_func_form)
1076 << Arg->getSourceRange();
1077
1078 // Cannot refer to non-static data members
1079 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1080 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1081 << Field << Arg->getSourceRange();
1082
1083 // Cannot refer to non-static member functions
1084 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1085 if (!Method->isStatic())
1086 return Diag(Arg->getSourceRange().getBegin(),
1087 diag::err_template_arg_method)
1088 << Method << Arg->getSourceRange();
1089
1090 // Functions must have external linkage.
1091 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1092 if (Func->getStorageClass() == FunctionDecl::Static) {
1093 Diag(Arg->getSourceRange().getBegin(),
1094 diag::err_template_arg_function_not_extern)
1095 << Func << Arg->getSourceRange();
1096 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1097 << true;
1098 return true;
1099 }
1100
1101 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001102 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001103 return Invalid;
1104 }
1105
1106 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1107 if (!Var->hasGlobalStorage()) {
1108 Diag(Arg->getSourceRange().getBegin(),
1109 diag::err_template_arg_object_not_extern)
1110 << Var << Arg->getSourceRange();
1111 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1112 << true;
1113 return true;
1114 }
1115
1116 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001117 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001118 return Invalid;
1119 }
1120
1121 // We found something else, but we don't know specifically what it is.
1122 Diag(Arg->getSourceRange().getBegin(),
1123 diag::err_template_arg_not_object_or_func)
1124 << Arg->getSourceRange();
1125 Diag(DRE->getDecl()->getLocation(),
1126 diag::note_template_arg_refers_here);
1127 return true;
1128}
1129
1130/// \brief Checks whether the given template argument is a pointer to
1131/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001132bool
1133Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001134 bool Invalid = false;
1135
1136 // See through any implicit casts we added to fix the type.
1137 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1138 Arg = Cast->getSubExpr();
1139
1140 // C++ [temp.arg.nontype]p1:
1141 //
1142 // A template-argument for a non-type, non-template
1143 // template-parameter shall be one of: [...]
1144 //
1145 // -- a pointer to member expressed as described in 5.3.1.
1146 QualifiedDeclRefExpr *DRE = 0;
1147
1148 // Ignore (and complain about) any excess parentheses.
1149 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1150 if (!Invalid) {
1151 Diag(Arg->getSourceRange().getBegin(),
1152 diag::err_template_arg_extra_parens)
1153 << Arg->getSourceRange();
1154 Invalid = true;
1155 }
1156
1157 Arg = Parens->getSubExpr();
1158 }
1159
1160 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1161 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1162 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1163
1164 if (!DRE)
1165 return Diag(Arg->getSourceRange().getBegin(),
1166 diag::err_template_arg_not_pointer_to_member_form)
1167 << Arg->getSourceRange();
1168
1169 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1170 assert((isa<FieldDecl>(DRE->getDecl()) ||
1171 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1172 "Only non-static member pointers can make it here");
1173
1174 // Okay: this is the address of a non-static member, and therefore
1175 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001176 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001177 return Invalid;
1178 }
1179
1180 // We found something else, but we don't know specifically what it is.
1181 Diag(Arg->getSourceRange().getBegin(),
1182 diag::err_template_arg_not_pointer_to_member_form)
1183 << Arg->getSourceRange();
1184 Diag(DRE->getDecl()->getLocation(),
1185 diag::note_template_arg_refers_here);
1186 return true;
1187}
1188
Douglas Gregorc15cb382009-02-09 23:23:08 +00001189/// \brief Check a template argument against its corresponding
1190/// non-type template parameter.
1191///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001192/// This routine implements the semantics of C++ [temp.arg.nontype].
1193/// It returns true if an error occurred, and false otherwise. \p
1194/// InstantiatedParamType is the type of the non-type template
1195/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001196///
1197/// If Converted is non-NULL and no errors occur, the value
1198/// of this argument will be added to the end of the Converted vector.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001199bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001200 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001201 llvm::SmallVectorImpl<TemplateArgument> *Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001202 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1203
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001204 // If either the parameter has a dependent type or the argument is
1205 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001206 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001207 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1208 // FIXME: Produce a cloned, canonical expression?
1209 Converted->push_back(TemplateArgument(Arg));
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001210 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001211 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001212
1213 // C++ [temp.arg.nontype]p5:
1214 // The following conversions are performed on each expression used
1215 // as a non-type template-argument. If a non-type
1216 // template-argument cannot be converted to the type of the
1217 // corresponding template-parameter then the program is
1218 // ill-formed.
1219 //
1220 // -- for a non-type template-parameter of integral or
1221 // enumeration type, integral promotions (4.5) and integral
1222 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001223 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001224 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001225 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001226 // C++ [temp.arg.nontype]p1:
1227 // A template-argument for a non-type, non-template
1228 // template-parameter shall be one of:
1229 //
1230 // -- an integral constant-expression of integral or enumeration
1231 // type; or
1232 // -- the name of a non-type template-parameter; or
1233 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001234 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001235 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1236 Diag(Arg->getSourceRange().getBegin(),
1237 diag::err_template_arg_not_integral_or_enumeral)
1238 << ArgType << Arg->getSourceRange();
1239 Diag(Param->getLocation(), diag::note_template_param_here);
1240 return true;
1241 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001242 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001243 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1244 << ArgType << Arg->getSourceRange();
1245 return true;
1246 }
1247
1248 // FIXME: We need some way to more easily get the unqualified form
1249 // of the types without going all the way to the
1250 // canonical type.
1251 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1252 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1253 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1254 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1255
1256 // Try to convert the argument to the parameter's type.
1257 if (ParamType == ArgType) {
1258 // Okay: no conversion necessary
1259 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1260 !ParamType->isEnumeralType()) {
1261 // This is an integral promotion or conversion.
1262 ImpCastExprToType(Arg, ParamType);
1263 } else {
1264 // We can't perform this conversion.
1265 Diag(Arg->getSourceRange().getBegin(),
1266 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001267 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001268 Diag(Param->getLocation(), diag::note_template_param_here);
1269 return true;
1270 }
1271
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001272 QualType IntegerType = Context.getCanonicalType(ParamType);
1273 if (const EnumType *Enum = IntegerType->getAsEnumType())
1274 IntegerType = Enum->getDecl()->getIntegerType();
1275
1276 if (!Arg->isValueDependent()) {
1277 // Check that an unsigned parameter does not receive a negative
1278 // value.
1279 if (IntegerType->isUnsignedIntegerType()
1280 && (Value.isSigned() && Value.isNegative())) {
1281 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1282 << Value.toString(10) << Param->getType()
1283 << Arg->getSourceRange();
1284 Diag(Param->getLocation(), diag::note_template_param_here);
1285 return true;
1286 }
1287
1288 // Check that we don't overflow the template parameter type.
1289 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1290 if (Value.getActiveBits() > AllowedBits) {
1291 Diag(Arg->getSourceRange().getBegin(),
1292 diag::err_template_arg_too_large)
1293 << Value.toString(10) << Param->getType()
1294 << Arg->getSourceRange();
1295 Diag(Param->getLocation(), diag::note_template_param_here);
1296 return true;
1297 }
1298
1299 if (Value.getBitWidth() != AllowedBits)
1300 Value.extOrTrunc(AllowedBits);
1301 Value.setIsSigned(IntegerType->isSignedIntegerType());
1302 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001303
1304 if (Converted) {
1305 // Add the value of this argument to the list of converted
1306 // arguments. We use the bitwidth and signedness of the template
1307 // parameter.
Douglas Gregorba498172009-03-13 21:01:28 +00001308 if (Arg->isValueDependent()) {
1309 // The argument is value-dependent. Create a new
1310 // TemplateArgument with the converted expression.
1311 Converted->push_back(TemplateArgument(Arg));
1312 return false;
1313 }
1314
Douglas Gregor5b0f7522009-03-14 00:03:48 +00001315 Converted->push_back(TemplateArgument(StartLoc, Value,
Douglas Gregorc971f862009-03-12 22:20:26 +00001316 Context.getCanonicalType(IntegerType)));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001317 }
1318
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001319 return false;
1320 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001321
Douglas Gregorb86b0572009-02-11 01:18:59 +00001322 // Handle pointer-to-function, reference-to-function, and
1323 // pointer-to-member-function all in (roughly) the same way.
1324 if (// -- For a non-type template-parameter of type pointer to
1325 // function, only the function-to-pointer conversion (4.3) is
1326 // applied. If the template-argument represents a set of
1327 // overloaded functions (or a pointer to such), the matching
1328 // function is selected from the set (13.4).
1329 (ParamType->isPointerType() &&
1330 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1331 // -- For a non-type template-parameter of type reference to
1332 // function, no conversions apply. If the template-argument
1333 // represents a set of overloaded functions, the matching
1334 // function is selected from the set (13.4).
1335 (ParamType->isReferenceType() &&
1336 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1337 // -- For a non-type template-parameter of type pointer to
1338 // member function, no conversions apply. If the
1339 // template-argument represents a set of overloaded member
1340 // functions, the matching member function is selected from
1341 // the set (13.4).
1342 (ParamType->isMemberPointerType() &&
1343 ParamType->getAsMemberPointerType()->getPointeeType()
1344 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001345 if (Context.hasSameUnqualifiedType(ArgType,
1346 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001347 // We don't have to do anything: the types already match.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001348 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001349 ArgType = Context.getPointerType(ArgType);
1350 ImpCastExprToType(Arg, ArgType);
1351 } else if (FunctionDecl *Fn
1352 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001353 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1354 return true;
1355
Douglas Gregora35284b2009-02-11 00:19:33 +00001356 FixOverloadedFunctionReference(Arg, Fn);
1357 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001358 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001359 ArgType = Context.getPointerType(Arg->getType());
1360 ImpCastExprToType(Arg, ArgType);
1361 }
1362 }
1363
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001364 if (!Context.hasSameUnqualifiedType(ArgType,
1365 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001366 // We can't perform this conversion.
1367 Diag(Arg->getSourceRange().getBegin(),
1368 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001369 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001370 Diag(Param->getLocation(), diag::note_template_param_here);
1371 return true;
1372 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001373
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001374 if (ParamType->isMemberPointerType()) {
1375 NamedDecl *Member = 0;
1376 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1377 return true;
1378
1379 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001380 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001381
1382 return false;
1383 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001384
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001385 NamedDecl *Entity = 0;
1386 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1387 return true;
1388
1389 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001390 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001391 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001392 }
1393
Chris Lattnerfe90de72009-02-20 21:37:53 +00001394 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001395 // -- for a non-type template-parameter of type pointer to
1396 // object, qualification conversions (4.4) and the
1397 // array-to-pointer conversion (4.2) are applied.
Chris Lattnerfe90de72009-02-20 21:37:53 +00001398 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001399 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001400
Douglas Gregorb86b0572009-02-11 01:18:59 +00001401 if (ArgType->isArrayType()) {
1402 ArgType = Context.getArrayDecayedType(ArgType);
1403 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001404 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001405
1406 if (IsQualificationConversion(ArgType, ParamType)) {
1407 ArgType = ParamType;
1408 ImpCastExprToType(Arg, ParamType);
1409 }
1410
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001411 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001412 // We can't perform this conversion.
1413 Diag(Arg->getSourceRange().getBegin(),
1414 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001415 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001416 Diag(Param->getLocation(), diag::note_template_param_here);
1417 return true;
1418 }
1419
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001420 NamedDecl *Entity = 0;
1421 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1422 return true;
1423
1424 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001425 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001426
1427 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001428 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001429
1430 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1431 // -- For a non-type template-parameter of type reference to
1432 // object, no conversions apply. The type referred to by the
1433 // reference may be more cv-qualified than the (otherwise
1434 // identical) type of the template-argument. The
1435 // template-parameter is bound directly to the
1436 // template-argument, which must be an lvalue.
1437 assert(ParamRefType->getPointeeType()->isObjectType() &&
1438 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001439
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001440 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001441 Diag(Arg->getSourceRange().getBegin(),
1442 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001443 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001444 << Arg->getSourceRange();
1445 Diag(Param->getLocation(), diag::note_template_param_here);
1446 return true;
1447 }
1448
1449 unsigned ParamQuals
1450 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1451 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1452
1453 if ((ParamQuals | ArgQuals) != ParamQuals) {
1454 Diag(Arg->getSourceRange().getBegin(),
1455 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001456 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001457 << Arg->getSourceRange();
1458 Diag(Param->getLocation(), diag::note_template_param_here);
1459 return true;
1460 }
1461
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001462 NamedDecl *Entity = 0;
1463 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1464 return true;
1465
1466 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001467 Converted->push_back(TemplateArgument(StartLoc, Entity));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001468
1469 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001470 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001471
1472 // -- For a non-type template-parameter of type pointer to data
1473 // member, qualification conversions (4.4) are applied.
1474 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1475
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001476 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001477 // Types match exactly: nothing more to do here.
1478 } else if (IsQualificationConversion(ArgType, ParamType)) {
1479 ImpCastExprToType(Arg, ParamType);
1480 } else {
1481 // We can't perform this conversion.
1482 Diag(Arg->getSourceRange().getBegin(),
1483 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001484 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001485 Diag(Param->getLocation(), diag::note_template_param_here);
1486 return true;
1487 }
1488
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001489 NamedDecl *Member = 0;
1490 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1491 return true;
1492
1493 if (Converted)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001494 Converted->push_back(TemplateArgument(StartLoc, Member));
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001495
1496 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001497}
1498
1499/// \brief Check a template argument against its corresponding
1500/// template template parameter.
1501///
1502/// This routine implements the semantics of C++ [temp.arg.template].
1503/// It returns true if an error occurred, and false otherwise.
1504bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1505 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001506 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1507 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1508
1509 // C++ [temp.arg.template]p1:
1510 // A template-argument for a template template-parameter shall be
1511 // the name of a class template, expressed as id-expression. Only
1512 // primary class templates are considered when matching the
1513 // template template argument with the corresponding parameter;
1514 // partial specializations are not considered even if their
1515 // parameter lists match that of the template template parameter.
1516 if (!isa<ClassTemplateDecl>(Template)) {
1517 assert(isa<FunctionTemplateDecl>(Template) &&
1518 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001519 Diag(Arg->getSourceRange().getBegin(),
1520 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001521 << Template;
1522 }
1523
1524 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1525 Param->getTemplateParameters(),
1526 true, true,
1527 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001528}
1529
Douglas Gregorddc29e12009-02-06 22:42:48 +00001530/// \brief Determine whether the given template parameter lists are
1531/// equivalent.
1532///
1533/// \param New The new template parameter list, typically written in the
1534/// source code as part of a new template declaration.
1535///
1536/// \param Old The old template parameter list, typically found via
1537/// name lookup of the template declared with this template parameter
1538/// list.
1539///
1540/// \param Complain If true, this routine will produce a diagnostic if
1541/// the template parameter lists are not equivalent.
1542///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001543/// \param IsTemplateTemplateParm If true, this routine is being
1544/// called to compare the template parameter lists of a template
1545/// template parameter.
1546///
1547/// \param TemplateArgLoc If this source location is valid, then we
1548/// are actually checking the template parameter list of a template
1549/// argument (New) against the template parameter list of its
1550/// corresponding template template parameter (Old). We produce
1551/// slightly different diagnostics in this scenario.
1552///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001553/// \returns True if the template parameter lists are equal, false
1554/// otherwise.
1555bool
1556Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1557 TemplateParameterList *Old,
1558 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001559 bool IsTemplateTemplateParm,
1560 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001561 if (Old->size() != New->size()) {
1562 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001563 unsigned NextDiag = diag::err_template_param_list_different_arity;
1564 if (TemplateArgLoc.isValid()) {
1565 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1566 NextDiag = diag::note_template_param_list_different_arity;
1567 }
1568 Diag(New->getTemplateLoc(), NextDiag)
1569 << (New->size() > Old->size())
1570 << IsTemplateTemplateParm
1571 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001572 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1573 << IsTemplateTemplateParm
1574 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1575 }
1576
1577 return false;
1578 }
1579
1580 for (TemplateParameterList::iterator OldParm = Old->begin(),
1581 OldParmEnd = Old->end(), NewParm = New->begin();
1582 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1583 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001584 unsigned NextDiag = diag::err_template_param_different_kind;
1585 if (TemplateArgLoc.isValid()) {
1586 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1587 NextDiag = diag::note_template_param_different_kind;
1588 }
1589 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001590 << IsTemplateTemplateParm;
1591 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1592 << IsTemplateTemplateParm;
1593 return false;
1594 }
1595
1596 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1597 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001598 // know we're at the same index).
1599#if 0
1600 // FIXME: Enable this code in debug mode *after* we properly go
1601 // through and "instantiate" the template parameter lists of
1602 // template template parameters. It's only after this
1603 // instantiation that (1) any dependent types within the
1604 // template parameter list of the template template parameter
1605 // can be checked, and (2) the template type parameter depths
1606 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001607 QualType OldParmType
1608 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1609 QualType NewParmType
1610 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1611 assert(Context.getCanonicalType(OldParmType) ==
1612 Context.getCanonicalType(NewParmType) &&
1613 "type parameter mismatch?");
1614#endif
1615 } else if (NonTypeTemplateParmDecl *OldNTTP
1616 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1617 // The types of non-type template parameters must agree.
1618 NonTypeTemplateParmDecl *NewNTTP
1619 = cast<NonTypeTemplateParmDecl>(*NewParm);
1620 if (Context.getCanonicalType(OldNTTP->getType()) !=
1621 Context.getCanonicalType(NewNTTP->getType())) {
1622 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001623 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1624 if (TemplateArgLoc.isValid()) {
1625 Diag(TemplateArgLoc,
1626 diag::err_template_arg_template_params_mismatch);
1627 NextDiag = diag::note_template_nontype_parm_different_type;
1628 }
1629 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001630 << NewNTTP->getType()
1631 << IsTemplateTemplateParm;
1632 Diag(OldNTTP->getLocation(),
1633 diag::note_template_nontype_parm_prev_declaration)
1634 << OldNTTP->getType();
1635 }
1636 return false;
1637 }
1638 } else {
1639 // The template parameter lists of template template
1640 // parameters must agree.
1641 // FIXME: Could we perform a faster "type" comparison here?
1642 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1643 "Only template template parameters handled here");
1644 TemplateTemplateParmDecl *OldTTP
1645 = cast<TemplateTemplateParmDecl>(*OldParm);
1646 TemplateTemplateParmDecl *NewTTP
1647 = cast<TemplateTemplateParmDecl>(*NewParm);
1648 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1649 OldTTP->getTemplateParameters(),
1650 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001651 /*IsTemplateTemplateParm=*/true,
1652 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001653 return false;
1654 }
1655 }
1656
1657 return true;
1658}
1659
1660/// \brief Check whether a template can be declared within this scope.
1661///
1662/// If the template declaration is valid in this scope, returns
1663/// false. Otherwise, issues a diagnostic and returns true.
1664bool
1665Sema::CheckTemplateDeclScope(Scope *S,
1666 MultiTemplateParamsArg &TemplateParameterLists) {
1667 assert(TemplateParameterLists.size() > 0 && "Not a template");
1668
1669 // Find the nearest enclosing declaration scope.
1670 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1671 (S->getFlags() & Scope::TemplateParamScope) != 0)
1672 S = S->getParent();
1673
1674 TemplateParameterList *TemplateParams =
1675 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1676 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1677 SourceRange TemplateRange
1678 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1679
1680 // C++ [temp]p2:
1681 // A template-declaration can appear only as a namespace scope or
1682 // class scope declaration.
1683 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1684 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1685 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1686 return Diag(TemplateLoc, diag::err_template_linkage)
1687 << TemplateRange;
1688
1689 Ctx = Ctx->getParent();
1690 }
1691
1692 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1693 return false;
1694
1695 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1696 << TemplateRange;
1697}
Douglas Gregorcc636682009-02-17 23:15:12 +00001698
Douglas Gregor88b70942009-02-25 22:02:03 +00001699/// \brief Check whether a class template specialization in the
1700/// current context is well-formed.
1701///
1702/// This routine determines whether a class template specialization
1703/// can be declared in the current context (C++ [temp.expl.spec]p2)
1704/// and emits appropriate diagnostics if there was an error. It
1705/// returns true if there was an error that we cannot recover from,
1706/// and false otherwise.
1707bool
1708Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
1709 ClassTemplateSpecializationDecl *PrevDecl,
1710 SourceLocation TemplateNameLoc,
1711 SourceRange ScopeSpecifierRange) {
1712 // C++ [temp.expl.spec]p2:
1713 // An explicit specialization shall be declared in the namespace
1714 // of which the template is a member, or, for member templates, in
1715 // the namespace of which the enclosing class or enclosing class
1716 // template is a member. An explicit specialization of a member
1717 // function, member class or static data member of a class
1718 // template shall be declared in the namespace of which the class
1719 // template is a member. Such a declaration may also be a
1720 // definition. If the declaration is not a definition, the
1721 // specialization may be defined later in the name- space in which
1722 // the explicit specialization was declared, or in a namespace
1723 // that encloses the one in which the explicit specialization was
1724 // declared.
1725 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
1726 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
1727 << ClassTemplate;
1728 return true;
1729 }
1730
1731 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
1732 DeclContext *TemplateContext
1733 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
1734 if (!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1735 // There is no prior declaration of this entity, so this
1736 // specialization must be in the same context as the template
1737 // itself.
1738 if (DC != TemplateContext) {
1739 if (isa<TranslationUnitDecl>(TemplateContext))
1740 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
1741 << ClassTemplate << ScopeSpecifierRange;
1742 else if (isa<NamespaceDecl>(TemplateContext))
1743 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
1744 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1745 << ScopeSpecifierRange;
1746
1747 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1748 }
1749
1750 return false;
1751 }
1752
1753 // We have a previous declaration of this entity. Make sure that
1754 // this redeclaration (or definition) occurs in an enclosing namespace.
1755 if (!CurContext->Encloses(TemplateContext)) {
1756 if (isa<TranslationUnitDecl>(TemplateContext))
1757 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
1758 << ClassTemplate << ScopeSpecifierRange;
1759 else if (isa<NamespaceDecl>(TemplateContext))
1760 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
1761 << ClassTemplate << cast<NamedDecl>(TemplateContext)
1762 << ScopeSpecifierRange;
1763
1764 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
1765 }
1766
1767 return false;
1768}
1769
Douglas Gregorcc636682009-02-17 23:15:12 +00001770Sema::DeclTy *
1771Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
1772 SourceLocation KWLoc,
1773 const CXXScopeSpec &SS,
1774 DeclTy *TemplateD,
1775 SourceLocation TemplateNameLoc,
1776 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001777 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00001778 SourceLocation *TemplateArgLocs,
1779 SourceLocation RAngleLoc,
1780 AttributeList *Attr,
1781 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00001782 // Find the class template we're specializing
1783 ClassTemplateDecl *ClassTemplate
1784 = dyn_cast_or_null<ClassTemplateDecl>(static_cast<Decl *>(TemplateD));
1785 if (!ClassTemplate)
1786 return 0;
1787
Douglas Gregor88b70942009-02-25 22:02:03 +00001788 // Check the validity of the template headers that introduce this
1789 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001790 // FIXME: Once we have member templates, we'll need to check
1791 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
1792 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001793 if (TemplateParameterLists.size() == 0)
1794 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00001795 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001796 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00001797 TemplateParameterList *TemplateParams
1798 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1799 if (TemplateParameterLists.size() > 1) {
1800 Diag(TemplateParams->getTemplateLoc(),
1801 diag::err_template_spec_extra_headers);
1802 return 0;
1803 }
1804
1805 if (TemplateParams->size() > 0) {
1806 // FIXME: No support for class template partial specialization.
1807 Diag(TemplateParams->getTemplateLoc(),
1808 diag::unsup_template_partial_spec);
1809 return 0;
1810 }
1811 }
1812
Douglas Gregorcc636682009-02-17 23:15:12 +00001813 // Check that the specialization uses the same tag kind as the
1814 // original template.
1815 TagDecl::TagKind Kind;
1816 switch (TagSpec) {
1817 default: assert(0 && "Unknown tag type!");
1818 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1819 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1820 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1821 }
1822 if (ClassTemplate->getTemplatedDecl()->getTagKind() != Kind) {
1823 Diag(KWLoc, diag::err_use_with_wrong_tag) << ClassTemplate;
1824 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
1825 diag::note_previous_use);
1826 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
1827 }
1828
Douglas Gregor40808ce2009-03-09 23:48:35 +00001829 // Translate the parser's template argument list in our AST format.
1830 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
1831 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
1832
Douglas Gregorcc636682009-02-17 23:15:12 +00001833 // Check that the template argument list is well-formed for this
1834 // template.
1835 llvm::SmallVector<TemplateArgument, 16> ConvertedTemplateArgs;
1836 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001837 &TemplateArgs[0], TemplateArgs.size(),
1838 RAngleLoc, ConvertedTemplateArgs))
Douglas Gregorcc636682009-02-17 23:15:12 +00001839 return 0;
1840
1841 assert((ConvertedTemplateArgs.size() ==
1842 ClassTemplate->getTemplateParameters()->size()) &&
1843 "Converted template argument list is too short!");
1844
1845 // Find the class template specialization declaration that
1846 // corresponds to these arguments.
1847 llvm::FoldingSetNodeID ID;
1848 ClassTemplateSpecializationDecl::Profile(ID, &ConvertedTemplateArgs[0],
1849 ConvertedTemplateArgs.size());
1850 void *InsertPos = 0;
1851 ClassTemplateSpecializationDecl *PrevDecl
1852 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1853
1854 ClassTemplateSpecializationDecl *Specialization = 0;
1855
Douglas Gregor88b70942009-02-25 22:02:03 +00001856 // Check whether we can declare a class template specialization in
1857 // the current scope.
1858 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
1859 TemplateNameLoc,
1860 SS.getRange()))
1861 return 0;
1862
Douglas Gregorcc636682009-02-17 23:15:12 +00001863 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
1864 // Since the only prior class template specialization with these
1865 // arguments was referenced but not declared, reuse that
1866 // declaration node as our own, updating its source location to
1867 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00001868 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001869 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00001870 PrevDecl = 0;
1871 } else {
1872 // Create a new class template specialization declaration node for
1873 // this explicit specialization.
1874 Specialization
1875 = ClassTemplateSpecializationDecl::Create(Context,
1876 ClassTemplate->getDeclContext(),
1877 TemplateNameLoc,
1878 ClassTemplate,
1879 &ConvertedTemplateArgs[0],
1880 ConvertedTemplateArgs.size(),
1881 PrevDecl);
1882
1883 if (PrevDecl) {
1884 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
1885 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
1886 } else {
1887 ClassTemplate->getSpecializations().InsertNode(Specialization,
1888 InsertPos);
1889 }
1890 }
1891
1892 // Note that this is an explicit specialization.
1893 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
1894
1895 // Check that this isn't a redefinition of this specialization.
1896 if (TK == TK_Definition) {
1897 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
1898 // FIXME: Should also handle explicit specialization after
1899 // implicit instantiation with a special diagnostic.
1900 SourceRange Range(TemplateNameLoc, RAngleLoc);
1901 Diag(TemplateNameLoc, diag::err_redefinition)
1902 << Specialization << Range;
1903 Diag(Def->getLocation(), diag::note_previous_definition);
1904 Specialization->setInvalidDecl();
1905 return 0;
1906 }
1907 }
1908
Douglas Gregorfc705b82009-02-26 22:19:44 +00001909 // Build the fully-sugared type for this class template
1910 // specialization as the user wrote in the specialization
1911 // itself. This means that we'll pretty-print the type retrieved
1912 // from the specialization's declaration the way that the user
1913 // actually wrote the specialization, rather than formatting the
1914 // name based on the "canonical" representation used to store the
1915 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00001916 QualType WrittenTy
1917 = Context.getClassTemplateSpecializationType(ClassTemplate,
1918 &TemplateArgs[0],
1919 TemplateArgs.size(),
1920 Context.getTypeDeclType(Specialization));
1921 Specialization->setTypeAsWritten(getQualifiedNameType(SS, WrittenTy));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001922 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00001923
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00001924 // C++ [temp.expl.spec]p9:
1925 // A template explicit specialization is in the scope of the
1926 // namespace in which the template was defined.
1927 //
1928 // We actually implement this paragraph where we set the semantic
1929 // context (in the creation of the ClassTemplateSpecializationDecl),
1930 // but we also maintain the lexical context where the actual
1931 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00001932 Specialization->setLexicalDeclContext(CurContext);
1933
1934 // We may be starting the definition of this specialization.
1935 if (TK == TK_Definition)
1936 Specialization->startDefinition();
1937
1938 // Add the specialization into its lexical context, so that it can
1939 // be seen when iterating through the list of declarations in that
1940 // context. However, specializations are not found by name lookup.
1941 CurContext->addDecl(Specialization);
1942 return Specialization;
1943}