blob: 26e56733a13ec08ac4cd85dbaf0c9a2e5da079fd [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 Gregorc45c2322009-03-31 00:43:58 +000029TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
Douglas Gregor7532dc62009-03-30 22:58:21 +000030 TemplateTy &TemplateResult,
Douglas Gregor39a8de12009-02-25 19:37:18 +000031 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
Douglas Gregor7532dc62009-03-30 22:58:21 +000034 TemplateNameKind TNK = TNK_Non_template;
35 TemplateDecl *Template = 0;
36
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000037 if (IIDecl) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000038 if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000039 if (isa<FunctionTemplateDecl>(IIDecl))
Douglas Gregor7532dc62009-03-30 22:58:21 +000040 TNK = TNK_Function_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +000041 else if (isa<ClassTemplateDecl>(IIDecl) ||
42 isa<TemplateTemplateParmDecl>(IIDecl))
43 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000044 else
45 assert(false && "Unknown template declaration kind");
Douglas Gregorbefc20e2009-03-26 00:10:35 +000046 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
47 // C++ [temp.local]p1:
48 // Like normal (non-template) classes, class templates have an
49 // injected-class-name (Clause 9). The injected-class-name
50 // can be used with or without a template-argument-list. When
51 // it is used without a template-argument-list, it is
52 // equivalent to the injected-class-name followed by the
53 // template-parameters of the class template enclosed in
54 // <>. When it is used with a template-argument-list, it
55 // refers to the specified class template specialization,
56 // which could be the current specialization or another
57 // specialization.
58 if (Record->isInjectedClassName()) {
59 Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
Douglas Gregor7532dc62009-03-30 22:58:21 +000060 if ((Template = Record->getDescribedClassTemplate()))
Douglas Gregorc45c2322009-03-31 00:43:58 +000061 TNK = TNK_Type_template;
Douglas Gregor7532dc62009-03-30 22:58:21 +000062 else if (ClassTemplateSpecializationDecl *Spec
Douglas Gregorbefc20e2009-03-26 00:10:35 +000063 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000064 Template = Spec->getSpecializedTemplate();
Douglas Gregorc45c2322009-03-31 00:43:58 +000065 TNK = TNK_Type_template;
Douglas Gregorbefc20e2009-03-26 00:10:35 +000066 }
67 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000068 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000069
Douglas Gregor55f6b142009-02-09 18:46:07 +000070 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000072 if (FD->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000073 TemplateResult = TemplateTy::make(FD);
Douglas Gregor55f6b142009-02-09 18:46:07 +000074 return TNK_Function_template;
75 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000076 } else if (OverloadedFunctionDecl *Ovl
77 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
78 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
79 FEnd = Ovl->function_end();
80 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000081 if ((*F)->getType()->isDependentType()) {
Douglas Gregor7532dc62009-03-30 22:58:21 +000082 TemplateResult = TemplateTy::make(Ovl);
Douglas Gregor55f6b142009-02-09 18:46:07 +000083 return TNK_Function_template;
84 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000085 }
86 }
Douglas Gregor7532dc62009-03-30 22:58:21 +000087
88 if (TNK != TNK_Non_template) {
89 if (SS && SS->isSet() && !SS->isInvalid()) {
90 NestedNameSpecifier *Qualifier
91 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
92 TemplateResult
93 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
94 false,
95 Template));
96 } else
97 TemplateResult = TemplateTy::make(TemplateName(Template));
98 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000099 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000100 return TNK;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000101}
102
Douglas Gregor72c3f312008-12-05 18:15:24 +0000103/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
104/// that the template parameter 'PrevDecl' is being shadowed by a new
105/// declaration at location Loc. Returns true to indicate that this is
106/// an error, and false otherwise.
107bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000108 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000109
110 // Microsoft Visual C++ permits template parameters to be shadowed.
111 if (getLangOptions().Microsoft)
112 return false;
113
114 // C++ [temp.local]p4:
115 // A template-parameter shall not be redeclared within its
116 // scope (including nested scopes).
117 Diag(Loc, diag::err_template_param_shadow)
118 << cast<NamedDecl>(PrevDecl)->getDeclName();
119 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
120 return true;
121}
122
Douglas Gregor2943aed2009-03-03 04:44:36 +0000123/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000124/// the parameter D to reference the templated declaration and return a pointer
125/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000126TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
127 if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
128 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000129 return Temp;
130 }
131 return 0;
132}
133
Douglas Gregor72c3f312008-12-05 18:15:24 +0000134/// ActOnTypeParameter - Called when a C++ template type parameter
135/// (e.g., "typename T") has been parsed. Typename specifies whether
136/// the keyword "typename" was used to declare the type parameter
137/// (otherwise, "class" was used), and KeyLoc is the location of the
138/// "class" or "typename" keyword. ParamName is the name of the
139/// parameter (NULL indicates an unnamed template parameter) and
140/// ParamName is the location of the parameter name (if any).
141/// If the type parameter has a default argument, it will be added
142/// later via ActOnTypeParameterDefault.
Anders Carlsson941df7d2009-06-12 19:58:00 +0000143Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
144 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000145 SourceLocation KeyLoc,
146 IdentifierInfo *ParamName,
147 SourceLocation ParamNameLoc,
148 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000149 assert(S->isTemplateParamScope() &&
150 "Template type parameter not in template parameter scope!");
151 bool Invalid = false;
152
153 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000154 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000155 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000156 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
157 PrevDecl);
158 }
159
Douglas Gregorddc29e12009-02-06 22:42:48 +0000160 SourceLocation Loc = ParamNameLoc;
161 if (!ParamName)
162 Loc = KeyLoc;
163
Douglas Gregor72c3f312008-12-05 18:15:24 +0000164 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000165 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000166 Depth, Position, ParamName, Typename,
167 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000168 if (Invalid)
169 Param->setInvalidDecl();
170
171 if (ParamName) {
172 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000173 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000174 IdResolver.AddDecl(Param);
175 }
176
Chris Lattnerb28317a2009-03-28 19:18:32 +0000177 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000178}
179
Douglas Gregord684b002009-02-10 19:49:53 +0000180/// ActOnTypeParameterDefault - Adds a default argument (the type
181/// Default) to the given template type parameter (TypeParam).
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000183 SourceLocation EqualLoc,
184 SourceLocation DefaultLoc,
185 TypeTy *DefaultT) {
186 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000187 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000188 QualType Default = QualType::getFromOpaquePtr(DefaultT);
189
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000190 // C++0x [temp.param]p9:
191 // A default template-argument may be specified for any kind of
192 // template-parameter that is not a template parameter pack.
193 if (Parm->isParameterPack()) {
194 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000195 return;
196 }
197
Douglas Gregord684b002009-02-10 19:49:53 +0000198 // C++ [temp.param]p14:
199 // A template-parameter shall not be used in its own default argument.
200 // FIXME: Implement this check! Needs a recursive walk over the types.
201
202 // Check the template argument itself.
203 if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
204 Parm->setInvalidDecl();
205 return;
206 }
207
208 Parm->setDefaultArgument(Default, DefaultLoc, false);
209}
210
Douglas Gregor2943aed2009-03-03 04:44:36 +0000211/// \brief Check that the type of a non-type template parameter is
212/// well-formed.
213///
214/// \returns the (possibly-promoted) parameter type if valid;
215/// otherwise, produces a diagnostic and returns a NULL type.
216QualType
217Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
218 // C++ [temp.param]p4:
219 //
220 // A non-type template-parameter shall have one of the following
221 // (optionally cv-qualified) types:
222 //
223 // -- integral or enumeration type,
224 if (T->isIntegralType() || T->isEnumeralType() ||
225 // -- pointer to object or pointer to function,
226 (T->isPointerType() &&
227 (T->getAsPointerType()->getPointeeType()->isObjectType() ||
228 T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
229 // -- reference to object or reference to function,
230 T->isReferenceType() ||
231 // -- pointer to member.
232 T->isMemberPointerType() ||
233 // If T is a dependent type, we can't do the check now, so we
234 // assume that it is well-formed.
235 T->isDependentType())
236 return T;
237 // C++ [temp.param]p8:
238 //
239 // A non-type template-parameter of type "array of T" or
240 // "function returning T" is adjusted to be of type "pointer to
241 // T" or "pointer to function returning T", respectively.
242 else if (T->isArrayType())
243 // FIXME: Keep the type prior to promotion?
244 return Context.getArrayDecayedType(T);
245 else if (T->isFunctionType())
246 // FIXME: Keep the type prior to promotion?
247 return Context.getPointerType(T);
248
249 Diag(Loc, diag::err_template_nontype_parm_bad_type)
250 << T;
251
252 return QualType();
253}
254
Douglas Gregor72c3f312008-12-05 18:15:24 +0000255/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
256/// template parameter (e.g., "int Size" in "template<int Size>
257/// class Array") has been parsed. S is the current scope and D is
258/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000259Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
260 unsigned Depth,
261 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000262 QualType T = GetTypeForDeclarator(D, S);
263
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000264 assert(S->isTemplateParamScope() &&
265 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000266 bool Invalid = false;
267
268 IdentifierInfo *ParamName = D.getIdentifier();
269 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000270 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000271 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000272 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000273 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000274 }
275
Douglas Gregor2943aed2009-03-03 04:44:36 +0000276 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000277 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000278 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000279 Invalid = true;
280 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000281
Douglas Gregor72c3f312008-12-05 18:15:24 +0000282 NonTypeTemplateParmDecl *Param
283 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000284 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000285 if (Invalid)
286 Param->setInvalidDecl();
287
288 if (D.getIdentifier()) {
289 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000290 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000291 IdResolver.AddDecl(Param);
292 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000293 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000294}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000295
Douglas Gregord684b002009-02-10 19:49:53 +0000296/// \brief Adds a default argument to the given non-type template
297/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000298void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000299 SourceLocation EqualLoc,
300 ExprArg DefaultE) {
301 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000302 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000303 Expr *Default = static_cast<Expr *>(DefaultE.get());
304
305 // C++ [temp.param]p14:
306 // A template-parameter shall not be used in its own default argument.
307 // FIXME: Implement this check! Needs a recursive walk over the types.
308
309 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000310 TemplateArgument Converted;
311 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
312 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000313 TemplateParm->setInvalidDecl();
314 return;
315 }
316
Anders Carlssone9146f22009-05-01 19:49:17 +0000317 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000318}
319
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000320
321/// ActOnTemplateTemplateParameter - Called when a C++ template template
322/// parameter (e.g. T in template <template <typename> class T> class array)
323/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000324Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
325 SourceLocation TmpLoc,
326 TemplateParamsTy *Params,
327 IdentifierInfo *Name,
328 SourceLocation NameLoc,
329 unsigned Depth,
330 unsigned Position)
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000331{
332 assert(S->isTemplateParamScope() &&
333 "Template template parameter not in template parameter scope!");
334
335 // Construct the parameter object.
336 TemplateTemplateParmDecl *Param =
337 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
338 Position, Name,
339 (TemplateParameterList*)Params);
340
341 // Make sure the parameter is valid.
342 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
343 // do anything yet. However, if the template parameter list or (eventual)
344 // default value is ever invalidated, that will propagate here.
345 bool Invalid = false;
346 if (Invalid) {
347 Param->setInvalidDecl();
348 }
349
350 // If the tt-param has a name, then link the identifier into the scope
351 // and lookup mechanisms.
352 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000353 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000354 IdResolver.AddDecl(Param);
355 }
356
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000358}
359
Douglas Gregord684b002009-02-10 19:49:53 +0000360/// \brief Adds a default argument to the given template template
361/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000362void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000363 SourceLocation EqualLoc,
364 ExprArg DefaultE) {
365 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000367
368 // Since a template-template parameter's default argument is an
369 // id-expression, it must be a DeclRefExpr.
370 DeclRefExpr *Default
371 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
372
373 // C++ [temp.param]p14:
374 // A template-parameter shall not be used in its own default argument.
375 // FIXME: Implement this check! Needs a recursive walk over the types.
376
377 // Check the well-formedness of the template argument.
378 if (!isa<TemplateDecl>(Default->getDecl())) {
379 Diag(Default->getSourceRange().getBegin(),
380 diag::err_template_arg_must_be_template)
381 << Default->getSourceRange();
382 TemplateParm->setInvalidDecl();
383 return;
384 }
385 if (CheckTemplateArgument(TemplateParm, Default)) {
386 TemplateParm->setInvalidDecl();
387 return;
388 }
389
390 DefaultE.release();
391 TemplateParm->setDefaultArgument(Default);
392}
393
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000394/// ActOnTemplateParameterList - Builds a TemplateParameterList that
395/// contains the template parameters in Params/NumParams.
396Sema::TemplateParamsTy *
397Sema::ActOnTemplateParameterList(unsigned Depth,
398 SourceLocation ExportLoc,
399 SourceLocation TemplateLoc,
400 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000401 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000402 SourceLocation RAngleLoc) {
403 if (ExportLoc.isValid())
404 Diag(ExportLoc, diag::note_template_export_unsupported);
405
Douglas Gregorddc29e12009-02-06 22:42:48 +0000406 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
407 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000408}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000409
Douglas Gregor212e81c2009-03-25 00:13:59 +0000410Sema::DeclResult
Douglas Gregorddc29e12009-02-06 22:42:48 +0000411Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
412 SourceLocation KWLoc, const CXXScopeSpec &SS,
413 IdentifierInfo *Name, SourceLocation NameLoc,
414 AttributeList *Attr,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000415 MultiTemplateParamsArg TemplateParameterLists,
416 AccessSpecifier AS) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000417 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
418 assert(TK != TK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000419 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000420
421 // Check that we can declare a template here.
422 if (CheckTemplateDeclScope(S, TemplateParameterLists))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000423 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000424
425 TagDecl::TagKind Kind;
426 switch (TagSpec) {
427 default: assert(0 && "Unknown tag type!");
428 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
429 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
430 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
431 }
432
433 // There is no such thing as an unnamed class template.
434 if (!Name) {
435 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000436 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000437 }
438
439 // Find any previous declaration with this name.
440 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
441 true);
442 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
443 NamedDecl *PrevDecl = 0;
444 if (Previous.begin() != Previous.end())
445 PrevDecl = *Previous.begin();
446
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000447 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
448 PrevDecl = 0;
449
Douglas Gregorddc29e12009-02-06 22:42:48 +0000450 DeclContext *SemanticContext = CurContext;
451 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000452 SemanticContext = computeDeclContext(SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000453
Mike Stump390b4cc2009-05-16 07:39:55 +0000454 // FIXME: need to match up several levels of template parameter lists here.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000455 }
456
457 // FIXME: member templates!
458 TemplateParameterList *TemplateParams
459 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
460
461 // If there is a previous declaration with the same name, check
462 // whether this is a valid redeclaration.
463 ClassTemplateDecl *PrevClassTemplate
464 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
465 if (PrevClassTemplate) {
466 // Ensure that the template parameter lists are compatible.
467 if (!TemplateParameterListsAreEqual(TemplateParams,
468 PrevClassTemplate->getTemplateParameters(),
469 /*Complain=*/true))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000470 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000471
472 // C++ [temp.class]p4:
473 // In a redeclaration, partial specialization, explicit
474 // specialization or explicit instantiation of a class template,
475 // the class-key shall agree in kind with the original class
476 // template declaration (7.1.5.3).
477 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000478 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Douglas Gregora3a83512009-04-01 23:51:29 +0000479 Diag(KWLoc, diag::err_use_with_wrong_tag)
480 << Name
481 << CodeModificationHint::CreateReplacement(KWLoc,
482 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000483 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000484 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000485 }
486
Douglas Gregorddc29e12009-02-06 22:42:48 +0000487 // Check for redefinition of this class template.
488 if (TK == TK_Definition) {
489 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
490 Diag(NameLoc, diag::err_redefinition) << Name;
491 Diag(Def->getLocation(), diag::note_previous_definition);
492 // FIXME: Would it make sense to try to "forget" the previous
493 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000494 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000495 }
496 }
497 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
498 // Maybe we will complain about the shadowed template parameter.
499 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
500 // Just pretend that we didn't see the previous declaration.
501 PrevDecl = 0;
502 } else if (PrevDecl) {
503 // C++ [temp]p5:
504 // A class template shall not have the same name as any other
505 // template, class, function, object, enumeration, enumerator,
506 // namespace, or type in the same scope (3.3), except as specified
507 // in (14.5.4).
508 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
509 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000510 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000511 }
512
Douglas Gregord684b002009-02-10 19:49:53 +0000513 // Check the template parameter list of this declaration, possibly
514 // merging in the template parameter list from the previous class
515 // template declaration.
516 if (CheckTemplateParameterList(TemplateParams,
517 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
518 Invalid = true;
519
Douglas Gregor7da97d02009-05-10 22:57:19 +0000520 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000521 // declaration!
522
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000523 CXXRecordDecl *NewClass =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000524 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
525 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000526 PrevClassTemplate->getTemplatedDecl() : 0,
527 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000528
529 ClassTemplateDecl *NewTemplate
530 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
531 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000532 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000533 NewClass->setDescribedClassTemplate(NewTemplate);
534
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000535 // Build the type for the class template declaration now.
536 QualType T =
537 Context.getTypeDeclType(NewClass,
538 PrevClassTemplate?
539 PrevClassTemplate->getTemplatedDecl() : 0);
540 assert(T->isDependentType() && "Class template type is not dependent?");
541 (void)T;
542
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000543 // Set the access specifier.
544 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
545
Douglas Gregorddc29e12009-02-06 22:42:48 +0000546 // Set the lexical context of these templates
547 NewClass->setLexicalDeclContext(CurContext);
548 NewTemplate->setLexicalDeclContext(CurContext);
549
550 if (TK == TK_Definition)
551 NewClass->startDefinition();
552
553 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000554 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000555
556 PushOnScopeChains(NewTemplate, S);
557
Douglas Gregord684b002009-02-10 19:49:53 +0000558 if (Invalid) {
559 NewTemplate->setInvalidDecl();
560 NewClass->setInvalidDecl();
561 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000562 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000563}
564
Douglas Gregord684b002009-02-10 19:49:53 +0000565/// \brief Checks the validity of a template parameter list, possibly
566/// considering the template parameter list from a previous
567/// declaration.
568///
569/// If an "old" template parameter list is provided, it must be
570/// equivalent (per TemplateParameterListsAreEqual) to the "new"
571/// template parameter list.
572///
573/// \param NewParams Template parameter list for a new template
574/// declaration. This template parameter list will be updated with any
575/// default arguments that are carried through from the previous
576/// template parameter list.
577///
578/// \param OldParams If provided, template parameter list from a
579/// previous declaration of the same template. Default template
580/// arguments will be merged from the old template parameter list to
581/// the new template parameter list.
582///
583/// \returns true if an error occurred, false otherwise.
584bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
585 TemplateParameterList *OldParams) {
586 bool Invalid = false;
587
588 // C++ [temp.param]p10:
589 // The set of default template-arguments available for use with a
590 // template declaration or definition is obtained by merging the
591 // default arguments from the definition (if in scope) and all
592 // declarations in scope in the same way default function
593 // arguments are (8.3.6).
594 bool SawDefaultArgument = false;
595 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000596
Anders Carlsson49d25572009-06-12 23:20:15 +0000597 bool SawParameterPack = false;
598 SourceLocation ParameterPackLoc;
599
Mike Stump1a35fde2009-02-11 23:03:27 +0000600 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +0000601 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +0000602 if (OldParams)
603 OldParam = OldParams->begin();
604
605 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
606 NewParamEnd = NewParams->end();
607 NewParam != NewParamEnd; ++NewParam) {
608 // Variables used to diagnose redundant default arguments
609 bool RedundantDefaultArg = false;
610 SourceLocation OldDefaultLoc;
611 SourceLocation NewDefaultLoc;
612
613 // Variables used to diagnose missing default arguments
614 bool MissingDefaultArg = false;
615
Anders Carlsson49d25572009-06-12 23:20:15 +0000616 // C++0x [temp.param]p11:
617 // If a template parameter of a class template is a template parameter pack,
618 // it must be the last template parameter.
619 if (SawParameterPack) {
620 Diag(ParameterPackLoc,
621 diag::err_template_param_pack_must_be_last_template_parameter);
622 Invalid = true;
623 }
624
Douglas Gregord684b002009-02-10 19:49:53 +0000625 // Merge default arguments for template type parameters.
626 if (TemplateTypeParmDecl *NewTypeParm
627 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
628 TemplateTypeParmDecl *OldTypeParm
629 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
630
Anders Carlsson49d25572009-06-12 23:20:15 +0000631 if (NewTypeParm->isParameterPack()) {
632 assert(!NewTypeParm->hasDefaultArgument() &&
633 "Parameter packs can't have a default argument!");
634 SawParameterPack = true;
635 ParameterPackLoc = NewTypeParm->getLocation();
636 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +0000637 NewTypeParm->hasDefaultArgument()) {
638 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
639 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
640 SawDefaultArgument = true;
641 RedundantDefaultArg = true;
642 PreviousDefaultArgLoc = NewDefaultLoc;
643 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
644 // Merge the default argument from the old declaration to the
645 // new declaration.
646 SawDefaultArgument = true;
647 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
648 OldTypeParm->getDefaultArgumentLoc(),
649 true);
650 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
651 } else if (NewTypeParm->hasDefaultArgument()) {
652 SawDefaultArgument = true;
653 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
654 } else if (SawDefaultArgument)
655 MissingDefaultArg = true;
656 }
657 // Merge default arguments for non-type template parameters
658 else if (NonTypeTemplateParmDecl *NewNonTypeParm
659 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
660 NonTypeTemplateParmDecl *OldNonTypeParm
661 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
662 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
663 NewNonTypeParm->hasDefaultArgument()) {
664 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
665 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
666 SawDefaultArgument = true;
667 RedundantDefaultArg = true;
668 PreviousDefaultArgLoc = NewDefaultLoc;
669 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
670 // Merge the default argument from the old declaration to the
671 // new declaration.
672 SawDefaultArgument = true;
673 // FIXME: We need to create a new kind of "default argument"
674 // expression that points to a previous template template
675 // parameter.
676 NewNonTypeParm->setDefaultArgument(
677 OldNonTypeParm->getDefaultArgument());
678 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
679 } else if (NewNonTypeParm->hasDefaultArgument()) {
680 SawDefaultArgument = true;
681 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
682 } else if (SawDefaultArgument)
683 MissingDefaultArg = true;
684 }
685 // Merge default arguments for template template parameters
686 else {
687 TemplateTemplateParmDecl *NewTemplateParm
688 = cast<TemplateTemplateParmDecl>(*NewParam);
689 TemplateTemplateParmDecl *OldTemplateParm
690 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
691 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
692 NewTemplateParm->hasDefaultArgument()) {
693 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
694 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
695 SawDefaultArgument = true;
696 RedundantDefaultArg = true;
697 PreviousDefaultArgLoc = NewDefaultLoc;
698 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
699 // Merge the default argument from the old declaration to the
700 // new declaration.
701 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +0000702 // FIXME: We need to create a new kind of "default argument" expression
703 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +0000704 NewTemplateParm->setDefaultArgument(
705 OldTemplateParm->getDefaultArgument());
706 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
707 } else if (NewTemplateParm->hasDefaultArgument()) {
708 SawDefaultArgument = true;
709 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
710 } else if (SawDefaultArgument)
711 MissingDefaultArg = true;
712 }
713
714 if (RedundantDefaultArg) {
715 // C++ [temp.param]p12:
716 // A template-parameter shall not be given default arguments
717 // by two different declarations in the same scope.
718 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
719 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
720 Invalid = true;
721 } else if (MissingDefaultArg) {
722 // C++ [temp.param]p11:
723 // If a template-parameter has a default template-argument,
724 // all subsequent template-parameters shall have a default
725 // template-argument supplied.
726 Diag((*NewParam)->getLocation(),
727 diag::err_template_param_default_arg_missing);
728 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
729 Invalid = true;
730 }
731
732 // If we have an old template parameter list that we're merging
733 // in, move on to the next parameter.
734 if (OldParams)
735 ++OldParam;
736 }
737
738 return Invalid;
739}
Douglas Gregorc15cb382009-02-09 23:23:08 +0000740
Douglas Gregor40808ce2009-03-09 23:48:35 +0000741/// \brief Translates template arguments as provided by the parser
742/// into template arguments used by semantic analysis.
743static void
744translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
745 SourceLocation *TemplateArgLocs,
746 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
747 TemplateArgs.reserve(TemplateArgsIn.size());
748
749 void **Args = TemplateArgsIn.getArgs();
750 bool *ArgIsType = TemplateArgsIn.getArgIsType();
751 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
752 TemplateArgs.push_back(
753 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
754 QualType::getFromOpaquePtr(Args[Arg]))
755 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
756 }
757}
758
Douglas Gregorc45c2322009-03-31 00:43:58 +0000759/// \brief Build a canonical version of a template argument list.
760///
761/// This function builds a canonical version of the given template
762/// argument list, where each of the template arguments has been
763/// converted into its canonical form. This routine is typically used
764/// to canonicalize a template argument list when the template name
765/// itself is dependent. When the template name refers to an actual
766/// template declaration, Sema::CheckTemplateArgumentList should be
767/// used to check and canonicalize the template arguments.
768///
769/// \param TemplateArgs The incoming template arguments.
770///
771/// \param NumTemplateArgs The number of template arguments in \p
772/// TemplateArgs.
773///
774/// \param Canonical A vector to be filled with the canonical versions
775/// of the template arguments.
776///
777/// \param Context The ASTContext in which the template arguments live.
778static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
779 unsigned NumTemplateArgs,
780 llvm::SmallVectorImpl<TemplateArgument> &Canonical,
781 ASTContext &Context) {
782 Canonical.reserve(NumTemplateArgs);
783 for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
784 switch (TemplateArgs[Idx].getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000785 case TemplateArgument::Null:
786 assert(false && "Should never see a NULL template argument here");
787 break;
788
Douglas Gregorc45c2322009-03-31 00:43:58 +0000789 case TemplateArgument::Expression:
790 // FIXME: Build canonical expression (!)
791 Canonical.push_back(TemplateArgs[Idx]);
792 break;
793
794 case TemplateArgument::Declaration:
Douglas Gregor7da97d02009-05-10 22:57:19 +0000795 Canonical.push_back(
796 TemplateArgument(SourceLocation(),
797 Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
Douglas Gregorc45c2322009-03-31 00:43:58 +0000798 break;
799
800 case TemplateArgument::Integral:
801 Canonical.push_back(TemplateArgument(SourceLocation(),
802 *TemplateArgs[Idx].getAsIntegral(),
803 TemplateArgs[Idx].getIntegralType()));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000804 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000805
806 case TemplateArgument::Type: {
807 QualType CanonType
808 = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
809 Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000810 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000811 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000812
813 case TemplateArgument::Pack:
814 assert(0 && "FIXME: Implement!");
815 break;
Douglas Gregorc45c2322009-03-31 00:43:58 +0000816 }
817 }
818}
819
Douglas Gregor7532dc62009-03-30 22:58:21 +0000820QualType Sema::CheckTemplateIdType(TemplateName Name,
821 SourceLocation TemplateLoc,
822 SourceLocation LAngleLoc,
823 const TemplateArgument *TemplateArgs,
824 unsigned NumTemplateArgs,
825 SourceLocation RAngleLoc) {
826 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +0000827 if (!Template) {
828 // The template name does not resolve to a template, so we just
829 // build a dependent template-id type.
830
831 // Canonicalize the template arguments to build the canonical
832 // template-id type.
833 llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
834 CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
835 CanonicalTemplateArgs, Context);
836
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000837 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000838 QualType CanonType
Douglas Gregor45fbaf02009-05-07 06:49:52 +0000839 = Context.getTemplateSpecializationType(CanonName,
840 &CanonicalTemplateArgs[0],
Douglas Gregorc45c2322009-03-31 00:43:58 +0000841 CanonicalTemplateArgs.size());
842
843 // Build the dependent template-id type.
844 return Context.getTemplateSpecializationType(Name, TemplateArgs,
845 NumTemplateArgs, CanonType);
846 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000847
Douglas Gregor40808ce2009-03-09 23:48:35 +0000848 // Check that the template argument list is well-formed for this
849 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +0000850 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
851 NumTemplateArgs);
Douglas Gregor7532dc62009-03-30 22:58:21 +0000852 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +0000853 TemplateArgs, NumTemplateArgs, RAngleLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +0000854 Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +0000855 return QualType();
856
Anders Carlssonfb250522009-06-23 01:26:57 +0000857 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +0000858 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +0000859 "Converted template argument list is too short!");
860
861 QualType CanonType;
862
Douglas Gregor7532dc62009-03-30 22:58:21 +0000863 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor40808ce2009-03-09 23:48:35 +0000864 TemplateArgs,
865 NumTemplateArgs)) {
866 // This class template specialization is a dependent
867 // type. Therefore, its canonical type is another class template
868 // specialization type that contains all of the converted
869 // arguments in canonical form. This ensures that, e.g., A<T> and
870 // A<T, T> have identical types when A is declared as:
871 //
872 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +0000873 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
874 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +0000875 Converted.getFlatArguments(),
876 Converted.flatSize());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000877 } else if (ClassTemplateDecl *ClassTemplate
878 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000879 // Find the class template specialization declaration that
880 // corresponds to these arguments.
881 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000882 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +0000883 Converted.getFlatArguments(),
884 Converted.flatSize());
Douglas Gregor40808ce2009-03-09 23:48:35 +0000885 void *InsertPos = 0;
886 ClassTemplateSpecializationDecl *Decl
887 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
888 if (!Decl) {
889 // This is the first time we have referenced this class template
890 // specialization. Create the canonical declaration and add it to
891 // the set of specializations.
892 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +0000893 ClassTemplate->getDeclContext(),
894 TemplateLoc,
895 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +0000896 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000897 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
898 Decl->setLexicalDeclContext(CurContext);
899 }
900
901 CanonType = Context.getTypeDeclType(Decl);
902 }
903
904 // Build the fully-sugared type for this class template
905 // specialization, which refers back to the class template
906 // specialization we created or found.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000907 return Context.getTemplateSpecializationType(Name, TemplateArgs,
908 NumTemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000909}
910
Douglas Gregorcc636682009-02-17 23:15:12 +0000911Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +0000912Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
913 SourceLocation LAngleLoc,
914 ASTTemplateArgsPtr TemplateArgsIn,
915 SourceLocation *TemplateArgLocs,
916 SourceLocation RAngleLoc) {
917 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000918
Douglas Gregor40808ce2009-03-09 23:48:35 +0000919 // Translate the parser's template argument list in our AST format.
920 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
921 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000922
Douglas Gregor7532dc62009-03-30 22:58:21 +0000923 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000924 TemplateArgs.data(),
925 TemplateArgs.size(),
Douglas Gregor7532dc62009-03-30 22:58:21 +0000926 RAngleLoc);
Douglas Gregor40808ce2009-03-09 23:48:35 +0000927 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000928
929 if (Result.isNull())
930 return true;
931
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000932 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000933}
934
Douglas Gregorc45c2322009-03-31 00:43:58 +0000935/// \brief Form a dependent template name.
936///
937/// This action forms a dependent template name given the template
938/// name and its (presumably dependent) scope specifier. For
939/// example, given "MetaFun::template apply", the scope specifier \p
940/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
941/// of the "template" keyword, and "apply" is the \p Name.
942Sema::TemplateTy
943Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
944 const IdentifierInfo &Name,
945 SourceLocation NameLoc,
946 const CXXScopeSpec &SS) {
947 if (!SS.isSet() || SS.isInvalid())
948 return TemplateTy();
949
950 NestedNameSpecifier *Qualifier
951 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
952
953 // FIXME: member of the current instantiation
954
955 if (!Qualifier->isDependent()) {
956 // C++0x [temp.names]p5:
957 // If a name prefixed by the keyword template is not the name of
958 // a template, the program is ill-formed. [Note: the keyword
959 // template may not be applied to non-template members of class
960 // templates. -end note ] [ Note: as is the case with the
961 // typename prefix, the template prefix is allowed in cases
962 // where it is not strictly necessary; i.e., when the
963 // nested-name-specifier or the expression on the left of the ->
964 // or . is not dependent on a template-parameter, or the use
965 // does not appear in the scope of a template. -end note]
966 //
967 // Note: C++03 was more strict here, because it banned the use of
968 // the "template" keyword prior to a template-name that was not a
969 // dependent name. C++ DR468 relaxed this requirement (the
970 // "template" keyword is now permitted). We follow the C++0x
971 // rules, even in C++03 mode, retroactively applying the DR.
972 TemplateTy Template;
973 TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
974 if (TNK == TNK_Non_template) {
975 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
976 << &Name;
977 return TemplateTy();
978 }
979
980 return Template;
981 }
982
983 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
984}
985
Anders Carlsson436b1562009-06-13 00:33:33 +0000986bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
987 const TemplateArgument &Arg,
988 TemplateArgumentListBuilder &Converted) {
989 // Check template type parameter.
990 if (Arg.getKind() != TemplateArgument::Type) {
991 // C++ [temp.arg.type]p1:
992 // A template-argument for a template-parameter which is a
993 // type shall be a type-id.
994
995 // We have a template type parameter but the template argument
996 // is not a type.
997 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
998 Diag(Param->getLocation(), diag::note_template_param_here);
999
1000 return true;
1001 }
1002
1003 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
1004 return true;
1005
1006 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001007 Converted.Append(
Anders Carlsson436b1562009-06-13 00:33:33 +00001008 TemplateArgument(Arg.getLocation(),
1009 Context.getCanonicalType(Arg.getAsType())));
1010 return false;
1011}
1012
Douglas Gregorc15cb382009-02-09 23:23:08 +00001013/// \brief Check that the given template argument list is well-formed
1014/// for specializing the given template.
1015bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1016 SourceLocation TemplateLoc,
1017 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00001018 const TemplateArgument *TemplateArgs,
1019 unsigned NumTemplateArgs,
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001020 SourceLocation RAngleLoc,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001021 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001022 TemplateParameterList *Params = Template->getTemplateParameters();
1023 unsigned NumParams = Params->size();
Douglas Gregor40808ce2009-03-09 23:48:35 +00001024 unsigned NumArgs = NumTemplateArgs;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001025 bool Invalid = false;
1026
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001027 bool HasParameterPack =
1028 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
1029
1030 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001031 NumArgs < Params->getMinRequiredArguments()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001032 // FIXME: point at either the first arg beyond what we can handle,
1033 // or the '>', depending on whether we have too many or too few
1034 // arguments.
1035 SourceRange Range;
1036 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00001037 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001038 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1039 << (NumArgs > NumParams)
1040 << (isa<ClassTemplateDecl>(Template)? 0 :
1041 isa<FunctionTemplateDecl>(Template)? 1 :
1042 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1043 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00001044 Diag(Template->getLocation(), diag::note_template_decl_here)
1045 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001046 Invalid = true;
1047 }
1048
1049 // C++ [temp.arg]p1:
1050 // [...] The type and form of each template-argument specified in
1051 // a template-id shall match the type and form specified for the
1052 // corresponding parameter declared by the template in its
1053 // template-parameter-list.
1054 unsigned ArgIdx = 0;
1055 for (TemplateParameterList::iterator Param = Params->begin(),
1056 ParamEnd = Params->end();
1057 Param != ParamEnd; ++Param, ++ArgIdx) {
1058 // Decode the template argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001059 TemplateArgument Arg;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001060 if (ArgIdx >= NumArgs) {
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001061 // Retrieve the default template argument from the template
1062 // parameter.
1063 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001064 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001065 // We have an empty argument pack.
1066 Converted.BeginPack();
1067 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001068 break;
1069 }
1070
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001071 if (!TTP->hasDefaultArgument())
1072 break;
1073
Douglas Gregor40808ce2009-03-09 23:48:35 +00001074 QualType ArgType = TTP->getDefaultArgument();
Douglas Gregor99ebf652009-02-27 19:31:52 +00001075
1076 // If the argument type is dependent, instantiate it now based
1077 // on the previously-computed template arguments.
Douglas Gregordf667e72009-03-10 20:44:00 +00001078 if (ArgType->isDependentType()) {
1079 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001080 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001081 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001082 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregor7e063902009-05-11 23:53:27 +00001083
Anders Carlssone9c904b2009-06-05 04:47:51 +00001084 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001085 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001086 ArgType = InstantiateType(ArgType, TemplateArgs,
Douglas Gregor99ebf652009-02-27 19:31:52 +00001087 TTP->getDefaultArgumentLoc(),
1088 TTP->getDeclName());
Douglas Gregordf667e72009-03-10 20:44:00 +00001089 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001090
1091 if (ArgType.isNull())
Douglas Gregorcd281c32009-02-28 00:25:32 +00001092 return true;
Douglas Gregor99ebf652009-02-27 19:31:52 +00001093
Douglas Gregor40808ce2009-03-09 23:48:35 +00001094 Arg = TemplateArgument(TTP->getLocation(), ArgType);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001095 } else if (NonTypeTemplateParmDecl *NTTP
1096 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1097 if (!NTTP->hasDefaultArgument())
1098 break;
1099
Anders Carlsson3b56c002009-06-11 16:06:49 +00001100 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001101 Template, Converted.getFlatArguments(),
Anders Carlsson3b56c002009-06-11 16:06:49 +00001102 Converted.flatSize(),
1103 SourceRange(TemplateLoc, RAngleLoc));
1104
1105 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001106 /*TakeArgs=*/false);
Anders Carlsson3b56c002009-06-11 16:06:49 +00001107
1108 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
1109 TemplateArgs);
1110 if (E.isInvalid())
1111 return true;
1112
1113 Arg = TemplateArgument(E.takeAs<Expr>());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001114 } else {
1115 TemplateTemplateParmDecl *TempParm
1116 = cast<TemplateTemplateParmDecl>(*Param);
1117
1118 if (!TempParm->hasDefaultArgument())
1119 break;
1120
Douglas Gregor2943aed2009-03-03 04:44:36 +00001121 // FIXME: Instantiate default argument
Douglas Gregor40808ce2009-03-09 23:48:35 +00001122 Arg = TemplateArgument(TempParm->getDefaultArgument());
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001123 }
1124 } else {
1125 // Retrieve the template argument produced by the user.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001126 Arg = TemplateArgs[ArgIdx];
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001127 }
1128
Douglas Gregorc15cb382009-02-09 23:23:08 +00001129
1130 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001131 if (TTP->isParameterPack()) {
Anders Carlssonfb250522009-06-23 01:26:57 +00001132 Converted.BeginPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001133 // Check all the remaining arguments (if any).
1134 for (; ArgIdx < NumArgs; ++ArgIdx) {
1135 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1136 Invalid = true;
1137 }
1138
Anders Carlssonfb250522009-06-23 01:26:57 +00001139 Converted.EndPack();
Anders Carlsson0ceffb52009-06-13 02:08:00 +00001140 } else {
1141 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1142 Invalid = true;
1143 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001144 } else if (NonTypeTemplateParmDecl *NTTP
1145 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1146 // Check non-type template parameters.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001147
1148 // Instantiate the type of the non-type template parameter with
1149 // the template arguments we've seen thus far.
1150 QualType NTTPType = NTTP->getType();
1151 if (NTTPType->isDependentType()) {
1152 // Instantiate the type of the non-type template parameter.
Douglas Gregordf667e72009-03-10 20:44:00 +00001153 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlssonfb250522009-06-23 01:26:57 +00001154 Template, Converted.getFlatArguments(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001155 Converted.flatSize(),
Douglas Gregordf667e72009-03-10 20:44:00 +00001156 SourceRange(TemplateLoc, RAngleLoc));
1157
Anders Carlssone9c904b2009-06-05 04:47:51 +00001158 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlssonfb250522009-06-23 01:26:57 +00001159 /*TakeArgs=*/false);
Douglas Gregor7e063902009-05-11 23:53:27 +00001160 NTTPType = InstantiateType(NTTPType, TemplateArgs,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001161 NTTP->getLocation(),
1162 NTTP->getDeclName());
1163 // If that worked, check the non-type template parameter type
1164 // for validity.
1165 if (!NTTPType.isNull())
1166 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1167 NTTP->getLocation());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001168 if (NTTPType.isNull()) {
1169 Invalid = true;
1170 break;
1171 }
1172 }
1173
Douglas Gregor40808ce2009-03-09 23:48:35 +00001174 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001175 case TemplateArgument::Null:
1176 assert(false && "Should never see a NULL template argument here");
1177 break;
1178
Douglas Gregor40808ce2009-03-09 23:48:35 +00001179 case TemplateArgument::Expression: {
1180 Expr *E = Arg.getAsExpr();
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001181 TemplateArgument Result;
1182 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregorc15cb382009-02-09 23:23:08 +00001183 Invalid = true;
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001184 else
Anders Carlssonfb250522009-06-23 01:26:57 +00001185 Converted.Append(Result);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001186 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001187 }
1188
Douglas Gregor40808ce2009-03-09 23:48:35 +00001189 case TemplateArgument::Declaration:
1190 case TemplateArgument::Integral:
1191 // We've already checked this template argument, so just copy
1192 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001193 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001194 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001195
Douglas Gregor40808ce2009-03-09 23:48:35 +00001196 case TemplateArgument::Type:
1197 // We have a non-type template parameter but the template
1198 // argument is a type.
1199
1200 // C++ [temp.arg]p2:
1201 // In a template-argument, an ambiguity between a type-id and
1202 // an expression is resolved to a type-id, regardless of the
1203 // form of the corresponding template-parameter.
1204 //
1205 // We warn specifically about this case, since it can be rather
1206 // confusing for users.
1207 if (Arg.getAsType()->isFunctionType())
1208 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
1209 << Arg.getAsType();
1210 else
1211 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
1212 Diag((*Param)->getLocation(), diag::note_template_param_here);
1213 Invalid = true;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001214 break;
1215
1216 case TemplateArgument::Pack:
1217 assert(0 && "FIXME: Implement!");
1218 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001219 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001220 } else {
1221 // Check template template parameters.
1222 TemplateTemplateParmDecl *TempParm
1223 = cast<TemplateTemplateParmDecl>(*Param);
1224
Douglas Gregor40808ce2009-03-09 23:48:35 +00001225 switch (Arg.getKind()) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001226 case TemplateArgument::Null:
1227 assert(false && "Should never see a NULL template argument here");
1228 break;
1229
Douglas Gregor40808ce2009-03-09 23:48:35 +00001230 case TemplateArgument::Expression: {
1231 Expr *ArgExpr = Arg.getAsExpr();
1232 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1233 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1234 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1235 Invalid = true;
1236
1237 // Add the converted template argument.
Douglas Gregor7da97d02009-05-10 22:57:19 +00001238 Decl *D
1239 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
Anders Carlssonfb250522009-06-23 01:26:57 +00001240 Converted.Append(TemplateArgument(Arg.getLocation(), D));
Douglas Gregor40808ce2009-03-09 23:48:35 +00001241 continue;
1242 }
1243 }
1244 // fall through
1245
1246 case TemplateArgument::Type: {
1247 // We have a template template parameter but the template
1248 // argument does not refer to a template.
1249 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1250 Invalid = true;
1251 break;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001252 }
1253
Douglas Gregor40808ce2009-03-09 23:48:35 +00001254 case TemplateArgument::Declaration:
1255 // We've already checked this template argument, so just copy
1256 // it to the list of converted arguments.
Anders Carlssonfb250522009-06-23 01:26:57 +00001257 Converted.Append(Arg);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001258 break;
1259
1260 case TemplateArgument::Integral:
1261 assert(false && "Integral argument with template template parameter");
1262 break;
Anders Carlssond01b1da2009-06-15 17:04:53 +00001263
1264 case TemplateArgument::Pack:
1265 assert(0 && "FIXME: Implement!");
1266 break;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001267 }
Douglas Gregorc15cb382009-02-09 23:23:08 +00001268 }
1269 }
1270
1271 return Invalid;
1272}
1273
1274/// \brief Check a template argument against its corresponding
1275/// template type parameter.
1276///
1277/// This routine implements the semantics of C++ [temp.arg.type]. It
1278/// returns true if an error occurred, and false otherwise.
1279bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
1280 QualType Arg, SourceLocation ArgLoc) {
1281 // C++ [temp.arg.type]p2:
1282 // A local type, a type with no linkage, an unnamed type or a type
1283 // compounded from any of these types shall not be used as a
1284 // template-argument for a template type-parameter.
1285 //
1286 // FIXME: Perform the recursive and no-linkage type checks.
1287 const TagType *Tag = 0;
1288 if (const EnumType *EnumT = Arg->getAsEnumType())
1289 Tag = EnumT;
1290 else if (const RecordType *RecordT = Arg->getAsRecordType())
1291 Tag = RecordT;
1292 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
1293 return Diag(ArgLoc, diag::err_template_arg_local_type)
1294 << QualType(Tag, 0);
Douglas Gregor98137532009-03-10 18:33:27 +00001295 else if (Tag && !Tag->getDecl()->getDeclName() &&
1296 !Tag->getDecl()->getTypedefForAnonDecl()) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00001297 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
1298 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1299 return true;
1300 }
1301
1302 return false;
1303}
1304
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001305/// \brief Checks whether the given template argument is the address
1306/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001307bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1308 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001309 bool Invalid = false;
1310
1311 // See through any implicit casts we added to fix the type.
1312 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1313 Arg = Cast->getSubExpr();
1314
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001315 // C++0x allows nullptr, and there's no further checking to be done for that.
1316 if (Arg->getType()->isNullPtrType())
1317 return false;
1318
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001319 // C++ [temp.arg.nontype]p1:
1320 //
1321 // A template-argument for a non-type, non-template
1322 // template-parameter shall be one of: [...]
1323 //
1324 // -- the address of an object or function with external
1325 // linkage, including function templates and function
1326 // template-ids but excluding non-static class members,
1327 // expressed as & id-expression where the & is optional if
1328 // the name refers to a function or array, or if the
1329 // corresponding template-parameter is a reference; or
1330 DeclRefExpr *DRE = 0;
1331
1332 // Ignore (and complain about) any excess parentheses.
1333 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1334 if (!Invalid) {
1335 Diag(Arg->getSourceRange().getBegin(),
1336 diag::err_template_arg_extra_parens)
1337 << Arg->getSourceRange();
1338 Invalid = true;
1339 }
1340
1341 Arg = Parens->getSubExpr();
1342 }
1343
1344 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1345 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1346 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1347 } else
1348 DRE = dyn_cast<DeclRefExpr>(Arg);
1349
1350 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
1351 return Diag(Arg->getSourceRange().getBegin(),
1352 diag::err_template_arg_not_object_or_func_form)
1353 << Arg->getSourceRange();
1354
1355 // Cannot refer to non-static data members
1356 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1357 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1358 << Field << Arg->getSourceRange();
1359
1360 // Cannot refer to non-static member functions
1361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1362 if (!Method->isStatic())
1363 return Diag(Arg->getSourceRange().getBegin(),
1364 diag::err_template_arg_method)
1365 << Method << Arg->getSourceRange();
1366
1367 // Functions must have external linkage.
1368 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1369 if (Func->getStorageClass() == FunctionDecl::Static) {
1370 Diag(Arg->getSourceRange().getBegin(),
1371 diag::err_template_arg_function_not_extern)
1372 << Func << Arg->getSourceRange();
1373 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1374 << true;
1375 return true;
1376 }
1377
1378 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001379 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001380 return Invalid;
1381 }
1382
1383 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1384 if (!Var->hasGlobalStorage()) {
1385 Diag(Arg->getSourceRange().getBegin(),
1386 diag::err_template_arg_object_not_extern)
1387 << Var << Arg->getSourceRange();
1388 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1389 << true;
1390 return true;
1391 }
1392
1393 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001394 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001395 return Invalid;
1396 }
1397
1398 // We found something else, but we don't know specifically what it is.
1399 Diag(Arg->getSourceRange().getBegin(),
1400 diag::err_template_arg_not_object_or_func)
1401 << Arg->getSourceRange();
1402 Diag(DRE->getDecl()->getLocation(),
1403 diag::note_template_arg_refers_here);
1404 return true;
1405}
1406
1407/// \brief Checks whether the given template argument is a pointer to
1408/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001409bool
1410Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001411 bool Invalid = false;
1412
1413 // See through any implicit casts we added to fix the type.
1414 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1415 Arg = Cast->getSubExpr();
1416
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001417 // C++0x allows nullptr, and there's no further checking to be done for that.
1418 if (Arg->getType()->isNullPtrType())
1419 return false;
1420
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001421 // C++ [temp.arg.nontype]p1:
1422 //
1423 // A template-argument for a non-type, non-template
1424 // template-parameter shall be one of: [...]
1425 //
1426 // -- a pointer to member expressed as described in 5.3.1.
1427 QualifiedDeclRefExpr *DRE = 0;
1428
1429 // Ignore (and complain about) any excess parentheses.
1430 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1431 if (!Invalid) {
1432 Diag(Arg->getSourceRange().getBegin(),
1433 diag::err_template_arg_extra_parens)
1434 << Arg->getSourceRange();
1435 Invalid = true;
1436 }
1437
1438 Arg = Parens->getSubExpr();
1439 }
1440
1441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
1442 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1443 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
1444
1445 if (!DRE)
1446 return Diag(Arg->getSourceRange().getBegin(),
1447 diag::err_template_arg_not_pointer_to_member_form)
1448 << Arg->getSourceRange();
1449
1450 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1451 assert((isa<FieldDecl>(DRE->getDecl()) ||
1452 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1453 "Only non-static member pointers can make it here");
1454
1455 // Okay: this is the address of a non-static member, and therefore
1456 // a member pointer constant.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001457 Member = DRE->getDecl();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001458 return Invalid;
1459 }
1460
1461 // We found something else, but we don't know specifically what it is.
1462 Diag(Arg->getSourceRange().getBegin(),
1463 diag::err_template_arg_not_pointer_to_member_form)
1464 << Arg->getSourceRange();
1465 Diag(DRE->getDecl()->getLocation(),
1466 diag::note_template_arg_refers_here);
1467 return true;
1468}
1469
Douglas Gregorc15cb382009-02-09 23:23:08 +00001470/// \brief Check a template argument against its corresponding
1471/// non-type template parameter.
1472///
Douglas Gregor2943aed2009-03-03 04:44:36 +00001473/// This routine implements the semantics of C++ [temp.arg.nontype].
1474/// It returns true if an error occurred, and false otherwise. \p
1475/// InstantiatedParamType is the type of the non-type template
1476/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001477///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001478/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00001479bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001481 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001482 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1483
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001484 // If either the parameter has a dependent type or the argument is
1485 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001486 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00001487 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1488 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001489 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001490 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001491 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001492
1493 // C++ [temp.arg.nontype]p5:
1494 // The following conversions are performed on each expression used
1495 // as a non-type template-argument. If a non-type
1496 // template-argument cannot be converted to the type of the
1497 // corresponding template-parameter then the program is
1498 // ill-formed.
1499 //
1500 // -- for a non-type template-parameter of integral or
1501 // enumeration type, integral promotions (4.5) and integral
1502 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001503 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00001504 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001505 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001506 // C++ [temp.arg.nontype]p1:
1507 // A template-argument for a non-type, non-template
1508 // template-parameter shall be one of:
1509 //
1510 // -- an integral constant-expression of integral or enumeration
1511 // type; or
1512 // -- the name of a non-type template-parameter; or
1513 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001514 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001515 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
1516 Diag(Arg->getSourceRange().getBegin(),
1517 diag::err_template_arg_not_integral_or_enumeral)
1518 << ArgType << Arg->getSourceRange();
1519 Diag(Param->getLocation(), diag::note_template_param_here);
1520 return true;
1521 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001522 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001523 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1524 << ArgType << Arg->getSourceRange();
1525 return true;
1526 }
1527
1528 // FIXME: We need some way to more easily get the unqualified form
1529 // of the types without going all the way to the
1530 // canonical type.
1531 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1532 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1533 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1534 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1535
1536 // Try to convert the argument to the parameter's type.
1537 if (ParamType == ArgType) {
1538 // Okay: no conversion necessary
1539 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1540 !ParamType->isEnumeralType()) {
1541 // This is an integral promotion or conversion.
1542 ImpCastExprToType(Arg, ParamType);
1543 } else {
1544 // We can't perform this conversion.
1545 Diag(Arg->getSourceRange().getBegin(),
1546 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001547 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001548 Diag(Param->getLocation(), diag::note_template_param_here);
1549 return true;
1550 }
1551
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001552 QualType IntegerType = Context.getCanonicalType(ParamType);
1553 if (const EnumType *Enum = IntegerType->getAsEnumType())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001554 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00001555
1556 if (!Arg->isValueDependent()) {
1557 // Check that an unsigned parameter does not receive a negative
1558 // value.
1559 if (IntegerType->isUnsignedIntegerType()
1560 && (Value.isSigned() && Value.isNegative())) {
1561 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
1562 << Value.toString(10) << Param->getType()
1563 << Arg->getSourceRange();
1564 Diag(Param->getLocation(), diag::note_template_param_here);
1565 return true;
1566 }
1567
1568 // Check that we don't overflow the template parameter type.
1569 unsigned AllowedBits = Context.getTypeSize(IntegerType);
1570 if (Value.getActiveBits() > AllowedBits) {
1571 Diag(Arg->getSourceRange().getBegin(),
1572 diag::err_template_arg_too_large)
1573 << Value.toString(10) << Param->getType()
1574 << Arg->getSourceRange();
1575 Diag(Param->getLocation(), diag::note_template_param_here);
1576 return true;
1577 }
1578
1579 if (Value.getBitWidth() != AllowedBits)
1580 Value.extOrTrunc(AllowedBits);
1581 Value.setIsSigned(IntegerType->isSignedIntegerType());
1582 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001583
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001584 // Add the value of this argument to the list of converted
1585 // arguments. We use the bitwidth and signedness of the template
1586 // parameter.
1587 if (Arg->isValueDependent()) {
1588 // The argument is value-dependent. Create a new
1589 // TemplateArgument with the converted expression.
1590 Converted = TemplateArgument(Arg);
1591 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001592 }
1593
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001594 Converted = TemplateArgument(StartLoc, Value,
1595 ParamType->isEnumeralType() ? ParamType
1596 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00001597 return false;
1598 }
Douglas Gregora35284b2009-02-11 00:19:33 +00001599
Douglas Gregorb86b0572009-02-11 01:18:59 +00001600 // Handle pointer-to-function, reference-to-function, and
1601 // pointer-to-member-function all in (roughly) the same way.
1602 if (// -- For a non-type template-parameter of type pointer to
1603 // function, only the function-to-pointer conversion (4.3) is
1604 // applied. If the template-argument represents a set of
1605 // overloaded functions (or a pointer to such), the matching
1606 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001607 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001608 (ParamType->isPointerType() &&
1609 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
1610 // -- For a non-type template-parameter of type reference to
1611 // function, no conversions apply. If the template-argument
1612 // represents a set of overloaded functions, the matching
1613 // function is selected from the set (13.4).
1614 (ParamType->isReferenceType() &&
1615 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
1616 // -- For a non-type template-parameter of type pointer to
1617 // member function, no conversions apply. If the
1618 // template-argument represents a set of overloaded member
1619 // functions, the matching member function is selected from
1620 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001621 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00001622 (ParamType->isMemberPointerType() &&
1623 ParamType->getAsMemberPointerType()->getPointeeType()
1624 ->isFunctionType())) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001625 if (Context.hasSameUnqualifiedType(ArgType,
1626 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001627 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001628 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
1629 ParamType->isMemberPointerType())) {
1630 ArgType = ParamType;
1631 ImpCastExprToType(Arg, ParamType);
Douglas Gregorb86b0572009-02-11 01:18:59 +00001632 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001633 ArgType = Context.getPointerType(ArgType);
1634 ImpCastExprToType(Arg, ArgType);
1635 } else if (FunctionDecl *Fn
1636 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001637 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
1638 return true;
1639
Douglas Gregora35284b2009-02-11 00:19:33 +00001640 FixOverloadedFunctionReference(Arg, Fn);
1641 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001642 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001643 ArgType = Context.getPointerType(Arg->getType());
1644 ImpCastExprToType(Arg, ArgType);
1645 }
1646 }
1647
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001648 if (!Context.hasSameUnqualifiedType(ArgType,
1649 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00001650 // We can't perform this conversion.
1651 Diag(Arg->getSourceRange().getBegin(),
1652 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001653 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00001654 Diag(Param->getLocation(), diag::note_template_param_here);
1655 return true;
1656 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001657
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001658 if (ParamType->isMemberPointerType()) {
1659 NamedDecl *Member = 0;
1660 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1661 return true;
1662
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001663 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1664 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001665 return false;
1666 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001667
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001668 NamedDecl *Entity = 0;
1669 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1670 return true;
1671
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001672 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1673 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001674 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00001675 }
1676
Chris Lattnerfe90de72009-02-20 21:37:53 +00001677 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001678 // -- for a non-type template-parameter of type pointer to
1679 // object, qualification conversions (4.4) and the
1680 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001681 // C++0x also allows a value of std::nullptr_t.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001682 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001683 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001684
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001685 if (ArgType->isNullPtrType()) {
1686 ArgType = ParamType;
1687 ImpCastExprToType(Arg, ParamType);
1688 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001689 ArgType = Context.getArrayDecayedType(ArgType);
1690 ImpCastExprToType(Arg, ArgType);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001691 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001692
Douglas Gregorb86b0572009-02-11 01:18:59 +00001693 if (IsQualificationConversion(ArgType, ParamType)) {
1694 ArgType = ParamType;
1695 ImpCastExprToType(Arg, ParamType);
1696 }
1697
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001698 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001699 // We can't perform this conversion.
1700 Diag(Arg->getSourceRange().getBegin(),
1701 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001702 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00001703 Diag(Param->getLocation(), diag::note_template_param_here);
1704 return true;
1705 }
1706
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001707 NamedDecl *Entity = 0;
1708 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1709 return true;
1710
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001711 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
1712 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001713 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001714 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00001715
1716 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
1717 // -- For a non-type template-parameter of type reference to
1718 // object, no conversions apply. The type referred to by the
1719 // reference may be more cv-qualified than the (otherwise
1720 // identical) type of the template-argument. The
1721 // template-parameter is bound directly to the
1722 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00001723 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00001724 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00001725
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001726 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00001727 Diag(Arg->getSourceRange().getBegin(),
1728 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001729 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001730 << Arg->getSourceRange();
1731 Diag(Param->getLocation(), diag::note_template_param_here);
1732 return true;
1733 }
1734
1735 unsigned ParamQuals
1736 = Context.getCanonicalType(ParamType).getCVRQualifiers();
1737 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
1738
1739 if ((ParamQuals | ArgQuals) != ParamQuals) {
1740 Diag(Arg->getSourceRange().getBegin(),
1741 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001742 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00001743 << Arg->getSourceRange();
1744 Diag(Param->getLocation(), diag::note_template_param_here);
1745 return true;
1746 }
1747
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001748 NamedDecl *Entity = 0;
1749 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
1750 return true;
1751
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001752 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
1753 Converted = TemplateArgument(StartLoc, Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001754 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00001755 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00001756
1757 // -- For a non-type template-parameter of type pointer to data
1758 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001759 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00001760 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
1761
Douglas Gregor8e6563b2009-02-11 18:22:40 +00001762 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00001763 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001764 } else if (ArgType->isNullPtrType()) {
1765 ImpCastExprToType(Arg, ParamType);
Douglas Gregor658bbb52009-02-11 16:16:59 +00001766 } else if (IsQualificationConversion(ArgType, ParamType)) {
1767 ImpCastExprToType(Arg, ParamType);
1768 } else {
1769 // We can't perform this conversion.
1770 Diag(Arg->getSourceRange().getBegin(),
1771 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00001772 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00001773 Diag(Param->getLocation(), diag::note_template_param_here);
1774 return true;
1775 }
1776
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001777 NamedDecl *Member = 0;
1778 if (CheckTemplateArgumentPointerToMember(Arg, Member))
1779 return true;
1780
Douglas Gregor02cbbd22009-06-11 18:10:32 +00001781 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
1782 Converted = TemplateArgument(StartLoc, Member);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00001783 return false;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001784}
1785
1786/// \brief Check a template argument against its corresponding
1787/// template template parameter.
1788///
1789/// This routine implements the semantics of C++ [temp.arg.template].
1790/// It returns true if an error occurred, and false otherwise.
1791bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1792 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001793 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1794 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1795
1796 // C++ [temp.arg.template]p1:
1797 // A template-argument for a template template-parameter shall be
1798 // the name of a class template, expressed as id-expression. Only
1799 // primary class templates are considered when matching the
1800 // template template argument with the corresponding parameter;
1801 // partial specializations are not considered even if their
1802 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00001803 //
1804 // Note that we also allow template template parameters here, which
1805 // will happen when we are dealing with, e.g., class template
1806 // partial specializations.
1807 if (!isa<ClassTemplateDecl>(Template) &&
1808 !isa<TemplateTemplateParmDecl>(Template)) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001809 assert(isa<FunctionTemplateDecl>(Template) &&
1810 "Only function templates are possible here");
Douglas Gregorcc45cb32009-02-11 19:52:55 +00001811 Diag(Arg->getSourceRange().getBegin(),
1812 diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00001813 << Template;
1814 }
1815
1816 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1817 Param->getTemplateParameters(),
1818 true, true,
1819 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +00001820}
1821
Douglas Gregorddc29e12009-02-06 22:42:48 +00001822/// \brief Determine whether the given template parameter lists are
1823/// equivalent.
1824///
1825/// \param New The new template parameter list, typically written in the
1826/// source code as part of a new template declaration.
1827///
1828/// \param Old The old template parameter list, typically found via
1829/// name lookup of the template declared with this template parameter
1830/// list.
1831///
1832/// \param Complain If true, this routine will produce a diagnostic if
1833/// the template parameter lists are not equivalent.
1834///
Douglas Gregordd0574e2009-02-10 00:24:35 +00001835/// \param IsTemplateTemplateParm If true, this routine is being
1836/// called to compare the template parameter lists of a template
1837/// template parameter.
1838///
1839/// \param TemplateArgLoc If this source location is valid, then we
1840/// are actually checking the template parameter list of a template
1841/// argument (New) against the template parameter list of its
1842/// corresponding template template parameter (Old). We produce
1843/// slightly different diagnostics in this scenario.
1844///
Douglas Gregorddc29e12009-02-06 22:42:48 +00001845/// \returns True if the template parameter lists are equal, false
1846/// otherwise.
1847bool
1848Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1849 TemplateParameterList *Old,
1850 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001851 bool IsTemplateTemplateParm,
1852 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00001853 if (Old->size() != New->size()) {
1854 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001855 unsigned NextDiag = diag::err_template_param_list_different_arity;
1856 if (TemplateArgLoc.isValid()) {
1857 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1858 NextDiag = diag::note_template_param_list_different_arity;
1859 }
1860 Diag(New->getTemplateLoc(), NextDiag)
1861 << (New->size() > Old->size())
1862 << IsTemplateTemplateParm
1863 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00001864 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1865 << IsTemplateTemplateParm
1866 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1867 }
1868
1869 return false;
1870 }
1871
1872 for (TemplateParameterList::iterator OldParm = Old->begin(),
1873 OldParmEnd = Old->end(), NewParm = New->begin();
1874 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1875 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001876 unsigned NextDiag = diag::err_template_param_different_kind;
1877 if (TemplateArgLoc.isValid()) {
1878 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1879 NextDiag = diag::note_template_param_different_kind;
1880 }
1881 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001882 << IsTemplateTemplateParm;
1883 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1884 << IsTemplateTemplateParm;
1885 return false;
1886 }
1887
1888 if (isa<TemplateTypeParmDecl>(*OldParm)) {
1889 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00001890 // know we're at the same index).
1891#if 0
Mike Stump390b4cc2009-05-16 07:39:55 +00001892 // FIXME: Enable this code in debug mode *after* we properly go through
1893 // and "instantiate" the template parameter lists of template template
1894 // parameters. It's only after this instantiation that (1) any dependent
1895 // types within the template parameter list of the template template
1896 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregordd0574e2009-02-10 00:24:35 +00001897 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +00001898 QualType OldParmType
1899 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1900 QualType NewParmType
1901 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1902 assert(Context.getCanonicalType(OldParmType) ==
1903 Context.getCanonicalType(NewParmType) &&
1904 "type parameter mismatch?");
1905#endif
1906 } else if (NonTypeTemplateParmDecl *OldNTTP
1907 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1908 // The types of non-type template parameters must agree.
1909 NonTypeTemplateParmDecl *NewNTTP
1910 = cast<NonTypeTemplateParmDecl>(*NewParm);
1911 if (Context.getCanonicalType(OldNTTP->getType()) !=
1912 Context.getCanonicalType(NewNTTP->getType())) {
1913 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00001914 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1915 if (TemplateArgLoc.isValid()) {
1916 Diag(TemplateArgLoc,
1917 diag::err_template_arg_template_params_mismatch);
1918 NextDiag = diag::note_template_nontype_parm_different_type;
1919 }
1920 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00001921 << NewNTTP->getType()
1922 << IsTemplateTemplateParm;
1923 Diag(OldNTTP->getLocation(),
1924 diag::note_template_nontype_parm_prev_declaration)
1925 << OldNTTP->getType();
1926 }
1927 return false;
1928 }
1929 } else {
1930 // The template parameter lists of template template
1931 // parameters must agree.
1932 // FIXME: Could we perform a faster "type" comparison here?
1933 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1934 "Only template template parameters handled here");
1935 TemplateTemplateParmDecl *OldTTP
1936 = cast<TemplateTemplateParmDecl>(*OldParm);
1937 TemplateTemplateParmDecl *NewTTP
1938 = cast<TemplateTemplateParmDecl>(*NewParm);
1939 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1940 OldTTP->getTemplateParameters(),
1941 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +00001942 /*IsTemplateTemplateParm=*/true,
1943 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00001944 return false;
1945 }
1946 }
1947
1948 return true;
1949}
1950
1951/// \brief Check whether a template can be declared within this scope.
1952///
1953/// If the template declaration is valid in this scope, returns
1954/// false. Otherwise, issues a diagnostic and returns true.
1955bool
1956Sema::CheckTemplateDeclScope(Scope *S,
1957 MultiTemplateParamsArg &TemplateParameterLists) {
1958 assert(TemplateParameterLists.size() > 0 && "Not a template");
1959
1960 // Find the nearest enclosing declaration scope.
1961 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1962 (S->getFlags() & Scope::TemplateParamScope) != 0)
1963 S = S->getParent();
1964
1965 TemplateParameterList *TemplateParams =
1966 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1967 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1968 SourceRange TemplateRange
1969 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1970
1971 // C++ [temp]p2:
1972 // A template-declaration can appear only as a namespace scope or
1973 // class scope declaration.
1974 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1975 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1976 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1977 return Diag(TemplateLoc, diag::err_template_linkage)
1978 << TemplateRange;
1979
1980 Ctx = Ctx->getParent();
1981 }
1982
1983 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1984 return false;
1985
1986 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1987 << TemplateRange;
1988}
Douglas Gregorcc636682009-02-17 23:15:12 +00001989
Douglas Gregorff668032009-05-13 18:28:20 +00001990/// \brief Check whether a class template specialization or explicit
1991/// instantiation in the current context is well-formed.
Douglas Gregor88b70942009-02-25 22:02:03 +00001992///
Douglas Gregorff668032009-05-13 18:28:20 +00001993/// This routine determines whether a class template specialization or
1994/// explicit instantiation can be declared in the current context
1995/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
1996/// appropriate diagnostics if there was an error. It returns true if
1997// there was an error that we cannot recover from, and false otherwise.
Douglas Gregor88b70942009-02-25 22:02:03 +00001998bool
1999Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
2000 ClassTemplateSpecializationDecl *PrevDecl,
2001 SourceLocation TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002002 SourceRange ScopeSpecifierRange,
Douglas Gregor16df8502009-06-12 22:21:45 +00002003 bool PartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002004 bool ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002005 // C++ [temp.expl.spec]p2:
2006 // An explicit specialization shall be declared in the namespace
2007 // of which the template is a member, or, for member templates, in
2008 // the namespace of which the enclosing class or enclosing class
2009 // template is a member. An explicit specialization of a member
2010 // function, member class or static data member of a class
2011 // template shall be declared in the namespace of which the class
2012 // template is a member. Such a declaration may also be a
2013 // definition. If the declaration is not a definition, the
2014 // specialization may be defined later in the name- space in which
2015 // the explicit specialization was declared, or in a namespace
2016 // that encloses the one in which the explicit specialization was
2017 // declared.
2018 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor16df8502009-06-12 22:21:45 +00002019 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregor88b70942009-02-25 22:02:03 +00002020 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002021 << Kind << ClassTemplate;
Douglas Gregor88b70942009-02-25 22:02:03 +00002022 return true;
2023 }
2024
2025 DeclContext *DC = CurContext->getEnclosingNamespaceContext();
2026 DeclContext *TemplateContext
2027 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregorff668032009-05-13 18:28:20 +00002028 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
2029 !ExplicitInstantiation) {
Douglas Gregor88b70942009-02-25 22:02:03 +00002030 // There is no prior declaration of this entity, so this
2031 // specialization must be in the same context as the template
2032 // itself.
2033 if (DC != TemplateContext) {
2034 if (isa<TranslationUnitDecl>(TemplateContext))
2035 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor16df8502009-06-12 22:21:45 +00002036 << PartialSpecialization
Douglas Gregor88b70942009-02-25 22:02:03 +00002037 << ClassTemplate << ScopeSpecifierRange;
2038 else if (isa<NamespaceDecl>(TemplateContext))
2039 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002040 << PartialSpecialization << ClassTemplate
2041 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
Douglas Gregor88b70942009-02-25 22:02:03 +00002042
2043 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
2044 }
2045
2046 return false;
2047 }
2048
2049 // We have a previous declaration of this entity. Make sure that
2050 // this redeclaration (or definition) occurs in an enclosing namespace.
2051 if (!CurContext->Encloses(TemplateContext)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002052 // FIXME: In C++98, we would like to turn these errors into warnings,
2053 // dependent on a -Wc++0x flag.
Douglas Gregorff668032009-05-13 18:28:20 +00002054 bool SuppressedDiag = false;
Douglas Gregor16df8502009-06-12 22:21:45 +00002055 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
Douglas Gregorff668032009-05-13 18:28:20 +00002056 if (isa<TranslationUnitDecl>(TemplateContext)) {
2057 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2058 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002059 << Kind << ClassTemplate << ScopeSpecifierRange;
Douglas Gregorff668032009-05-13 18:28:20 +00002060 else
2061 SuppressedDiag = true;
2062 } else if (isa<NamespaceDecl>(TemplateContext)) {
2063 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
2064 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
Douglas Gregor16df8502009-06-12 22:21:45 +00002065 << Kind << ClassTemplate
Douglas Gregorff668032009-05-13 18:28:20 +00002066 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
2067 else
2068 SuppressedDiag = true;
2069 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002070
Douglas Gregorff668032009-05-13 18:28:20 +00002071 if (!SuppressedDiag)
2072 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
Douglas Gregor88b70942009-02-25 22:02:03 +00002073 }
2074
2075 return false;
2076}
2077
Douglas Gregore94866f2009-06-12 21:21:02 +00002078/// \brief Check the non-type template arguments of a class template
2079/// partial specialization according to C++ [temp.class.spec]p9.
2080///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002081/// \param TemplateParams the template parameters of the primary class
2082/// template.
2083///
2084/// \param TemplateArg the template arguments of the class template
2085/// partial specialization.
2086///
2087/// \param MirrorsPrimaryTemplate will be set true if the class
2088/// template partial specialization arguments are identical to the
2089/// implicit template arguments of the primary template. This is not
2090/// necessarily an error (C++0x), and it is left to the caller to diagnose
2091/// this condition when it is an error.
2092///
Douglas Gregore94866f2009-06-12 21:21:02 +00002093/// \returns true if there was an error, false otherwise.
2094bool Sema::CheckClassTemplatePartialSpecializationArgs(
2095 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00002096 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002097 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002098 // FIXME: the interface to this function will have to change to
2099 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002100 MirrorsPrimaryTemplate = true;
Anders Carlsson6360be72009-06-13 18:20:51 +00002101
Anders Carlssonfb250522009-06-23 01:26:57 +00002102 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Anders Carlsson6360be72009-06-13 18:20:51 +00002103
Douglas Gregore94866f2009-06-12 21:21:02 +00002104 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002105 // Determine whether the template argument list of the partial
2106 // specialization is identical to the implicit argument list of
2107 // the primary template. The caller may need to diagnostic this as
2108 // an error per C++ [temp.class.spec]p9b3.
2109 if (MirrorsPrimaryTemplate) {
2110 if (TemplateTypeParmDecl *TTP
2111 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2112 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00002113 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002114 MirrorsPrimaryTemplate = false;
2115 } else if (TemplateTemplateParmDecl *TTP
2116 = dyn_cast<TemplateTemplateParmDecl>(
2117 TemplateParams->getParam(I))) {
2118 // FIXME: We should settle on either Declaration storage or
2119 // Expression storage for template template parameters.
2120 TemplateTemplateParmDecl *ArgDecl
2121 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson6360be72009-06-13 18:20:51 +00002122 ArgList[I].getAsDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002123 if (!ArgDecl)
2124 if (DeclRefExpr *DRE
Anders Carlsson6360be72009-06-13 18:20:51 +00002125 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002126 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2127
2128 if (!ArgDecl ||
2129 ArgDecl->getIndex() != TTP->getIndex() ||
2130 ArgDecl->getDepth() != TTP->getDepth())
2131 MirrorsPrimaryTemplate = false;
2132 }
2133 }
2134
Douglas Gregore94866f2009-06-12 21:21:02 +00002135 NonTypeTemplateParmDecl *Param
2136 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002137 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00002138 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002139 }
2140
Anders Carlsson6360be72009-06-13 18:20:51 +00002141 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002142 if (!ArgExpr) {
2143 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002144 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002145 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002146
2147 // C++ [temp.class.spec]p8:
2148 // A non-type argument is non-specialized if it is the name of a
2149 // non-type parameter. All other non-type arguments are
2150 // specialized.
2151 //
2152 // Below, we check the two conditions that only apply to
2153 // specialized non-type arguments, so skip any non-specialized
2154 // arguments.
2155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002156 if (NonTypeTemplateParmDecl *NTTP
2157 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
2158 if (MirrorsPrimaryTemplate &&
2159 (Param->getIndex() != NTTP->getIndex() ||
2160 Param->getDepth() != NTTP->getDepth()))
2161 MirrorsPrimaryTemplate = false;
2162
Douglas Gregore94866f2009-06-12 21:21:02 +00002163 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002164 }
Douglas Gregore94866f2009-06-12 21:21:02 +00002165
2166 // C++ [temp.class.spec]p9:
2167 // Within the argument list of a class template partial
2168 // specialization, the following restrictions apply:
2169 // -- A partially specialized non-type argument expression
2170 // shall not involve a template parameter of the partial
2171 // specialization except when the argument expression is a
2172 // simple identifier.
2173 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
2174 Diag(ArgExpr->getLocStart(),
2175 diag::err_dependent_non_type_arg_in_partial_spec)
2176 << ArgExpr->getSourceRange();
2177 return true;
2178 }
2179
2180 // -- The type of a template parameter corresponding to a
2181 // specialized non-type argument shall not be dependent on a
2182 // parameter of the specialization.
2183 if (Param->getType()->isDependentType()) {
2184 Diag(ArgExpr->getLocStart(),
2185 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2186 << Param->getType()
2187 << ArgExpr->getSourceRange();
2188 Diag(Param->getLocation(), diag::note_template_param_here);
2189 return true;
2190 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002191
2192 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00002193 }
2194
2195 return false;
2196}
2197
Douglas Gregor212e81c2009-03-25 00:13:59 +00002198Sema::DeclResult
Douglas Gregorcc636682009-02-17 23:15:12 +00002199Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
2200 SourceLocation KWLoc,
2201 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002202 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00002203 SourceLocation TemplateNameLoc,
2204 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00002205 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00002206 SourceLocation *TemplateArgLocs,
2207 SourceLocation RAngleLoc,
2208 AttributeList *Attr,
2209 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorcc636682009-02-17 23:15:12 +00002210 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00002211 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Douglas Gregorcc636682009-02-17 23:15:12 +00002212 ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00002213 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregorcc636682009-02-17 23:15:12 +00002214
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002215 bool isPartialSpecialization = false;
2216
Douglas Gregor88b70942009-02-25 22:02:03 +00002217 // Check the validity of the template headers that introduce this
2218 // template.
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002219 // FIXME: Once we have member templates, we'll need to check
2220 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
2221 // template<> headers.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002222 if (TemplateParameterLists.size() == 0)
2223 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +00002224 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00002225 else {
Douglas Gregor88b70942009-02-25 22:02:03 +00002226 TemplateParameterList *TemplateParams
2227 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
Chris Lattnerb28317a2009-03-28 19:18:32 +00002228 if (TemplateParameterLists.size() > 1) {
2229 Diag(TemplateParams->getTemplateLoc(),
2230 diag::err_template_spec_extra_headers);
2231 return true;
2232 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002233
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002234 if (TemplateParams->size() > 0) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002235 isPartialSpecialization = true;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002236
2237 // C++ [temp.class.spec]p10:
2238 // The template parameter list of a specialization shall not
2239 // contain default template argument values.
2240 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2241 Decl *Param = TemplateParams->getParam(I);
2242 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2243 if (TTP->hasDefaultArgument()) {
2244 Diag(TTP->getDefaultArgumentLoc(),
2245 diag::err_default_arg_in_partial_spec);
2246 TTP->setDefaultArgument(QualType(), SourceLocation(), false);
2247 }
2248 } else if (NonTypeTemplateParmDecl *NTTP
2249 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2250 if (Expr *DefArg = NTTP->getDefaultArgument()) {
2251 Diag(NTTP->getDefaultArgumentLoc(),
2252 diag::err_default_arg_in_partial_spec)
2253 << DefArg->getSourceRange();
2254 NTTP->setDefaultArgument(0);
2255 DefArg->Destroy(Context);
2256 }
2257 } else {
2258 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2259 if (Expr *DefArg = TTP->getDefaultArgument()) {
2260 Diag(TTP->getDefaultArgumentLoc(),
2261 diag::err_default_arg_in_partial_spec)
2262 << DefArg->getSourceRange();
2263 TTP->setDefaultArgument(0);
2264 DefArg->Destroy(Context);
2265 }
2266 }
2267 }
2268 }
Douglas Gregor88b70942009-02-25 22:02:03 +00002269 }
2270
Douglas Gregorcc636682009-02-17 23:15:12 +00002271 // Check that the specialization uses the same tag kind as the
2272 // original template.
2273 TagDecl::TagKind Kind;
2274 switch (TagSpec) {
2275 default: assert(0 && "Unknown tag type!");
2276 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2277 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2278 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2279 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002280 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2281 Kind, KWLoc,
2282 *ClassTemplate->getIdentifier())) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002283 Diag(KWLoc, diag::err_use_with_wrong_tag)
2284 << ClassTemplate
2285 << CodeModificationHint::CreateReplacement(KWLoc,
2286 ClassTemplate->getTemplatedDecl()->getKindName());
Douglas Gregorcc636682009-02-17 23:15:12 +00002287 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2288 diag::note_previous_use);
2289 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2290 }
2291
Douglas Gregor40808ce2009-03-09 23:48:35 +00002292 // Translate the parser's template argument list in our AST format.
2293 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2294 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2295
Douglas Gregorcc636682009-02-17 23:15:12 +00002296 // Check that the template argument list is well-formed for this
2297 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002298 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2299 TemplateArgs.size());
Douglas Gregorcc636682009-02-17 23:15:12 +00002300 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson6360be72009-06-13 18:20:51 +00002301 TemplateArgs.data(), TemplateArgs.size(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002302 RAngleLoc, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002303 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002304
Anders Carlssonfb250522009-06-23 01:26:57 +00002305 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00002306 ClassTemplate->getTemplateParameters()->size()) &&
2307 "Converted template argument list is too short!");
2308
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002309 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00002310 // corresponds to these arguments.
2311 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002312 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002313 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00002314 if (CheckClassTemplatePartialSpecializationArgs(
2315 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002316 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00002317 return true;
2318
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00002319 if (MirrorsPrimaryTemplate) {
2320 // C++ [temp.class.spec]p9b3:
2321 //
2322 // -- The argument list of the specialization shall not be identical
2323 // to the implicit argument list of the primary template.
2324 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2325 << (TK == TK_Definition)
2326 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
2327 RAngleLoc));
2328 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
2329 ClassTemplate->getIdentifier(),
2330 TemplateNameLoc,
2331 Attr,
2332 move(TemplateParameterLists),
2333 AS_none);
2334 }
2335
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002336 // FIXME: Template parameter list matters, too
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002337 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002338 Converted.getFlatArguments(),
2339 Converted.flatSize());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002340 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002341 else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002342 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002343 Converted.getFlatArguments(),
2344 Converted.flatSize());
Douglas Gregorcc636682009-02-17 23:15:12 +00002345 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002346 ClassTemplateSpecializationDecl *PrevDecl = 0;
2347
2348 if (isPartialSpecialization)
2349 PrevDecl
2350 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
2351 InsertPos);
2352 else
2353 PrevDecl
2354 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00002355
2356 ClassTemplateSpecializationDecl *Specialization = 0;
2357
Douglas Gregor88b70942009-02-25 22:02:03 +00002358 // Check whether we can declare a class template specialization in
2359 // the current scope.
2360 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
2361 TemplateNameLoc,
Douglas Gregorff668032009-05-13 18:28:20 +00002362 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002363 isPartialSpecialization,
Douglas Gregorff668032009-05-13 18:28:20 +00002364 /*ExplicitInstantiation=*/false))
Douglas Gregor212e81c2009-03-25 00:13:59 +00002365 return true;
Douglas Gregor88b70942009-02-25 22:02:03 +00002366
Douglas Gregorcc636682009-02-17 23:15:12 +00002367 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2368 // Since the only prior class template specialization with these
2369 // arguments was referenced but not declared, reuse that
2370 // declaration node as our own, updating its source location to
2371 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00002372 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002373 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00002374 PrevDecl = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002375 } else if (isPartialSpecialization) {
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002376 // Create a new class template partial specialization declaration node.
2377 TemplateParameterList *TemplateParams
2378 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
2379 ClassTemplatePartialSpecializationDecl *PrevPartial
2380 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
2381 ClassTemplatePartialSpecializationDecl *Partial
2382 = ClassTemplatePartialSpecializationDecl::Create(Context,
2383 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002384 TemplateNameLoc,
2385 TemplateParams,
2386 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002387 Converted,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002388 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002389
2390 if (PrevPartial) {
2391 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2392 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2393 } else {
2394 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2395 }
2396 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00002397
2398 // Check that all of the template parameters of the class template
2399 // partial specialization are deducible from the template
2400 // arguments. If not, this class template partial specialization
2401 // will never be used.
2402 llvm::SmallVector<bool, 8> DeducibleParams;
2403 DeducibleParams.resize(TemplateParams->size());
2404 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
2405 unsigned NumNonDeducible = 0;
2406 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2407 if (!DeducibleParams[I])
2408 ++NumNonDeducible;
2409
2410 if (NumNonDeducible) {
2411 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2412 << (NumNonDeducible > 1)
2413 << SourceRange(TemplateNameLoc, RAngleLoc);
2414 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2415 if (!DeducibleParams[I]) {
2416 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2417 if (Param->getDeclName())
2418 Diag(Param->getLocation(),
2419 diag::note_partial_spec_unused_parameter)
2420 << Param->getDeclName();
2421 else
2422 Diag(Param->getLocation(),
2423 diag::note_partial_spec_unused_parameter)
2424 << std::string("<anonymous>");
2425 }
2426 }
2427 }
2428
Douglas Gregorcc636682009-02-17 23:15:12 +00002429 } else {
2430 // Create a new class template specialization declaration node for
2431 // this explicit specialization.
2432 Specialization
2433 = ClassTemplateSpecializationDecl::Create(Context,
2434 ClassTemplate->getDeclContext(),
2435 TemplateNameLoc,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00002436 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002437 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00002438 PrevDecl);
2439
2440 if (PrevDecl) {
2441 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2442 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2443 } else {
2444 ClassTemplate->getSpecializations().InsertNode(Specialization,
2445 InsertPos);
2446 }
2447 }
2448
2449 // Note that this is an explicit specialization.
2450 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2451
2452 // Check that this isn't a redefinition of this specialization.
2453 if (TK == TK_Definition) {
2454 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002455 // FIXME: Should also handle explicit specialization after implicit
2456 // instantiation with a special diagnostic.
Douglas Gregorcc636682009-02-17 23:15:12 +00002457 SourceRange Range(TemplateNameLoc, RAngleLoc);
2458 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002459 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00002460 Diag(Def->getLocation(), diag::note_previous_definition);
2461 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00002462 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00002463 }
2464 }
2465
Douglas Gregorfc705b82009-02-26 22:19:44 +00002466 // Build the fully-sugared type for this class template
2467 // specialization as the user wrote in the specialization
2468 // itself. This means that we'll pretty-print the type retrieved
2469 // from the specialization's declaration the way that the user
2470 // actually wrote the specialization, rather than formatting the
2471 // name based on the "canonical" representation used to store the
2472 // template arguments in the specialization.
Douglas Gregore6258932009-03-19 00:39:20 +00002473 QualType WrittenTy
Douglas Gregor7532dc62009-03-30 22:58:21 +00002474 = Context.getTemplateSpecializationType(Name,
Anders Carlsson6360be72009-06-13 18:20:51 +00002475 TemplateArgs.data(),
Douglas Gregor7532dc62009-03-30 22:58:21 +00002476 TemplateArgs.size(),
Douglas Gregore6258932009-03-19 00:39:20 +00002477 Context.getTypeDeclType(Specialization));
Douglas Gregor7532dc62009-03-30 22:58:21 +00002478 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00002479 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00002480
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00002481 // C++ [temp.expl.spec]p9:
2482 // A template explicit specialization is in the scope of the
2483 // namespace in which the template was defined.
2484 //
2485 // We actually implement this paragraph where we set the semantic
2486 // context (in the creation of the ClassTemplateSpecializationDecl),
2487 // but we also maintain the lexical context where the actual
2488 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00002489 Specialization->setLexicalDeclContext(CurContext);
2490
2491 // We may be starting the definition of this specialization.
2492 if (TK == TK_Definition)
2493 Specialization->startDefinition();
2494
2495 // Add the specialization into its lexical context, so that it can
2496 // be seen when iterating through the list of declarations in that
2497 // context. However, specializations are not found by name lookup.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002498 CurContext->addDecl(Context, Specialization);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002499 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00002500}
Douglas Gregord57959a2009-03-27 23:10:48 +00002501
Douglas Gregore542c862009-06-23 23:11:28 +00002502Sema::DeclPtrTy
2503Sema::ActOnTemplateDeclarator(Scope *S,
2504 MultiTemplateParamsArg TemplateParameterLists,
2505 Declarator &D) {
2506 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
2507}
2508
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002509// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002510Sema::DeclResult
2511Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2512 unsigned TagSpec,
2513 SourceLocation KWLoc,
2514 const CXXScopeSpec &SS,
2515 TemplateTy TemplateD,
2516 SourceLocation TemplateNameLoc,
2517 SourceLocation LAngleLoc,
2518 ASTTemplateArgsPtr TemplateArgsIn,
2519 SourceLocation *TemplateArgLocs,
2520 SourceLocation RAngleLoc,
2521 AttributeList *Attr) {
2522 // Find the class template we're specializing
2523 TemplateName Name = TemplateD.getAsVal<TemplateName>();
2524 ClassTemplateDecl *ClassTemplate
2525 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
2526
2527 // Check that the specialization uses the same tag kind as the
2528 // original template.
2529 TagDecl::TagKind Kind;
2530 switch (TagSpec) {
2531 default: assert(0 && "Unknown tag type!");
2532 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2533 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2534 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2535 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00002536 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
2537 Kind, KWLoc,
2538 *ClassTemplate->getIdentifier())) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002539 Diag(KWLoc, diag::err_use_with_wrong_tag)
2540 << ClassTemplate
2541 << CodeModificationHint::CreateReplacement(KWLoc,
2542 ClassTemplate->getTemplatedDecl()->getKindName());
2543 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
2544 diag::note_previous_use);
2545 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2546 }
2547
Douglas Gregorff668032009-05-13 18:28:20 +00002548 // C++0x [temp.explicit]p2:
2549 // [...] An explicit instantiation shall appear in an enclosing
2550 // namespace of its template. [...]
2551 //
2552 // This is C++ DR 275.
2553 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
2554 TemplateNameLoc,
2555 SS.getRange(),
Douglas Gregor16df8502009-06-12 22:21:45 +00002556 /*PartialSpecialization=*/false,
Douglas Gregorff668032009-05-13 18:28:20 +00002557 /*ExplicitInstantiation=*/true))
2558 return true;
2559
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002560 // Translate the parser's template argument list in our AST format.
2561 llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
2562 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2563
2564 // Check that the template argument list is well-formed for this
2565 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00002566 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2567 TemplateArgs.size());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002568 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson9bff9a92009-06-05 02:12:32 +00002569 TemplateArgs.data(), TemplateArgs.size(),
Anders Carlssonfb250522009-06-23 01:26:57 +00002570 RAngleLoc, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002571 return true;
2572
Anders Carlssonfb250522009-06-23 01:26:57 +00002573 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002574 ClassTemplate->getTemplateParameters()->size()) &&
2575 "Converted template argument list is too short!");
2576
2577 // Find the class template specialization declaration that
2578 // corresponds to these arguments.
2579 llvm::FoldingSetNodeID ID;
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002580 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00002581 Converted.getFlatArguments(),
2582 Converted.flatSize());
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002583 void *InsertPos = 0;
2584 ClassTemplateSpecializationDecl *PrevDecl
2585 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
2586
2587 ClassTemplateSpecializationDecl *Specialization = 0;
2588
Douglas Gregorff668032009-05-13 18:28:20 +00002589 bool SpecializationRequiresInstantiation = true;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002590 if (PrevDecl) {
Douglas Gregorff668032009-05-13 18:28:20 +00002591 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002592 // This particular specialization has already been declared or
2593 // instantiated. We cannot explicitly instantiate it.
Douglas Gregorff668032009-05-13 18:28:20 +00002594 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
2595 << Context.getTypeDeclType(PrevDecl);
2596 Diag(PrevDecl->getLocation(),
2597 diag::note_previous_explicit_instantiation);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002598 return DeclPtrTy::make(PrevDecl);
2599 }
2600
Douglas Gregorff668032009-05-13 18:28:20 +00002601 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002602 // C++ DR 259, C++0x [temp.explicit]p4:
Douglas Gregorff668032009-05-13 18:28:20 +00002603 // For a given set of template parameters, if an explicit
2604 // instantiation of a template appears after a declaration of
2605 // an explicit specialization for that template, the explicit
2606 // instantiation has no effect.
2607 if (!getLangOptions().CPlusPlus0x) {
2608 Diag(TemplateNameLoc,
2609 diag::ext_explicit_instantiation_after_specialization)
2610 << Context.getTypeDeclType(PrevDecl);
2611 Diag(PrevDecl->getLocation(),
2612 diag::note_previous_template_specialization);
2613 }
2614
2615 // Create a new class template specialization declaration node
2616 // for this explicit specialization. This node is only used to
2617 // record the existence of this explicit instantiation for
2618 // accurate reproduction of the source code; we don't actually
2619 // use it for anything, since it is semantically irrelevant.
2620 Specialization
2621 = ClassTemplateSpecializationDecl::Create(Context,
2622 ClassTemplate->getDeclContext(),
2623 TemplateNameLoc,
2624 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002625 Converted, 0);
Douglas Gregorff668032009-05-13 18:28:20 +00002626 Specialization->setLexicalDeclContext(CurContext);
2627 CurContext->addDecl(Context, Specialization);
2628 return DeclPtrTy::make(Specialization);
2629 }
2630
2631 // If we have already (implicitly) instantiated this
2632 // specialization, there is less work to do.
2633 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
2634 SpecializationRequiresInstantiation = false;
2635
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002636 // Since the only prior class template specialization with these
2637 // arguments was referenced but not declared, reuse that
2638 // declaration node as our own, updating its source location to
2639 // reflect our new declaration.
2640 Specialization = PrevDecl;
2641 Specialization->setLocation(TemplateNameLoc);
2642 PrevDecl = 0;
2643 } else {
2644 // Create a new class template specialization declaration node for
2645 // this explicit specialization.
2646 Specialization
2647 = ClassTemplateSpecializationDecl::Create(Context,
2648 ClassTemplate->getDeclContext(),
2649 TemplateNameLoc,
2650 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00002651 Converted, 0);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002652
2653 ClassTemplate->getSpecializations().InsertNode(Specialization,
2654 InsertPos);
2655 }
2656
2657 // Build the fully-sugared type for this explicit instantiation as
2658 // the user wrote in the explicit instantiation itself. This means
2659 // that we'll pretty-print the type retrieved from the
2660 // specialization's declaration the way that the user actually wrote
2661 // the explicit instantiation, rather than formatting the name based
2662 // on the "canonical" representation used to store the template
2663 // arguments in the specialization.
2664 QualType WrittenTy
2665 = Context.getTemplateSpecializationType(Name,
Anders Carlssonf4e2a2c2009-06-05 02:45:24 +00002666 TemplateArgs.data(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002667 TemplateArgs.size(),
2668 Context.getTypeDeclType(Specialization));
2669 Specialization->setTypeAsWritten(WrittenTy);
2670 TemplateArgsIn.release();
2671
2672 // Add the explicit instantiation into its lexical context. However,
2673 // since explicit instantiations are never found by name lookup, we
2674 // just put it into the declaration context directly.
2675 Specialization->setLexicalDeclContext(CurContext);
2676 CurContext->addDecl(Context, Specialization);
2677
2678 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002679 // A definition of a class template or class member template
2680 // shall be in scope at the point of the explicit instantiation of
2681 // the class template or class member template.
2682 //
2683 // This check comes when we actually try to perform the
2684 // instantiation.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002685 if (SpecializationRequiresInstantiation)
2686 InstantiateClassTemplateSpecialization(Specialization, true);
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002687 else // Instantiate the members of this class template specialization.
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002688 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00002689
2690 return DeclPtrTy::make(Specialization);
2691}
2692
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002693// Explicit instantiation of a member class of a class template.
2694Sema::DeclResult
2695Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
2696 unsigned TagSpec,
2697 SourceLocation KWLoc,
2698 const CXXScopeSpec &SS,
2699 IdentifierInfo *Name,
2700 SourceLocation NameLoc,
2701 AttributeList *Attr) {
2702
Douglas Gregor402abb52009-05-28 23:31:59 +00002703 bool Owned = false;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002704 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
Douglas Gregor402abb52009-05-28 23:31:59 +00002705 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002706 if (!TagD)
2707 return true;
2708
2709 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
2710 if (Tag->isEnum()) {
2711 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
2712 << Context.getTypeDeclType(Tag);
2713 return true;
2714 }
2715
Douglas Gregord0c87372009-05-27 17:30:49 +00002716 if (Tag->isInvalidDecl())
2717 return true;
2718
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002719 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
2720 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2721 if (!Pattern) {
2722 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
2723 << Context.getTypeDeclType(Record);
2724 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
2725 return true;
2726 }
2727
2728 // C++0x [temp.explicit]p2:
2729 // [...] An explicit instantiation shall appear in an enclosing
2730 // namespace of its template. [...]
2731 //
2732 // This is C++ DR 275.
2733 if (getLangOptions().CPlusPlus0x) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002734 // FIXME: In C++98, we would like to turn these errors into warnings,
2735 // dependent on a -Wc++0x flag.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002736 DeclContext *PatternContext
2737 = Pattern->getDeclContext()->getEnclosingNamespaceContext();
2738 if (!CurContext->Encloses(PatternContext)) {
2739 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
2740 << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
2741 Diag(Pattern->getLocation(), diag::note_previous_declaration);
2742 }
2743 }
2744
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002745 if (!Record->getDefinition(Context)) {
2746 // If the class has a definition, instantiate it (and all of its
2747 // members, recursively).
2748 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
2749 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002750 getTemplateInstantiationArgs(Record),
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002751 /*ExplicitInstantiation=*/true))
2752 return true;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002753 } else // Instantiate all of the members of class.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002754 InstantiateClassMembers(TemplateLoc, Record,
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002755 getTemplateInstantiationArgs(Record));
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002756
Mike Stump390b4cc2009-05-16 07:39:55 +00002757 // FIXME: We don't have any representation for explicit instantiations of
2758 // member classes. Such a representation is not needed for compilation, but it
2759 // should be available for clients that want to see all of the declarations in
2760 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00002761 return TagD;
2762}
2763
Douglas Gregord57959a2009-03-27 23:10:48 +00002764Sema::TypeResult
2765Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2766 const IdentifierInfo &II, SourceLocation IdLoc) {
2767 NestedNameSpecifier *NNS
2768 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2769 if (!NNS)
2770 return true;
2771
2772 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00002773 if (T.isNull())
2774 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00002775 return T.getAsOpaquePtr();
2776}
2777
Douglas Gregor17343172009-04-01 00:28:59 +00002778Sema::TypeResult
2779Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
2780 SourceLocation TemplateLoc, TypeTy *Ty) {
2781 QualType T = QualType::getFromOpaquePtr(Ty);
2782 NestedNameSpecifier *NNS
2783 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2784 const TemplateSpecializationType *TemplateId
2785 = T->getAsTemplateSpecializationType();
2786 assert(TemplateId && "Expected a template specialization type");
2787
2788 if (NNS->isDependent())
2789 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
2790
2791 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
2792}
2793
Douglas Gregord57959a2009-03-27 23:10:48 +00002794/// \brief Build the type that describes a C++ typename specifier,
2795/// e.g., "typename T::type".
2796QualType
2797Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
2798 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00002799 CXXRecordDecl *CurrentInstantiation = 0;
2800 if (NNS->isDependent()) {
2801 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00002802
Douglas Gregor42af25f2009-05-11 19:58:34 +00002803 // If the nested-name-specifier does not refer to the current
2804 // instantiation, then build a typename type.
2805 if (!CurrentInstantiation)
2806 return Context.getTypenameType(NNS, &II);
2807 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002808
Douglas Gregor42af25f2009-05-11 19:58:34 +00002809 DeclContext *Ctx = 0;
2810
2811 if (CurrentInstantiation)
2812 Ctx = CurrentInstantiation;
2813 else {
2814 CXXScopeSpec SS;
2815 SS.setScopeRep(NNS);
2816 SS.setRange(Range);
2817 if (RequireCompleteDeclContext(SS))
2818 return QualType();
2819
2820 Ctx = computeDeclContext(SS);
2821 }
Douglas Gregord57959a2009-03-27 23:10:48 +00002822 assert(Ctx && "No declaration context?");
2823
2824 DeclarationName Name(&II);
2825 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
2826 false);
2827 unsigned DiagID = 0;
2828 Decl *Referenced = 0;
2829 switch (Result.getKind()) {
2830 case LookupResult::NotFound:
2831 if (Ctx->isTranslationUnit())
2832 DiagID = diag::err_typename_nested_not_found_global;
2833 else
2834 DiagID = diag::err_typename_nested_not_found;
2835 break;
2836
2837 case LookupResult::Found:
2838 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
2839 // We found a type. Build a QualifiedNameType, since the
2840 // typename-specifier was just sugar. FIXME: Tell
2841 // QualifiedNameType that it has a "typename" prefix.
2842 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
2843 }
2844
2845 DiagID = diag::err_typename_nested_not_type;
2846 Referenced = Result.getAsDecl();
2847 break;
2848
2849 case LookupResult::FoundOverloaded:
2850 DiagID = diag::err_typename_nested_not_type;
2851 Referenced = *Result.begin();
2852 break;
2853
2854 case LookupResult::AmbiguousBaseSubobjectTypes:
2855 case LookupResult::AmbiguousBaseSubobjects:
2856 case LookupResult::AmbiguousReference:
2857 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
2858 return QualType();
2859 }
2860
2861 // If we get here, it's because name lookup did not find a
2862 // type. Emit an appropriate diagnostic and return an error.
2863 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
2864 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
2865 else
2866 Diag(Range.getEnd(), DiagID) << Range << Name;
2867 if (Referenced)
2868 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
2869 << Name;
2870 return QualType();
2871}